OpenTTD Source  13.0-beta2
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 <stdarg.h>
13 
14 #include "debug.h"
15 #include "fileio_func.h"
16 #include "engine_func.h"
17 #include "engine_base.h"
18 #include "bridge.h"
19 #include "town.h"
20 #include "newgrf_engine.h"
21 #include "newgrf_text.h"
22 #include "fontcache.h"
23 #include "currency.h"
24 #include "landscape.h"
25 #include "newgrf_cargo.h"
26 #include "newgrf_house.h"
27 #include "newgrf_sound.h"
28 #include "newgrf_station.h"
29 #include "industrytype.h"
30 #include "industry_map.h"
31 #include "newgrf_canal.h"
32 #include "newgrf_townname.h"
33 #include "newgrf_industries.h"
34 #include "newgrf_airporttiles.h"
35 #include "newgrf_airport.h"
36 #include "newgrf_object.h"
37 #include "rev.h"
38 #include "fios.h"
39 #include "strings_func.h"
40 #include "date_func.h"
41 #include "string_func.h"
42 #include "network/core/config.h"
43 #include <map>
44 #include "smallmap_gui.h"
45 #include "genworld.h"
46 #include "error.h"
47 #include "vehicle_func.h"
48 #include "language.h"
49 #include "vehicle_base.h"
50 #include "road.h"
51 
52 #include "table/strings.h"
53 #include "table/build_industry.h"
54 
55 #include "safeguards.h"
56 
57 /* TTDPatch extended GRF format codec
58  * (c) Petr Baudis 2004 (GPL'd)
59  * Changes by Florian octo Forster are (c) by the OpenTTD development team.
60  *
61  * Contains portions of documentation by TTDPatch team.
62  * Thanks especially to Josef Drexler for the documentation as well as a lot
63  * of help at #tycoon. Also thanks to Michael Blunck for his GRF files which
64  * served as subject to the initial testing of this codec. */
65 
67 static std::vector<GRFFile *> _grf_files;
68 
69 const std::vector<GRFFile *> &GetAllGRFFiles()
70 {
71  return _grf_files;
72 }
73 
76 
78 static uint32 _ttdpatch_flags[8];
79 
82 
83 static const uint MAX_SPRITEGROUP = UINT8_MAX;
84 
87 private:
89  struct SpriteSet {
91  uint num_sprites;
92  };
93 
95  std::map<uint, SpriteSet> spritesets[GSF_END];
96 
97 public:
98  /* Global state */
99  GrfLoadingStage stage;
101 
102  /* Local state in the file */
106  uint32 nfo_line;
107 
108  /* Kind of return values when processing certain actions */
110 
111  /* Currently referenceable spritegroups */
112  const SpriteGroup *spritegroups[MAX_SPRITEGROUP + 1];
113 
116  {
117  this->nfo_line = 0;
118  this->skip_sprites = 0;
119 
120  for (uint i = 0; i < GSF_END; i++) {
121  this->spritesets[i].clear();
122  }
123 
124  memset(this->spritegroups, 0, sizeof(this->spritegroups));
125  }
126 
135  void AddSpriteSets(byte feature, SpriteID first_sprite, uint first_set, uint numsets, uint numents)
136  {
137  assert(feature < GSF_END);
138  for (uint i = 0; i < numsets; i++) {
139  SpriteSet &set = this->spritesets[feature][first_set + i];
140  set.sprite = first_sprite + i * numents;
141  set.num_sprites = numents;
142  }
143  }
144 
151  bool HasValidSpriteSets(byte feature) const
152  {
153  assert(feature < GSF_END);
154  return !this->spritesets[feature].empty();
155  }
156 
164  bool IsValidSpriteSet(byte feature, uint set) const
165  {
166  assert(feature < GSF_END);
167  return this->spritesets[feature].find(set) != this->spritesets[feature].end();
168  }
169 
176  SpriteID GetSprite(byte feature, uint set) const
177  {
178  assert(IsValidSpriteSet(feature, set));
179  return this->spritesets[feature].find(set)->second.sprite;
180  }
181 
188  uint GetNumEnts(byte feature, uint set) const
189  {
190  assert(IsValidSpriteSet(feature, set));
191  return this->spritesets[feature].find(set)->second.num_sprites;
192  }
193 };
194 
195 static GrfProcessingState _cur;
196 
197 
204 template <VehicleType T>
205 static inline bool IsValidNewGRFImageIndex(uint8 image_index)
206 {
207  return image_index == 0xFD || IsValidImageIndex<T>(image_index);
208 }
209 
211 
213 class ByteReader {
214 protected:
215  byte *data;
216  byte *end;
217 
218 public:
219  ByteReader(byte *data, byte *end) : data(data), end(end) { }
220 
221  inline byte *ReadBytes(size_t size)
222  {
223  if (data + size >= end) {
224  /* Put data at the end, as would happen if every byte had been individually read. */
225  data = end;
226  throw OTTDByteReaderSignal();
227  }
228 
229  byte *ret = data;
230  data += size;
231  return ret;
232  }
233 
234  inline byte ReadByte()
235  {
236  if (data < end) return *(data)++;
237  throw OTTDByteReaderSignal();
238  }
239 
240  uint16 ReadWord()
241  {
242  uint16 val = ReadByte();
243  return val | (ReadByte() << 8);
244  }
245 
246  uint16 ReadExtendedByte()
247  {
248  uint16 val = ReadByte();
249  return val == 0xFF ? ReadWord() : val;
250  }
251 
252  uint32 ReadDWord()
253  {
254  uint32 val = ReadWord();
255  return val | (ReadWord() << 16);
256  }
257 
258  uint32 ReadVarSize(byte size)
259  {
260  switch (size) {
261  case 1: return ReadByte();
262  case 2: return ReadWord();
263  case 4: return ReadDWord();
264  default:
265  NOT_REACHED();
266  return 0;
267  }
268  }
269 
270  const char *ReadString()
271  {
272  char *string = reinterpret_cast<char *>(data);
273  size_t string_length = ttd_strnlen(string, Remaining());
274 
275  if (string_length == Remaining()) {
276  /* String was not NUL terminated, so make sure it is now. */
277  string[string_length - 1] = '\0';
278  grfmsg(7, "String was not terminated with a zero byte.");
279  } else {
280  /* Increase the string length to include the NUL byte. */
281  string_length++;
282  }
283  Skip(string_length);
284 
285  return string;
286  }
287 
288  inline size_t Remaining() const
289  {
290  return end - data;
291  }
292 
293  inline bool HasData(size_t count = 1) const
294  {
295  return data + count <= end;
296  }
297 
298  inline byte *Data()
299  {
300  return data;
301  }
302 
303  inline void Skip(size_t len)
304  {
305  data += len;
306  /* It is valid to move the buffer to exactly the end of the data,
307  * as there may not be any more data read. */
308  if (data > end) throw OTTDByteReaderSignal();
309  }
310 };
311 
312 typedef void (*SpecialSpriteHandler)(ByteReader *buf);
313 
314 static const uint NUM_STATIONS_PER_GRF = 255;
315 
320  UNSET = 0,
323  };
324 
325  uint16 cargo_allowed;
326  uint16 cargo_disallowed;
327  RailTypeLabel railtypelabel;
328  uint8 roadtramtype;
331  bool prop27_set;
332  uint8 rv_max_speed;
333  CargoTypes ctt_include_mask;
334  CargoTypes ctt_exclude_mask;
335 
340  void UpdateRefittability(bool non_empty)
341  {
342  if (non_empty) {
343  this->refittability = NONEMPTY;
344  } else if (this->refittability == UNSET) {
345  this->refittability = EMPTY;
346  }
347  }
348 };
349 
351 
356 static uint32 _grm_engines[256];
357 
359 static uint32 _grm_cargoes[NUM_CARGO * 2];
360 
361 struct GRFLocation {
362  uint32 grfid;
363  uint32 nfoline;
364 
365  GRFLocation(uint32 grfid, uint32 nfoline) : grfid(grfid), nfoline(nfoline) { }
366 
367  bool operator<(const GRFLocation &other) const
368  {
369  return this->grfid < other.grfid || (this->grfid == other.grfid && this->nfoline < other.nfoline);
370  }
371 
372  bool operator == (const GRFLocation &other) const
373  {
374  return this->grfid == other.grfid && this->nfoline == other.nfoline;
375  }
376 };
377 
378 static std::map<GRFLocation, SpriteID> _grm_sprites;
379 typedef std::map<GRFLocation, byte*> GRFLineToSpriteOverride;
380 static GRFLineToSpriteOverride _grf_line_to_action6_sprite_override;
381 
392 void CDECL grfmsg(int severity, const char *str, ...)
393 {
394  char buf[1024];
395  va_list va;
396 
397  va_start(va, str);
398  vseprintf(buf, lastof(buf), str, va);
399  va_end(va);
400 
401  Debug(grf, severity, "[{}:{}] {}", _cur.grfconfig->filename, _cur.nfo_line, buf);
402 }
403 
409 static GRFFile *GetFileByGRFID(uint32 grfid)
410 {
411  for (GRFFile * const file : _grf_files) {
412  if (file->grfid == grfid) return file;
413  }
414  return nullptr;
415 }
416 
422 static GRFFile *GetFileByFilename(const char *filename)
423 {
424  for (GRFFile * const file : _grf_files) {
425  if (strcmp(file->filename, filename) == 0) return file;
426  }
427  return nullptr;
428 }
429 
432 {
433  /* Clear the GOTO labels used for GRF processing */
434  for (GRFLabel *l = gf->label; l != nullptr;) {
435  GRFLabel *l2 = l->next;
436  free(l);
437  l = l2;
438  }
439  gf->label = nullptr;
440 }
441 
448 static GRFError *DisableGrf(StringID message = STR_NULL, GRFConfig *config = nullptr)
449 {
450  GRFFile *file;
451  if (config != nullptr) {
452  file = GetFileByGRFID(config->ident.grfid);
453  } else {
454  config = _cur.grfconfig;
455  file = _cur.grffile;
456  }
457 
458  config->status = GCS_DISABLED;
459  if (file != nullptr) ClearTemporaryNewGRFData(file);
460  if (config == _cur.grfconfig) _cur.skip_sprites = -1;
461 
462  if (message != STR_NULL) {
463  delete config->error;
464  config->error = new GRFError(STR_NEWGRF_ERROR_MSG_FATAL, message);
465  if (config == _cur.grfconfig) config->error->param_value[0] = _cur.nfo_line;
466  }
467 
468  return config->error;
469 }
470 
475  uint32 grfid;
478 };
479 typedef std::vector<StringIDMapping> StringIDMappingVector;
480 static StringIDMappingVector _string_to_grf_mapping;
481 
487 static void AddStringForMapping(StringID source, StringID *target)
488 {
489  *target = STR_UNDEFINED;
490  _string_to_grf_mapping.push_back({_cur.grffile->grfid, source, target});
491 }
492 
501 {
502  /* StringID table for TextIDs 0x4E->0x6D */
503  static const StringID units_volume[] = {
504  STR_ITEMS, STR_PASSENGERS, STR_TONS, STR_BAGS,
505  STR_LITERS, STR_ITEMS, STR_CRATES, STR_TONS,
506  STR_TONS, STR_TONS, STR_TONS, STR_BAGS,
507  STR_TONS, STR_TONS, STR_TONS, STR_BAGS,
508  STR_TONS, STR_TONS, STR_BAGS, STR_LITERS,
509  STR_TONS, STR_LITERS, STR_TONS, STR_ITEMS,
510  STR_BAGS, STR_LITERS, STR_TONS, STR_ITEMS,
511  STR_TONS, STR_ITEMS, STR_LITERS, STR_ITEMS
512  };
513 
514  /* A string straight from a NewGRF; this was already translated by MapGRFStringID(). */
515  assert(!IsInsideMM(str, 0xD000, 0xD7FF));
516 
517 #define TEXTID_TO_STRINGID(begin, end, stringid, stringend) \
518  static_assert(stringend - stringid == end - begin); \
519  if (str >= begin && str <= end) return str + (stringid - begin)
520 
521  /* We have some changes in our cargo strings, resulting in some missing. */
522  TEXTID_TO_STRINGID(0x000E, 0x002D, STR_CARGO_PLURAL_NOTHING, STR_CARGO_PLURAL_FIZZY_DRINKS);
523  TEXTID_TO_STRINGID(0x002E, 0x004D, STR_CARGO_SINGULAR_NOTHING, STR_CARGO_SINGULAR_FIZZY_DRINK);
524  if (str >= 0x004E && str <= 0x006D) return units_volume[str - 0x004E];
525  TEXTID_TO_STRINGID(0x006E, 0x008D, STR_QUANTITY_NOTHING, STR_QUANTITY_FIZZY_DRINKS);
526  TEXTID_TO_STRINGID(0x008E, 0x00AD, STR_ABBREV_NOTHING, STR_ABBREV_FIZZY_DRINKS);
527  TEXTID_TO_STRINGID(0x00D1, 0x00E0, STR_COLOUR_DARK_BLUE, STR_COLOUR_WHITE);
528 
529  /* Map building names according to our lang file changes. There are several
530  * ranges of house ids, all of which need to be remapped to allow newgrfs
531  * to use original house names. */
532  TEXTID_TO_STRINGID(0x200F, 0x201F, STR_TOWN_BUILDING_NAME_TALL_OFFICE_BLOCK_1, STR_TOWN_BUILDING_NAME_OLD_HOUSES_1);
533  TEXTID_TO_STRINGID(0x2036, 0x2041, STR_TOWN_BUILDING_NAME_COTTAGES_1, STR_TOWN_BUILDING_NAME_SHOPPING_MALL_1);
534  TEXTID_TO_STRINGID(0x2059, 0x205C, STR_TOWN_BUILDING_NAME_IGLOO_1, STR_TOWN_BUILDING_NAME_PIGGY_BANK_1);
535 
536  /* Same thing for industries */
537  TEXTID_TO_STRINGID(0x4802, 0x4826, STR_INDUSTRY_NAME_COAL_MINE, STR_INDUSTRY_NAME_SUGAR_MINE);
538  TEXTID_TO_STRINGID(0x482D, 0x482E, STR_NEWS_INDUSTRY_CONSTRUCTION, STR_NEWS_INDUSTRY_PLANTED);
539  TEXTID_TO_STRINGID(0x4832, 0x4834, STR_NEWS_INDUSTRY_CLOSURE_GENERAL, STR_NEWS_INDUSTRY_CLOSURE_LACK_OF_TREES);
540  TEXTID_TO_STRINGID(0x4835, 0x4838, STR_NEWS_INDUSTRY_PRODUCTION_INCREASE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_INCREASE_FARM);
541  TEXTID_TO_STRINGID(0x4839, 0x483A, STR_NEWS_INDUSTRY_PRODUCTION_DECREASE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_DECREASE_FARM);
542 
543  switch (str) {
544  case 0x4830: return STR_ERROR_CAN_T_CONSTRUCT_THIS_INDUSTRY;
545  case 0x4831: return STR_ERROR_FOREST_CAN_ONLY_BE_PLANTED;
546  case 0x483B: return STR_ERROR_CAN_ONLY_BE_POSITIONED;
547  }
548 #undef TEXTID_TO_STRINGID
549 
550  if (str == STR_NULL) return STR_EMPTY;
551 
552  Debug(grf, 0, "Unknown StringID 0x{:04X} remapped to STR_EMPTY. Please open a Feature Request if you need it", str);
553 
554  return STR_EMPTY;
555 }
556 
564 StringID MapGRFStringID(uint32 grfid, StringID str)
565 {
566  if (IsInsideMM(str, 0xD800, 0xE000)) {
567  /* General text provided by NewGRF.
568  * In the specs this is called the 0xDCxx range (misc persistent texts),
569  * but we meanwhile extended the range to 0xD800-0xDFFF.
570  * Note: We are not involved in the "persistent" business, since we do not store
571  * any NewGRF strings in savegames. */
572  return GetGRFStringID(grfid, str);
573  } else if (IsInsideMM(str, 0xD000, 0xD800)) {
574  /* Callback text provided by NewGRF.
575  * In the specs this is called the 0xD0xx range (misc graphics texts).
576  * These texts can be returned by various callbacks.
577  *
578  * Due to how TTDP implements the GRF-local- to global-textid translation
579  * texts included via 0x80 or 0x81 control codes have to add 0x400 to the textid.
580  * We do not care about that difference and just mask out the 0x400 bit.
581  */
582  str &= ~0x400;
583  return GetGRFStringID(grfid, str);
584  } else {
585  /* The NewGRF wants to include/reference an original TTD string.
586  * Try our best to find an equivalent one. */
588  }
589 }
590 
591 static std::map<uint32, uint32> _grf_id_overrides;
592 
598 static void SetNewGRFOverride(uint32 source_grfid, uint32 target_grfid)
599 {
600  _grf_id_overrides[source_grfid] = target_grfid;
601  grfmsg(5, "SetNewGRFOverride: Added override of 0x%X to 0x%X", BSWAP32(source_grfid), BSWAP32(target_grfid));
602 }
603 
612 static Engine *GetNewEngine(const GRFFile *file, VehicleType type, uint16 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 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  uint32 override = _grf_id_overrides[file->grfid];
621  if (override != 0) {
622  scope_grfid = override;
623  const GRFFile *grf_match = GetFileByGRFID(override);
624  if (grf_match == nullptr) {
625  grfmsg(5, "Tried mapping from GRFID %x to %x but target is not loaded", BSWAP32(file->grfid), BSWAP32(override));
626  } else {
627  grfmsg(5, "Mapping from GRFID %x to %x", BSWAP32(file->grfid), BSWAP32(override));
628  }
629  }
630 
631  /* Check if the engine is registered in the override manager */
632  EngineID engine = _engine_mngr.GetID(type, internal_id, scope_grfid);
633  if (engine != INVALID_ENGINE) {
634  Engine *e = Engine::Get(engine);
635  if (e->grf_prop.grffile == nullptr) e->grf_prop.grffile = file;
636  return e;
637  }
638  }
639 
640  /* Check if there is an unreserved slot */
641  EngineID engine = _engine_mngr.GetID(type, internal_id, INVALID_GRFID);
642  if (engine != INVALID_ENGINE) {
643  Engine *e = Engine::Get(engine);
644 
645  if (e->grf_prop.grffile == nullptr) {
646  e->grf_prop.grffile = file;
647  grfmsg(5, "Replaced engine at index %d for GRFID %x, type %d, index %d", e->index, BSWAP32(file->grfid), type, internal_id);
648  }
649 
650  /* Reserve the engine slot */
651  if (!static_access) {
652  EngineIDMapping *eid = _engine_mngr.data() + engine;
653  eid->grfid = scope_grfid; // Note: this is INVALID_GRFID if dynamic_engines is disabled, so no reservation
654  }
655 
656  return e;
657  }
658 
659  if (static_access) return nullptr;
660 
661  if (!Engine::CanAllocateItem()) {
662  grfmsg(0, "Can't allocate any more engines");
663  return nullptr;
664  }
665 
666  size_t engine_pool_size = Engine::GetPoolSize();
667 
668  /* ... it's not, so create a new one based off an existing engine */
669  Engine *e = new Engine(type, internal_id);
670  e->grf_prop.grffile = file;
671 
672  /* Reserve the engine slot */
673  assert(_engine_mngr.size() == e->index);
674  _engine_mngr.push_back({
675  scope_grfid, // Note: this is INVALID_GRFID if dynamic_engines is disabled, so no reservation
676  internal_id,
677  type,
678  std::min<uint8>(internal_id, _engine_counts[type]) // substitute_id == _engine_counts[subtype] means "no substitute"
679  });
680 
681  if (engine_pool_size != Engine::GetPoolSize()) {
682  /* Resize temporary engine data ... */
684 
685  /* and blank the new block. */
686  size_t len = (Engine::GetPoolSize() - engine_pool_size) * sizeof(*_gted);
687  memset(_gted + engine_pool_size, 0, len);
688  }
689  if (type == VEH_TRAIN) {
690  _gted[e->index].railtypelabel = GetRailTypeInfo(e->u.rail.railtype)->label;
691  }
692 
693  grfmsg(5, "Created new engine at index %d for GRFID %x, type %d, index %d", e->index, BSWAP32(file->grfid), type, internal_id);
694 
695  return e;
696 }
697 
708 EngineID GetNewEngineID(const GRFFile *file, VehicleType type, uint16 internal_id)
709 {
710  uint32 scope_grfid = INVALID_GRFID; // If not using dynamic_engines, all newgrfs share their ID range
712  scope_grfid = file->grfid;
713  uint32 override = _grf_id_overrides[file->grfid];
714  if (override != 0) scope_grfid = override;
715  }
716 
717  return _engine_mngr.GetID(type, internal_id, scope_grfid);
718 }
719 
724 static void MapSpriteMappingRecolour(PalSpriteID *grf_sprite)
725 {
726  if (HasBit(grf_sprite->pal, 14)) {
727  ClrBit(grf_sprite->pal, 14);
728  SetBit(grf_sprite->sprite, SPRITE_MODIFIER_OPAQUE);
729  }
730 
731  if (HasBit(grf_sprite->sprite, 14)) {
732  ClrBit(grf_sprite->sprite, 14);
734  }
735 
736  if (HasBit(grf_sprite->sprite, 15)) {
737  ClrBit(grf_sprite->sprite, 15);
738  SetBit(grf_sprite->sprite, PALETTE_MODIFIER_COLOUR);
739  }
740 }
741 
755 static TileLayoutFlags ReadSpriteLayoutSprite(ByteReader *buf, bool read_flags, bool invert_action1_flag, bool use_cur_spritesets, int feature, PalSpriteID *grf_sprite, uint16 *max_sprite_offset = nullptr, uint16 *max_palette_offset = nullptr)
756 {
757  grf_sprite->sprite = buf->ReadWord();
758  grf_sprite->pal = buf->ReadWord();
759  TileLayoutFlags flags = read_flags ? (TileLayoutFlags)buf->ReadWord() : TLF_NOTHING;
760 
761  MapSpriteMappingRecolour(grf_sprite);
762 
763  bool custom_sprite = HasBit(grf_sprite->pal, 15) != invert_action1_flag;
764  ClrBit(grf_sprite->pal, 15);
765  if (custom_sprite) {
766  /* Use sprite from Action 1 */
767  uint index = GB(grf_sprite->sprite, 0, 14);
768  if (use_cur_spritesets && (!_cur.IsValidSpriteSet(feature, index) || _cur.GetNumEnts(feature, index) == 0)) {
769  grfmsg(1, "ReadSpriteLayoutSprite: Spritelayout uses undefined custom spriteset %d", index);
770  grf_sprite->sprite = SPR_IMG_QUERY;
771  grf_sprite->pal = PAL_NONE;
772  } else {
773  SpriteID sprite = use_cur_spritesets ? _cur.GetSprite(feature, index) : index;
774  if (max_sprite_offset != nullptr) *max_sprite_offset = use_cur_spritesets ? _cur.GetNumEnts(feature, index) : UINT16_MAX;
775  SB(grf_sprite->sprite, 0, SPRITE_WIDTH, sprite);
777  }
778  } else if ((flags & TLF_SPRITE_VAR10) && !(flags & TLF_SPRITE_REG_FLAGS)) {
779  grfmsg(1, "ReadSpriteLayoutSprite: Spritelayout specifies var10 value for non-action-1 sprite");
780  DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
781  return flags;
782  }
783 
784  if (flags & TLF_CUSTOM_PALETTE) {
785  /* Use palette from Action 1 */
786  uint index = GB(grf_sprite->pal, 0, 14);
787  if (use_cur_spritesets && (!_cur.IsValidSpriteSet(feature, index) || _cur.GetNumEnts(feature, index) == 0)) {
788  grfmsg(1, "ReadSpriteLayoutSprite: Spritelayout uses undefined custom spriteset %d for 'palette'", index);
789  grf_sprite->pal = PAL_NONE;
790  } else {
791  SpriteID sprite = use_cur_spritesets ? _cur.GetSprite(feature, index) : index;
792  if (max_palette_offset != nullptr) *max_palette_offset = use_cur_spritesets ? _cur.GetNumEnts(feature, index) : UINT16_MAX;
793  SB(grf_sprite->pal, 0, SPRITE_WIDTH, sprite);
795  }
796  } else if ((flags & TLF_PALETTE_VAR10) && !(flags & TLF_PALETTE_REG_FLAGS)) {
797  grfmsg(1, "ReadSpriteLayoutRegisters: Spritelayout specifies var10 value for non-action-1 palette");
798  DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
799  return flags;
800  }
801 
802  return flags;
803 }
804 
813 static void ReadSpriteLayoutRegisters(ByteReader *buf, TileLayoutFlags flags, bool is_parent, NewGRFSpriteLayout *dts, uint index)
814 {
815  if (!(flags & TLF_DRAWING_FLAGS)) return;
816 
817  if (dts->registers == nullptr) dts->AllocateRegisters();
818  TileLayoutRegisters &regs = const_cast<TileLayoutRegisters&>(dts->registers[index]);
819  regs.flags = flags & TLF_DRAWING_FLAGS;
820 
821  if (flags & TLF_DODRAW) regs.dodraw = buf->ReadByte();
822  if (flags & TLF_SPRITE) regs.sprite = buf->ReadByte();
823  if (flags & TLF_PALETTE) regs.palette = buf->ReadByte();
824 
825  if (is_parent) {
826  if (flags & TLF_BB_XY_OFFSET) {
827  regs.delta.parent[0] = buf->ReadByte();
828  regs.delta.parent[1] = buf->ReadByte();
829  }
830  if (flags & TLF_BB_Z_OFFSET) regs.delta.parent[2] = buf->ReadByte();
831  } else {
832  if (flags & TLF_CHILD_X_OFFSET) regs.delta.child[0] = buf->ReadByte();
833  if (flags & TLF_CHILD_Y_OFFSET) regs.delta.child[1] = buf->ReadByte();
834  }
835 
836  if (flags & TLF_SPRITE_VAR10) {
837  regs.sprite_var10 = buf->ReadByte();
838  if (regs.sprite_var10 > TLR_MAX_VAR10) {
839  grfmsg(1, "ReadSpriteLayoutRegisters: Spritelayout specifies var10 (%d) exceeding the maximal allowed value %d", regs.sprite_var10, TLR_MAX_VAR10);
840  DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
841  return;
842  }
843  }
844 
845  if (flags & TLF_PALETTE_VAR10) {
846  regs.palette_var10 = buf->ReadByte();
847  if (regs.palette_var10 > TLR_MAX_VAR10) {
848  grfmsg(1, "ReadSpriteLayoutRegisters: Spritelayout specifies var10 (%d) exceeding the maximal allowed value %d", regs.palette_var10, TLR_MAX_VAR10);
849  DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
850  return;
851  }
852  }
853 }
854 
866 static bool ReadSpriteLayout(ByteReader *buf, uint num_building_sprites, bool use_cur_spritesets, byte feature, bool allow_var10, bool no_z_position, NewGRFSpriteLayout *dts)
867 {
868  bool has_flags = HasBit(num_building_sprites, 6);
869  ClrBit(num_building_sprites, 6);
870  TileLayoutFlags valid_flags = TLF_KNOWN_FLAGS;
871  if (!allow_var10) valid_flags &= ~TLF_VAR10_FLAGS;
872  dts->Allocate(num_building_sprites); // allocate before reading groundsprite flags
873 
874  uint16 *max_sprite_offset = AllocaM(uint16, num_building_sprites + 1);
875  uint16 *max_palette_offset = AllocaM(uint16, num_building_sprites + 1);
876  MemSetT(max_sprite_offset, 0, num_building_sprites + 1);
877  MemSetT(max_palette_offset, 0, num_building_sprites + 1);
878 
879  /* Groundsprite */
880  TileLayoutFlags flags = ReadSpriteLayoutSprite(buf, has_flags, false, use_cur_spritesets, feature, &dts->ground, max_sprite_offset, max_palette_offset);
881  if (_cur.skip_sprites < 0) return true;
882 
883  if (flags & ~(valid_flags & ~TLF_NON_GROUND_FLAGS)) {
884  grfmsg(1, "ReadSpriteLayout: Spritelayout uses invalid flag 0x%x for ground sprite", flags & ~(valid_flags & ~TLF_NON_GROUND_FLAGS));
885  DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
886  return true;
887  }
888 
889  ReadSpriteLayoutRegisters(buf, flags, false, dts, 0);
890  if (_cur.skip_sprites < 0) return true;
891 
892  for (uint i = 0; i < num_building_sprites; i++) {
893  DrawTileSeqStruct *seq = const_cast<DrawTileSeqStruct*>(&dts->seq[i]);
894 
895  flags = ReadSpriteLayoutSprite(buf, has_flags, false, use_cur_spritesets, feature, &seq->image, max_sprite_offset + i + 1, max_palette_offset + i + 1);
896  if (_cur.skip_sprites < 0) return true;
897 
898  if (flags & ~valid_flags) {
899  grfmsg(1, "ReadSpriteLayout: Spritelayout uses unknown flag 0x%x", flags & ~valid_flags);
900  DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
901  return true;
902  }
903 
904  seq->delta_x = buf->ReadByte();
905  seq->delta_y = buf->ReadByte();
906 
907  if (!no_z_position) seq->delta_z = buf->ReadByte();
908 
909  if (seq->IsParentSprite()) {
910  seq->size_x = buf->ReadByte();
911  seq->size_y = buf->ReadByte();
912  seq->size_z = buf->ReadByte();
913  }
914 
915  ReadSpriteLayoutRegisters(buf, flags, seq->IsParentSprite(), dts, i + 1);
916  if (_cur.skip_sprites < 0) return true;
917  }
918 
919  /* Check if the number of sprites per spriteset is consistent */
920  bool is_consistent = true;
921  dts->consistent_max_offset = 0;
922  for (uint i = 0; i < num_building_sprites + 1; i++) {
923  if (max_sprite_offset[i] > 0) {
924  if (dts->consistent_max_offset == 0) {
925  dts->consistent_max_offset = max_sprite_offset[i];
926  } else if (dts->consistent_max_offset != max_sprite_offset[i]) {
927  is_consistent = false;
928  break;
929  }
930  }
931  if (max_palette_offset[i] > 0) {
932  if (dts->consistent_max_offset == 0) {
933  dts->consistent_max_offset = max_palette_offset[i];
934  } else if (dts->consistent_max_offset != max_palette_offset[i]) {
935  is_consistent = false;
936  break;
937  }
938  }
939  }
940 
941  /* When the Action1 sets are unknown, everything should be 0 (no spriteset usage) or UINT16_MAX (some spriteset usage) */
942  assert(use_cur_spritesets || (is_consistent && (dts->consistent_max_offset == 0 || dts->consistent_max_offset == UINT16_MAX)));
943 
944  if (!is_consistent || dts->registers != nullptr) {
945  dts->consistent_max_offset = 0;
946  if (dts->registers == nullptr) dts->AllocateRegisters();
947 
948  for (uint i = 0; i < num_building_sprites + 1; i++) {
949  TileLayoutRegisters &regs = const_cast<TileLayoutRegisters&>(dts->registers[i]);
950  regs.max_sprite_offset = max_sprite_offset[i];
951  regs.max_palette_offset = max_palette_offset[i];
952  }
953  }
954 
955  return false;
956 }
957 
961 static CargoTypes TranslateRefitMask(uint32 refit_mask)
962 {
963  CargoTypes result = 0;
964  for (uint8 bit : SetBitIterator(refit_mask)) {
965  CargoID cargo = GetCargoTranslation(bit, _cur.grffile, true);
966  if (cargo != CT_INVALID) SetBit(result, cargo);
967  }
968  return result;
969 }
970 
978 static void ConvertTTDBasePrice(uint32 base_pointer, const char *error_location, Price *index)
979 {
980  /* Special value for 'none' */
981  if (base_pointer == 0) {
982  *index = INVALID_PRICE;
983  return;
984  }
985 
986  static const uint32 start = 0x4B34;
987  static const uint32 size = 6;
988 
989  if (base_pointer < start || (base_pointer - start) % size != 0 || (base_pointer - start) / size >= PR_END) {
990  grfmsg(1, "%s: Unsupported running cost base 0x%04X, ignoring", error_location, base_pointer);
991  return;
992  }
993 
994  *index = (Price)((base_pointer - start) / size);
995 }
996 
1004 };
1005 
1006 typedef ChangeInfoResult (*VCI_Handler)(uint engine, int numinfo, int prop, ByteReader *buf);
1007 
1016 {
1017  switch (prop) {
1018  case 0x00: // Introduction date
1019  ei->base_intro = buf->ReadWord() + DAYS_TILL_ORIGINAL_BASE_YEAR;
1020  break;
1021 
1022  case 0x02: // Decay speed
1023  ei->decay_speed = buf->ReadByte();
1024  break;
1025 
1026  case 0x03: // Vehicle life
1027  ei->lifelength = buf->ReadByte();
1028  break;
1029 
1030  case 0x04: // Model life
1031  ei->base_life = buf->ReadByte();
1032  break;
1033 
1034  case 0x06: // Climates available
1035  ei->climates = buf->ReadByte();
1036  break;
1037 
1038  case PROP_VEHICLE_LOAD_AMOUNT: // 0x07 Loading speed
1039  /* Amount of cargo loaded during a vehicle's "loading tick" */
1040  ei->load_amount = buf->ReadByte();
1041  break;
1042 
1043  default:
1044  return CIR_UNKNOWN;
1045  }
1046 
1047  return CIR_SUCCESS;
1048 }
1049 
1058 static ChangeInfoResult RailVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader *buf)
1059 {
1061 
1062  for (int i = 0; i < numinfo; i++) {
1063  Engine *e = GetNewEngine(_cur.grffile, VEH_TRAIN, engine + i);
1064  if (e == nullptr) return CIR_INVALID_ID; // No engine could be allocated, so neither can any next vehicles
1065 
1066  EngineInfo *ei = &e->info;
1067  RailVehicleInfo *rvi = &e->u.rail;
1068 
1069  switch (prop) {
1070  case 0x05: { // Track type
1071  uint8 tracktype = buf->ReadByte();
1072 
1073  if (tracktype < _cur.grffile->railtype_list.size()) {
1074  _gted[e->index].railtypelabel = _cur.grffile->railtype_list[tracktype];
1075  break;
1076  }
1077 
1078  switch (tracktype) {
1079  case 0: _gted[e->index].railtypelabel = rvi->engclass >= 2 ? RAILTYPE_ELECTRIC_LABEL : RAILTYPE_RAIL_LABEL; break;
1080  case 1: _gted[e->index].railtypelabel = RAILTYPE_MONO_LABEL; break;
1081  case 2: _gted[e->index].railtypelabel = RAILTYPE_MAGLEV_LABEL; break;
1082  default:
1083  grfmsg(1, "RailVehicleChangeInfo: Invalid track type %d specified, ignoring", tracktype);
1084  break;
1085  }
1086  break;
1087  }
1088 
1089  case 0x08: // AI passenger service
1090  /* Tells the AI that this engine is designed for
1091  * passenger services and shouldn't be used for freight. */
1092  rvi->ai_passenger_only = buf->ReadByte();
1093  break;
1094 
1095  case PROP_TRAIN_SPEED: { // 0x09 Speed (1 unit is 1 km-ish/h)
1096  uint16 speed = buf->ReadWord();
1097  if (speed == 0xFFFF) speed = 0;
1098 
1099  rvi->max_speed = speed;
1100  break;
1101  }
1102 
1103  case PROP_TRAIN_POWER: // 0x0B Power
1104  rvi->power = buf->ReadWord();
1105 
1106  /* Set engine / wagon state based on power */
1107  if (rvi->power != 0) {
1108  if (rvi->railveh_type == RAILVEH_WAGON) {
1109  rvi->railveh_type = RAILVEH_SINGLEHEAD;
1110  }
1111  } else {
1112  rvi->railveh_type = RAILVEH_WAGON;
1113  }
1114  break;
1115 
1116  case PROP_TRAIN_RUNNING_COST_FACTOR: // 0x0D Running cost factor
1117  rvi->running_cost = buf->ReadByte();
1118  break;
1119 
1120  case 0x0E: // Running cost base
1121  ConvertTTDBasePrice(buf->ReadDWord(), "RailVehicleChangeInfo", &rvi->running_cost_class);
1122  break;
1123 
1124  case 0x12: { // Sprite ID
1125  uint8 spriteid = buf->ReadByte();
1126  uint8 orig_spriteid = spriteid;
1127 
1128  /* TTD sprite IDs point to a location in a 16bit array, but we use it
1129  * as an array index, so we need it to be half the original value. */
1130  if (spriteid < 0xFD) spriteid >>= 1;
1131 
1132  if (IsValidNewGRFImageIndex<VEH_TRAIN>(spriteid)) {
1133  rvi->image_index = spriteid;
1134  } else {
1135  grfmsg(1, "RailVehicleChangeInfo: Invalid Sprite %d specified, ignoring", orig_spriteid);
1136  rvi->image_index = 0;
1137  }
1138  break;
1139  }
1140 
1141  case 0x13: { // Dual-headed
1142  uint8 dual = buf->ReadByte();
1143 
1144  if (dual != 0) {
1145  rvi->railveh_type = RAILVEH_MULTIHEAD;
1146  } else {
1147  rvi->railveh_type = rvi->power == 0 ?
1149  }
1150  break;
1151  }
1152 
1153  case PROP_TRAIN_CARGO_CAPACITY: // 0x14 Cargo capacity
1154  rvi->capacity = buf->ReadByte();
1155  break;
1156 
1157  case 0x15: { // Cargo type
1158  _gted[e->index].defaultcargo_grf = _cur.grffile;
1159  uint8 ctype = buf->ReadByte();
1160 
1161  if (ctype == 0xFF) {
1162  /* 0xFF is specified as 'use first refittable' */
1163  ei->cargo_type = CT_INVALID;
1164  } else if (_cur.grffile->grf_version >= 8) {
1165  /* Use translated cargo. Might result in CT_INVALID (first refittable), if cargo is not defined. */
1166  ei->cargo_type = GetCargoTranslation(ctype, _cur.grffile);
1167  } else if (ctype < NUM_CARGO) {
1168  /* Use untranslated cargo. */
1169  ei->cargo_type = ctype;
1170  } else {
1171  ei->cargo_type = CT_INVALID;
1172  grfmsg(2, "RailVehicleChangeInfo: Invalid cargo type %d, using first refittable", ctype);
1173  }
1174  break;
1175  }
1176 
1177  case PROP_TRAIN_WEIGHT: // 0x16 Weight
1178  SB(rvi->weight, 0, 8, buf->ReadByte());
1179  break;
1180 
1181  case PROP_TRAIN_COST_FACTOR: // 0x17 Cost factor
1182  rvi->cost_factor = buf->ReadByte();
1183  break;
1184 
1185  case 0x18: // AI rank
1186  grfmsg(2, "RailVehicleChangeInfo: Property 0x18 'AI rank' not used by NoAI, ignored.");
1187  buf->ReadByte();
1188  break;
1189 
1190  case 0x19: { // Engine traction type
1191  /* What do the individual numbers mean?
1192  * 0x00 .. 0x07: Steam
1193  * 0x08 .. 0x27: Diesel
1194  * 0x28 .. 0x31: Electric
1195  * 0x32 .. 0x37: Monorail
1196  * 0x38 .. 0x41: Maglev
1197  */
1198  uint8 traction = buf->ReadByte();
1199  EngineClass engclass;
1200 
1201  if (traction <= 0x07) {
1202  engclass = EC_STEAM;
1203  } else if (traction <= 0x27) {
1204  engclass = EC_DIESEL;
1205  } else if (traction <= 0x31) {
1206  engclass = EC_ELECTRIC;
1207  } else if (traction <= 0x37) {
1208  engclass = EC_MONORAIL;
1209  } else if (traction <= 0x41) {
1210  engclass = EC_MAGLEV;
1211  } else {
1212  break;
1213  }
1214 
1215  if (_cur.grffile->railtype_list.size() == 0) {
1216  /* Use traction type to select between normal and electrified
1217  * rail only when no translation list is in place. */
1218  if (_gted[e->index].railtypelabel == RAILTYPE_RAIL_LABEL && engclass >= EC_ELECTRIC) _gted[e->index].railtypelabel = RAILTYPE_ELECTRIC_LABEL;
1219  if (_gted[e->index].railtypelabel == RAILTYPE_ELECTRIC_LABEL && engclass < EC_ELECTRIC) _gted[e->index].railtypelabel = RAILTYPE_RAIL_LABEL;
1220  }
1221 
1222  rvi->engclass = engclass;
1223  break;
1224  }
1225 
1226  case 0x1A: // Alter purchase list sort order
1227  AlterVehicleListOrder(e->index, buf->ReadExtendedByte());
1228  break;
1229 
1230  case 0x1B: // Powered wagons power bonus
1231  rvi->pow_wag_power = buf->ReadWord();
1232  break;
1233 
1234  case 0x1C: // Refit cost
1235  ei->refit_cost = buf->ReadByte();
1236  break;
1237 
1238  case 0x1D: { // Refit cargo
1239  uint32 mask = buf->ReadDWord();
1240  _gted[e->index].UpdateRefittability(mask != 0);
1241  ei->refit_mask = TranslateRefitMask(mask);
1242  _gted[e->index].defaultcargo_grf = _cur.grffile;
1243  break;
1244  }
1245 
1246  case 0x1E: // Callback
1247  ei->callback_mask = buf->ReadByte();
1248  break;
1249 
1250  case PROP_TRAIN_TRACTIVE_EFFORT: // 0x1F Tractive effort coefficient
1251  rvi->tractive_effort = buf->ReadByte();
1252  break;
1253 
1254  case 0x20: // Air drag
1255  rvi->air_drag = buf->ReadByte();
1256  break;
1257 
1258  case PROP_TRAIN_SHORTEN_FACTOR: // 0x21 Shorter vehicle
1259  rvi->shorten_factor = buf->ReadByte();
1260  break;
1261 
1262  case 0x22: // Visual effect
1263  rvi->visual_effect = buf->ReadByte();
1264  /* Avoid accidentally setting visual_effect to the default value
1265  * Since bit 6 (disable effects) is set anyways, we can safely erase some bits. */
1266  if (rvi->visual_effect == VE_DEFAULT) {
1267  assert(HasBit(rvi->visual_effect, VE_DISABLE_EFFECT));
1269  }
1270  break;
1271 
1272  case 0x23: // Powered wagons weight bonus
1273  rvi->pow_wag_weight = buf->ReadByte();
1274  break;
1275 
1276  case 0x24: { // High byte of vehicle weight
1277  byte weight = buf->ReadByte();
1278 
1279  if (weight > 4) {
1280  grfmsg(2, "RailVehicleChangeInfo: Nonsensical weight of %d tons, ignoring", weight << 8);
1281  } else {
1282  SB(rvi->weight, 8, 8, weight);
1283  }
1284  break;
1285  }
1286 
1287  case PROP_TRAIN_USER_DATA: // 0x25 User-defined bit mask to set when checking veh. var. 42
1288  rvi->user_def_data = buf->ReadByte();
1289  break;
1290 
1291  case 0x26: // Retire vehicle early
1292  ei->retire_early = buf->ReadByte();
1293  break;
1294 
1295  case 0x27: // Miscellaneous flags
1296  ei->misc_flags = buf->ReadByte();
1298  _gted[e->index].prop27_set = true;
1299  break;
1300 
1301  case 0x28: // Cargo classes allowed
1302  _gted[e->index].cargo_allowed = buf->ReadWord();
1303  _gted[e->index].UpdateRefittability(_gted[e->index].cargo_allowed != 0);
1304  _gted[e->index].defaultcargo_grf = _cur.grffile;
1305  break;
1306 
1307  case 0x29: // Cargo classes disallowed
1308  _gted[e->index].cargo_disallowed = buf->ReadWord();
1309  _gted[e->index].UpdateRefittability(false);
1310  break;
1311 
1312  case 0x2A: // Long format introduction date (days since year 0)
1313  ei->base_intro = buf->ReadDWord();
1314  break;
1315 
1316  case PROP_TRAIN_CARGO_AGE_PERIOD: // 0x2B Cargo aging period
1317  ei->cargo_age_period = buf->ReadWord();
1318  break;
1319 
1320  case 0x2C: // CTT refit include list
1321  case 0x2D: { // CTT refit exclude list
1322  uint8 count = buf->ReadByte();
1323  _gted[e->index].UpdateRefittability(prop == 0x2C && count != 0);
1324  if (prop == 0x2C) _gted[e->index].defaultcargo_grf = _cur.grffile;
1325  CargoTypes &ctt = prop == 0x2C ? _gted[e->index].ctt_include_mask : _gted[e->index].ctt_exclude_mask;
1326  ctt = 0;
1327  while (count--) {
1328  CargoID ctype = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
1329  if (ctype == CT_INVALID) continue;
1330  SetBit(ctt, ctype);
1331  }
1332  break;
1333  }
1334 
1335  case PROP_TRAIN_CURVE_SPEED_MOD: // 0x2E Curve speed modifier
1336  rvi->curve_speed_mod = buf->ReadWord();
1337  break;
1338 
1339  default:
1340  ret = CommonVehicleChangeInfo(ei, prop, buf);
1341  break;
1342  }
1343  }
1344 
1345  return ret;
1346 }
1347 
1356 static ChangeInfoResult RoadVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader *buf)
1357 {
1359 
1360  for (int i = 0; i < numinfo; i++) {
1361  Engine *e = GetNewEngine(_cur.grffile, VEH_ROAD, engine + i);
1362  if (e == nullptr) return CIR_INVALID_ID; // No engine could be allocated, so neither can any next vehicles
1363 
1364  EngineInfo *ei = &e->info;
1365  RoadVehicleInfo *rvi = &e->u.road;
1366 
1367  switch (prop) {
1368  case 0x05: // Road/tram type
1369  /* RoadTypeLabel is looked up later after the engine's road/tram
1370  * flag is set, however 0 means the value has not been set. */
1371  _gted[e->index].roadtramtype = buf->ReadByte() + 1;
1372  break;
1373 
1374  case 0x08: // Speed (1 unit is 0.5 kmh)
1375  rvi->max_speed = buf->ReadByte();
1376  break;
1377 
1378  case PROP_ROADVEH_RUNNING_COST_FACTOR: // 0x09 Running cost factor
1379  rvi->running_cost = buf->ReadByte();
1380  break;
1381 
1382  case 0x0A: // Running cost base
1383  ConvertTTDBasePrice(buf->ReadDWord(), "RoadVehicleChangeInfo", &rvi->running_cost_class);
1384  break;
1385 
1386  case 0x0E: { // Sprite ID
1387  uint8 spriteid = buf->ReadByte();
1388  uint8 orig_spriteid = spriteid;
1389 
1390  /* cars have different custom id in the GRF file */
1391  if (spriteid == 0xFF) spriteid = 0xFD;
1392 
1393  if (spriteid < 0xFD) spriteid >>= 1;
1394 
1395  if (IsValidNewGRFImageIndex<VEH_ROAD>(spriteid)) {
1396  rvi->image_index = spriteid;
1397  } else {
1398  grfmsg(1, "RoadVehicleChangeInfo: Invalid Sprite %d specified, ignoring", orig_spriteid);
1399  rvi->image_index = 0;
1400  }
1401  break;
1402  }
1403 
1404  case PROP_ROADVEH_CARGO_CAPACITY: // 0x0F Cargo capacity
1405  rvi->capacity = buf->ReadByte();
1406  break;
1407 
1408  case 0x10: { // Cargo type
1409  _gted[e->index].defaultcargo_grf = _cur.grffile;
1410  uint8 ctype = buf->ReadByte();
1411 
1412  if (ctype == 0xFF) {
1413  /* 0xFF is specified as 'use first refittable' */
1414  ei->cargo_type = CT_INVALID;
1415  } else if (_cur.grffile->grf_version >= 8) {
1416  /* Use translated cargo. Might result in CT_INVALID (first refittable), if cargo is not defined. */
1417  ei->cargo_type = GetCargoTranslation(ctype, _cur.grffile);
1418  } else if (ctype < NUM_CARGO) {
1419  /* Use untranslated cargo. */
1420  ei->cargo_type = ctype;
1421  } else {
1422  ei->cargo_type = CT_INVALID;
1423  grfmsg(2, "RailVehicleChangeInfo: Invalid cargo type %d, using first refittable", ctype);
1424  }
1425  break;
1426  }
1427 
1428  case PROP_ROADVEH_COST_FACTOR: // 0x11 Cost factor
1429  rvi->cost_factor = buf->ReadByte();
1430  break;
1431 
1432  case 0x12: // SFX
1433  rvi->sfx = GetNewGRFSoundID(_cur.grffile, buf->ReadByte());
1434  break;
1435 
1436  case PROP_ROADVEH_POWER: // Power in units of 10 HP.
1437  rvi->power = buf->ReadByte();
1438  break;
1439 
1440  case PROP_ROADVEH_WEIGHT: // Weight in units of 1/4 tons.
1441  rvi->weight = buf->ReadByte();
1442  break;
1443 
1444  case PROP_ROADVEH_SPEED: // Speed in mph/0.8
1445  _gted[e->index].rv_max_speed = buf->ReadByte();
1446  break;
1447 
1448  case 0x16: { // Cargoes available for refitting
1449  uint32 mask = buf->ReadDWord();
1450  _gted[e->index].UpdateRefittability(mask != 0);
1451  ei->refit_mask = TranslateRefitMask(mask);
1452  _gted[e->index].defaultcargo_grf = _cur.grffile;
1453  break;
1454  }
1455 
1456  case 0x17: // Callback mask
1457  ei->callback_mask = buf->ReadByte();
1458  break;
1459 
1460  case PROP_ROADVEH_TRACTIVE_EFFORT: // Tractive effort coefficient in 1/256.
1461  rvi->tractive_effort = buf->ReadByte();
1462  break;
1463 
1464  case 0x19: // Air drag
1465  rvi->air_drag = buf->ReadByte();
1466  break;
1467 
1468  case 0x1A: // Refit cost
1469  ei->refit_cost = buf->ReadByte();
1470  break;
1471 
1472  case 0x1B: // Retire vehicle early
1473  ei->retire_early = buf->ReadByte();
1474  break;
1475 
1476  case 0x1C: // Miscellaneous flags
1477  ei->misc_flags = buf->ReadByte();
1479  break;
1480 
1481  case 0x1D: // Cargo classes allowed
1482  _gted[e->index].cargo_allowed = buf->ReadWord();
1483  _gted[e->index].UpdateRefittability(_gted[e->index].cargo_allowed != 0);
1484  _gted[e->index].defaultcargo_grf = _cur.grffile;
1485  break;
1486 
1487  case 0x1E: // Cargo classes disallowed
1488  _gted[e->index].cargo_disallowed = buf->ReadWord();
1489  _gted[e->index].UpdateRefittability(false);
1490  break;
1491 
1492  case 0x1F: // Long format introduction date (days since year 0)
1493  ei->base_intro = buf->ReadDWord();
1494  break;
1495 
1496  case 0x20: // Alter purchase list sort order
1497  AlterVehicleListOrder(e->index, buf->ReadExtendedByte());
1498  break;
1499 
1500  case 0x21: // Visual effect
1501  rvi->visual_effect = buf->ReadByte();
1502  /* Avoid accidentally setting visual_effect to the default value
1503  * Since bit 6 (disable effects) is set anyways, we can safely erase some bits. */
1504  if (rvi->visual_effect == VE_DEFAULT) {
1505  assert(HasBit(rvi->visual_effect, VE_DISABLE_EFFECT));
1507  }
1508  break;
1509 
1510  case PROP_ROADVEH_CARGO_AGE_PERIOD: // 0x22 Cargo aging period
1511  ei->cargo_age_period = buf->ReadWord();
1512  break;
1513 
1514  case PROP_ROADVEH_SHORTEN_FACTOR: // 0x23 Shorter vehicle
1515  rvi->shorten_factor = buf->ReadByte();
1516  break;
1517 
1518  case 0x24: // CTT refit include list
1519  case 0x25: { // CTT refit exclude list
1520  uint8 count = buf->ReadByte();
1521  _gted[e->index].UpdateRefittability(prop == 0x24 && count != 0);
1522  if (prop == 0x24) _gted[e->index].defaultcargo_grf = _cur.grffile;
1523  CargoTypes &ctt = prop == 0x24 ? _gted[e->index].ctt_include_mask : _gted[e->index].ctt_exclude_mask;
1524  ctt = 0;
1525  while (count--) {
1526  CargoID ctype = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
1527  if (ctype == CT_INVALID) continue;
1528  SetBit(ctt, ctype);
1529  }
1530  break;
1531  }
1532 
1533  default:
1534  ret = CommonVehicleChangeInfo(ei, prop, buf);
1535  break;
1536  }
1537  }
1538 
1539  return ret;
1540 }
1541 
1550 static ChangeInfoResult ShipVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader *buf)
1551 {
1553 
1554  for (int i = 0; i < numinfo; i++) {
1555  Engine *e = GetNewEngine(_cur.grffile, VEH_SHIP, engine + i);
1556  if (e == nullptr) return CIR_INVALID_ID; // No engine could be allocated, so neither can any next vehicles
1557 
1558  EngineInfo *ei = &e->info;
1559  ShipVehicleInfo *svi = &e->u.ship;
1560 
1561  switch (prop) {
1562  case 0x08: { // Sprite ID
1563  uint8 spriteid = buf->ReadByte();
1564  uint8 orig_spriteid = spriteid;
1565 
1566  /* ships have different custom id in the GRF file */
1567  if (spriteid == 0xFF) spriteid = 0xFD;
1568 
1569  if (spriteid < 0xFD) spriteid >>= 1;
1570 
1571  if (IsValidNewGRFImageIndex<VEH_SHIP>(spriteid)) {
1572  svi->image_index = spriteid;
1573  } else {
1574  grfmsg(1, "ShipVehicleChangeInfo: Invalid Sprite %d specified, ignoring", orig_spriteid);
1575  svi->image_index = 0;
1576  }
1577  break;
1578  }
1579 
1580  case 0x09: // Refittable
1581  svi->old_refittable = (buf->ReadByte() != 0);
1582  break;
1583 
1584  case PROP_SHIP_COST_FACTOR: // 0x0A Cost factor
1585  svi->cost_factor = buf->ReadByte();
1586  break;
1587 
1588  case PROP_SHIP_SPEED: // 0x0B Speed (1 unit is 0.5 km-ish/h)
1589  svi->max_speed = buf->ReadByte();
1590  break;
1591 
1592  case 0x0C: { // Cargo type
1593  _gted[e->index].defaultcargo_grf = _cur.grffile;
1594  uint8 ctype = buf->ReadByte();
1595 
1596  if (ctype == 0xFF) {
1597  /* 0xFF is specified as 'use first refittable' */
1598  ei->cargo_type = CT_INVALID;
1599  } else if (_cur.grffile->grf_version >= 8) {
1600  /* Use translated cargo. Might result in CT_INVALID (first refittable), if cargo is not defined. */
1601  ei->cargo_type = GetCargoTranslation(ctype, _cur.grffile);
1602  } else if (ctype < NUM_CARGO) {
1603  /* Use untranslated cargo. */
1604  ei->cargo_type = ctype;
1605  } else {
1606  ei->cargo_type = CT_INVALID;
1607  grfmsg(2, "RailVehicleChangeInfo: Invalid cargo type %d, using first refittable", ctype);
1608  }
1609  break;
1610  }
1611 
1612  case PROP_SHIP_CARGO_CAPACITY: // 0x0D Cargo capacity
1613  svi->capacity = buf->ReadWord();
1614  break;
1615 
1616  case PROP_SHIP_RUNNING_COST_FACTOR: // 0x0F Running cost factor
1617  svi->running_cost = buf->ReadByte();
1618  break;
1619 
1620  case 0x10: // SFX
1621  svi->sfx = GetNewGRFSoundID(_cur.grffile, buf->ReadByte());
1622  break;
1623 
1624  case 0x11: { // Cargoes available for refitting
1625  uint32 mask = buf->ReadDWord();
1626  _gted[e->index].UpdateRefittability(mask != 0);
1627  ei->refit_mask = TranslateRefitMask(mask);
1628  _gted[e->index].defaultcargo_grf = _cur.grffile;
1629  break;
1630  }
1631 
1632  case 0x12: // Callback mask
1633  ei->callback_mask = buf->ReadByte();
1634  break;
1635 
1636  case 0x13: // Refit cost
1637  ei->refit_cost = buf->ReadByte();
1638  break;
1639 
1640  case 0x14: // Ocean speed fraction
1641  svi->ocean_speed_frac = buf->ReadByte();
1642  break;
1643 
1644  case 0x15: // Canal speed fraction
1645  svi->canal_speed_frac = buf->ReadByte();
1646  break;
1647 
1648  case 0x16: // Retire vehicle early
1649  ei->retire_early = buf->ReadByte();
1650  break;
1651 
1652  case 0x17: // Miscellaneous flags
1653  ei->misc_flags = buf->ReadByte();
1655  break;
1656 
1657  case 0x18: // Cargo classes allowed
1658  _gted[e->index].cargo_allowed = buf->ReadWord();
1659  _gted[e->index].UpdateRefittability(_gted[e->index].cargo_allowed != 0);
1660  _gted[e->index].defaultcargo_grf = _cur.grffile;
1661  break;
1662 
1663  case 0x19: // Cargo classes disallowed
1664  _gted[e->index].cargo_disallowed = buf->ReadWord();
1665  _gted[e->index].UpdateRefittability(false);
1666  break;
1667 
1668  case 0x1A: // Long format introduction date (days since year 0)
1669  ei->base_intro = buf->ReadDWord();
1670  break;
1671 
1672  case 0x1B: // Alter purchase list sort order
1673  AlterVehicleListOrder(e->index, buf->ReadExtendedByte());
1674  break;
1675 
1676  case 0x1C: // Visual effect
1677  svi->visual_effect = buf->ReadByte();
1678  /* Avoid accidentally setting visual_effect to the default value
1679  * Since bit 6 (disable effects) is set anyways, we can safely erase some bits. */
1680  if (svi->visual_effect == VE_DEFAULT) {
1681  assert(HasBit(svi->visual_effect, VE_DISABLE_EFFECT));
1683  }
1684  break;
1685 
1686  case PROP_SHIP_CARGO_AGE_PERIOD: // 0x1D Cargo aging period
1687  ei->cargo_age_period = buf->ReadWord();
1688  break;
1689 
1690  case 0x1E: // CTT refit include list
1691  case 0x1F: { // CTT refit exclude list
1692  uint8 count = buf->ReadByte();
1693  _gted[e->index].UpdateRefittability(prop == 0x1E && count != 0);
1694  if (prop == 0x1E) _gted[e->index].defaultcargo_grf = _cur.grffile;
1695  CargoTypes &ctt = prop == 0x1E ? _gted[e->index].ctt_include_mask : _gted[e->index].ctt_exclude_mask;
1696  ctt = 0;
1697  while (count--) {
1698  CargoID ctype = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
1699  if (ctype == CT_INVALID) continue;
1700  SetBit(ctt, ctype);
1701  }
1702  break;
1703  }
1704 
1705  default:
1706  ret = CommonVehicleChangeInfo(ei, prop, buf);
1707  break;
1708  }
1709  }
1710 
1711  return ret;
1712 }
1713 
1722 static ChangeInfoResult AircraftVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader *buf)
1723 {
1725 
1726  for (int i = 0; i < numinfo; i++) {
1727  Engine *e = GetNewEngine(_cur.grffile, VEH_AIRCRAFT, engine + i);
1728  if (e == nullptr) return CIR_INVALID_ID; // No engine could be allocated, so neither can any next vehicles
1729 
1730  EngineInfo *ei = &e->info;
1731  AircraftVehicleInfo *avi = &e->u.air;
1732 
1733  switch (prop) {
1734  case 0x08: { // Sprite ID
1735  uint8 spriteid = buf->ReadByte();
1736  uint8 orig_spriteid = spriteid;
1737 
1738  /* aircraft have different custom id in the GRF file */
1739  if (spriteid == 0xFF) spriteid = 0xFD;
1740 
1741  if (spriteid < 0xFD) spriteid >>= 1;
1742 
1743  if (IsValidNewGRFImageIndex<VEH_AIRCRAFT>(spriteid)) {
1744  avi->image_index = spriteid;
1745  } else {
1746  grfmsg(1, "AircraftVehicleChangeInfo: Invalid Sprite %d specified, ignoring", orig_spriteid);
1747  avi->image_index = 0;
1748  }
1749  break;
1750  }
1751 
1752  case 0x09: // Helicopter
1753  if (buf->ReadByte() == 0) {
1754  avi->subtype = AIR_HELI;
1755  } else {
1756  SB(avi->subtype, 0, 1, 1); // AIR_CTOL
1757  }
1758  break;
1759 
1760  case 0x0A: // Large
1761  SB(avi->subtype, 1, 1, (buf->ReadByte() != 0 ? 1 : 0)); // AIR_FAST
1762  break;
1763 
1764  case PROP_AIRCRAFT_COST_FACTOR: // 0x0B Cost factor
1765  avi->cost_factor = buf->ReadByte();
1766  break;
1767 
1768  case PROP_AIRCRAFT_SPEED: // 0x0C Speed (1 unit is 8 mph, we translate to 1 unit is 1 km-ish/h)
1769  avi->max_speed = (buf->ReadByte() * 128) / 10;
1770  break;
1771 
1772  case 0x0D: // Acceleration
1773  avi->acceleration = buf->ReadByte();
1774  break;
1775 
1776  case PROP_AIRCRAFT_RUNNING_COST_FACTOR: // 0x0E Running cost factor
1777  avi->running_cost = buf->ReadByte();
1778  break;
1779 
1780  case PROP_AIRCRAFT_PASSENGER_CAPACITY: // 0x0F Passenger capacity
1781  avi->passenger_capacity = buf->ReadWord();
1782  break;
1783 
1784  case PROP_AIRCRAFT_MAIL_CAPACITY: // 0x11 Mail capacity
1785  avi->mail_capacity = buf->ReadByte();
1786  break;
1787 
1788  case 0x12: // SFX
1789  avi->sfx = GetNewGRFSoundID(_cur.grffile, buf->ReadByte());
1790  break;
1791 
1792  case 0x13: { // Cargoes available for refitting
1793  uint32 mask = buf->ReadDWord();
1794  _gted[e->index].UpdateRefittability(mask != 0);
1795  ei->refit_mask = TranslateRefitMask(mask);
1796  _gted[e->index].defaultcargo_grf = _cur.grffile;
1797  break;
1798  }
1799 
1800  case 0x14: // Callback mask
1801  ei->callback_mask = buf->ReadByte();
1802  break;
1803 
1804  case 0x15: // Refit cost
1805  ei->refit_cost = buf->ReadByte();
1806  break;
1807 
1808  case 0x16: // Retire vehicle early
1809  ei->retire_early = buf->ReadByte();
1810  break;
1811 
1812  case 0x17: // Miscellaneous flags
1813  ei->misc_flags = buf->ReadByte();
1815  break;
1816 
1817  case 0x18: // Cargo classes allowed
1818  _gted[e->index].cargo_allowed = buf->ReadWord();
1819  _gted[e->index].UpdateRefittability(_gted[e->index].cargo_allowed != 0);
1820  _gted[e->index].defaultcargo_grf = _cur.grffile;
1821  break;
1822 
1823  case 0x19: // Cargo classes disallowed
1824  _gted[e->index].cargo_disallowed = buf->ReadWord();
1825  _gted[e->index].UpdateRefittability(false);
1826  break;
1827 
1828  case 0x1A: // Long format introduction date (days since year 0)
1829  ei->base_intro = buf->ReadDWord();
1830  break;
1831 
1832  case 0x1B: // Alter purchase list sort order
1833  AlterVehicleListOrder(e->index, buf->ReadExtendedByte());
1834  break;
1835 
1836  case PROP_AIRCRAFT_CARGO_AGE_PERIOD: // 0x1C Cargo aging period
1837  ei->cargo_age_period = buf->ReadWord();
1838  break;
1839 
1840  case 0x1D: // CTT refit include list
1841  case 0x1E: { // CTT refit exclude list
1842  uint8 count = buf->ReadByte();
1843  _gted[e->index].UpdateRefittability(prop == 0x1D && count != 0);
1844  if (prop == 0x1D) _gted[e->index].defaultcargo_grf = _cur.grffile;
1845  CargoTypes &ctt = prop == 0x1D ? _gted[e->index].ctt_include_mask : _gted[e->index].ctt_exclude_mask;
1846  ctt = 0;
1847  while (count--) {
1848  CargoID ctype = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
1849  if (ctype == CT_INVALID) continue;
1850  SetBit(ctt, ctype);
1851  }
1852  break;
1853  }
1854 
1855  case PROP_AIRCRAFT_RANGE: // 0x1F Max aircraft range
1856  avi->max_range = buf->ReadWord();
1857  break;
1858 
1859  default:
1860  ret = CommonVehicleChangeInfo(ei, prop, buf);
1861  break;
1862  }
1863  }
1864 
1865  return ret;
1866 }
1867 
1876 static ChangeInfoResult StationChangeInfo(uint stid, int numinfo, int prop, ByteReader *buf)
1877 {
1879 
1880  if (stid + numinfo > NUM_STATIONS_PER_GRF) {
1881  grfmsg(1, "StationChangeInfo: Station %u is invalid, max %u, ignoring", stid + numinfo, NUM_STATIONS_PER_GRF);
1882  return CIR_INVALID_ID;
1883  }
1884 
1885  /* Allocate station specs if necessary */
1886  if (_cur.grffile->stations == nullptr) _cur.grffile->stations = CallocT<StationSpec*>(NUM_STATIONS_PER_GRF);
1887 
1888  for (int i = 0; i < numinfo; i++) {
1889  StationSpec *statspec = _cur.grffile->stations[stid + i];
1890 
1891  /* Check that the station we are modifying is defined. */
1892  if (statspec == nullptr && prop != 0x08) {
1893  grfmsg(2, "StationChangeInfo: Attempt to modify undefined station %u, ignoring", stid + i);
1894  return CIR_INVALID_ID;
1895  }
1896 
1897  switch (prop) {
1898  case 0x08: { // Class ID
1899  StationSpec **spec = &_cur.grffile->stations[stid + i];
1900 
1901  /* Property 0x08 is special; it is where the station is allocated */
1902  if (*spec == nullptr) *spec = new StationSpec();
1903 
1904  /* Swap classid because we read it in BE meaning WAYP or DFLT */
1905  uint32 classid = buf->ReadDWord();
1906  (*spec)->cls_id = StationClass::Allocate(BSWAP32(classid));
1907  break;
1908  }
1909 
1910  case 0x09: { // Define sprite layout
1911  uint16 tiles = buf->ReadExtendedByte();
1912  statspec->renderdata.clear(); // delete earlier loaded stuff
1913  statspec->renderdata.reserve(tiles);
1914 
1915  for (uint t = 0; t < tiles; t++) {
1916  NewGRFSpriteLayout *dts = &statspec->renderdata.emplace_back();
1917  dts->consistent_max_offset = UINT16_MAX; // Spritesets are unknown, so no limit.
1918 
1919  if (buf->HasData(4) && *(uint32*)buf->Data() == 0) {
1920  buf->Skip(4);
1921  extern const DrawTileSprites _station_display_datas_rail[8];
1922  dts->Clone(&_station_display_datas_rail[t % 8]);
1923  continue;
1924  }
1925 
1926  ReadSpriteLayoutSprite(buf, false, false, false, GSF_STATIONS, &dts->ground);
1927  /* On error, bail out immediately. Temporary GRF data was already freed */
1928  if (_cur.skip_sprites < 0) return CIR_DISABLED;
1929 
1930  static std::vector<DrawTileSeqStruct> tmp_layout;
1931  tmp_layout.clear();
1932  for (;;) {
1933  /* no relative bounding box support */
1934  DrawTileSeqStruct &dtss = tmp_layout.emplace_back();
1935  MemSetT(&dtss, 0);
1936 
1937  dtss.delta_x = buf->ReadByte();
1938  if (dtss.IsTerminator()) break;
1939  dtss.delta_y = buf->ReadByte();
1940  dtss.delta_z = buf->ReadByte();
1941  dtss.size_x = buf->ReadByte();
1942  dtss.size_y = buf->ReadByte();
1943  dtss.size_z = buf->ReadByte();
1944 
1945  ReadSpriteLayoutSprite(buf, false, true, false, GSF_STATIONS, &dtss.image);
1946  /* On error, bail out immediately. Temporary GRF data was already freed */
1947  if (_cur.skip_sprites < 0) return CIR_DISABLED;
1948  }
1949  dts->Clone(tmp_layout.data());
1950  }
1951 
1952  /* Number of layouts must be even, alternating X and Y */
1953  if (statspec->renderdata.size() & 1) {
1954  grfmsg(1, "StationChangeInfo: Station %u defines an odd number of sprite layouts, dropping the last item", stid + i);
1955  statspec->renderdata.pop_back();
1956  }
1957  break;
1958  }
1959 
1960  case 0x0A: { // Copy sprite layout
1961  byte srcid = buf->ReadByte();
1962  const StationSpec *srcstatspec = _cur.grffile->stations[srcid];
1963 
1964  if (srcstatspec == nullptr) {
1965  grfmsg(1, "StationChangeInfo: Station %u is not defined, cannot copy sprite layout to %u.", srcid, stid + i);
1966  continue;
1967  }
1968 
1969  statspec->renderdata.clear(); // delete earlier loaded stuff
1970  statspec->renderdata.reserve(srcstatspec->renderdata.size());
1971 
1972  for (const auto &it : srcstatspec->renderdata) {
1973  NewGRFSpriteLayout *dts = &statspec->renderdata.emplace_back();
1974  dts->Clone(&it);
1975  }
1976  break;
1977  }
1978 
1979  case 0x0B: // Callback mask
1980  statspec->callback_mask = buf->ReadByte();
1981  break;
1982 
1983  case 0x0C: // Disallowed number of platforms
1984  statspec->disallowed_platforms = buf->ReadByte();
1985  break;
1986 
1987  case 0x0D: // Disallowed platform lengths
1988  statspec->disallowed_lengths = buf->ReadByte();
1989  break;
1990 
1991  case 0x0E: // Define custom layout
1992  while (buf->HasData()) {
1993  byte length = buf->ReadByte();
1994  byte number = buf->ReadByte();
1995 
1996  if (length == 0 || number == 0) break;
1997 
1998  if (statspec->layouts.size() < length) statspec->layouts.resize(length);
1999  if (statspec->layouts[length - 1].size() < number) statspec->layouts[length - 1].resize(number);
2000 
2001  const byte *layout = buf->ReadBytes(length * number);
2002  statspec->layouts[length - 1][number - 1].assign(layout, layout + length * number);
2003 
2004  /* Validate tile values are only the permitted 00, 02, 04 and 06. */
2005  for (auto &tile : statspec->layouts[length - 1][number - 1]) {
2006  if ((tile & 6) != tile) {
2007  grfmsg(1, "StationChangeInfo: Invalid tile %u in layout %ux%u", tile, length, number);
2008  tile &= 6;
2009  }
2010  }
2011  }
2012  break;
2013 
2014  case 0x0F: { // Copy custom layout
2015  byte srcid = buf->ReadByte();
2016  const StationSpec *srcstatspec = _cur.grffile->stations[srcid];
2017 
2018  if (srcstatspec == nullptr) {
2019  grfmsg(1, "StationChangeInfo: Station %u is not defined, cannot copy tile layout to %u.", srcid, stid + i);
2020  continue;
2021  }
2022 
2023  statspec->layouts = srcstatspec->layouts;
2024  break;
2025  }
2026 
2027  case 0x10: // Little/lots cargo threshold
2028  statspec->cargo_threshold = buf->ReadWord();
2029  break;
2030 
2031  case 0x11: // Pylon placement
2032  statspec->pylons = buf->ReadByte();
2033  break;
2034 
2035  case 0x12: // Cargo types for random triggers
2036  if (_cur.grffile->grf_version >= 7) {
2037  statspec->cargo_triggers = TranslateRefitMask(buf->ReadDWord());
2038  } else {
2039  statspec->cargo_triggers = (CargoTypes)buf->ReadDWord();
2040  }
2041  break;
2042 
2043  case 0x13: // General flags
2044  statspec->flags = buf->ReadByte();
2045  break;
2046 
2047  case 0x14: // Overhead wire placement
2048  statspec->wires = buf->ReadByte();
2049  break;
2050 
2051  case 0x15: // Blocked tiles
2052  statspec->blocked = buf->ReadByte();
2053  break;
2054 
2055  case 0x16: // Animation info
2056  statspec->animation.frames = buf->ReadByte();
2057  statspec->animation.status = buf->ReadByte();
2058  break;
2059 
2060  case 0x17: // Animation speed
2061  statspec->animation.speed = buf->ReadByte();
2062  break;
2063 
2064  case 0x18: // Animation triggers
2065  statspec->animation.triggers = buf->ReadWord();
2066  break;
2067 
2068  case 0x1A: { // Advanced sprite layout
2069  uint16 tiles = buf->ReadExtendedByte();
2070  statspec->renderdata.clear(); // delete earlier loaded stuff
2071  statspec->renderdata.reserve(tiles);
2072 
2073  for (uint t = 0; t < tiles; t++) {
2074  NewGRFSpriteLayout *dts = &statspec->renderdata.emplace_back();
2075  uint num_building_sprites = buf->ReadByte();
2076  /* On error, bail out immediately. Temporary GRF data was already freed */
2077  if (ReadSpriteLayout(buf, num_building_sprites, false, GSF_STATIONS, true, false, dts)) return CIR_DISABLED;
2078  }
2079 
2080  /* Number of layouts must be even, alternating X and Y */
2081  if (statspec->renderdata.size() & 1) {
2082  grfmsg(1, "StationChangeInfo: Station %u defines an odd number of sprite layouts, dropping the last item", stid + i);
2083  statspec->renderdata.pop_back();
2084  }
2085  break;
2086  }
2087 
2088  default:
2089  ret = CIR_UNKNOWN;
2090  break;
2091  }
2092  }
2093 
2094  return ret;
2095 }
2096 
2105 static ChangeInfoResult CanalChangeInfo(uint id, int numinfo, int prop, ByteReader *buf)
2106 {
2108 
2109  if (id + numinfo > CF_END) {
2110  grfmsg(1, "CanalChangeInfo: Canal feature 0x%02X is invalid, max %u, ignoring", id + numinfo, CF_END);
2111  return CIR_INVALID_ID;
2112  }
2113 
2114  for (int i = 0; i < numinfo; i++) {
2115  CanalProperties *cp = &_cur.grffile->canal_local_properties[id + i];
2116 
2117  switch (prop) {
2118  case 0x08:
2119  cp->callback_mask = buf->ReadByte();
2120  break;
2121 
2122  case 0x09:
2123  cp->flags = buf->ReadByte();
2124  break;
2125 
2126  default:
2127  ret = CIR_UNKNOWN;
2128  break;
2129  }
2130  }
2131 
2132  return ret;
2133 }
2134 
2143 static ChangeInfoResult BridgeChangeInfo(uint brid, int numinfo, int prop, ByteReader *buf)
2144 {
2146 
2147  if (brid + numinfo > MAX_BRIDGES) {
2148  grfmsg(1, "BridgeChangeInfo: Bridge %u is invalid, max %u, ignoring", brid + numinfo, MAX_BRIDGES);
2149  return CIR_INVALID_ID;
2150  }
2151 
2152  for (int i = 0; i < numinfo; i++) {
2153  BridgeSpec *bridge = &_bridge[brid + i];
2154 
2155  switch (prop) {
2156  case 0x08: { // Year of availability
2157  /* We treat '0' as always available */
2158  byte year = buf->ReadByte();
2159  bridge->avail_year = (year > 0 ? ORIGINAL_BASE_YEAR + year : 0);
2160  break;
2161  }
2162 
2163  case 0x09: // Minimum length
2164  bridge->min_length = buf->ReadByte();
2165  break;
2166 
2167  case 0x0A: // Maximum length
2168  bridge->max_length = buf->ReadByte();
2169  if (bridge->max_length > 16) bridge->max_length = 0xFFFF;
2170  break;
2171 
2172  case 0x0B: // Cost factor
2173  bridge->price = buf->ReadByte();
2174  break;
2175 
2176  case 0x0C: // Maximum speed
2177  bridge->speed = buf->ReadWord();
2178  break;
2179 
2180  case 0x0D: { // Bridge sprite tables
2181  byte tableid = buf->ReadByte();
2182  byte numtables = buf->ReadByte();
2183 
2184  if (bridge->sprite_table == nullptr) {
2185  /* Allocate memory for sprite table pointers and zero out */
2186  bridge->sprite_table = CallocT<PalSpriteID*>(7);
2187  }
2188 
2189  for (; numtables-- != 0; tableid++) {
2190  if (tableid >= 7) { // skip invalid data
2191  grfmsg(1, "BridgeChangeInfo: Table %d >= 7, skipping", tableid);
2192  for (byte sprite = 0; sprite < 32; sprite++) buf->ReadDWord();
2193  continue;
2194  }
2195 
2196  if (bridge->sprite_table[tableid] == nullptr) {
2197  bridge->sprite_table[tableid] = MallocT<PalSpriteID>(32);
2198  }
2199 
2200  for (byte sprite = 0; sprite < 32; sprite++) {
2201  SpriteID image = buf->ReadWord();
2202  PaletteID pal = buf->ReadWord();
2203 
2204  bridge->sprite_table[tableid][sprite].sprite = image;
2205  bridge->sprite_table[tableid][sprite].pal = pal;
2206 
2207  MapSpriteMappingRecolour(&bridge->sprite_table[tableid][sprite]);
2208  }
2209  }
2210  break;
2211  }
2212 
2213  case 0x0E: // Flags; bit 0 - disable far pillars
2214  bridge->flags = buf->ReadByte();
2215  break;
2216 
2217  case 0x0F: // Long format year of availability (year since year 0)
2218  bridge->avail_year = Clamp(buf->ReadDWord(), MIN_YEAR, MAX_YEAR);
2219  break;
2220 
2221  case 0x10: { // purchase string
2222  StringID newone = GetGRFStringID(_cur.grffile->grfid, buf->ReadWord());
2223  if (newone != STR_UNDEFINED) bridge->material = newone;
2224  break;
2225  }
2226 
2227  case 0x11: // description of bridge with rails or roads
2228  case 0x12: {
2229  StringID newone = GetGRFStringID(_cur.grffile->grfid, buf->ReadWord());
2230  if (newone != STR_UNDEFINED) bridge->transport_name[prop - 0x11] = newone;
2231  break;
2232  }
2233 
2234  case 0x13: // 16 bits cost multiplier
2235  bridge->price = buf->ReadWord();
2236  break;
2237 
2238  default:
2239  ret = CIR_UNKNOWN;
2240  break;
2241  }
2242  }
2243 
2244  return ret;
2245 }
2246 
2254 {
2256 
2257  switch (prop) {
2258  case 0x09:
2259  case 0x0B:
2260  case 0x0C:
2261  case 0x0D:
2262  case 0x0E:
2263  case 0x0F:
2264  case 0x11:
2265  case 0x14:
2266  case 0x15:
2267  case 0x16:
2268  case 0x18:
2269  case 0x19:
2270  case 0x1A:
2271  case 0x1B:
2272  case 0x1C:
2273  case 0x1D:
2274  case 0x1F:
2275  buf->ReadByte();
2276  break;
2277 
2278  case 0x0A:
2279  case 0x10:
2280  case 0x12:
2281  case 0x13:
2282  case 0x21:
2283  case 0x22:
2284  buf->ReadWord();
2285  break;
2286 
2287  case 0x1E:
2288  buf->ReadDWord();
2289  break;
2290 
2291  case 0x17:
2292  for (uint j = 0; j < 4; j++) buf->ReadByte();
2293  break;
2294 
2295  case 0x20: {
2296  byte count = buf->ReadByte();
2297  for (byte j = 0; j < count; j++) buf->ReadByte();
2298  break;
2299  }
2300 
2301  case 0x23:
2302  buf->Skip(buf->ReadByte() * 2);
2303  break;
2304 
2305  default:
2306  ret = CIR_UNKNOWN;
2307  break;
2308  }
2309  return ret;
2310 }
2311 
2320 static ChangeInfoResult TownHouseChangeInfo(uint hid, int numinfo, int prop, ByteReader *buf)
2321 {
2323 
2324  if (hid + numinfo > NUM_HOUSES_PER_GRF) {
2325  grfmsg(1, "TownHouseChangeInfo: Too many houses loaded (%u), max (%u). Ignoring.", hid + numinfo, NUM_HOUSES_PER_GRF);
2326  return CIR_INVALID_ID;
2327  }
2328 
2329  /* Allocate house specs if they haven't been allocated already. */
2330  if (_cur.grffile->housespec == nullptr) {
2331  _cur.grffile->housespec = CallocT<HouseSpec*>(NUM_HOUSES_PER_GRF);
2332  }
2333 
2334  for (int i = 0; i < numinfo; i++) {
2335  HouseSpec *housespec = _cur.grffile->housespec[hid + i];
2336 
2337  if (prop != 0x08 && housespec == nullptr) {
2338  /* If the house property 08 is not yet set, ignore this property */
2339  ChangeInfoResult cir = IgnoreTownHouseProperty(prop, buf);
2340  if (cir > ret) ret = cir;
2341  continue;
2342  }
2343 
2344  switch (prop) {
2345  case 0x08: { // Substitute building type, and definition of a new house
2346  HouseSpec **house = &_cur.grffile->housespec[hid + i];
2347  byte subs_id = buf->ReadByte();
2348 
2349  if (subs_id == 0xFF) {
2350  /* Instead of defining a new house, a substitute house id
2351  * of 0xFF disables the old house with the current id. */
2352  HouseSpec::Get(hid + i)->enabled = false;
2353  continue;
2354  } else if (subs_id >= NEW_HOUSE_OFFSET) {
2355  /* The substitute id must be one of the original houses. */
2356  grfmsg(2, "TownHouseChangeInfo: Attempt to use new house %u as substitute house for %u. Ignoring.", subs_id, hid + i);
2357  continue;
2358  }
2359 
2360  /* Allocate space for this house. */
2361  if (*house == nullptr) *house = CallocT<HouseSpec>(1);
2362 
2363  housespec = *house;
2364 
2365  MemCpyT(housespec, HouseSpec::Get(subs_id));
2366 
2367  housespec->enabled = true;
2368  housespec->grf_prop.local_id = hid + i;
2369  housespec->grf_prop.subst_id = subs_id;
2370  housespec->grf_prop.grffile = _cur.grffile;
2371  housespec->random_colour[0] = 0x04; // those 4 random colours are the base colour
2372  housespec->random_colour[1] = 0x08; // for all new houses
2373  housespec->random_colour[2] = 0x0C; // they stand for red, blue, orange and green
2374  housespec->random_colour[3] = 0x06;
2375 
2376  /* Make sure that the third cargo type is valid in this
2377  * climate. This can cause problems when copying the properties
2378  * of a house that accepts food, where the new house is valid
2379  * in the temperate climate. */
2380  if (!CargoSpec::Get(housespec->accepts_cargo[2])->IsValid()) {
2381  housespec->cargo_acceptance[2] = 0;
2382  }
2383  break;
2384  }
2385 
2386  case 0x09: // Building flags
2387  housespec->building_flags = (BuildingFlags)buf->ReadByte();
2388  break;
2389 
2390  case 0x0A: { // Availability years
2391  uint16 years = buf->ReadWord();
2392  housespec->min_year = GB(years, 0, 8) > 150 ? MAX_YEAR : ORIGINAL_BASE_YEAR + GB(years, 0, 8);
2393  housespec->max_year = GB(years, 8, 8) > 150 ? MAX_YEAR : ORIGINAL_BASE_YEAR + GB(years, 8, 8);
2394  break;
2395  }
2396 
2397  case 0x0B: // Population
2398  housespec->population = buf->ReadByte();
2399  break;
2400 
2401  case 0x0C: // Mail generation multiplier
2402  housespec->mail_generation = buf->ReadByte();
2403  break;
2404 
2405  case 0x0D: // Passenger acceptance
2406  case 0x0E: // Mail acceptance
2407  housespec->cargo_acceptance[prop - 0x0D] = buf->ReadByte();
2408  break;
2409 
2410  case 0x0F: { // Goods/candy, food/fizzy drinks acceptance
2411  int8 goods = buf->ReadByte();
2412 
2413  /* If value of goods is negative, it means in fact food or, if in toyland, fizzy_drink acceptance.
2414  * Else, we have "standard" 3rd cargo type, goods or candy, for toyland once more */
2415  CargoID cid = (goods >= 0) ? ((_settings_game.game_creation.landscape == LT_TOYLAND) ? CT_CANDY : CT_GOODS) :
2416  ((_settings_game.game_creation.landscape == LT_TOYLAND) ? CT_FIZZY_DRINKS : CT_FOOD);
2417 
2418  /* Make sure the cargo type is valid in this climate. */
2419  if (!CargoSpec::Get(cid)->IsValid()) goods = 0;
2420 
2421  housespec->accepts_cargo[2] = cid;
2422  housespec->cargo_acceptance[2] = abs(goods); // but we do need positive value here
2423  break;
2424  }
2425 
2426  case 0x10: // Local authority rating decrease on removal
2427  housespec->remove_rating_decrease = buf->ReadWord();
2428  break;
2429 
2430  case 0x11: // Removal cost multiplier
2431  housespec->removal_cost = buf->ReadByte();
2432  break;
2433 
2434  case 0x12: // Building name ID
2435  AddStringForMapping(buf->ReadWord(), &housespec->building_name);
2436  break;
2437 
2438  case 0x13: // Building availability mask
2439  housespec->building_availability = (HouseZones)buf->ReadWord();
2440  break;
2441 
2442  case 0x14: // House callback mask
2443  housespec->callback_mask |= buf->ReadByte();
2444  break;
2445 
2446  case 0x15: { // House override byte
2447  byte override = buf->ReadByte();
2448 
2449  /* The house being overridden must be an original house. */
2450  if (override >= NEW_HOUSE_OFFSET) {
2451  grfmsg(2, "TownHouseChangeInfo: Attempt to override new house %u with house id %u. Ignoring.", override, hid + i);
2452  continue;
2453  }
2454 
2455  _house_mngr.Add(hid + i, _cur.grffile->grfid, override);
2456  break;
2457  }
2458 
2459  case 0x16: // Periodic refresh multiplier
2460  housespec->processing_time = std::min<byte>(buf->ReadByte(), 63u);
2461  break;
2462 
2463  case 0x17: // Four random colours to use
2464  for (uint j = 0; j < 4; j++) housespec->random_colour[j] = buf->ReadByte();
2465  break;
2466 
2467  case 0x18: // Relative probability of appearing
2468  housespec->probability = buf->ReadByte();
2469  break;
2470 
2471  case 0x19: // Extra flags
2472  housespec->extra_flags = (HouseExtraFlags)buf->ReadByte();
2473  break;
2474 
2475  case 0x1A: // Animation frames
2476  housespec->animation.frames = buf->ReadByte();
2477  housespec->animation.status = GB(housespec->animation.frames, 7, 1);
2478  SB(housespec->animation.frames, 7, 1, 0);
2479  break;
2480 
2481  case 0x1B: // Animation speed
2482  housespec->animation.speed = Clamp(buf->ReadByte(), 2, 16);
2483  break;
2484 
2485  case 0x1C: // Class of the building type
2486  housespec->class_id = AllocateHouseClassID(buf->ReadByte(), _cur.grffile->grfid);
2487  break;
2488 
2489  case 0x1D: // Callback mask part 2
2490  housespec->callback_mask |= (buf->ReadByte() << 8);
2491  break;
2492 
2493  case 0x1E: { // Accepted cargo types
2494  uint32 cargotypes = buf->ReadDWord();
2495 
2496  /* Check if the cargo types should not be changed */
2497  if (cargotypes == 0xFFFFFFFF) break;
2498 
2499  for (uint j = 0; j < 3; j++) {
2500  /* Get the cargo number from the 'list' */
2501  uint8 cargo_part = GB(cargotypes, 8 * j, 8);
2502  CargoID cargo = GetCargoTranslation(cargo_part, _cur.grffile);
2503 
2504  if (cargo == CT_INVALID) {
2505  /* Disable acceptance of invalid cargo type */
2506  housespec->cargo_acceptance[j] = 0;
2507  } else {
2508  housespec->accepts_cargo[j] = cargo;
2509  }
2510  }
2511  break;
2512  }
2513 
2514  case 0x1F: // Minimum life span
2515  housespec->minimum_life = buf->ReadByte();
2516  break;
2517 
2518  case 0x20: { // Cargo acceptance watch list
2519  byte count = buf->ReadByte();
2520  for (byte j = 0; j < count; j++) {
2521  CargoID cargo = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
2522  if (cargo != CT_INVALID) SetBit(housespec->watched_cargoes, cargo);
2523  }
2524  break;
2525  }
2526 
2527  case 0x21: // long introduction year
2528  housespec->min_year = buf->ReadWord();
2529  break;
2530 
2531  case 0x22: // long maximum year
2532  housespec->max_year = buf->ReadWord();
2533  break;
2534 
2535  case 0x23: { // variable length cargo types accepted
2536  uint count = buf->ReadByte();
2537  if (count > lengthof(housespec->accepts_cargo)) {
2538  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
2539  error->param_value[1] = prop;
2540  return CIR_DISABLED;
2541  }
2542  /* Always write the full accepts_cargo array, and check each index for being inside the
2543  * provided data. This ensures all values are properly initialized, and also avoids
2544  * any risks of array overrun. */
2545  for (uint i = 0; i < lengthof(housespec->accepts_cargo); i++) {
2546  if (i < count) {
2547  housespec->accepts_cargo[i] = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
2548  housespec->cargo_acceptance[i] = buf->ReadByte();
2549  } else {
2550  housespec->accepts_cargo[i] = CT_INVALID;
2551  housespec->cargo_acceptance[i] = 0;
2552  }
2553  }
2554  break;
2555  }
2556 
2557  default:
2558  ret = CIR_UNKNOWN;
2559  break;
2560  }
2561  }
2562 
2563  return ret;
2564 }
2565 
2572 /* static */ const LanguageMap *LanguageMap::GetLanguageMap(uint32 grfid, uint8 language_id)
2573 {
2574  /* LanguageID "MAX_LANG", i.e. 7F is any. This language can't have a gender/case mapping, but has to be handled gracefully. */
2575  const GRFFile *grffile = GetFileByGRFID(grfid);
2576  return (grffile != nullptr && grffile->language_map != nullptr && language_id < MAX_LANG) ? &grffile->language_map[language_id] : nullptr;
2577 }
2578 
2588 template <typename T>
2589 static ChangeInfoResult LoadTranslationTable(uint gvid, int numinfo, ByteReader *buf, T &translation_table, const char *name)
2590 {
2591  if (gvid != 0) {
2592  grfmsg(1, "LoadTranslationTable: %s translation table must start at zero", name);
2593  return CIR_INVALID_ID;
2594  }
2595 
2596  translation_table.clear();
2597  for (int i = 0; i < numinfo; i++) {
2598  uint32 item = buf->ReadDWord();
2599  translation_table.push_back(BSWAP32(item));
2600  }
2601 
2602  return CIR_SUCCESS;
2603 }
2604 
2611 static std::string ReadDWordAsString(ByteReader *reader)
2612 {
2613  char output[5];
2614  for (int i = 0; i < 4; i++) output[i] = reader->ReadByte();
2615  output[4] = '\0';
2616  StrMakeValidInPlace(output, lastof(output));
2617 
2618  return std::string(output);
2619 }
2620 
2629 static ChangeInfoResult GlobalVarChangeInfo(uint gvid, int numinfo, int prop, ByteReader *buf)
2630 {
2631  /* Properties which are handled as a whole */
2632  switch (prop) {
2633  case 0x09: // Cargo Translation Table; loading during both reservation and activation stage (in case it is selected depending on defined cargos)
2634  return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->cargo_list, "Cargo");
2635 
2636  case 0x12: // Rail type translation table; loading during both reservation and activation stage (in case it is selected depending on defined railtypes)
2637  return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->railtype_list, "Rail type");
2638 
2639  case 0x16: // Road type translation table; loading during both reservation and activation stage (in case it is selected depending on defined railtypes)
2640  return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->roadtype_list, "Road type");
2641 
2642  case 0x17: // Tram type translation table; loading during both reservation and activation stage (in case it is selected depending on defined railtypes)
2643  return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->tramtype_list, "Tram type");
2644 
2645  default:
2646  break;
2647  }
2648 
2649  /* Properties which are handled per item */
2651  for (int i = 0; i < numinfo; i++) {
2652  switch (prop) {
2653  case 0x08: { // Cost base factor
2654  int factor = buf->ReadByte();
2655  uint price = gvid + i;
2656 
2657  if (price < PR_END) {
2658  _cur.grffile->price_base_multipliers[price] = std::min<int>(factor - 8, MAX_PRICE_MODIFIER);
2659  } else {
2660  grfmsg(1, "GlobalVarChangeInfo: Price %d out of range, ignoring", price);
2661  }
2662  break;
2663  }
2664 
2665  case 0x0A: { // Currency display names
2666  uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
2667  StringID newone = GetGRFStringID(_cur.grffile->grfid, buf->ReadWord());
2668 
2669  if ((newone != STR_UNDEFINED) && (curidx < CURRENCY_END)) {
2670  _currency_specs[curidx].name = newone;
2671  }
2672  break;
2673  }
2674 
2675  case 0x0B: { // Currency multipliers
2676  uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
2677  uint32 rate = buf->ReadDWord();
2678 
2679  if (curidx < CURRENCY_END) {
2680  /* TTDPatch uses a multiple of 1000 for its conversion calculations,
2681  * which OTTD does not. For this reason, divide grf value by 1000,
2682  * to be compatible */
2683  _currency_specs[curidx].rate = rate / 1000;
2684  } else {
2685  grfmsg(1, "GlobalVarChangeInfo: Currency multipliers %d out of range, ignoring", curidx);
2686  }
2687  break;
2688  }
2689 
2690  case 0x0C: { // Currency options
2691  uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
2692  uint16 options = buf->ReadWord();
2693 
2694  if (curidx < CURRENCY_END) {
2695  _currency_specs[curidx].separator.clear();
2696  _currency_specs[curidx].separator.push_back(GB(options, 0, 8));
2697  /* By specifying only one bit, we prevent errors,
2698  * since newgrf specs said that only 0 and 1 can be set for symbol_pos */
2699  _currency_specs[curidx].symbol_pos = GB(options, 8, 1);
2700  } else {
2701  grfmsg(1, "GlobalVarChangeInfo: Currency option %d out of range, ignoring", curidx);
2702  }
2703  break;
2704  }
2705 
2706  case 0x0D: { // Currency prefix symbol
2707  uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
2708  std::string prefix = ReadDWordAsString(buf);
2709 
2710  if (curidx < CURRENCY_END) {
2711  _currency_specs[curidx].prefix = prefix;
2712  } else {
2713  grfmsg(1, "GlobalVarChangeInfo: Currency symbol %d out of range, ignoring", curidx);
2714  }
2715  break;
2716  }
2717 
2718  case 0x0E: { // Currency suffix symbol
2719  uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
2720  std::string suffix = ReadDWordAsString(buf);
2721 
2722  if (curidx < CURRENCY_END) {
2723  _currency_specs[curidx].suffix = suffix;
2724  } else {
2725  grfmsg(1, "GlobalVarChangeInfo: Currency symbol %d out of range, ignoring", curidx);
2726  }
2727  break;
2728  }
2729 
2730  case 0x0F: { // Euro introduction dates
2731  uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
2732  Year year_euro = buf->ReadWord();
2733 
2734  if (curidx < CURRENCY_END) {
2735  _currency_specs[curidx].to_euro = year_euro;
2736  } else {
2737  grfmsg(1, "GlobalVarChangeInfo: Euro intro date %d out of range, ignoring", curidx);
2738  }
2739  break;
2740  }
2741 
2742  case 0x10: // Snow line height table
2743  if (numinfo > 1 || IsSnowLineSet()) {
2744  grfmsg(1, "GlobalVarChangeInfo: The snowline can only be set once (%d)", numinfo);
2745  } else if (buf->Remaining() < SNOW_LINE_MONTHS * SNOW_LINE_DAYS) {
2746  grfmsg(1, "GlobalVarChangeInfo: Not enough entries set in the snowline table (" PRINTF_SIZE ")", buf->Remaining());
2747  } else {
2748  byte table[SNOW_LINE_MONTHS][SNOW_LINE_DAYS];
2749 
2750  for (uint i = 0; i < SNOW_LINE_MONTHS; i++) {
2751  for (uint j = 0; j < SNOW_LINE_DAYS; j++) {
2752  table[i][j] = buf->ReadByte();
2753  if (_cur.grffile->grf_version >= 8) {
2754  if (table[i][j] != 0xFF) table[i][j] = table[i][j] * (1 + _settings_game.construction.map_height_limit) / 256;
2755  } else {
2756  if (table[i][j] >= 128) {
2757  /* no snow */
2758  table[i][j] = 0xFF;
2759  } else {
2760  table[i][j] = table[i][j] * (1 + _settings_game.construction.map_height_limit) / 128;
2761  }
2762  }
2763  }
2764  }
2765  SetSnowLine(table);
2766  }
2767  break;
2768 
2769  case 0x11: // GRF match for engine allocation
2770  /* This is loaded during the reservation stage, so just skip it here. */
2771  /* Each entry is 8 bytes. */
2772  buf->Skip(8);
2773  break;
2774 
2775  case 0x13: // Gender translation table
2776  case 0x14: // Case translation table
2777  case 0x15: { // Plural form translation
2778  uint curidx = gvid + i; // The current index, i.e. language.
2779  const LanguageMetadata *lang = curidx < MAX_LANG ? GetLanguage(curidx) : nullptr;
2780  if (lang == nullptr) {
2781  grfmsg(1, "GlobalVarChangeInfo: Language %d is not known, ignoring", curidx);
2782  /* Skip over the data. */
2783  if (prop == 0x15) {
2784  buf->ReadByte();
2785  } else {
2786  while (buf->ReadByte() != 0) {
2787  buf->ReadString();
2788  }
2789  }
2790  break;
2791  }
2792 
2793  if (_cur.grffile->language_map == nullptr) _cur.grffile->language_map = new LanguageMap[MAX_LANG];
2794 
2795  if (prop == 0x15) {
2796  uint plural_form = buf->ReadByte();
2797  if (plural_form >= LANGUAGE_MAX_PLURAL) {
2798  grfmsg(1, "GlobalVarChanceInfo: Plural form %d is out of range, ignoring", plural_form);
2799  } else {
2800  _cur.grffile->language_map[curidx].plural_form = plural_form;
2801  }
2802  break;
2803  }
2804 
2805  byte newgrf_id = buf->ReadByte(); // The NewGRF (custom) identifier.
2806  while (newgrf_id != 0) {
2807  const char *name = buf->ReadString(); // The name for the OpenTTD identifier.
2808 
2809  /* We'll just ignore the UTF8 identifier character. This is (fairly)
2810  * safe as OpenTTD's strings gender/cases are usually in ASCII which
2811  * is just a subset of UTF8, or they need the bigger UTF8 characters
2812  * such as Cyrillic. Thus we will simply assume they're all UTF8. */
2813  WChar c;
2814  size_t len = Utf8Decode(&c, name);
2815  if (c == NFO_UTF8_IDENTIFIER) name += len;
2816 
2818  map.newgrf_id = newgrf_id;
2819  if (prop == 0x13) {
2820  map.openttd_id = lang->GetGenderIndex(name);
2821  if (map.openttd_id >= MAX_NUM_GENDERS) {
2822  grfmsg(1, "GlobalVarChangeInfo: Gender name %s is not known, ignoring", name);
2823  } else {
2824  _cur.grffile->language_map[curidx].gender_map.push_back(map);
2825  }
2826  } else {
2827  map.openttd_id = lang->GetCaseIndex(name);
2828  if (map.openttd_id >= MAX_NUM_CASES) {
2829  grfmsg(1, "GlobalVarChangeInfo: Case name %s is not known, ignoring", name);
2830  } else {
2831  _cur.grffile->language_map[curidx].case_map.push_back(map);
2832  }
2833  }
2834  newgrf_id = buf->ReadByte();
2835  }
2836  break;
2837  }
2838 
2839  default:
2840  ret = CIR_UNKNOWN;
2841  break;
2842  }
2843  }
2844 
2845  return ret;
2846 }
2847 
2848 static ChangeInfoResult GlobalVarReserveInfo(uint gvid, int numinfo, int prop, ByteReader *buf)
2849 {
2850  /* Properties which are handled as a whole */
2851  switch (prop) {
2852  case 0x09: // Cargo Translation Table; loading during both reservation and activation stage (in case it is selected depending on defined cargos)
2853  return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->cargo_list, "Cargo");
2854 
2855  case 0x12: // Rail type translation table; loading during both reservation and activation stage (in case it is selected depending on defined railtypes)
2856  return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->railtype_list, "Rail type");
2857 
2858  case 0x16: // Road type translation table; loading during both reservation and activation stage (in case it is selected depending on defined roadtypes)
2859  return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->roadtype_list, "Road type");
2860 
2861  case 0x17: // Tram type translation table; loading during both reservation and activation stage (in case it is selected depending on defined tramtypes)
2862  return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->tramtype_list, "Tram type");
2863 
2864  default:
2865  break;
2866  }
2867 
2868  /* Properties which are handled per item */
2870  for (int i = 0; i < numinfo; i++) {
2871  switch (prop) {
2872  case 0x08: // Cost base factor
2873  case 0x15: // Plural form translation
2874  buf->ReadByte();
2875  break;
2876 
2877  case 0x0A: // Currency display names
2878  case 0x0C: // Currency options
2879  case 0x0F: // Euro introduction dates
2880  buf->ReadWord();
2881  break;
2882 
2883  case 0x0B: // Currency multipliers
2884  case 0x0D: // Currency prefix symbol
2885  case 0x0E: // Currency suffix symbol
2886  buf->ReadDWord();
2887  break;
2888 
2889  case 0x10: // Snow line height table
2890  buf->Skip(SNOW_LINE_MONTHS * SNOW_LINE_DAYS);
2891  break;
2892 
2893  case 0x11: { // GRF match for engine allocation
2894  uint32 s = buf->ReadDWord();
2895  uint32 t = buf->ReadDWord();
2896  SetNewGRFOverride(s, t);
2897  break;
2898  }
2899 
2900  case 0x13: // Gender translation table
2901  case 0x14: // Case translation table
2902  while (buf->ReadByte() != 0) {
2903  buf->ReadString();
2904  }
2905  break;
2906 
2907  default:
2908  ret = CIR_UNKNOWN;
2909  break;
2910  }
2911  }
2912 
2913  return ret;
2914 }
2915 
2916 
2925 static ChangeInfoResult CargoChangeInfo(uint cid, int numinfo, int prop, ByteReader *buf)
2926 {
2928 
2929  if (cid + numinfo > NUM_CARGO) {
2930  grfmsg(2, "CargoChangeInfo: Cargo type %d out of range (max %d)", cid + numinfo, NUM_CARGO - 1);
2931  return CIR_INVALID_ID;
2932  }
2933 
2934  for (int i = 0; i < numinfo; i++) {
2935  CargoSpec *cs = CargoSpec::Get(cid + i);
2936 
2937  switch (prop) {
2938  case 0x08: // Bit number of cargo
2939  cs->bitnum = buf->ReadByte();
2940  if (cs->IsValid()) {
2941  cs->grffile = _cur.grffile;
2942  SetBit(_cargo_mask, cid + i);
2943  } else {
2944  ClrBit(_cargo_mask, cid + i);
2945  }
2946  break;
2947 
2948  case 0x09: // String ID for cargo type name
2949  AddStringForMapping(buf->ReadWord(), &cs->name);
2950  break;
2951 
2952  case 0x0A: // String for 1 unit of cargo
2953  AddStringForMapping(buf->ReadWord(), &cs->name_single);
2954  break;
2955 
2956  case 0x0B: // String for singular quantity of cargo (e.g. 1 tonne of coal)
2957  case 0x1B: // String for cargo units
2958  /* String for units of cargo. This is different in OpenTTD
2959  * (e.g. tonnes) to TTDPatch (e.g. {COMMA} tonne of coal).
2960  * Property 1B is used to set OpenTTD's behaviour. */
2961  AddStringForMapping(buf->ReadWord(), &cs->units_volume);
2962  break;
2963 
2964  case 0x0C: // String for plural quantity of cargo (e.g. 10 tonnes of coal)
2965  case 0x1C: // String for any amount of cargo
2966  /* Strings for an amount of cargo. This is different in OpenTTD
2967  * (e.g. {WEIGHT} of coal) to TTDPatch (e.g. {COMMA} tonnes of coal).
2968  * Property 1C is used to set OpenTTD's behaviour. */
2969  AddStringForMapping(buf->ReadWord(), &cs->quantifier);
2970  break;
2971 
2972  case 0x0D: // String for two letter cargo abbreviation
2973  AddStringForMapping(buf->ReadWord(), &cs->abbrev);
2974  break;
2975 
2976  case 0x0E: // Sprite ID for cargo icon
2977  cs->sprite = buf->ReadWord();
2978  break;
2979 
2980  case 0x0F: // Weight of one unit of cargo
2981  cs->weight = buf->ReadByte();
2982  break;
2983 
2984  case 0x10: // Used for payment calculation
2985  cs->transit_days[0] = buf->ReadByte();
2986  break;
2987 
2988  case 0x11: // Used for payment calculation
2989  cs->transit_days[1] = buf->ReadByte();
2990  break;
2991 
2992  case 0x12: // Base cargo price
2993  cs->initial_payment = buf->ReadDWord();
2994  break;
2995 
2996  case 0x13: // Colour for station rating bars
2997  cs->rating_colour = buf->ReadByte();
2998  break;
2999 
3000  case 0x14: // Colour for cargo graph
3001  cs->legend_colour = buf->ReadByte();
3002  break;
3003 
3004  case 0x15: // Freight status
3005  cs->is_freight = (buf->ReadByte() != 0);
3006  break;
3007 
3008  case 0x16: // Cargo classes
3009  cs->classes = buf->ReadWord();
3010  break;
3011 
3012  case 0x17: // Cargo label
3013  cs->label = buf->ReadDWord();
3014  cs->label = BSWAP32(cs->label);
3015  break;
3016 
3017  case 0x18: { // Town growth substitute type
3018  uint8 substitute_type = buf->ReadByte();
3019 
3020  switch (substitute_type) {
3021  case 0x00: cs->town_effect = TE_PASSENGERS; break;
3022  case 0x02: cs->town_effect = TE_MAIL; break;
3023  case 0x05: cs->town_effect = TE_GOODS; break;
3024  case 0x09: cs->town_effect = TE_WATER; break;
3025  case 0x0B: cs->town_effect = TE_FOOD; break;
3026  default:
3027  grfmsg(1, "CargoChangeInfo: Unknown town growth substitute value %d, setting to none.", substitute_type);
3028  FALLTHROUGH;
3029  case 0xFF: cs->town_effect = TE_NONE; break;
3030  }
3031  break;
3032  }
3033 
3034  case 0x19: // Town growth coefficient
3035  buf->ReadWord();
3036  break;
3037 
3038  case 0x1A: // Bitmask of callbacks to use
3039  cs->callback_mask = buf->ReadByte();
3040  break;
3041 
3042  case 0x1D: // Vehicle capacity muliplier
3043  cs->multiplier = std::max<uint16>(1u, buf->ReadWord());
3044  break;
3045 
3046  default:
3047  ret = CIR_UNKNOWN;
3048  break;
3049  }
3050  }
3051 
3052  return ret;
3053 }
3054 
3055 
3064 static ChangeInfoResult SoundEffectChangeInfo(uint sid, int numinfo, int prop, ByteReader *buf)
3065 {
3067 
3068  if (_cur.grffile->sound_offset == 0) {
3069  grfmsg(1, "SoundEffectChangeInfo: No effects defined, skipping");
3070  return CIR_INVALID_ID;
3071  }
3072 
3073  if (sid + numinfo - ORIGINAL_SAMPLE_COUNT > _cur.grffile->num_sounds) {
3074  grfmsg(1, "SoundEffectChangeInfo: Attempting to change undefined sound effect (%u), max (%u). Ignoring.", sid + numinfo, ORIGINAL_SAMPLE_COUNT + _cur.grffile->num_sounds);
3075  return CIR_INVALID_ID;
3076  }
3077 
3078  for (int i = 0; i < numinfo; i++) {
3079  SoundEntry *sound = GetSound(sid + i + _cur.grffile->sound_offset - ORIGINAL_SAMPLE_COUNT);
3080 
3081  switch (prop) {
3082  case 0x08: // Relative volume
3083  sound->volume = buf->ReadByte();
3084  break;
3085 
3086  case 0x09: // Priority
3087  sound->priority = buf->ReadByte();
3088  break;
3089 
3090  case 0x0A: { // Override old sound
3091  SoundID orig_sound = buf->ReadByte();
3092 
3093  if (orig_sound >= ORIGINAL_SAMPLE_COUNT) {
3094  grfmsg(1, "SoundEffectChangeInfo: Original sound %d not defined (max %d)", orig_sound, ORIGINAL_SAMPLE_COUNT);
3095  } else {
3096  SoundEntry *old_sound = GetSound(orig_sound);
3097 
3098  /* Literally copy the data of the new sound over the original */
3099  *old_sound = *sound;
3100  }
3101  break;
3102  }
3103 
3104  default:
3105  ret = CIR_UNKNOWN;
3106  break;
3107  }
3108  }
3109 
3110  return ret;
3111 }
3112 
3120 {
3122 
3123  switch (prop) {
3124  case 0x09:
3125  case 0x0D:
3126  case 0x0E:
3127  case 0x10:
3128  case 0x11:
3129  case 0x12:
3130  buf->ReadByte();
3131  break;
3132 
3133  case 0x0A:
3134  case 0x0B:
3135  case 0x0C:
3136  case 0x0F:
3137  buf->ReadWord();
3138  break;
3139 
3140  case 0x13:
3141  buf->Skip(buf->ReadByte() * 2);
3142  break;
3143 
3144  default:
3145  ret = CIR_UNKNOWN;
3146  break;
3147  }
3148  return ret;
3149 }
3150 
3159 static ChangeInfoResult IndustrytilesChangeInfo(uint indtid, int numinfo, int prop, ByteReader *buf)
3160 {
3162 
3163  if (indtid + numinfo > NUM_INDUSTRYTILES_PER_GRF) {
3164  grfmsg(1, "IndustryTilesChangeInfo: Too many industry tiles loaded (%u), max (%u). Ignoring.", indtid + numinfo, NUM_INDUSTRYTILES_PER_GRF);
3165  return CIR_INVALID_ID;
3166  }
3167 
3168  /* Allocate industry tile specs if they haven't been allocated already. */
3169  if (_cur.grffile->indtspec == nullptr) {
3170  _cur.grffile->indtspec = CallocT<IndustryTileSpec*>(NUM_INDUSTRYTILES_PER_GRF);
3171  }
3172 
3173  for (int i = 0; i < numinfo; i++) {
3174  IndustryTileSpec *tsp = _cur.grffile->indtspec[indtid + i];
3175 
3176  if (prop != 0x08 && tsp == nullptr) {
3178  if (cir > ret) ret = cir;
3179  continue;
3180  }
3181 
3182  switch (prop) {
3183  case 0x08: { // Substitute industry tile type
3184  IndustryTileSpec **tilespec = &_cur.grffile->indtspec[indtid + i];
3185  byte subs_id = buf->ReadByte();
3186 
3187  if (subs_id >= NEW_INDUSTRYTILEOFFSET) {
3188  /* The substitute id must be one of the original industry tile. */
3189  grfmsg(2, "IndustryTilesChangeInfo: Attempt to use new industry tile %u as substitute industry tile for %u. Ignoring.", subs_id, indtid + i);
3190  continue;
3191  }
3192 
3193  /* Allocate space for this industry. */
3194  if (*tilespec == nullptr) {
3195  *tilespec = CallocT<IndustryTileSpec>(1);
3196  tsp = *tilespec;
3197 
3198  memcpy(tsp, &_industry_tile_specs[subs_id], sizeof(_industry_tile_specs[subs_id]));
3199  tsp->enabled = true;
3200 
3201  /* A copied tile should not have the animation infos copied too.
3202  * The anim_state should be left untouched, though
3203  * It is up to the author to animate them */
3206 
3207  tsp->grf_prop.local_id = indtid + i;
3208  tsp->grf_prop.subst_id = subs_id;
3209  tsp->grf_prop.grffile = _cur.grffile;
3210  _industile_mngr.AddEntityID(indtid + i, _cur.grffile->grfid, subs_id); // pre-reserve the tile slot
3211  }
3212  break;
3213  }
3214 
3215  case 0x09: { // Industry tile override
3216  byte ovrid = buf->ReadByte();
3217 
3218  /* The industry being overridden must be an original industry. */
3219  if (ovrid >= NEW_INDUSTRYTILEOFFSET) {
3220  grfmsg(2, "IndustryTilesChangeInfo: Attempt to override new industry tile %u with industry tile id %u. Ignoring.", ovrid, indtid + i);
3221  continue;
3222  }
3223 
3224  _industile_mngr.Add(indtid + i, _cur.grffile->grfid, ovrid);
3225  break;
3226  }
3227 
3228  case 0x0A: // Tile acceptance
3229  case 0x0B:
3230  case 0x0C: {
3231  uint16 acctp = buf->ReadWord();
3232  tsp->accepts_cargo[prop - 0x0A] = GetCargoTranslation(GB(acctp, 0, 8), _cur.grffile);
3233  tsp->acceptance[prop - 0x0A] = Clamp(GB(acctp, 8, 8), 0, 16);
3234  break;
3235  }
3236 
3237  case 0x0D: // Land shape flags
3238  tsp->slopes_refused = (Slope)buf->ReadByte();
3239  break;
3240 
3241  case 0x0E: // Callback mask
3242  tsp->callback_mask = buf->ReadByte();
3243  break;
3244 
3245  case 0x0F: // Animation information
3246  tsp->animation.frames = buf->ReadByte();
3247  tsp->animation.status = buf->ReadByte();
3248  break;
3249 
3250  case 0x10: // Animation speed
3251  tsp->animation.speed = buf->ReadByte();
3252  break;
3253 
3254  case 0x11: // Triggers for callback 25
3255  tsp->animation.triggers = buf->ReadByte();
3256  break;
3257 
3258  case 0x12: // Special flags
3259  tsp->special_flags = (IndustryTileSpecialFlags)buf->ReadByte();
3260  break;
3261 
3262  case 0x13: { // variable length cargo acceptance
3263  byte num_cargoes = buf->ReadByte();
3264  if (num_cargoes > lengthof(tsp->acceptance)) {
3265  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
3266  error->param_value[1] = prop;
3267  return CIR_DISABLED;
3268  }
3269  for (uint i = 0; i < lengthof(tsp->acceptance); i++) {
3270  if (i < num_cargoes) {
3271  tsp->accepts_cargo[i] = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
3272  /* Tile acceptance can be negative to counteract the INDTILE_SPECIAL_ACCEPTS_ALL_CARGO flag */
3273  tsp->acceptance[i] = (int8)buf->ReadByte();
3274  } else {
3275  tsp->accepts_cargo[i] = CT_INVALID;
3276  tsp->acceptance[i] = 0;
3277  }
3278  }
3279  break;
3280  }
3281 
3282  default:
3283  ret = CIR_UNKNOWN;
3284  break;
3285  }
3286  }
3287 
3288  return ret;
3289 }
3290 
3298 {
3300 
3301  switch (prop) {
3302  case 0x09:
3303  case 0x0B:
3304  case 0x0F:
3305  case 0x12:
3306  case 0x13:
3307  case 0x14:
3308  case 0x17:
3309  case 0x18:
3310  case 0x19:
3311  case 0x21:
3312  case 0x22:
3313  buf->ReadByte();
3314  break;
3315 
3316  case 0x0C:
3317  case 0x0D:
3318  case 0x0E:
3319  case 0x10:
3320  case 0x1B:
3321  case 0x1F:
3322  case 0x24:
3323  buf->ReadWord();
3324  break;
3325 
3326  case 0x11:
3327  case 0x1A:
3328  case 0x1C:
3329  case 0x1D:
3330  case 0x1E:
3331  case 0x20:
3332  case 0x23:
3333  buf->ReadDWord();
3334  break;
3335 
3336  case 0x0A: {
3337  byte num_table = buf->ReadByte();
3338  for (byte j = 0; j < num_table; j++) {
3339  for (uint k = 0;; k++) {
3340  byte x = buf->ReadByte();
3341  if (x == 0xFE && k == 0) {
3342  buf->ReadByte();
3343  buf->ReadByte();
3344  break;
3345  }
3346 
3347  byte y = buf->ReadByte();
3348  if (x == 0 && y == 0x80) break;
3349 
3350  byte gfx = buf->ReadByte();
3351  if (gfx == 0xFE) buf->ReadWord();
3352  }
3353  }
3354  break;
3355  }
3356 
3357  case 0x16:
3358  for (byte j = 0; j < 3; j++) buf->ReadByte();
3359  break;
3360 
3361  case 0x15:
3362  case 0x25:
3363  case 0x26:
3364  case 0x27:
3365  buf->Skip(buf->ReadByte());
3366  break;
3367 
3368  case 0x28: {
3369  int num_inputs = buf->ReadByte();
3370  int num_outputs = buf->ReadByte();
3371  buf->Skip(num_inputs * num_outputs * 2);
3372  break;
3373  }
3374 
3375  default:
3376  ret = CIR_UNKNOWN;
3377  break;
3378  }
3379  return ret;
3380 }
3381 
3387 static bool ValidateIndustryLayout(const IndustryTileLayout &layout)
3388 {
3389  const size_t size = layout.size();
3390  if (size == 0) return false;
3391 
3392  for (size_t i = 0; i < size - 1; i++) {
3393  for (size_t j = i + 1; j < size; j++) {
3394  if (layout[i].ti.x == layout[j].ti.x &&
3395  layout[i].ti.y == layout[j].ti.y) {
3396  return false;
3397  }
3398  }
3399  }
3400 
3401  bool have_regular_tile = false;
3402  for (size_t i = 0; i < size; i++) {
3403  if (layout[i].gfx != GFX_WATERTILE_SPECIALCHECK) {
3404  have_regular_tile = true;
3405  break;
3406  }
3407  }
3408 
3409  return have_regular_tile;
3410 }
3411 
3420 static ChangeInfoResult IndustriesChangeInfo(uint indid, int numinfo, int prop, ByteReader *buf)
3421 {
3423 
3424  if (indid + numinfo > NUM_INDUSTRYTYPES_PER_GRF) {
3425  grfmsg(1, "IndustriesChangeInfo: Too many industries loaded (%u), max (%u). Ignoring.", indid + numinfo, NUM_INDUSTRYTYPES_PER_GRF);
3426  return CIR_INVALID_ID;
3427  }
3428 
3429  /* Allocate industry specs if they haven't been allocated already. */
3430  if (_cur.grffile->industryspec == nullptr) {
3431  _cur.grffile->industryspec = CallocT<IndustrySpec*>(NUM_INDUSTRYTYPES_PER_GRF);
3432  }
3433 
3434  for (int i = 0; i < numinfo; i++) {
3435  IndustrySpec *indsp = _cur.grffile->industryspec[indid + i];
3436 
3437  if (prop != 0x08 && indsp == nullptr) {
3438  ChangeInfoResult cir = IgnoreIndustryProperty(prop, buf);
3439  if (cir > ret) ret = cir;
3440  continue;
3441  }
3442 
3443  switch (prop) {
3444  case 0x08: { // Substitute industry type
3445  IndustrySpec **indspec = &_cur.grffile->industryspec[indid + i];
3446  byte subs_id = buf->ReadByte();
3447 
3448  if (subs_id == 0xFF) {
3449  /* Instead of defining a new industry, a substitute industry id
3450  * of 0xFF disables the old industry with the current id. */
3451  _industry_specs[indid + i].enabled = false;
3452  continue;
3453  } else if (subs_id >= NEW_INDUSTRYOFFSET) {
3454  /* The substitute id must be one of the original industry. */
3455  grfmsg(2, "_industry_specs: Attempt to use new industry %u as substitute industry for %u. Ignoring.", subs_id, indid + i);
3456  continue;
3457  }
3458 
3459  /* Allocate space for this industry.
3460  * Only need to do it once. If ever it is called again, it should not
3461  * do anything */
3462  if (*indspec == nullptr) {
3463  *indspec = new IndustrySpec;
3464  indsp = *indspec;
3465 
3466  *indsp = _origin_industry_specs[subs_id];
3467  indsp->enabled = true;
3468  indsp->grf_prop.local_id = indid + i;
3469  indsp->grf_prop.subst_id = subs_id;
3470  indsp->grf_prop.grffile = _cur.grffile;
3471  /* If the grf industry needs to check its surrounding upon creation, it should
3472  * rely on callbacks, not on the original placement functions */
3473  indsp->check_proc = CHECK_NOTHING;
3474  }
3475  break;
3476  }
3477 
3478  case 0x09: { // Industry type override
3479  byte ovrid = buf->ReadByte();
3480 
3481  /* The industry being overridden must be an original industry. */
3482  if (ovrid >= NEW_INDUSTRYOFFSET) {
3483  grfmsg(2, "IndustriesChangeInfo: Attempt to override new industry %u with industry id %u. Ignoring.", ovrid, indid + i);
3484  continue;
3485  }
3486  indsp->grf_prop.override = ovrid;
3487  _industry_mngr.Add(indid + i, _cur.grffile->grfid, ovrid);
3488  break;
3489  }
3490 
3491  case 0x0A: { // Set industry layout(s)
3492  byte new_num_layouts = buf->ReadByte();
3493  uint32 definition_size = buf->ReadDWord();
3494  uint32 bytes_read = 0;
3495  std::vector<IndustryTileLayout> new_layouts;
3496  IndustryTileLayout layout;
3497 
3498  for (byte j = 0; j < new_num_layouts; j++) {
3499  layout.clear();
3500 
3501  for (uint k = 0;; k++) {
3502  if (bytes_read >= definition_size) {
3503  grfmsg(3, "IndustriesChangeInfo: Incorrect size for industry tile layout definition for industry %u.", indid);
3504  /* Avoid warning twice */
3505  definition_size = UINT32_MAX;
3506  }
3507 
3508  layout.push_back(IndustryTileLayoutTile{});
3509  IndustryTileLayoutTile &it = layout.back();
3510 
3511  it.ti.x = buf->ReadByte(); // Offsets from northermost tile
3512  ++bytes_read;
3513 
3514  if (it.ti.x == 0xFE && k == 0) {
3515  /* This means we have to borrow the layout from an old industry */
3516  IndustryType type = buf->ReadByte();
3517  byte laynbr = buf->ReadByte();
3518  bytes_read += 2;
3519 
3520  if (type >= lengthof(_origin_industry_specs)) {
3521  grfmsg(1, "IndustriesChangeInfo: Invalid original industry number for layout import, industry %u", indid);
3522  DisableGrf(STR_NEWGRF_ERROR_INVALID_ID);
3523  return CIR_DISABLED;
3524  }
3525  if (laynbr >= _origin_industry_specs[type].layouts.size()) {
3526  grfmsg(1, "IndustriesChangeInfo: Invalid original industry layout index for layout import, industry %u", indid);
3527  DisableGrf(STR_NEWGRF_ERROR_INVALID_ID);
3528  return CIR_DISABLED;
3529  }
3530  layout = _origin_industry_specs[type].layouts[laynbr];
3531  break;
3532  }
3533 
3534  it.ti.y = buf->ReadByte(); // Or table definition finalisation
3535  ++bytes_read;
3536 
3537  if (it.ti.x == 0 && it.ti.y == 0x80) {
3538  /* Terminator, remove and finish up */
3539  layout.pop_back();
3540  break;
3541  }
3542 
3543  it.gfx = buf->ReadByte();
3544  ++bytes_read;
3545 
3546  if (it.gfx == 0xFE) {
3547  /* Use a new tile from this GRF */
3548  int local_tile_id = buf->ReadWord();
3549  bytes_read += 2;
3550 
3551  /* Read the ID from the _industile_mngr. */
3552  int tempid = _industile_mngr.GetID(local_tile_id, _cur.grffile->grfid);
3553 
3554  if (tempid == INVALID_INDUSTRYTILE) {
3555  grfmsg(2, "IndustriesChangeInfo: Attempt to use industry tile %u with industry id %u, not yet defined. Ignoring.", local_tile_id, indid);
3556  } else {
3557  /* Declared as been valid, can be used */
3558  it.gfx = tempid;
3559  }
3560  } else if (it.gfx == GFX_WATERTILE_SPECIALCHECK) {
3561  it.ti.x = (int8)GB(it.ti.x, 0, 8);
3562  it.ti.y = (int8)GB(it.ti.y, 0, 8);
3563 
3564  /* When there were only 256x256 maps, TileIndex was a uint16 and
3565  * it.ti was just a TileIndexDiff that was added to it.
3566  * As such negative "x" values were shifted into the "y" position.
3567  * x = -1, y = 1 -> x = 255, y = 0
3568  * Since GRF version 8 the position is interpreted as pair of independent int8.
3569  * For GRF version < 8 we need to emulate the old shifting behaviour.
3570  */
3571  if (_cur.grffile->grf_version < 8 && it.ti.x < 0) it.ti.y += 1;
3572  }
3573  }
3574 
3575  if (!ValidateIndustryLayout(layout)) {
3576  /* The industry layout was not valid, so skip this one. */
3577  grfmsg(1, "IndustriesChangeInfo: Invalid industry layout for industry id %u. Ignoring", indid);
3578  new_num_layouts--;
3579  j--;
3580  } else {
3581  new_layouts.push_back(layout);
3582  }
3583  }
3584 
3585  /* Install final layout construction in the industry spec */
3586  indsp->layouts = new_layouts;
3587  break;
3588  }
3589 
3590  case 0x0B: // Industry production flags
3591  indsp->life_type = (IndustryLifeType)buf->ReadByte();
3592  break;
3593 
3594  case 0x0C: // Industry closure message
3595  AddStringForMapping(buf->ReadWord(), &indsp->closure_text);
3596  break;
3597 
3598  case 0x0D: // Production increase message
3599  AddStringForMapping(buf->ReadWord(), &indsp->production_up_text);
3600  break;
3601 
3602  case 0x0E: // Production decrease message
3603  AddStringForMapping(buf->ReadWord(), &indsp->production_down_text);
3604  break;
3605 
3606  case 0x0F: // Fund cost multiplier
3607  indsp->cost_multiplier = buf->ReadByte();
3608  break;
3609 
3610  case 0x10: // Production cargo types
3611  for (byte j = 0; j < 2; j++) {
3612  indsp->produced_cargo[j] = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
3613  }
3614  break;
3615 
3616  case 0x11: // Acceptance cargo types
3617  for (byte j = 0; j < 3; j++) {
3618  indsp->accepts_cargo[j] = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
3619  }
3620  buf->ReadByte(); // Unnused, eat it up
3621  break;
3622 
3623  case 0x12: // Production multipliers
3624  case 0x13:
3625  indsp->production_rate[prop - 0x12] = buf->ReadByte();
3626  break;
3627 
3628  case 0x14: // Minimal amount of cargo distributed
3629  indsp->minimal_cargo = buf->ReadByte();
3630  break;
3631 
3632  case 0x15: { // Random sound effects
3633  indsp->number_of_sounds = buf->ReadByte();
3634  uint8 *sounds = MallocT<uint8>(indsp->number_of_sounds);
3635 
3636  try {
3637  for (uint8 j = 0; j < indsp->number_of_sounds; j++) {
3638  sounds[j] = buf->ReadByte();
3639  }
3640  } catch (...) {
3641  free(sounds);
3642  throw;
3643  }
3644 
3645  if (HasBit(indsp->cleanup_flag, CLEAN_RANDOMSOUNDS)) {
3646  free(indsp->random_sounds);
3647  }
3648  indsp->random_sounds = sounds;
3650  break;
3651  }
3652 
3653  case 0x16: // Conflicting industry types
3654  for (byte j = 0; j < 3; j++) indsp->conflicting[j] = buf->ReadByte();
3655  break;
3656 
3657  case 0x17: // Probability in random game
3658  indsp->appear_creation[_settings_game.game_creation.landscape] = buf->ReadByte();
3659  break;
3660 
3661  case 0x18: // Probability during gameplay
3662  indsp->appear_ingame[_settings_game.game_creation.landscape] = buf->ReadByte();
3663  break;
3664 
3665  case 0x19: // Map colour
3666  indsp->map_colour = buf->ReadByte();
3667  break;
3668 
3669  case 0x1A: // Special industry flags to define special behavior
3670  indsp->behaviour = (IndustryBehaviour)buf->ReadDWord();
3671  break;
3672 
3673  case 0x1B: // New industry text ID
3674  AddStringForMapping(buf->ReadWord(), &indsp->new_industry_text);
3675  break;
3676 
3677  case 0x1C: // Input cargo multipliers for the three input cargo types
3678  case 0x1D:
3679  case 0x1E: {
3680  uint32 multiples = buf->ReadDWord();
3681  indsp->input_cargo_multiplier[prop - 0x1C][0] = GB(multiples, 0, 16);
3682  indsp->input_cargo_multiplier[prop - 0x1C][1] = GB(multiples, 16, 16);
3683  break;
3684  }
3685 
3686  case 0x1F: // Industry name
3687  AddStringForMapping(buf->ReadWord(), &indsp->name);
3688  break;
3689 
3690  case 0x20: // Prospecting success chance
3691  indsp->prospecting_chance = buf->ReadDWord();
3692  break;
3693 
3694  case 0x21: // Callback mask
3695  case 0x22: { // Callback additional mask
3696  byte aflag = buf->ReadByte();
3697  SB(indsp->callback_mask, (prop - 0x21) * 8, 8, aflag);
3698  break;
3699  }
3700 
3701  case 0x23: // removal cost multiplier
3702  indsp->removal_cost_multiplier = buf->ReadDWord();
3703  break;
3704 
3705  case 0x24: { // name for nearby station
3706  uint16 str = buf->ReadWord();
3707  if (str == 0) {
3708  indsp->station_name = STR_NULL;
3709  } else {
3710  AddStringForMapping(str, &indsp->station_name);
3711  }
3712  break;
3713  }
3714 
3715  case 0x25: { // variable length produced cargoes
3716  byte num_cargoes = buf->ReadByte();
3717  if (num_cargoes > lengthof(indsp->produced_cargo)) {
3718  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
3719  error->param_value[1] = prop;
3720  return CIR_DISABLED;
3721  }
3722  for (uint i = 0; i < lengthof(indsp->produced_cargo); i++) {
3723  if (i < num_cargoes) {
3724  CargoID cargo = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
3725  indsp->produced_cargo[i] = cargo;
3726  } else {
3727  indsp->produced_cargo[i] = CT_INVALID;
3728  }
3729  }
3730  break;
3731  }
3732 
3733  case 0x26: { // variable length accepted cargoes
3734  byte num_cargoes = buf->ReadByte();
3735  if (num_cargoes > lengthof(indsp->accepts_cargo)) {
3736  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
3737  error->param_value[1] = prop;
3738  return CIR_DISABLED;
3739  }
3740  for (uint i = 0; i < lengthof(indsp->accepts_cargo); i++) {
3741  if (i < num_cargoes) {
3742  CargoID cargo = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
3743  indsp->accepts_cargo[i] = cargo;
3744  } else {
3745  indsp->accepts_cargo[i] = CT_INVALID;
3746  }
3747  }
3748  break;
3749  }
3750 
3751  case 0x27: { // variable length production rates
3752  byte num_cargoes = buf->ReadByte();
3753  if (num_cargoes > lengthof(indsp->production_rate)) {
3754  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
3755  error->param_value[1] = prop;
3756  return CIR_DISABLED;
3757  }
3758  for (uint i = 0; i < lengthof(indsp->production_rate); i++) {
3759  if (i < num_cargoes) {
3760  indsp->production_rate[i] = buf->ReadByte();
3761  } else {
3762  indsp->production_rate[i] = 0;
3763  }
3764  }
3765  break;
3766  }
3767 
3768  case 0x28: { // variable size input/output production multiplier table
3769  byte num_inputs = buf->ReadByte();
3770  byte num_outputs = buf->ReadByte();
3771  if (num_inputs > lengthof(indsp->accepts_cargo) || num_outputs > lengthof(indsp->produced_cargo)) {
3772  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
3773  error->param_value[1] = prop;
3774  return CIR_DISABLED;
3775  }
3776  for (uint i = 0; i < lengthof(indsp->accepts_cargo); i++) {
3777  for (uint j = 0; j < lengthof(indsp->produced_cargo); j++) {
3778  uint16 mult = 0;
3779  if (i < num_inputs && j < num_outputs) mult = buf->ReadWord();
3780  indsp->input_cargo_multiplier[i][j] = mult;
3781  }
3782  }
3783  break;
3784  }
3785 
3786  default:
3787  ret = CIR_UNKNOWN;
3788  break;
3789  }
3790  }
3791 
3792  return ret;
3793 }
3794 
3801 {
3802  AirportTileTable **table_list = MallocT<AirportTileTable*>(as->num_table);
3803  for (int i = 0; i < as->num_table; i++) {
3804  uint num_tiles = 1;
3805  const AirportTileTable *it = as->table[0];
3806  do {
3807  num_tiles++;
3808  } while ((++it)->ti.x != -0x80);
3809  table_list[i] = MallocT<AirportTileTable>(num_tiles);
3810  MemCpyT(table_list[i], as->table[i], num_tiles);
3811  }
3812  as->table = table_list;
3813  HangarTileTable *depot_table = MallocT<HangarTileTable>(as->nof_depots);
3814  MemCpyT(depot_table, as->depot_table, as->nof_depots);
3815  as->depot_table = depot_table;
3816  Direction *rotation = MallocT<Direction>(as->num_table);
3817  MemCpyT(rotation, as->rotation, as->num_table);
3818  as->rotation = rotation;
3819 }
3820 
3829 static ChangeInfoResult AirportChangeInfo(uint airport, int numinfo, int prop, ByteReader *buf)
3830 {
3832 
3833  if (airport + numinfo > NUM_AIRPORTS_PER_GRF) {
3834  grfmsg(1, "AirportChangeInfo: Too many airports, trying id (%u), max (%u). Ignoring.", airport + numinfo, NUM_AIRPORTS_PER_GRF);
3835  return CIR_INVALID_ID;
3836  }
3837 
3838  /* Allocate industry specs if they haven't been allocated already. */
3839  if (_cur.grffile->airportspec == nullptr) {
3840  _cur.grffile->airportspec = CallocT<AirportSpec*>(NUM_AIRPORTS_PER_GRF);
3841  }
3842 
3843  for (int i = 0; i < numinfo; i++) {
3844  AirportSpec *as = _cur.grffile->airportspec[airport + i];
3845 
3846  if (as == nullptr && prop != 0x08 && prop != 0x09) {
3847  grfmsg(2, "AirportChangeInfo: Attempt to modify undefined airport %u, ignoring", airport + i);
3848  return CIR_INVALID_ID;
3849  }
3850 
3851  switch (prop) {
3852  case 0x08: { // Modify original airport
3853  byte subs_id = buf->ReadByte();
3854 
3855  if (subs_id == 0xFF) {
3856  /* Instead of defining a new airport, an airport id
3857  * of 0xFF disables the old airport with the current id. */
3858  AirportSpec::GetWithoutOverride(airport + i)->enabled = false;
3859  continue;
3860  } else if (subs_id >= NEW_AIRPORT_OFFSET) {
3861  /* The substitute id must be one of the original airports. */
3862  grfmsg(2, "AirportChangeInfo: Attempt to use new airport %u as substitute airport for %u. Ignoring.", subs_id, airport + i);
3863  continue;
3864  }
3865 
3866  AirportSpec **spec = &_cur.grffile->airportspec[airport + i];
3867  /* Allocate space for this airport.
3868  * Only need to do it once. If ever it is called again, it should not
3869  * do anything */
3870  if (*spec == nullptr) {
3871  *spec = MallocT<AirportSpec>(1);
3872  as = *spec;
3873 
3874  memcpy(as, AirportSpec::GetWithoutOverride(subs_id), sizeof(*as));
3875  as->enabled = true;
3876  as->grf_prop.local_id = airport + i;
3877  as->grf_prop.subst_id = subs_id;
3878  as->grf_prop.grffile = _cur.grffile;
3879  /* override the default airport */
3880  _airport_mngr.Add(airport + i, _cur.grffile->grfid, subs_id);
3881  /* Create a copy of the original tiletable so it can be freed later. */
3882  DuplicateTileTable(as);
3883  }
3884  break;
3885  }
3886 
3887  case 0x0A: { // Set airport layout
3888  byte old_num_table = as->num_table;
3889  free(as->rotation);
3890  as->num_table = buf->ReadByte(); // Number of layaouts
3891  as->rotation = MallocT<Direction>(as->num_table);
3892  uint32 defsize = buf->ReadDWord(); // Total size of the definition
3893  AirportTileTable **tile_table = CallocT<AirportTileTable*>(as->num_table); // Table with tiles to compose the airport
3894  AirportTileTable *att = CallocT<AirportTileTable>(defsize); // Temporary array to read the tile layouts from the GRF
3895  int size;
3896  const AirportTileTable *copy_from;
3897  try {
3898  for (byte j = 0; j < as->num_table; j++) {
3899  const_cast<Direction&>(as->rotation[j]) = (Direction)buf->ReadByte();
3900  for (int k = 0;; k++) {
3901  att[k].ti.x = buf->ReadByte(); // Offsets from northermost tile
3902  att[k].ti.y = buf->ReadByte();
3903 
3904  if (att[k].ti.x == 0 && att[k].ti.y == 0x80) {
3905  /* Not the same terminator. The one we are using is rather
3906  * x = -80, y = 0 . So, adjust it. */
3907  att[k].ti.x = -0x80;
3908  att[k].ti.y = 0;
3909  att[k].gfx = 0;
3910 
3911  size = k + 1;
3912  copy_from = att;
3913  break;
3914  }
3915 
3916  att[k].gfx = buf->ReadByte();
3917 
3918  if (att[k].gfx == 0xFE) {
3919  /* Use a new tile from this GRF */
3920  int local_tile_id = buf->ReadWord();
3921 
3922  /* Read the ID from the _airporttile_mngr. */
3923  uint16 tempid = _airporttile_mngr.GetID(local_tile_id, _cur.grffile->grfid);
3924 
3925  if (tempid == INVALID_AIRPORTTILE) {
3926  grfmsg(2, "AirportChangeInfo: Attempt to use airport tile %u with airport id %u, not yet defined. Ignoring.", local_tile_id, airport + i);
3927  } else {
3928  /* Declared as been valid, can be used */
3929  att[k].gfx = tempid;
3930  }
3931  } else if (att[k].gfx == 0xFF) {
3932  att[k].ti.x = (int8)GB(att[k].ti.x, 0, 8);
3933  att[k].ti.y = (int8)GB(att[k].ti.y, 0, 8);
3934  }
3935 
3936  if (as->rotation[j] == DIR_E || as->rotation[j] == DIR_W) {
3937  as->size_x = std::max<byte>(as->size_x, att[k].ti.y + 1);
3938  as->size_y = std::max<byte>(as->size_y, att[k].ti.x + 1);
3939  } else {
3940  as->size_x = std::max<byte>(as->size_x, att[k].ti.x + 1);
3941  as->size_y = std::max<byte>(as->size_y, att[k].ti.y + 1);
3942  }
3943  }
3944  tile_table[j] = CallocT<AirportTileTable>(size);
3945  memcpy(tile_table[j], copy_from, sizeof(*copy_from) * size);
3946  }
3947  /* Free old layouts in the airport spec */
3948  for (int j = 0; j < old_num_table; j++) {
3949  /* remove the individual layouts */
3950  free(as->table[j]);
3951  }
3952  free(as->table);
3953  /* Install final layout construction in the airport spec */
3954  as->table = tile_table;
3955  free(att);
3956  } catch (...) {
3957  for (int i = 0; i < as->num_table; i++) {
3958  free(tile_table[i]);
3959  }
3960  free(tile_table);
3961  free(att);
3962  throw;
3963  }
3964  break;
3965  }
3966 
3967  case 0x0C:
3968  as->min_year = buf->ReadWord();
3969  as->max_year = buf->ReadWord();
3970  if (as->max_year == 0xFFFF) as->max_year = MAX_YEAR;
3971  break;
3972 
3973  case 0x0D:
3974  as->ttd_airport_type = (TTDPAirportType)buf->ReadByte();
3975  break;
3976 
3977  case 0x0E:
3978  as->catchment = Clamp(buf->ReadByte(), 1, MAX_CATCHMENT);
3979  break;
3980 
3981  case 0x0F:
3982  as->noise_level = buf->ReadByte();
3983  break;
3984 
3985  case 0x10:
3986  AddStringForMapping(buf->ReadWord(), &as->name);
3987  break;
3988 
3989  case 0x11: // Maintenance cost factor
3990  as->maintenance_cost = buf->ReadWord();
3991  break;
3992 
3993  default:
3994  ret = CIR_UNKNOWN;
3995  break;
3996  }
3997  }
3998 
3999  return ret;
4000 }
4001 
4009 {
4011 
4012  switch (prop) {
4013  case 0x0B:
4014  case 0x0C:
4015  case 0x0D:
4016  case 0x12:
4017  case 0x14:
4018  case 0x16:
4019  case 0x17:
4020  buf->ReadByte();
4021  break;
4022 
4023  case 0x09:
4024  case 0x0A:
4025  case 0x10:
4026  case 0x11:
4027  case 0x13:
4028  case 0x15:
4029  buf->ReadWord();
4030  break;
4031 
4032  case 0x08:
4033  case 0x0E:
4034  case 0x0F:
4035  buf->ReadDWord();
4036  break;
4037 
4038  default:
4039  ret = CIR_UNKNOWN;
4040  break;
4041  }
4042 
4043  return ret;
4044 }
4045 
4054 static ChangeInfoResult ObjectChangeInfo(uint id, int numinfo, int prop, ByteReader *buf)
4055 {
4057 
4058  if (id + numinfo > NUM_OBJECTS_PER_GRF) {
4059  grfmsg(1, "ObjectChangeInfo: Too many objects loaded (%u), max (%u). Ignoring.", id + numinfo, NUM_OBJECTS_PER_GRF);
4060  return CIR_INVALID_ID;
4061  }
4062 
4063  /* Allocate object specs if they haven't been allocated already. */
4064  if (_cur.grffile->objectspec == nullptr) {
4065  _cur.grffile->objectspec = CallocT<ObjectSpec*>(NUM_OBJECTS_PER_GRF);
4066  }
4067 
4068  for (int i = 0; i < numinfo; i++) {
4069  ObjectSpec *spec = _cur.grffile->objectspec[id + i];
4070 
4071  if (prop != 0x08 && spec == nullptr) {
4072  /* If the object property 08 is not yet set, ignore this property */
4073  ChangeInfoResult cir = IgnoreObjectProperty(prop, buf);
4074  if (cir > ret) ret = cir;
4075  continue;
4076  }
4077 
4078  switch (prop) {
4079  case 0x08: { // Class ID
4080  ObjectSpec **ospec = &_cur.grffile->objectspec[id + i];
4081 
4082  /* Allocate space for this object. */
4083  if (*ospec == nullptr) {
4084  *ospec = CallocT<ObjectSpec>(1);
4085  (*ospec)->views = 1; // Default for NewGRFs that don't set it.
4086  (*ospec)->size = OBJECT_SIZE_1X1; // Default for NewGRFs that manage to not set it (1x1)
4087  }
4088 
4089  /* Swap classid because we read it in BE. */
4090  uint32 classid = buf->ReadDWord();
4091  (*ospec)->cls_id = ObjectClass::Allocate(BSWAP32(classid));
4092  (*ospec)->enabled = true;
4093  break;
4094  }
4095 
4096  case 0x09: { // Class name
4097  ObjectClass *objclass = ObjectClass::Get(spec->cls_id);
4098  AddStringForMapping(buf->ReadWord(), &objclass->name);
4099  break;
4100  }
4101 
4102  case 0x0A: // Object name
4103  AddStringForMapping(buf->ReadWord(), &spec->name);
4104  break;
4105 
4106  case 0x0B: // Climate mask
4107  spec->climate = buf->ReadByte();
4108  break;
4109 
4110  case 0x0C: // Size
4111  spec->size = buf->ReadByte();
4112  if (GB(spec->size, 0, 4) == 0 || GB(spec->size, 4, 4) == 0) {
4113  grfmsg(0, "ObjectChangeInfo: Invalid object size requested (0x%x) for object id %u. Ignoring.", spec->size, id + i);
4114  spec->size = OBJECT_SIZE_1X1;
4115  }
4116  break;
4117 
4118  case 0x0D: // Build cost multipler
4119  spec->build_cost_multiplier = buf->ReadByte();
4121  break;
4122 
4123  case 0x0E: // Introduction date
4124  spec->introduction_date = buf->ReadDWord();
4125  break;
4126 
4127  case 0x0F: // End of life
4128  spec->end_of_life_date = buf->ReadDWord();
4129  break;
4130 
4131  case 0x10: // Flags
4132  spec->flags = (ObjectFlags)buf->ReadWord();
4134  break;
4135 
4136  case 0x11: // Animation info
4137  spec->animation.frames = buf->ReadByte();
4138  spec->animation.status = buf->ReadByte();
4139  break;
4140 
4141  case 0x12: // Animation speed
4142  spec->animation.speed = buf->ReadByte();
4143  break;
4144 
4145  case 0x13: // Animation triggers
4146  spec->animation.triggers = buf->ReadWord();
4147  break;
4148 
4149  case 0x14: // Removal cost multiplier
4150  spec->clear_cost_multiplier = buf->ReadByte();
4151  break;
4152 
4153  case 0x15: // Callback mask
4154  spec->callback_mask = buf->ReadWord();
4155  break;
4156 
4157  case 0x16: // Building height
4158  spec->height = buf->ReadByte();
4159  break;
4160 
4161  case 0x17: // Views
4162  spec->views = buf->ReadByte();
4163  if (spec->views != 1 && spec->views != 2 && spec->views != 4) {
4164  grfmsg(2, "ObjectChangeInfo: Invalid number of views (%u) for object id %u. Ignoring.", spec->views, id + i);
4165  spec->views = 1;
4166  }
4167  break;
4168 
4169  case 0x18: // Amount placed on 256^2 map on map creation
4170  spec->generate_amount = buf->ReadByte();
4171  break;
4172 
4173  default:
4174  ret = CIR_UNKNOWN;
4175  break;
4176  }
4177  }
4178 
4179  return ret;
4180 }
4181 
4190 static ChangeInfoResult RailTypeChangeInfo(uint id, int numinfo, int prop, ByteReader *buf)
4191 {
4193 
4194  extern RailtypeInfo _railtypes[RAILTYPE_END];
4195 
4196  if (id + numinfo > RAILTYPE_END) {
4197  grfmsg(1, "RailTypeChangeInfo: Rail type %u is invalid, max %u, ignoring", id + numinfo, RAILTYPE_END);
4198  return CIR_INVALID_ID;
4199  }
4200 
4201  for (int i = 0; i < numinfo; i++) {
4202  RailType rt = _cur.grffile->railtype_map[id + i];
4203  if (rt == INVALID_RAILTYPE) return CIR_INVALID_ID;
4204 
4205  RailtypeInfo *rti = &_railtypes[rt];
4206 
4207  switch (prop) {
4208  case 0x08: // Label of rail type
4209  /* Skipped here as this is loaded during reservation stage. */
4210  buf->ReadDWord();
4211  break;
4212 
4213  case 0x09: { // Toolbar caption of railtype (sets name as well for backwards compatibility for grf ver < 8)
4214  uint16 str = buf->ReadWord();
4216  if (_cur.grffile->grf_version < 8) {
4217  AddStringForMapping(str, &rti->strings.name);
4218  }
4219  break;
4220  }
4221 
4222  case 0x0A: // Menu text of railtype
4223  AddStringForMapping(buf->ReadWord(), &rti->strings.menu_text);
4224  break;
4225 
4226  case 0x0B: // Build window caption
4227  AddStringForMapping(buf->ReadWord(), &rti->strings.build_caption);
4228  break;
4229 
4230  case 0x0C: // Autoreplace text
4231  AddStringForMapping(buf->ReadWord(), &rti->strings.replace_text);
4232  break;
4233 
4234  case 0x0D: // New locomotive text
4235  AddStringForMapping(buf->ReadWord(), &rti->strings.new_loco);
4236  break;
4237 
4238  case 0x0E: // Compatible railtype list
4239  case 0x0F: // Powered railtype list
4240  case 0x18: // Railtype list required for date introduction
4241  case 0x19: // Introduced railtype list
4242  {
4243  /* Rail type compatibility bits are added to the existing bits
4244  * to allow multiple GRFs to modify compatibility with the
4245  * default rail types. */
4246  int n = buf->ReadByte();
4247  for (int j = 0; j != n; j++) {
4248  RailTypeLabel label = buf->ReadDWord();
4249  RailType rt = GetRailTypeByLabel(BSWAP32(label), false);
4250  if (rt != INVALID_RAILTYPE) {
4251  switch (prop) {
4252  case 0x0F: SetBit(rti->powered_railtypes, rt); FALLTHROUGH; // Powered implies compatible.
4253  case 0x0E: SetBit(rti->compatible_railtypes, rt); break;
4254  case 0x18: SetBit(rti->introduction_required_railtypes, rt); break;
4255  case 0x19: SetBit(rti->introduces_railtypes, rt); break;
4256  }
4257  }
4258  }
4259  break;
4260  }
4261 
4262  case 0x10: // Rail Type flags
4263  rti->flags = (RailTypeFlags)buf->ReadByte();
4264  break;
4265 
4266  case 0x11: // Curve speed advantage
4267  rti->curve_speed = buf->ReadByte();
4268  break;
4269 
4270  case 0x12: // Station graphic
4271  rti->fallback_railtype = Clamp(buf->ReadByte(), 0, 2);
4272  break;
4273 
4274  case 0x13: // Construction cost factor
4275  rti->cost_multiplier = buf->ReadWord();
4276  break;
4277 
4278  case 0x14: // Speed limit
4279  rti->max_speed = buf->ReadWord();
4280  break;
4281 
4282  case 0x15: // Acceleration model
4283  rti->acceleration_type = Clamp(buf->ReadByte(), 0, 2);
4284  break;
4285 
4286  case 0x16: // Map colour
4287  rti->map_colour = buf->ReadByte();
4288  break;
4289 
4290  case 0x17: // Introduction date
4291  rti->introduction_date = buf->ReadDWord();
4292  break;
4293 
4294  case 0x1A: // Sort order
4295  rti->sorting_order = buf->ReadByte();
4296  break;
4297 
4298  case 0x1B: // Name of railtype (overridden by prop 09 for grf ver < 8)
4299  AddStringForMapping(buf->ReadWord(), &rti->strings.name);
4300  break;
4301 
4302  case 0x1C: // Maintenance cost factor
4303  rti->maintenance_multiplier = buf->ReadWord();
4304  break;
4305 
4306  case 0x1D: // Alternate rail type label list
4307  /* Skipped here as this is loaded during reservation stage. */
4308  for (int j = buf->ReadByte(); j != 0; j--) buf->ReadDWord();
4309  break;
4310 
4311  default:
4312  ret = CIR_UNKNOWN;
4313  break;
4314  }
4315  }
4316 
4317  return ret;
4318 }
4319 
4320 static ChangeInfoResult RailTypeReserveInfo(uint id, int numinfo, int prop, ByteReader *buf)
4321 {
4323 
4324  extern RailtypeInfo _railtypes[RAILTYPE_END];
4325 
4326  if (id + numinfo > RAILTYPE_END) {
4327  grfmsg(1, "RailTypeReserveInfo: Rail type %u is invalid, max %u, ignoring", id + numinfo, RAILTYPE_END);
4328  return CIR_INVALID_ID;
4329  }
4330 
4331  for (int i = 0; i < numinfo; i++) {
4332  switch (prop) {
4333  case 0x08: // Label of rail type
4334  {
4335  RailTypeLabel rtl = buf->ReadDWord();
4336  rtl = BSWAP32(rtl);
4337 
4338  RailType rt = GetRailTypeByLabel(rtl, false);
4339  if (rt == INVALID_RAILTYPE) {
4340  /* Set up new rail type */
4341  rt = AllocateRailType(rtl);
4342  }
4343 
4344  _cur.grffile->railtype_map[id + i] = rt;
4345  break;
4346  }
4347 
4348  case 0x09: // Toolbar caption of railtype
4349  case 0x0A: // Menu text
4350  case 0x0B: // Build window caption
4351  case 0x0C: // Autoreplace text
4352  case 0x0D: // New loco
4353  case 0x13: // Construction cost
4354  case 0x14: // Speed limit
4355  case 0x1B: // Name of railtype
4356  case 0x1C: // Maintenance cost factor
4357  buf->ReadWord();
4358  break;
4359 
4360  case 0x1D: // Alternate rail type label list
4361  if (_cur.grffile->railtype_map[id + i] != INVALID_RAILTYPE) {
4362  int n = buf->ReadByte();
4363  for (int j = 0; j != n; j++) {
4364  _railtypes[_cur.grffile->railtype_map[id + i]].alternate_labels.push_back(BSWAP32(buf->ReadDWord()));
4365  }
4366  break;
4367  }
4368  grfmsg(1, "RailTypeReserveInfo: Ignoring property 1D for rail type %u because no label was set", id + i);
4369  FALLTHROUGH;
4370 
4371  case 0x0E: // Compatible railtype list
4372  case 0x0F: // Powered railtype list
4373  case 0x18: // Railtype list required for date introduction
4374  case 0x19: // Introduced railtype list
4375  for (int j = buf->ReadByte(); j != 0; j--) buf->ReadDWord();
4376  break;
4377 
4378  case 0x10: // Rail Type flags
4379  case 0x11: // Curve speed advantage
4380  case 0x12: // Station graphic
4381  case 0x15: // Acceleration model
4382  case 0x16: // Map colour
4383  case 0x1A: // Sort order
4384  buf->ReadByte();
4385  break;
4386 
4387  case 0x17: // Introduction date
4388  buf->ReadDWord();
4389  break;
4390 
4391  default:
4392  ret = CIR_UNKNOWN;
4393  break;
4394  }
4395  }
4396 
4397  return ret;
4398 }
4399 
4408 static ChangeInfoResult RoadTypeChangeInfo(uint id, int numinfo, int prop, ByteReader *buf, RoadTramType rtt)
4409 {
4411 
4412  extern RoadTypeInfo _roadtypes[ROADTYPE_END];
4413  RoadType *type_map = (rtt == RTT_TRAM) ? _cur.grffile->tramtype_map : _cur.grffile->roadtype_map;
4414 
4415  if (id + numinfo > ROADTYPE_END) {
4416  grfmsg(1, "RoadTypeChangeInfo: Road type %u is invalid, max %u, ignoring", id + numinfo, ROADTYPE_END);
4417  return CIR_INVALID_ID;
4418  }
4419 
4420  for (int i = 0; i < numinfo; i++) {
4421  RoadType rt = type_map[id + i];
4422  if (rt == INVALID_ROADTYPE) return CIR_INVALID_ID;
4423 
4424  RoadTypeInfo *rti = &_roadtypes[rt];
4425 
4426  switch (prop) {
4427  case 0x08: // Label of road type
4428  /* Skipped here as this is loaded during reservation stage. */
4429  buf->ReadDWord();
4430  break;
4431 
4432  case 0x09: { // Toolbar caption of roadtype (sets name as well for backwards compatibility for grf ver < 8)
4433  uint16 str = buf->ReadWord();
4435  break;
4436  }
4437 
4438  case 0x0A: // Menu text of roadtype
4439  AddStringForMapping(buf->ReadWord(), &rti->strings.menu_text);
4440  break;
4441 
4442  case 0x0B: // Build window caption
4443  AddStringForMapping(buf->ReadWord(), &rti->strings.build_caption);
4444  break;
4445 
4446  case 0x0C: // Autoreplace text
4447  AddStringForMapping(buf->ReadWord(), &rti->strings.replace_text);
4448  break;
4449 
4450  case 0x0D: // New engine text
4451  AddStringForMapping(buf->ReadWord(), &rti->strings.new_engine);
4452  break;
4453 
4454  case 0x0F: // Powered roadtype list
4455  case 0x18: // Roadtype list required for date introduction
4456  case 0x19: { // Introduced roadtype list
4457  /* Road type compatibility bits are added to the existing bits
4458  * to allow multiple GRFs to modify compatibility with the
4459  * default road types. */
4460  int n = buf->ReadByte();
4461  for (int j = 0; j != n; j++) {
4462  RoadTypeLabel label = buf->ReadDWord();
4463  RoadType rt = GetRoadTypeByLabel(BSWAP32(label), false);
4464  if (rt != INVALID_ROADTYPE) {
4465  switch (prop) {
4466  case 0x0F: SetBit(rti->powered_roadtypes, rt); break;
4467  case 0x18: SetBit(rti->introduction_required_roadtypes, rt); break;
4468  case 0x19: SetBit(rti->introduces_roadtypes, rt); break;
4469  }
4470  }
4471  }
4472  break;
4473  }
4474 
4475  case 0x10: // Road Type flags
4476  rti->flags = (RoadTypeFlags)buf->ReadByte();
4477  break;
4478 
4479  case 0x13: // Construction cost factor
4480  rti->cost_multiplier = buf->ReadWord();
4481  break;
4482 
4483  case 0x14: // Speed limit
4484  rti->max_speed = buf->ReadWord();
4485  break;
4486 
4487  case 0x16: // Map colour
4488  rti->map_colour = buf->ReadByte();
4489  break;
4490 
4491  case 0x17: // Introduction date
4492  rti->introduction_date = buf->ReadDWord();
4493  break;
4494 
4495  case 0x1A: // Sort order
4496  rti->sorting_order = buf->ReadByte();
4497  break;
4498 
4499  case 0x1B: // Name of roadtype
4500  AddStringForMapping(buf->ReadWord(), &rti->strings.name);
4501  break;
4502 
4503  case 0x1C: // Maintenance cost factor
4504  rti->maintenance_multiplier = buf->ReadWord();
4505  break;
4506 
4507  case 0x1D: // Alternate road type label list
4508  /* Skipped here as this is loaded during reservation stage. */
4509  for (int j = buf->ReadByte(); j != 0; j--) buf->ReadDWord();
4510  break;
4511 
4512  default:
4513  ret = CIR_UNKNOWN;
4514  break;
4515  }
4516  }
4517 
4518  return ret;
4519 }
4520 
4521 static ChangeInfoResult RoadTypeChangeInfo(uint id, int numinfo, int prop, ByteReader *buf)
4522 {
4523  return RoadTypeChangeInfo(id, numinfo, prop, buf, RTT_ROAD);
4524 }
4525 
4526 static ChangeInfoResult TramTypeChangeInfo(uint id, int numinfo, int prop, ByteReader *buf)
4527 {
4528  return RoadTypeChangeInfo(id, numinfo, prop, buf, RTT_TRAM);
4529 }
4530 
4531 
4532 static ChangeInfoResult RoadTypeReserveInfo(uint id, int numinfo, int prop, ByteReader *buf, RoadTramType rtt)
4533 {
4535 
4536  extern RoadTypeInfo _roadtypes[ROADTYPE_END];
4537  RoadType *type_map = (rtt == RTT_TRAM) ? _cur.grffile->tramtype_map : _cur.grffile->roadtype_map;
4538 
4539  if (id + numinfo > ROADTYPE_END) {
4540  grfmsg(1, "RoadTypeReserveInfo: Road type %u is invalid, max %u, ignoring", id + numinfo, ROADTYPE_END);
4541  return CIR_INVALID_ID;
4542  }
4543 
4544  for (int i = 0; i < numinfo; i++) {
4545  switch (prop) {
4546  case 0x08: { // Label of road type
4547  RoadTypeLabel rtl = buf->ReadDWord();
4548  rtl = BSWAP32(rtl);
4549 
4550  RoadType rt = GetRoadTypeByLabel(rtl, false);
4551  if (rt == INVALID_ROADTYPE) {
4552  /* Set up new road type */
4553  rt = AllocateRoadType(rtl, rtt);
4554  } else if (GetRoadTramType(rt) != rtt) {
4555  grfmsg(1, "RoadTypeReserveInfo: Road type %u is invalid type (road/tram), ignoring", id + numinfo);
4556  return CIR_INVALID_ID;
4557  }
4558 
4559  type_map[id + i] = rt;
4560  break;
4561  }
4562  case 0x09: // Toolbar caption of roadtype
4563  case 0x0A: // Menu text
4564  case 0x0B: // Build window caption
4565  case 0x0C: // Autoreplace text
4566  case 0x0D: // New loco
4567  case 0x13: // Construction cost
4568  case 0x14: // Speed limit
4569  case 0x1B: // Name of roadtype
4570  case 0x1C: // Maintenance cost factor
4571  buf->ReadWord();
4572  break;
4573 
4574  case 0x1D: // Alternate road type label list
4575  if (type_map[id + i] != INVALID_ROADTYPE) {
4576  int n = buf->ReadByte();
4577  for (int j = 0; j != n; j++) {
4578  _roadtypes[type_map[id + i]].alternate_labels.push_back(BSWAP32(buf->ReadDWord()));
4579  }
4580  break;
4581  }
4582  grfmsg(1, "RoadTypeReserveInfo: Ignoring property 1D for road type %u because no label was set", id + i);
4583  /* FALL THROUGH */
4584 
4585  case 0x0F: // Powered roadtype list
4586  case 0x18: // Roadtype list required for date introduction
4587  case 0x19: // Introduced roadtype list
4588  for (int j = buf->ReadByte(); j != 0; j--) buf->ReadDWord();
4589  break;
4590 
4591  case 0x10: // Road Type flags
4592  case 0x16: // Map colour
4593  case 0x1A: // Sort order
4594  buf->ReadByte();
4595  break;
4596 
4597  case 0x17: // Introduction date
4598  buf->ReadDWord();
4599  break;
4600 
4601  default:
4602  ret = CIR_UNKNOWN;
4603  break;
4604  }
4605  }
4606 
4607  return ret;
4608 }
4609 
4610 static ChangeInfoResult RoadTypeReserveInfo(uint id, int numinfo, int prop, ByteReader *buf)
4611 {
4612  return RoadTypeReserveInfo(id, numinfo, prop, buf, RTT_ROAD);
4613 }
4614 
4615 static ChangeInfoResult TramTypeReserveInfo(uint id, int numinfo, int prop, ByteReader *buf)
4616 {
4617  return RoadTypeReserveInfo(id, numinfo, prop, buf, RTT_TRAM);
4618 }
4619 
4620 static ChangeInfoResult AirportTilesChangeInfo(uint airtid, int numinfo, int prop, ByteReader *buf)
4621 {
4623 
4624  if (airtid + numinfo > NUM_AIRPORTTILES_PER_GRF) {
4625  grfmsg(1, "AirportTileChangeInfo: Too many airport tiles loaded (%u), max (%u). Ignoring.", airtid + numinfo, NUM_AIRPORTTILES_PER_GRF);
4626  return CIR_INVALID_ID;
4627  }
4628 
4629  /* Allocate airport tile specs if they haven't been allocated already. */
4630  if (_cur.grffile->airtspec == nullptr) {
4631  _cur.grffile->airtspec = CallocT<AirportTileSpec*>(NUM_AIRPORTTILES_PER_GRF);
4632  }
4633 
4634  for (int i = 0; i < numinfo; i++) {
4635  AirportTileSpec *tsp = _cur.grffile->airtspec[airtid + i];
4636 
4637  if (prop != 0x08 && tsp == nullptr) {
4638  grfmsg(2, "AirportTileChangeInfo: Attempt to modify undefined airport tile %u. Ignoring.", airtid + i);
4639  return CIR_INVALID_ID;
4640  }
4641 
4642  switch (prop) {
4643  case 0x08: { // Substitute airport tile type
4644  AirportTileSpec **tilespec = &_cur.grffile->airtspec[airtid + i];
4645  byte subs_id = buf->ReadByte();
4646 
4647  if (subs_id >= NEW_AIRPORTTILE_OFFSET) {
4648  /* The substitute id must be one of the original airport tiles. */
4649  grfmsg(2, "AirportTileChangeInfo: Attempt to use new airport tile %u as substitute airport tile for %u. Ignoring.", subs_id, airtid + i);
4650  continue;
4651  }
4652 
4653  /* Allocate space for this airport tile. */
4654  if (*tilespec == nullptr) {
4655  *tilespec = CallocT<AirportTileSpec>(1);
4656  tsp = *tilespec;
4657 
4658  memcpy(tsp, AirportTileSpec::Get(subs_id), sizeof(AirportTileSpec));
4659  tsp->enabled = true;
4660 
4662 
4663  tsp->grf_prop.local_id = airtid + i;
4664  tsp->grf_prop.subst_id = subs_id;
4665  tsp->grf_prop.grffile = _cur.grffile;
4666  _airporttile_mngr.AddEntityID(airtid + i, _cur.grffile->grfid, subs_id); // pre-reserve the tile slot
4667  }
4668  break;
4669  }
4670 
4671  case 0x09: { // Airport tile override
4672  byte override = buf->ReadByte();
4673 
4674  /* The airport tile being overridden must be an original airport tile. */
4675  if (override >= NEW_AIRPORTTILE_OFFSET) {
4676  grfmsg(2, "AirportTileChangeInfo: Attempt to override new airport tile %u with airport tile id %u. Ignoring.", override, airtid + i);
4677  continue;
4678  }
4679 
4680  _airporttile_mngr.Add(airtid + i, _cur.grffile->grfid, override);
4681  break;
4682  }
4683 
4684  case 0x0E: // Callback mask
4685  tsp->callback_mask = buf->ReadByte();
4686  break;
4687 
4688  case 0x0F: // Animation information
4689  tsp->animation.frames = buf->ReadByte();
4690  tsp->animation.status = buf->ReadByte();
4691  break;
4692 
4693  case 0x10: // Animation speed
4694  tsp->animation.speed = buf->ReadByte();
4695  break;
4696 
4697  case 0x11: // Animation triggers
4698  tsp->animation.triggers = buf->ReadByte();
4699  break;
4700 
4701  default:
4702  ret = CIR_UNKNOWN;
4703  break;
4704  }
4705  }
4706 
4707  return ret;
4708 }
4709 
4710 static bool HandleChangeInfoResult(const char *caller, ChangeInfoResult cir, uint8 feature, uint8 property)
4711 {
4712  switch (cir) {
4713  default: NOT_REACHED();
4714 
4715  case CIR_DISABLED:
4716  /* Error has already been printed; just stop parsing */
4717  return true;
4718 
4719  case CIR_SUCCESS:
4720  return false;
4721 
4722  case CIR_UNHANDLED:
4723  grfmsg(1, "%s: Ignoring property 0x%02X of feature 0x%02X (not implemented)", caller, property, feature);
4724  return false;
4725 
4726  case CIR_UNKNOWN:
4727  grfmsg(0, "%s: Unknown property 0x%02X of feature 0x%02X, disabling", caller, property, feature);
4728  FALLTHROUGH;
4729 
4730  case CIR_INVALID_ID: {
4731  /* No debug message for an invalid ID, as it has already been output */
4732  GRFError *error = DisableGrf(cir == CIR_INVALID_ID ? STR_NEWGRF_ERROR_INVALID_ID : STR_NEWGRF_ERROR_UNKNOWN_PROPERTY);
4733  if (cir != CIR_INVALID_ID) error->param_value[1] = property;
4734  return true;
4735  }
4736  }
4737 }
4738 
4739 /* Action 0x00 */
4740 static void FeatureChangeInfo(ByteReader *buf)
4741 {
4742  /* <00> <feature> <num-props> <num-info> <id> (<property <new-info>)...
4743  *
4744  * B feature
4745  * B num-props how many properties to change per vehicle/station
4746  * B num-info how many vehicles/stations to change
4747  * E id ID of first vehicle/station to change, if num-info is
4748  * greater than one, this one and the following
4749  * vehicles/stations will be changed
4750  * B property what property to change, depends on the feature
4751  * V new-info new bytes of info (variable size; depends on properties) */
4752 
4753  static const VCI_Handler handler[] = {
4754  /* GSF_TRAINS */ RailVehicleChangeInfo,
4755  /* GSF_ROADVEHICLES */ RoadVehicleChangeInfo,
4756  /* GSF_SHIPS */ ShipVehicleChangeInfo,
4757  /* GSF_AIRCRAFT */ AircraftVehicleChangeInfo,
4758  /* GSF_STATIONS */ StationChangeInfo,
4759  /* GSF_CANALS */ CanalChangeInfo,
4760  /* GSF_BRIDGES */ BridgeChangeInfo,
4761  /* GSF_HOUSES */ TownHouseChangeInfo,
4762  /* GSF_GLOBALVAR */ GlobalVarChangeInfo,
4763  /* GSF_INDUSTRYTILES */ IndustrytilesChangeInfo,
4764  /* GSF_INDUSTRIES */ IndustriesChangeInfo,
4765  /* GSF_CARGOES */ nullptr, // Cargo is handled during reservation
4766  /* GSF_SOUNDFX */ SoundEffectChangeInfo,
4767  /* GSF_AIRPORTS */ AirportChangeInfo,
4768  /* GSF_SIGNALS */ nullptr,
4769  /* GSF_OBJECTS */ ObjectChangeInfo,
4770  /* GSF_RAILTYPES */ RailTypeChangeInfo,
4771  /* GSF_AIRPORTTILES */ AirportTilesChangeInfo,
4772  /* GSF_ROADTYPES */ RoadTypeChangeInfo,
4773  /* GSF_TRAMTYPES */ TramTypeChangeInfo,
4774  };
4775  static_assert(GSF_END == lengthof(handler));
4776 
4777  uint8 feature = buf->ReadByte();
4778  uint8 numprops = buf->ReadByte();
4779  uint numinfo = buf->ReadByte();
4780  uint engine = buf->ReadExtendedByte();
4781 
4782  if (feature >= GSF_END) {
4783  grfmsg(1, "FeatureChangeInfo: Unsupported feature 0x%02X, skipping", feature);
4784  return;
4785  }
4786 
4787  grfmsg(6, "FeatureChangeInfo: Feature 0x%02X, %d properties, to apply to %d+%d",
4788  feature, numprops, engine, numinfo);
4789 
4790  if (handler[feature] == nullptr) {
4791  if (feature != GSF_CARGOES) grfmsg(1, "FeatureChangeInfo: Unsupported feature 0x%02X, skipping", feature);
4792  return;
4793  }
4794 
4795  /* Mark the feature as used by the grf */
4796  SetBit(_cur.grffile->grf_features, feature);
4797 
4798  while (numprops-- && buf->HasData()) {
4799  uint8 prop = buf->ReadByte();
4800 
4801  ChangeInfoResult cir = handler[feature](engine, numinfo, prop, buf);
4802  if (HandleChangeInfoResult("FeatureChangeInfo", cir, feature, prop)) return;
4803  }
4804 }
4805 
4806 /* Action 0x00 (GLS_SAFETYSCAN) */
4807 static void SafeChangeInfo(ByteReader *buf)
4808 {
4809  uint8 feature = buf->ReadByte();
4810  uint8 numprops = buf->ReadByte();
4811  uint numinfo = buf->ReadByte();
4812  buf->ReadExtendedByte(); // id
4813 
4814  if (feature == GSF_BRIDGES && numprops == 1) {
4815  uint8 prop = buf->ReadByte();
4816  /* Bridge property 0x0D is redefinition of sprite layout tables, which
4817  * is considered safe. */
4818  if (prop == 0x0D) return;
4819  } else if (feature == GSF_GLOBALVAR && numprops == 1) {
4820  uint8 prop = buf->ReadByte();
4821  /* Engine ID Mappings are safe, if the source is static */
4822  if (prop == 0x11) {
4823  bool is_safe = true;
4824  for (uint i = 0; i < numinfo; i++) {
4825  uint32 s = buf->ReadDWord();
4826  buf->ReadDWord(); // dest
4827  const GRFConfig *grfconfig = GetGRFConfig(s);
4828  if (grfconfig != nullptr && !HasBit(grfconfig->flags, GCF_STATIC)) {
4829  is_safe = false;
4830  break;
4831  }
4832  }
4833  if (is_safe) return;
4834  }
4835  }
4836 
4837  SetBit(_cur.grfconfig->flags, GCF_UNSAFE);
4838 
4839  /* Skip remainder of GRF */
4840  _cur.skip_sprites = -1;
4841 }
4842 
4843 /* Action 0x00 (GLS_RESERVE) */
4844 static void ReserveChangeInfo(ByteReader *buf)
4845 {
4846  uint8 feature = buf->ReadByte();
4847 
4848  if (feature != GSF_CARGOES && feature != GSF_GLOBALVAR && feature != GSF_RAILTYPES && feature != GSF_ROADTYPES && feature != GSF_TRAMTYPES) return;
4849 
4850  uint8 numprops = buf->ReadByte();
4851  uint8 numinfo = buf->ReadByte();
4852  uint8 index = buf->ReadExtendedByte();
4853 
4854  while (numprops-- && buf->HasData()) {
4855  uint8 prop = buf->ReadByte();
4857 
4858  switch (feature) {
4859  default: NOT_REACHED();
4860  case GSF_CARGOES:
4861  cir = CargoChangeInfo(index, numinfo, prop, buf);
4862  break;
4863 
4864  case GSF_GLOBALVAR:
4865  cir = GlobalVarReserveInfo(index, numinfo, prop, buf);
4866  break;
4867 
4868  case GSF_RAILTYPES:
4869  cir = RailTypeReserveInfo(index, numinfo, prop, buf);
4870  break;
4871 
4872  case GSF_ROADTYPES:
4873  cir = RoadTypeReserveInfo(index, numinfo, prop, buf);
4874  break;
4875 
4876  case GSF_TRAMTYPES:
4877  cir = TramTypeReserveInfo(index, numinfo, prop, buf);
4878  break;
4879  }
4880 
4881  if (HandleChangeInfoResult("ReserveChangeInfo", cir, feature, prop)) return;
4882  }
4883 }
4884 
4885 /* Action 0x01 */
4886 static void NewSpriteSet(ByteReader *buf)
4887 {
4888  /* Basic format: <01> <feature> <num-sets> <num-ent>
4889  * Extended format: <01> <feature> 00 <first-set> <num-sets> <num-ent>
4890  *
4891  * B feature feature to define sprites for
4892  * 0, 1, 2, 3: veh-type, 4: train stations
4893  * E first-set first sprite set to define
4894  * B num-sets number of sprite sets (extended byte in extended format)
4895  * E num-ent how many entries per sprite set
4896  * For vehicles, this is the number of different
4897  * vehicle directions in each sprite set
4898  * Set num-dirs=8, unless your sprites are symmetric.
4899  * In that case, use num-dirs=4.
4900  */
4901 
4902  uint8 feature = buf->ReadByte();
4903  uint16 num_sets = buf->ReadByte();
4904  uint16 first_set = 0;
4905 
4906  if (num_sets == 0 && buf->HasData(3)) {
4907  /* Extended Action1 format.
4908  * Some GRFs define zero sets of zero sprites, though there is actually no use in that. Ignore them. */
4909  first_set = buf->ReadExtendedByte();
4910  num_sets = buf->ReadExtendedByte();
4911  }
4912  uint16 num_ents = buf->ReadExtendedByte();
4913 
4914  if (feature >= GSF_END) {
4915  _cur.skip_sprites = num_sets * num_ents;
4916  grfmsg(1, "NewSpriteSet: Unsupported feature 0x%02X, skipping %d sprites", feature, _cur.skip_sprites);
4917  return;
4918  }
4919 
4920  _cur.AddSpriteSets(feature, _cur.spriteid, first_set, num_sets, num_ents);
4921 
4922  grfmsg(7, "New sprite set at %d of feature 0x%02X, consisting of %d sets with %d views each (total %d)",
4923  _cur.spriteid, feature, num_sets, num_ents, num_sets * num_ents
4924  );
4925 
4926  for (int i = 0; i < num_sets * num_ents; i++) {
4927  _cur.nfo_line++;
4928  LoadNextSprite(_cur.spriteid++, *_cur.file, _cur.nfo_line);
4929  }
4930 }
4931 
4932 /* Action 0x01 (SKIP) */
4933 static void SkipAct1(ByteReader *buf)
4934 {
4935  buf->ReadByte();
4936  uint16 num_sets = buf->ReadByte();
4937 
4938  if (num_sets == 0 && buf->HasData(3)) {
4939  /* Extended Action1 format.
4940  * Some GRFs define zero sets of zero sprites, though there is actually no use in that. Ignore them. */
4941  buf->ReadExtendedByte(); // first_set
4942  num_sets = buf->ReadExtendedByte();
4943  }
4944  uint16 num_ents = buf->ReadExtendedByte();
4945 
4946  _cur.skip_sprites = num_sets * num_ents;
4947 
4948  grfmsg(3, "SkipAct1: Skipping %d sprites", _cur.skip_sprites);
4949 }
4950 
4951 /* Helper function to either create a callback or link to a previously
4952  * defined spritegroup. */
4953 static const SpriteGroup *GetGroupFromGroupID(byte setid, byte type, uint16 groupid)
4954 {
4955  if (HasBit(groupid, 15)) {
4957  return new CallbackResultSpriteGroup(groupid, _cur.grffile->grf_version >= 8);
4958  }
4959 
4960  if (groupid > MAX_SPRITEGROUP || _cur.spritegroups[groupid] == nullptr) {
4961  grfmsg(1, "GetGroupFromGroupID(0x%02X:0x%02X): Groupid 0x%04X does not exist, leaving empty", setid, type, groupid);
4962  return nullptr;
4963  }
4964 
4965  return _cur.spritegroups[groupid];
4966 }
4967 
4976 static const SpriteGroup *CreateGroupFromGroupID(byte feature, byte setid, byte type, uint16 spriteid)
4977 {
4978  if (HasBit(spriteid, 15)) {
4980  return new CallbackResultSpriteGroup(spriteid, _cur.grffile->grf_version >= 8);
4981  }
4982 
4983  if (!_cur.IsValidSpriteSet(feature, spriteid)) {
4984  grfmsg(1, "CreateGroupFromGroupID(0x%02X:0x%02X): Sprite set %u invalid", setid, type, spriteid);
4985  return nullptr;
4986  }
4987 
4988  SpriteID spriteset_start = _cur.GetSprite(feature, spriteid);
4989  uint num_sprites = _cur.GetNumEnts(feature, spriteid);
4990 
4991  /* Ensure that the sprites are loeded */
4992  assert(spriteset_start + num_sprites <= _cur.spriteid);
4993 
4995  return new ResultSpriteGroup(spriteset_start, num_sprites);
4996 }
4997 
4998 /* Action 0x02 */
4999 static void NewSpriteGroup(ByteReader *buf)
5000 {
5001  /* <02> <feature> <set-id> <type/num-entries> <feature-specific-data...>
5002  *
5003  * B feature see action 1
5004  * B set-id ID of this particular definition
5005  * B type/num-entries
5006  * if 80 or greater, this is a randomized or variational
5007  * list definition, see below
5008  * otherwise it specifies a number of entries, the exact
5009  * meaning depends on the feature
5010  * V feature-specific-data (huge mess, don't even look it up --pasky) */
5011  const SpriteGroup *act_group = nullptr;
5012 
5013  uint8 feature = buf->ReadByte();
5014  if (feature >= GSF_END) {
5015  grfmsg(1, "NewSpriteGroup: Unsupported feature 0x%02X, skipping", feature);
5016  return;
5017  }
5018 
5019  uint8 setid = buf->ReadByte();
5020  uint8 type = buf->ReadByte();
5021 
5022  /* Sprite Groups are created here but they are allocated from a pool, so
5023  * we do not need to delete anything if there is an exception from the
5024  * ByteReader. */
5025 
5026  switch (type) {
5027  /* Deterministic Sprite Group */
5028  case 0x81: // Self scope, byte
5029  case 0x82: // Parent scope, byte
5030  case 0x85: // Self scope, word
5031  case 0x86: // Parent scope, word
5032  case 0x89: // Self scope, dword
5033  case 0x8A: // Parent scope, dword
5034  {
5035  byte varadjust;
5036  byte varsize;
5037 
5040  group->nfo_line = _cur.nfo_line;
5041  act_group = group;
5042  group->var_scope = HasBit(type, 1) ? VSG_SCOPE_PARENT : VSG_SCOPE_SELF;
5043 
5044  switch (GB(type, 2, 2)) {
5045  default: NOT_REACHED();
5046  case 0: group->size = DSG_SIZE_BYTE; varsize = 1; break;
5047  case 1: group->size = DSG_SIZE_WORD; varsize = 2; break;
5048  case 2: group->size = DSG_SIZE_DWORD; varsize = 4; break;
5049  }
5050 
5051  /* Loop through the var adjusts. Unfortunately we don't know how many we have
5052  * from the outset, so we shall have to keep reallocing. */
5053  do {
5054  DeterministicSpriteGroupAdjust &adjust = group->adjusts.emplace_back();
5055 
5056  /* The first var adjust doesn't have an operation specified, so we set it to add. */
5057  adjust.operation = group->adjusts.size() == 1 ? DSGA_OP_ADD : (DeterministicSpriteGroupAdjustOperation)buf->ReadByte();
5058  adjust.variable = buf->ReadByte();
5059  if (adjust.variable == 0x7E) {
5060  /* Link subroutine group */
5061  adjust.subroutine = GetGroupFromGroupID(setid, type, buf->ReadByte());
5062  } else {
5063  adjust.parameter = IsInsideMM(adjust.variable, 0x60, 0x80) ? buf->ReadByte() : 0;
5064  }
5065 
5066  varadjust = buf->ReadByte();
5067  adjust.shift_num = GB(varadjust, 0, 5);
5068  adjust.type = (DeterministicSpriteGroupAdjustType)GB(varadjust, 6, 2);
5069  adjust.and_mask = buf->ReadVarSize(varsize);
5070 
5071  if (adjust.type != DSGA_TYPE_NONE) {
5072  adjust.add_val = buf->ReadVarSize(varsize);
5073  adjust.divmod_val = buf->ReadVarSize(varsize);
5074  } else {
5075  adjust.add_val = 0;
5076  adjust.divmod_val = 0;
5077  }
5078 
5079  /* Continue reading var adjusts while bit 5 is set. */
5080  } while (HasBit(varadjust, 5));
5081 
5082  std::vector<DeterministicSpriteGroupRange> ranges;
5083  ranges.resize(buf->ReadByte());
5084  for (uint i = 0; i < ranges.size(); i++) {
5085  ranges[i].group = GetGroupFromGroupID(setid, type, buf->ReadWord());
5086  ranges[i].low = buf->ReadVarSize(varsize);
5087  ranges[i].high = buf->ReadVarSize(varsize);
5088  }
5089 
5090  group->default_group = GetGroupFromGroupID(setid, type, buf->ReadWord());
5091  group->error_group = ranges.size() > 0 ? ranges[0].group : group->default_group;
5092  /* nvar == 0 is a special case -- we turn our value into a callback result */
5093  group->calculated_result = ranges.size() == 0;
5094 
5095  /* Sort ranges ascending. When ranges overlap, this may required clamping or splitting them */
5096  std::vector<uint32> bounds;
5097  for (uint i = 0; i < ranges.size(); i++) {
5098  bounds.push_back(ranges[i].low);
5099  if (ranges[i].high != UINT32_MAX) bounds.push_back(ranges[i].high + 1);
5100  }
5101  std::sort(bounds.begin(), bounds.end());
5102  bounds.erase(std::unique(bounds.begin(), bounds.end()), bounds.end());
5103 
5104  std::vector<const SpriteGroup *> target;
5105  for (uint j = 0; j < bounds.size(); ++j) {
5106  uint32 v = bounds[j];
5107  const SpriteGroup *t = group->default_group;
5108  for (uint i = 0; i < ranges.size(); i++) {
5109  if (ranges[i].low <= v && v <= ranges[i].high) {
5110  t = ranges[i].group;
5111  break;
5112  }
5113  }
5114  target.push_back(t);
5115  }
5116  assert(target.size() == bounds.size());
5117 
5118  for (uint j = 0; j < bounds.size(); ) {
5119  if (target[j] != group->default_group) {
5120  DeterministicSpriteGroupRange &r = group->ranges.emplace_back();
5121  r.group = target[j];
5122  r.low = bounds[j];
5123  while (j < bounds.size() && target[j] == r.group) {
5124  j++;
5125  }
5126  r.high = j < bounds.size() ? bounds[j] - 1 : UINT32_MAX;
5127  } else {
5128  j++;
5129  }
5130  }
5131 
5132  break;
5133  }
5134 
5135  /* Randomized Sprite Group */
5136  case 0x80: // Self scope
5137  case 0x83: // Parent scope
5138  case 0x84: // Relative scope
5139  {
5142  group->nfo_line = _cur.nfo_line;
5143  act_group = group;
5144  group->var_scope = HasBit(type, 1) ? VSG_SCOPE_PARENT : VSG_SCOPE_SELF;
5145 
5146  if (HasBit(type, 2)) {
5147  if (feature <= GSF_AIRCRAFT) group->var_scope = VSG_SCOPE_RELATIVE;
5148  group->count = buf->ReadByte();
5149  }
5150 
5151  uint8 triggers = buf->ReadByte();
5152  group->triggers = GB(triggers, 0, 7);
5153  group->cmp_mode = HasBit(triggers, 7) ? RSG_CMP_ALL : RSG_CMP_ANY;
5154  group->lowest_randbit = buf->ReadByte();
5155 
5156  byte num_groups = buf->ReadByte();
5157  if (!HasExactlyOneBit(num_groups)) {
5158  grfmsg(1, "NewSpriteGroup: Random Action 2 nrand should be power of 2");
5159  }
5160 
5161  for (uint i = 0; i < num_groups; i++) {
5162  group->groups.push_back(GetGroupFromGroupID(setid, type, buf->ReadWord()));
5163  }
5164 
5165  break;
5166  }
5167 
5168  /* Neither a variable or randomized sprite group... must be a real group */
5169  default:
5170  {
5171  switch (feature) {
5172  case GSF_TRAINS:
5173  case GSF_ROADVEHICLES:
5174  case GSF_SHIPS:
5175  case GSF_AIRCRAFT:
5176  case GSF_STATIONS:
5177  case GSF_CANALS:
5178  case GSF_CARGOES:
5179  case GSF_AIRPORTS:
5180  case GSF_RAILTYPES:
5181  case GSF_ROADTYPES:
5182  case GSF_TRAMTYPES:
5183  {
5184  byte num_loaded = type;
5185  byte num_loading = buf->ReadByte();
5186 
5187  if (!_cur.HasValidSpriteSets(feature)) {
5188  grfmsg(0, "NewSpriteGroup: No sprite set to work on! Skipping");
5189  return;
5190  }
5191 
5192  grfmsg(6, "NewSpriteGroup: New SpriteGroup 0x%02X, %u loaded, %u loading",
5193  setid, num_loaded, num_loading);
5194 
5195  if (num_loaded + num_loading == 0) {
5196  grfmsg(1, "NewSpriteGroup: no result, skipping invalid RealSpriteGroup");
5197  break;
5198  }
5199 
5200  if (num_loaded + num_loading == 1) {
5201  /* Avoid creating 'Real' sprite group if only one option. */
5202  uint16 spriteid = buf->ReadWord();
5203  act_group = CreateGroupFromGroupID(feature, setid, type, spriteid);
5204  grfmsg(8, "NewSpriteGroup: one result, skipping RealSpriteGroup = subset %u", spriteid);
5205  break;
5206  }
5207 
5208  std::vector<uint16> loaded;
5209  std::vector<uint16> loading;
5210 
5211  for (uint i = 0; i < num_loaded; i++) {
5212  loaded.push_back(buf->ReadWord());
5213  grfmsg(8, "NewSpriteGroup: + rg->loaded[%i] = subset %u", i, loaded[i]);
5214  }
5215 
5216  for (uint i = 0; i < num_loading; i++) {
5217  loading.push_back(buf->ReadWord());
5218  grfmsg(8, "NewSpriteGroup: + rg->loading[%i] = subset %u", i, loading[i]);
5219  }
5220 
5221  if (std::adjacent_find(loaded.begin(), loaded.end(), std::not_equal_to<>()) == loaded.end() &&
5222  std::adjacent_find(loading.begin(), loading.end(), std::not_equal_to<>()) == loading.end() &&
5223  loaded[0] == loading[0])
5224  {
5225  /* Both lists only contain the same value, so don't create 'Real' sprite group */
5226  act_group = CreateGroupFromGroupID(feature, setid, type, loaded[0]);
5227  grfmsg(8, "NewSpriteGroup: same result, skipping RealSpriteGroup = subset %u", loaded[0]);
5228  break;
5229  }
5230 
5232  RealSpriteGroup *group = new RealSpriteGroup();
5233  group->nfo_line = _cur.nfo_line;
5234  act_group = group;
5235 
5236  for (uint16 spriteid : loaded) {
5237  const SpriteGroup *t = CreateGroupFromGroupID(feature, setid, type, spriteid);
5238  group->loaded.push_back(t);
5239  }
5240 
5241  for (uint16 spriteid : loading) {
5242  const SpriteGroup *t = CreateGroupFromGroupID(feature, setid, type, spriteid);
5243  group->loading.push_back(t);
5244  }
5245 
5246  break;
5247  }
5248 
5249  case GSF_HOUSES:
5250  case GSF_AIRPORTTILES:
5251  case GSF_OBJECTS:
5252  case GSF_INDUSTRYTILES: {
5253  byte num_building_sprites = std::max((uint8)1, type);
5254 
5257  group->nfo_line = _cur.nfo_line;
5258  act_group = group;
5259 
5260  /* On error, bail out immediately. Temporary GRF data was already freed */
5261  if (ReadSpriteLayout(buf, num_building_sprites, true, feature, false, type == 0, &group->dts)) return;
5262  break;
5263  }
5264 
5265  case GSF_INDUSTRIES: {
5266  if (type > 2) {
5267  grfmsg(1, "NewSpriteGroup: Unsupported industry production version %d, skipping", type);
5268  break;
5269  }
5270 
5273  group->nfo_line = _cur.nfo_line;
5274  act_group = group;
5275  group->version = type;
5276  if (type == 0) {
5277  group->num_input = 3;
5278  for (uint i = 0; i < 3; i++) {
5279  group->subtract_input[i] = (int16)buf->ReadWord(); // signed
5280  }
5281  group->num_output = 2;
5282  for (uint i = 0; i < 2; i++) {
5283  group->add_output[i] = buf->ReadWord(); // unsigned
5284  }
5285  group->again = buf->ReadByte();
5286  } else if (type == 1) {
5287  group->num_input = 3;
5288  for (uint i = 0; i < 3; i++) {
5289  group->subtract_input[i] = buf->ReadByte();
5290  }
5291  group->num_output = 2;
5292  for (uint i = 0; i < 2; i++) {
5293  group->add_output[i] = buf->ReadByte();
5294  }
5295  group->again = buf->ReadByte();
5296  } else if (type == 2) {
5297  group->num_input = buf->ReadByte();
5298  if (group->num_input > lengthof(group->subtract_input)) {
5299  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK);
5300  error->data = "too many inputs (max 16)";
5301  return;
5302  }
5303  for (uint i = 0; i < group->num_input; i++) {
5304  byte rawcargo = buf->ReadByte();
5305  CargoID cargo = GetCargoTranslation(rawcargo, _cur.grffile);
5306  if (cargo == CT_INVALID) {
5307  /* The mapped cargo is invalid. This is permitted at this point,
5308  * as long as the result is not used. Mark it invalid so this
5309  * can be tested later. */
5310  group->version = 0xFF;
5311  } else if (std::find(group->cargo_input, group->cargo_input + i, cargo) != group->cargo_input + i) {
5312  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK);
5313  error->data = "duplicate input cargo";
5314  return;
5315  }
5316  group->cargo_input[i] = cargo;
5317  group->subtract_input[i] = buf->ReadByte();
5318  }
5319  group->num_output = buf->ReadByte();
5320  if (group->num_output > lengthof(group->add_output)) {
5321  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK);
5322  error->data = "too many outputs (max 16)";
5323  return;
5324  }
5325  for (uint i = 0; i < group->num_output; i++) {
5326  byte rawcargo = buf->ReadByte();
5327  CargoID cargo = GetCargoTranslation(rawcargo, _cur.grffile);
5328  if (cargo == CT_INVALID) {
5329  /* Mark this result as invalid to use */
5330  group->version = 0xFF;
5331  } else if (std::find(group->cargo_output, group->cargo_output + i, cargo) != group->cargo_output + i) {
5332  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK);
5333  error->data = "duplicate output cargo";
5334  return;
5335  }
5336  group->cargo_output[i] = cargo;
5337  group->add_output[i] = buf->ReadByte();
5338  }
5339  group->again = buf->ReadByte();
5340  } else {
5341  NOT_REACHED();
5342  }
5343  break;
5344  }
5345 
5346  /* Loading of Tile Layout and Production Callback groups would happen here */
5347  default: grfmsg(1, "NewSpriteGroup: Unsupported feature 0x%02X, skipping", feature);
5348  }
5349  }
5350  }
5351 
5352  _cur.spritegroups[setid] = act_group;
5353 }
5354 
5355 static CargoID TranslateCargo(uint8 feature, uint8 ctype)
5356 {
5357  if (feature == GSF_OBJECTS) {
5358  switch (ctype) {
5359  case 0: return 0;
5360  case 0xFF: return CT_PURCHASE_OBJECT;
5361  default:
5362  grfmsg(1, "TranslateCargo: Invalid cargo bitnum %d for objects, skipping.", ctype);
5363  return CT_INVALID;
5364  }
5365  }
5366  /* Special cargo types for purchase list and stations */
5367  if (feature == GSF_STATIONS && ctype == 0xFE) return CT_DEFAULT_NA;
5368  if (ctype == 0xFF) return CT_PURCHASE;
5369 
5370  if (_cur.grffile->cargo_list.size() == 0) {
5371  /* No cargo table, so use bitnum values */
5372  if (ctype >= 32) {
5373  grfmsg(1, "TranslateCargo: Cargo bitnum %d out of range (max 31), skipping.", ctype);
5374  return CT_INVALID;
5375  }
5376 
5377  for (const CargoSpec *cs : CargoSpec::Iterate()) {
5378  if (cs->bitnum == ctype) {
5379  grfmsg(6, "TranslateCargo: Cargo bitnum %d mapped to cargo type %d.", ctype, cs->Index());
5380  return cs->Index();
5381  }
5382  }
5383 
5384  grfmsg(5, "TranslateCargo: Cargo bitnum %d not available in this climate, skipping.", ctype);
5385  return CT_INVALID;
5386  }
5387 
5388  /* Check if the cargo type is out of bounds of the cargo translation table */
5389  if (ctype >= _cur.grffile->cargo_list.size()) {
5390  grfmsg(1, "TranslateCargo: Cargo type %d out of range (max %d), skipping.", ctype, (unsigned int)_cur.grffile->cargo_list.size() - 1);
5391  return CT_INVALID;
5392  }
5393 
5394  /* Look up the cargo label from the translation table */
5395  CargoLabel cl = _cur.grffile->cargo_list[ctype];
5396  if (cl == 0) {
5397  grfmsg(5, "TranslateCargo: Cargo type %d not available in this climate, skipping.", ctype);
5398  return CT_INVALID;
5399  }
5400 
5401  ctype = GetCargoIDByLabel(cl);
5402  if (ctype == CT_INVALID) {
5403  grfmsg(5, "TranslateCargo: Cargo '%c%c%c%c' unsupported, skipping.", GB(cl, 24, 8), GB(cl, 16, 8), GB(cl, 8, 8), GB(cl, 0, 8));
5404  return CT_INVALID;
5405  }
5406 
5407  grfmsg(6, "TranslateCargo: Cargo '%c%c%c%c' mapped to cargo type %d.", GB(cl, 24, 8), GB(cl, 16, 8), GB(cl, 8, 8), GB(cl, 0, 8), ctype);
5408  return ctype;
5409 }
5410 
5411 
5412 static bool IsValidGroupID(uint16 groupid, const char *function)
5413 {
5414  if (groupid > MAX_SPRITEGROUP || _cur.spritegroups[groupid] == nullptr) {
5415  grfmsg(1, "%s: Spritegroup 0x%04X out of range or empty, skipping.", function, groupid);
5416  return false;
5417  }
5418 
5419  return true;
5420 }
5421 
5422 static void VehicleMapSpriteGroup(ByteReader *buf, byte feature, uint8 idcount)
5423 {
5424  static EngineID *last_engines;
5425  static uint last_engines_count;
5426  bool wagover = false;
5427 
5428  /* Test for 'wagon override' flag */
5429  if (HasBit(idcount, 7)) {
5430  wagover = true;
5431  /* Strip off the flag */
5432  idcount = GB(idcount, 0, 7);
5433 
5434  if (last_engines_count == 0) {
5435  grfmsg(0, "VehicleMapSpriteGroup: WagonOverride: No engine to do override with");
5436  return;
5437  }
5438 
5439  grfmsg(6, "VehicleMapSpriteGroup: WagonOverride: %u engines, %u wagons",
5440  last_engines_count, idcount);
5441  } else {
5442  if (last_engines_count != idcount) {
5443  last_engines = ReallocT(last_engines, idcount);
5444  last_engines_count = idcount;
5445  }
5446  }
5447 
5448  EngineID *engines = AllocaM(EngineID, idcount);
5449  for (uint i = 0; i < idcount; i++) {
5450  Engine *e = GetNewEngine(_cur.grffile, (VehicleType)feature, buf->ReadExtendedByte());
5451  if (e == nullptr) {
5452  /* No engine could be allocated?!? Deal with it. Okay,
5453  * this might look bad. Also make sure this NewGRF
5454  * gets disabled, as a half loaded one is bad. */
5455  HandleChangeInfoResult("VehicleMapSpriteGroup", CIR_INVALID_ID, 0, 0);
5456  return;
5457  }
5458 
5459  engines[i] = e->index;
5460  if (!wagover) last_engines[i] = engines[i];
5461  }
5462 
5463  uint8 cidcount = buf->ReadByte();
5464  for (uint c = 0; c < cidcount; c++) {
5465  uint8 ctype = buf->ReadByte();
5466  uint16 groupid = buf->ReadWord();
5467  if (!IsValidGroupID(groupid, "VehicleMapSpriteGroup")) continue;
5468 
5469  grfmsg(8, "VehicleMapSpriteGroup: * [%d] Cargo type 0x%X, group id 0x%02X", c, ctype, groupid);
5470 
5471  ctype = TranslateCargo(feature, ctype);
5472  if (ctype == CT_INVALID) continue;
5473 
5474  for (uint i = 0; i < idcount; i++) {
5475  EngineID engine = engines[i];
5476 
5477  grfmsg(7, "VehicleMapSpriteGroup: [%d] Engine %d...", i, engine);
5478 
5479  if (wagover) {
5480  SetWagonOverrideSprites(engine, ctype, _cur.spritegroups[groupid], last_engines, last_engines_count);
5481  } else {
5482  SetCustomEngineSprites(engine, ctype, _cur.spritegroups[groupid]);
5483  }
5484  }
5485  }
5486 
5487  uint16 groupid = buf->ReadWord();
5488  if (!IsValidGroupID(groupid, "VehicleMapSpriteGroup")) return;
5489 
5490  grfmsg(8, "-- Default group id 0x%04X", groupid);
5491 
5492  for (uint i = 0; i < idcount; i++) {
5493  EngineID engine = engines[i];
5494 
5495  if (wagover) {
5496  SetWagonOverrideSprites(engine, CT_DEFAULT, _cur.spritegroups[groupid], last_engines, last_engines_count);
5497  } else {
5498  SetCustomEngineSprites(engine, CT_DEFAULT, _cur.spritegroups[groupid]);
5499  SetEngineGRF(engine, _cur.grffile);
5500  }
5501  }
5502 }
5503 
5504 
5505 static void CanalMapSpriteGroup(ByteReader *buf, uint8 idcount)
5506 {
5507  CanalFeature *cfs = AllocaM(CanalFeature, idcount);
5508  for (uint i = 0; i < idcount; i++) {
5509  cfs[i] = (CanalFeature)buf->ReadByte();
5510  }
5511 
5512  uint8 cidcount = buf->ReadByte();
5513  buf->Skip(cidcount * 3);
5514 
5515  uint16 groupid = buf->ReadWord();
5516  if (!IsValidGroupID(groupid, "CanalMapSpriteGroup")) return;
5517 
5518  for (uint i = 0; i < idcount; i++) {
5519  CanalFeature cf = cfs[i];
5520 
5521  if (cf >= CF_END) {
5522  grfmsg(1, "CanalMapSpriteGroup: Canal subset %d out of range, skipping", cf);
5523  continue;
5524  }
5525 
5526  _water_feature[cf].grffile = _cur.grffile;
5527  _water_feature[cf].group = _cur.spritegroups[groupid];
5528  }
5529 }
5530 
5531 
5532 static void StationMapSpriteGroup(ByteReader *buf, uint8 idcount)
5533 {
5534  uint8 *stations = AllocaM(uint8, idcount);
5535  for (uint i = 0; i < idcount; i++) {
5536  stations[i] = buf->ReadByte();
5537  }
5538 
5539  uint8 cidcount = buf->ReadByte();
5540  for (uint c = 0; c < cidcount; c++) {
5541  uint8 ctype = buf->ReadByte();
5542  uint16 groupid = buf->ReadWord();
5543  if (!IsValidGroupID(groupid, "StationMapSpriteGroup")) continue;
5544 
5545  ctype = TranslateCargo(GSF_STATIONS, ctype);
5546  if (ctype == CT_INVALID) continue;
5547 
5548  for (uint i = 0; i < idcount; i++) {
5549  StationSpec *statspec = _cur.grffile->stations == nullptr ? nullptr : _cur.grffile->stations[stations[i]];
5550 
5551  if (statspec == nullptr) {
5552  grfmsg(1, "StationMapSpriteGroup: Station with ID 0x%02X does not exist, skipping", stations[i]);
5553  continue;
5554  }
5555 
5556  statspec->grf_prop.spritegroup[ctype] = _cur.spritegroups[groupid];
5557  }
5558  }
5559 
5560  uint16 groupid = buf->ReadWord();
5561  if (!IsValidGroupID(groupid, "StationMapSpriteGroup")) return;
5562 
5563  for (uint i = 0; i < idcount; i++) {
5564  StationSpec *statspec = _cur.grffile->stations == nullptr ? nullptr : _cur.grffile->stations[stations[i]];
5565 
5566  if (statspec == nullptr) {
5567  grfmsg(1, "StationMapSpriteGroup: Station with ID 0x%02X does not exist, skipping", stations[i]);
5568  continue;
5569  }
5570 
5571  if (statspec->grf_prop.grffile != nullptr) {
5572  grfmsg(1, "StationMapSpriteGroup: Station with ID 0x%02X mapped multiple times, skipping", stations[i]);
5573  continue;
5574  }
5575 
5576  statspec->grf_prop.spritegroup[CT_DEFAULT] = _cur.spritegroups[groupid];
5577  statspec->grf_prop.grffile = _cur.grffile;
5578  statspec->grf_prop.local_id = stations[i];
5579  StationClass::Assign(statspec);
5580  }
5581 }
5582 
5583 
5584 static void TownHouseMapSpriteGroup(ByteReader *buf, uint8 idcount)
5585 {
5586  uint8 *houses = AllocaM(uint8, idcount);
5587  for (uint i = 0; i < idcount; i++) {
5588  houses[i] = buf->ReadByte();
5589  }
5590 
5591  /* Skip the cargo type section, we only care about the default group */
5592  uint8 cidcount = buf->ReadByte();
5593  buf->Skip(cidcount * 3);
5594 
5595  uint16 groupid = buf->ReadWord();
5596  if (!IsValidGroupID(groupid, "TownHouseMapSpriteGroup")) return;
5597 
5598  if (_cur.grffile->housespec == nullptr) {
5599  grfmsg(1, "TownHouseMapSpriteGroup: No houses defined, skipping");
5600  return;
5601  }
5602 
5603  for (uint i = 0; i < idcount; i++) {
5604  HouseSpec *hs = _cur.grffile->housespec[houses[i]];
5605 
5606  if (hs == nullptr) {
5607  grfmsg(1, "TownHouseMapSpriteGroup: House %d undefined, skipping.", houses[i]);
5608  continue;
5609  }
5610 
5611  hs->grf_prop.spritegroup[0] = _cur.spritegroups[groupid];
5612  }
5613 }
5614 
5615 static void IndustryMapSpriteGroup(ByteReader *buf, uint8 idcount)
5616 {
5617  uint8 *industries = AllocaM(uint8, idcount);
5618  for (uint i = 0; i < idcount; i++) {
5619  industries[i] = buf->ReadByte();
5620  }
5621 
5622  /* Skip the cargo type section, we only care about the default group */
5623  uint8 cidcount = buf->ReadByte();
5624  buf->Skip(cidcount * 3);
5625 
5626  uint16 groupid = buf->ReadWord();
5627  if (!IsValidGroupID(groupid, "IndustryMapSpriteGroup")) return;
5628 
5629  if (_cur.grffile->industryspec == nullptr) {
5630  grfmsg(1, "IndustryMapSpriteGroup: No industries defined, skipping");
5631  return;
5632  }
5633 
5634  for (uint i = 0; i < idcount; i++) {
5635  IndustrySpec *indsp = _cur.grffile->industryspec[industries[i]];
5636 
5637  if (indsp == nullptr) {
5638  grfmsg(1, "IndustryMapSpriteGroup: Industry %d undefined, skipping", industries[i]);
5639  continue;
5640  }
5641 
5642  indsp->grf_prop.spritegroup[0] = _cur.spritegroups[groupid];
5643  }
5644 }
5645 
5646 static void IndustrytileMapSpriteGroup(ByteReader *buf, uint8 idcount)
5647 {
5648  uint8 *indtiles = AllocaM(uint8, idcount);
5649  for (uint i = 0; i < idcount; i++) {
5650  indtiles[i] = buf->ReadByte();
5651  }
5652 
5653  /* Skip the cargo type section, we only care about the default group */
5654  uint8 cidcount = buf->ReadByte();
5655  buf->Skip(cidcount * 3);
5656 
5657  uint16 groupid = buf->ReadWord();
5658  if (!IsValidGroupID(groupid, "IndustrytileMapSpriteGroup")) return;
5659 
5660  if (_cur.grffile->indtspec == nullptr) {
5661  grfmsg(1, "IndustrytileMapSpriteGroup: No industry tiles defined, skipping");
5662  return;
5663  }
5664 
5665  for (uint i = 0; i < idcount; i++) {
5666  IndustryTileSpec *indtsp = _cur.grffile->indtspec[indtiles[i]];
5667 
5668  if (indtsp == nullptr) {
5669  grfmsg(1, "IndustrytileMapSpriteGroup: Industry tile %d undefined, skipping", indtiles[i]);
5670  continue;
5671  }
5672 
5673  indtsp->grf_prop.spritegroup[0] = _cur.spritegroups[groupid];
5674  }
5675 }
5676 
5677 static void CargoMapSpriteGroup(ByteReader *buf, uint8 idcount)
5678 {
5679  CargoID *cargoes = AllocaM(CargoID, idcount);
5680  for (uint i = 0; i < idcount; i++) {
5681  cargoes[i] = buf->ReadByte();
5682  }
5683 
5684  /* Skip the cargo type section, we only care about the default group */
5685  uint8 cidcount = buf->ReadByte();
5686  buf->Skip(cidcount * 3);
5687 
5688  uint16 groupid = buf->ReadWord();
5689  if (!IsValidGroupID(groupid, "CargoMapSpriteGroup")) return;
5690 
5691  for (uint i = 0; i < idcount; i++) {
5692  CargoID cid = cargoes[i];
5693 
5694  if (cid >= NUM_CARGO) {
5695  grfmsg(1, "CargoMapSpriteGroup: Cargo ID %d out of range, skipping", cid);
5696  continue;
5697  }
5698 
5699  CargoSpec *cs = CargoSpec::Get(cid);
5700  cs->grffile = _cur.grffile;
5701  cs->group = _cur.spritegroups[groupid];
5702  }
5703 }
5704 
5705 static void ObjectMapSpriteGroup(ByteReader *buf, uint8 idcount)
5706 {
5707  if (_cur.grffile->objectspec == nullptr) {
5708  grfmsg(1, "ObjectMapSpriteGroup: No object tiles defined, skipping");
5709  return;
5710  }
5711 
5712  uint8 *objects = AllocaM(uint8, idcount);
5713  for (uint i = 0; i < idcount; i++) {
5714  objects[i] = buf->ReadByte();
5715  }
5716 
5717  uint8 cidcount = buf->ReadByte();
5718  for (uint c = 0; c < cidcount; c++) {
5719  uint8 ctype = buf->ReadByte();
5720  uint16 groupid = buf->ReadWord();
5721  if (!IsValidGroupID(groupid, "ObjectMapSpriteGroup")) continue;
5722 
5723  ctype = TranslateCargo(GSF_OBJECTS, ctype);
5724  if (ctype == CT_INVALID) continue;
5725 
5726  for (uint i = 0; i < idcount; i++) {
5727  ObjectSpec *spec = _cur.grffile->objectspec[objects[i]];
5728 
5729  if (spec == nullptr) {
5730  grfmsg(1, "ObjectMapSpriteGroup: Object with ID 0x%02X undefined, skipping", objects[i]);
5731  continue;
5732  }
5733 
5734  spec->grf_prop.spritegroup[ctype] = _cur.spritegroups[groupid];
5735  }
5736  }
5737 
5738  uint16 groupid = buf->ReadWord();
5739  if (!IsValidGroupID(groupid, "ObjectMapSpriteGroup")) return;
5740 
5741  for (uint i = 0; i < idcount; i++) {
5742  ObjectSpec *spec = _cur.grffile->objectspec[objects[i]];
5743 
5744  if (spec == nullptr) {
5745  grfmsg(1, "ObjectMapSpriteGroup: Object with ID 0x%02X undefined, skipping", objects[i]);
5746  continue;
5747  }
5748 
5749  if (spec->grf_prop.grffile != nullptr) {
5750  grfmsg(1, "ObjectMapSpriteGroup: Object with ID 0x%02X mapped multiple times, skipping", objects[i]);
5751  continue;
5752  }
5753 
5754  spec->grf_prop.spritegroup[0] = _cur.spritegroups[groupid];
5755  spec->grf_prop.grffile = _cur.grffile;
5756  spec->grf_prop.local_id = objects[i];
5757  }
5758 }
5759 
5760 static void RailTypeMapSpriteGroup(ByteReader *buf, uint8 idcount)
5761 {
5762  uint8 *railtypes = AllocaM(uint8, idcount);
5763  for (uint i = 0; i < idcount; i++) {
5764  uint8 id = buf->ReadByte();
5765  railtypes[i] = id < RAILTYPE_END ? _cur.grffile->railtype_map[id] : INVALID_RAILTYPE;
5766  }
5767 
5768  uint8 cidcount = buf->ReadByte();
5769  for (uint c = 0; c < cidcount; c++) {
5770  uint8 ctype = buf->ReadByte();
5771  uint16 groupid = buf->ReadWord();
5772  if (!IsValidGroupID(groupid, "RailTypeMapSpriteGroup")) continue;
5773 
5774  if (ctype >= RTSG_END) continue;
5775 
5776  extern RailtypeInfo _railtypes[RAILTYPE_END];
5777  for (uint i = 0; i < idcount; i++) {
5778  if (railtypes[i] != INVALID_RAILTYPE) {
5779  RailtypeInfo *rti = &_railtypes[railtypes[i]];
5780 
5781  rti->grffile[ctype] = _cur.grffile;
5782  rti->group[ctype] = _cur.spritegroups[groupid];
5783  }
5784  }
5785  }
5786 
5787  /* Railtypes do not use the default group. */
5788  buf->ReadWord();
5789 }
5790 
5791 static void RoadTypeMapSpriteGroup(ByteReader *buf, uint8 idcount, RoadTramType rtt)
5792 {
5793  RoadType *type_map = (rtt == RTT_TRAM) ? _cur.grffile->tramtype_map : _cur.grffile->roadtype_map;
5794 
5795  uint8 *roadtypes = AllocaM(uint8, idcount);
5796  for (uint i = 0; i < idcount; i++) {
5797  uint8 id = buf->ReadByte();
5798  roadtypes[i] = id < ROADTYPE_END ? type_map[id] : INVALID_ROADTYPE;
5799  }
5800 
5801  uint8 cidcount = buf->ReadByte();
5802  for (uint c = 0; c < cidcount; c++) {
5803  uint8 ctype = buf->ReadByte();
5804  uint16 groupid = buf->ReadWord();
5805  if (!IsValidGroupID(groupid, "RoadTypeMapSpriteGroup")) continue;
5806 
5807  if (ctype >= ROTSG_END) continue;
5808 
5809  extern RoadTypeInfo _roadtypes[ROADTYPE_END];
5810  for (uint i = 0; i < idcount; i++) {
5811  if (roadtypes[i] != INVALID_ROADTYPE) {
5812  RoadTypeInfo *rti = &_roadtypes[roadtypes[i]];
5813 
5814  rti->grffile[ctype] = _cur.grffile;
5815  rti->group[ctype] = _cur.spritegroups[groupid];
5816  }
5817  }
5818  }
5819 
5820  /* Roadtypes do not use the default group. */
5821  buf->ReadWord();
5822 }
5823 
5824 static void AirportMapSpriteGroup(ByteReader *buf, uint8 idcount)
5825 {
5826  uint8 *airports = AllocaM(uint8, idcount);
5827  for (uint i = 0; i < idcount; i++) {
5828  airports[i] = buf->ReadByte();
5829  }
5830 
5831  /* Skip the cargo type section, we only care about the default group */
5832  uint8 cidcount = buf->ReadByte();
5833  buf->Skip(cidcount * 3);
5834 
5835  uint16 groupid = buf->ReadWord();
5836  if (!IsValidGroupID(groupid, "AirportMapSpriteGroup")) return;
5837 
5838  if (_cur.grffile->airportspec == nullptr) {
5839  grfmsg(1, "AirportMapSpriteGroup: No airports defined, skipping");
5840  return;
5841  }
5842 
5843  for (uint i = 0; i < idcount; i++) {
5844  AirportSpec *as = _cur.grffile->airportspec[airports[i]];
5845 
5846  if (as == nullptr) {
5847  grfmsg(1, "AirportMapSpriteGroup: Airport %d undefined, skipping", airports[i]);
5848  continue;
5849  }
5850 
5851  as->grf_prop.spritegroup[0] = _cur.spritegroups[groupid];
5852  }
5853 }
5854 
5855 static void AirportTileMapSpriteGroup(ByteReader *buf, uint8 idcount)
5856 {
5857  uint8 *airptiles = AllocaM(uint8, idcount);
5858  for (uint i = 0; i < idcount; i++) {
5859  airptiles[i] = buf->ReadByte();
5860  }
5861 
5862  /* Skip the cargo type section, we only care about the default group */
5863  uint8 cidcount = buf->ReadByte();
5864  buf->Skip(cidcount * 3);
5865 
5866  uint16 groupid = buf->ReadWord();
5867  if (!IsValidGroupID(groupid, "AirportTileMapSpriteGroup")) return;
5868 
5869  if (_cur.grffile->airtspec == nullptr) {
5870  grfmsg(1, "AirportTileMapSpriteGroup: No airport tiles defined, skipping");
5871  return;
5872  }
5873 
5874  for (uint i = 0; i < idcount; i++) {
5875  AirportTileSpec *airtsp = _cur.grffile->airtspec[airptiles[i]];
5876 
5877  if (airtsp == nullptr) {
5878  grfmsg(1, "AirportTileMapSpriteGroup: Airport tile %d undefined, skipping", airptiles[i]);
5879  continue;
5880  }
5881 
5882  airtsp->grf_prop.spritegroup[0] = _cur.spritegroups[groupid];
5883  }
5884 }
5885 
5886 
5887 /* Action 0x03 */
5888 static void FeatureMapSpriteGroup(ByteReader *buf)
5889 {
5890  /* <03> <feature> <n-id> <ids>... <num-cid> [<cargo-type> <cid>]... <def-cid>
5891  * id-list := [<id>] [id-list]
5892  * cargo-list := <cargo-type> <cid> [cargo-list]
5893  *
5894  * B feature see action 0
5895  * B n-id bits 0-6: how many IDs this definition applies to
5896  * bit 7: if set, this is a wagon override definition (see below)
5897  * B ids the IDs for which this definition applies
5898  * B num-cid number of cargo IDs (sprite group IDs) in this definition
5899  * can be zero, in that case the def-cid is used always
5900  * B cargo-type type of this cargo type (e.g. mail=2, wood=7, see below)
5901  * W cid cargo ID (sprite group ID) for this type of cargo
5902  * W def-cid default cargo ID (sprite group ID) */
5903 
5904  uint8 feature = buf->ReadByte();
5905  uint8 idcount = buf->ReadByte();
5906 
5907  if (feature >= GSF_END) {
5908  grfmsg(1, "FeatureMapSpriteGroup: Unsupported feature 0x%02X, skipping", feature);
5909  return;
5910  }
5911 
5912  /* If idcount is zero, this is a feature callback */
5913  if (idcount == 0) {
5914  /* Skip number of cargo ids? */
5915  buf->ReadByte();
5916  uint16 groupid = buf->ReadWord();
5917  if (!IsValidGroupID(groupid, "FeatureMapSpriteGroup")) return;
5918 
5919  grfmsg(6, "FeatureMapSpriteGroup: Adding generic feature callback for feature 0x%02X", feature);
5920 
5921  AddGenericCallback(feature, _cur.grffile, _cur.spritegroups[groupid]);
5922  return;
5923  }
5924 
5925  /* Mark the feature as used by the grf (generic callbacks do not count) */
5926  SetBit(_cur.grffile->grf_features, feature);
5927 
5928  grfmsg(6, "FeatureMapSpriteGroup: Feature 0x%02X, %d ids", feature, idcount);
5929 
5930  switch (feature) {
5931  case GSF_TRAINS:
5932  case GSF_ROADVEHICLES:
5933  case GSF_SHIPS:
5934  case GSF_AIRCRAFT:
5935  VehicleMapSpriteGroup(buf, feature, idcount);
5936  return;
5937 
5938  case GSF_CANALS:
5939  CanalMapSpriteGroup(buf, idcount);
5940  return;
5941 
5942  case GSF_STATIONS:
5943  StationMapSpriteGroup(buf, idcount);
5944  return;
5945 
5946  case GSF_HOUSES:
5947  TownHouseMapSpriteGroup(buf, idcount);
5948  return;
5949 
5950  case GSF_INDUSTRIES:
5951  IndustryMapSpriteGroup(buf, idcount);
5952  return;
5953 
5954  case GSF_INDUSTRYTILES:
5955  IndustrytileMapSpriteGroup(buf, idcount);
5956  return;
5957 
5958  case GSF_CARGOES:
5959  CargoMapSpriteGroup(buf, idcount);
5960  return;
5961 
5962  case GSF_AIRPORTS:
5963  AirportMapSpriteGroup(buf, idcount);
5964  return;
5965 
5966  case GSF_OBJECTS:
5967  ObjectMapSpriteGroup(buf, idcount);
5968  break;
5969 
5970  case GSF_RAILTYPES:
5971  RailTypeMapSpriteGroup(buf, idcount);
5972  break;
5973 
5974  case GSF_ROADTYPES:
5975  RoadTypeMapSpriteGroup(buf, idcount, RTT_ROAD);
5976  break;
5977 
5978  case GSF_TRAMTYPES:
5979  RoadTypeMapSpriteGroup(buf, idcount, RTT_TRAM);
5980  break;
5981 
5982  case GSF_AIRPORTTILES:
5983  AirportTileMapSpriteGroup(buf, idcount);
5984  return;
5985 
5986  default:
5987  grfmsg(1, "FeatureMapSpriteGroup: Unsupported feature 0x%02X, skipping", feature);
5988  return;
5989  }
5990 }
5991 
5992 /* Action 0x04 */
5993 static void FeatureNewName(ByteReader *buf)
5994 {
5995  /* <04> <veh-type> <language-id> <num-veh> <offset> <data...>
5996  *
5997  * B veh-type see action 0 (as 00..07, + 0A
5998  * But IF veh-type = 48, then generic text
5999  * B language-id If bit 6 is set, This is the extended language scheme,
6000  * with up to 64 language.
6001  * Otherwise, it is a mapping where set bits have meaning
6002  * 0 = american, 1 = english, 2 = german, 3 = french, 4 = spanish
6003  * Bit 7 set means this is a generic text, not a vehicle one (or else)
6004  * B num-veh number of vehicles which are getting a new name
6005  * B/W offset number of the first vehicle that gets a new name
6006  * Byte : ID of vehicle to change
6007  * Word : ID of string to change/add
6008  * S data new texts, each of them zero-terminated, after
6009  * which the next name begins. */
6010 
6011  bool new_scheme = _cur.grffile->grf_version >= 7;
6012 
6013  uint8 feature = buf->ReadByte();
6014  if (feature >= GSF_END && feature != 0x48) {
6015  grfmsg(1, "FeatureNewName: Unsupported feature 0x%02X, skipping", feature);
6016  return;
6017  }
6018 
6019  uint8 lang = buf->ReadByte();
6020  uint8 num = buf->ReadByte();
6021  bool generic = HasBit(lang, 7);
6022  uint16 id;
6023  if (generic) {
6024  id = buf->ReadWord();
6025  } else if (feature <= GSF_AIRCRAFT) {
6026  id = buf->ReadExtendedByte();
6027  } else {
6028  id = buf->ReadByte();
6029  }
6030 
6031  ClrBit(lang, 7);
6032 
6033  uint16 endid = id + num;
6034 
6035  grfmsg(6, "FeatureNewName: About to rename engines %d..%d (feature 0x%02X) in language 0x%02X",
6036  id, endid, feature, lang);
6037 
6038  for (; id < endid && buf->HasData(); id++) {
6039  const char *name = buf->ReadString();
6040  grfmsg(8, "FeatureNewName: 0x%04X <- %s", id, name);
6041 
6042  switch (feature) {
6043  case GSF_TRAINS:
6044  case GSF_ROADVEHICLES:
6045  case GSF_SHIPS:
6046  case GSF_AIRCRAFT:
6047  if (!generic) {
6048  Engine *e = GetNewEngine(_cur.grffile, (VehicleType)feature, id, HasBit(_cur.grfconfig->flags, GCF_STATIC));
6049  if (e == nullptr) break;
6050  StringID string = AddGRFString(_cur.grffile->grfid, e->index, lang, new_scheme, false, name, e->info.string_id);
6051  e->info.string_id = string;
6052  } else {
6053  AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, true, name, STR_UNDEFINED);
6054  }
6055  break;
6056 
6057  default:
6058  if (IsInsideMM(id, 0xD000, 0xD400) || IsInsideMM(id, 0xD800, 0xE000)) {
6059  AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, true, name, STR_UNDEFINED);
6060  break;
6061  }
6062 
6063  switch (GB(id, 8, 8)) {
6064  case 0xC4: // Station class name
6065  if (_cur.grffile->stations == nullptr || _cur.grffile->stations[GB(id, 0, 8)] == nullptr) {
6066  grfmsg(1, "FeatureNewName: Attempt to name undefined station 0x%X, ignoring", GB(id, 0, 8));
6067  } else {
6068  StationClassID cls_id = _cur.grffile->stations[GB(id, 0, 8)]->cls_id;
6069  StationClass::Get(cls_id)->name = AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
6070  }
6071  break;
6072 
6073  case 0xC5: // Station name
6074  if (_cur.grffile->stations == nullptr || _cur.grffile->stations[GB(id, 0, 8)] == nullptr) {
6075  grfmsg(1, "FeatureNewName: Attempt to name undefined station 0x%X, ignoring", GB(id, 0, 8));
6076  } else {
6077  _cur.grffile->stations[GB(id, 0, 8)]->name = AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
6078  }
6079  break;
6080 
6081  case 0xC7: // Airporttile name
6082  if (_cur.grffile->airtspec == nullptr || _cur.grffile->airtspec[GB(id, 0, 8)] == nullptr) {
6083  grfmsg(1, "FeatureNewName: Attempt to name undefined airport tile 0x%X, ignoring", GB(id, 0, 8));
6084  } else {
6085  _cur.grffile->airtspec[GB(id, 0, 8)]->name = AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
6086  }
6087  break;
6088 
6089  case 0xC9: // House name
6090  if (_cur.grffile->housespec == nullptr || _cur.grffile->housespec[GB(id, 0, 8)] == nullptr) {
6091  grfmsg(1, "FeatureNewName: Attempt to name undefined house 0x%X, ignoring.", GB(id, 0, 8));
6092  } else {
6093  _cur.grffile->housespec[GB(id, 0, 8)]->building_name = AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
6094  }
6095  break;
6096 
6097  default:
6098  grfmsg(7, "FeatureNewName: Unsupported ID (0x%04X)", id);
6099  break;
6100  }
6101  break;
6102  }
6103  }
6104 }
6105 
6114 static uint16 SanitizeSpriteOffset(uint16& num, uint16 offset, int max_sprites, const char *name)
6115 {
6116 
6117  if (offset >= max_sprites) {
6118  grfmsg(1, "GraphicsNew: %s sprite offset must be less than %i, skipping", name, max_sprites);
6119  uint orig_num = num;
6120  num = 0;
6121  return orig_num;
6122  }
6123 
6124  if (offset + num > max_sprites) {
6125  grfmsg(4, "GraphicsNew: %s sprite overflow, truncating...", name);
6126  uint orig_num = num;
6127  num = std::max(max_sprites - offset, 0);
6128  return orig_num - num;
6129  }
6130 
6131  return 0;
6132 }
6133 
6134 
6140 };
6142 struct Action5Type {
6145  uint16 min_sprites;
6146  uint16 max_sprites;
6147  const char *name;
6148 };
6149 
6151 static const Action5Type _action5_types[] = {
6152  /* Note: min_sprites should not be changed. Therefore these constants are directly here and not in sprites.h */
6153  /* 0x00 */ { A5BLOCK_INVALID, 0, 0, 0, "Type 0x00" },
6154  /* 0x01 */ { A5BLOCK_INVALID, 0, 0, 0, "Type 0x01" },
6155  /* 0x02 */ { A5BLOCK_INVALID, 0, 0, 0, "Type 0x02" },
6156  /* 0x03 */ { A5BLOCK_INVALID, 0, 0, 0, "Type 0x03" },
6157  /* 0x04 */ { A5BLOCK_ALLOW_OFFSET, SPR_SIGNALS_BASE, 1, PRESIGNAL_SEMAPHORE_AND_PBS_SPRITE_COUNT, "Signal graphics" },
6158  /* 0x05 */ { A5BLOCK_ALLOW_OFFSET, SPR_ELRAIL_BASE, 1, ELRAIL_SPRITE_COUNT, "Rail catenary graphics" },
6159  /* 0x06 */ { A5BLOCK_ALLOW_OFFSET, SPR_SLOPES_BASE, 1, NORMAL_AND_HALFTILE_FOUNDATION_SPRITE_COUNT, "Foundation graphics" },
6160  /* 0x07 */ { A5BLOCK_INVALID, 0, 75, 0, "TTDP GUI graphics" }, // Not used by OTTD.
6161  /* 0x08 */ { A5BLOCK_ALLOW_OFFSET, SPR_CANALS_BASE, 1, CANALS_SPRITE_COUNT, "Canal graphics" },
6162  /* 0x09 */ { A5BLOCK_ALLOW_OFFSET, SPR_ONEWAY_BASE, 1, ONEWAY_SPRITE_COUNT, "One way road graphics" },
6163  /* 0x0A */ { A5BLOCK_ALLOW_OFFSET, SPR_2CCMAP_BASE, 1, TWOCCMAP_SPRITE_COUNT, "2CC colour maps" },
6164  /* 0x0B */ { A5BLOCK_ALLOW_OFFSET, SPR_TRAMWAY_BASE, 1, TRAMWAY_SPRITE_COUNT, "Tramway graphics" },
6165  /* 0x0C */ { A5BLOCK_INVALID, 0, 133, 0, "Snowy temperate tree" }, // Not yet used by OTTD.
6166  /* 0x0D */ { A5BLOCK_FIXED, SPR_SHORE_BASE, 16, SPR_SHORE_SPRITE_COUNT, "Shore graphics" },
6167  /* 0x0E */ { A5BLOCK_INVALID, 0, 0, 0, "New Signals graphics" }, // Not yet used by OTTD.
6168  /* 0x0F */ { A5BLOCK_ALLOW_OFFSET, SPR_TRACKS_FOR_SLOPES_BASE, 1, TRACKS_FOR_SLOPES_SPRITE_COUNT, "Sloped rail track" },
6169  /* 0x10 */ { A5BLOCK_ALLOW_OFFSET, SPR_AIRPORTX_BASE, 1, AIRPORTX_SPRITE_COUNT, "Airport graphics" },
6170  /* 0x11 */ { A5BLOCK_ALLOW_OFFSET, SPR_ROADSTOP_BASE, 1, ROADSTOP_SPRITE_COUNT, "Road stop graphics" },
6171  /* 0x12 */ { A5BLOCK_ALLOW_OFFSET, SPR_AQUEDUCT_BASE, 1, AQUEDUCT_SPRITE_COUNT, "Aqueduct graphics" },
6172  /* 0x13 */ { A5BLOCK_ALLOW_OFFSET, SPR_AUTORAIL_BASE, 1, AUTORAIL_SPRITE_COUNT, "Autorail graphics" },
6173  /* 0x14 */ { A5BLOCK_INVALID, 0, 1, 0, "Flag graphics" }, // deprecated, no longer used.
6174  /* 0x15 */ { A5BLOCK_ALLOW_OFFSET, SPR_OPENTTD_BASE, 1, OPENTTD_SPRITE_COUNT, "OpenTTD GUI graphics" },
6175  /* 0x16 */ { A5BLOCK_ALLOW_OFFSET, SPR_AIRPORT_PREVIEW_BASE, 1, SPR_AIRPORT_PREVIEW_COUNT, "Airport preview graphics" },
6176  /* 0x17 */ { A5BLOCK_ALLOW_OFFSET, SPR_RAILTYPE_TUNNEL_BASE, 1, RAILTYPE_TUNNEL_BASE_COUNT, "Railtype tunnel base" },
6177  /* 0x18 */ { A5BLOCK_ALLOW_OFFSET, SPR_PALETTE_BASE, 1, PALETTE_SPRITE_COUNT, "Palette" },
6178 };
6179 
6180 /* Action 0x05 */
6181 static void GraphicsNew(ByteReader *buf)
6182 {
6183  /* <05> <graphics-type> <num-sprites> <other data...>
6184  *
6185  * B graphics-type What set of graphics the sprites define.
6186  * E num-sprites How many sprites are in this set?
6187  * V other data Graphics type specific data. Currently unused. */
6188 
6189  uint8 type = buf->ReadByte();
6190  uint16 num = buf->ReadExtendedByte();
6191  uint16 offset = HasBit(type, 7) ? buf->ReadExtendedByte() : 0;
6192  ClrBit(type, 7); // Clear the high bit as that only indicates whether there is an offset.
6193 
6194  if ((type == 0x0D) && (num == 10) && HasBit(_cur.grfconfig->flags, GCF_SYSTEM)) {
6195  /* Special not-TTDP-compatible case used in openttd.grf
6196  * Missing shore sprites and initialisation of SPR_SHORE_BASE */
6197  grfmsg(2, "GraphicsNew: Loading 10 missing shore sprites from extra grf.");
6198  LoadNextSprite(SPR_SHORE_BASE + 0, *_cur.file, _cur.nfo_line++); // SLOPE_STEEP_S
6199  LoadNextSprite(SPR_SHORE_BASE + 5, *_cur.file, _cur.nfo_line++); // SLOPE_STEEP_W
6200  LoadNextSprite(SPR_SHORE_BASE + 7, *_cur.file, _cur.nfo_line++); // SLOPE_WSE
6201  LoadNextSprite(SPR_SHORE_BASE + 10, *_cur.file, _cur.nfo_line++); // SLOPE_STEEP_N
6202  LoadNextSprite(SPR_SHORE_BASE + 11, *_cur.file, _cur.nfo_line++); // SLOPE_NWS
6203  LoadNextSprite(SPR_SHORE_BASE + 13, *_cur.file, _cur.nfo_line++); // SLOPE_ENW
6204  LoadNextSprite(SPR_SHORE_BASE + 14, *_cur.file, _cur.nfo_line++); // SLOPE_SEN
6205  LoadNextSprite(SPR_SHORE_BASE + 15, *_cur.file, _cur.nfo_line++); // SLOPE_STEEP_E
6206  LoadNextSprite(SPR_SHORE_BASE + 16, *_cur.file, _cur.nfo_line++); // SLOPE_EW
6207  LoadNextSprite(SPR_SHORE_BASE + 17, *_cur.file, _cur.nfo_line++); // SLOPE_NS
6209  return;
6210  }
6211 
6212  /* Supported type? */
6213  if ((type >= lengthof(_action5_types)) || (_action5_types[type].block_type == A5BLOCK_INVALID)) {
6214  grfmsg(2, "GraphicsNew: Custom graphics (type 0x%02X) sprite block of length %u (unimplemented, ignoring)", type, num);
6215  _cur.skip_sprites = num;
6216  return;
6217  }
6218 
6219  const Action5Type *action5_type = &_action5_types[type];
6220 
6221  /* Contrary to TTDP we allow always to specify too few sprites as we allow always an offset,
6222  * except for the long version of the shore type:
6223  * Ignore offset if not allowed */
6224  if ((action5_type->block_type != A5BLOCK_ALLOW_OFFSET) && (offset != 0)) {
6225  grfmsg(1, "GraphicsNew: %s (type 0x%02X) do not allow an <offset> field. Ignoring offset.", action5_type->name, type);
6226  offset = 0;
6227  }
6228 
6229  /* Ignore action5 if too few sprites are specified. (for TTDP compatibility)
6230  * This does not make sense, if <offset> is allowed */
6231  if ((action5_type->block_type == A5BLOCK_FIXED) && (num < action5_type->min_sprites)) {
6232  grfmsg(1, "GraphicsNew: %s (type 0x%02X) count must be at least %d. Only %d were specified. Skipping.", action5_type->name, type, action5_type->min_sprites, num);
6233  _cur.skip_sprites = num;
6234  return;
6235  }
6236 
6237  /* Load at most max_sprites sprites. Skip remaining sprites. (for compatibility with TTDP and future extensions) */
6238  uint16 skip_num = SanitizeSpriteOffset(num, offset, action5_type->max_sprites, action5_type->name);
6239  SpriteID replace = action5_type->sprite_base + offset;
6240 
6241  /* Load <num> sprites starting from <replace>, then skip <skip_num> sprites. */
6242  grfmsg(2, "GraphicsNew: Replacing sprites %d to %d of %s (type 0x%02X) at SpriteID 0x%04X", offset, offset + num - 1, action5_type->name, type, replace);
6243 
6245 
6246  if (type == 0x0B) {
6247  static const SpriteID depot_with_track_offset = SPR_TRAMWAY_DEPOT_WITH_TRACK - SPR_TRAMWAY_BASE;
6248  static const SpriteID depot_no_track_offset = SPR_TRAMWAY_DEPOT_NO_TRACK - SPR_TRAMWAY_BASE;
6249  if (offset <= depot_with_track_offset && offset + num > depot_with_track_offset) _loaded_newgrf_features.tram = TRAMWAY_REPLACE_DEPOT_WITH_TRACK;
6250  if (offset <= depot_no_track_offset && offset + num > depot_no_track_offset) _loaded_newgrf_features.tram = TRAMWAY_REPLACE_DEPOT_NO_TRACK;
6251  }
6252 
6253  for (; num > 0; num--) {
6254  _cur.nfo_line++;
6255  LoadNextSprite(replace == 0 ? _cur.spriteid++ : replace++, *_cur.file, _cur.nfo_line);
6256  }
6257 
6258  _cur.skip_sprites = skip_num;
6259 }
6260 
6261 /* Action 0x05 (SKIP) */
6262 static void SkipAct5(ByteReader *buf)
6263 {
6264  /* Ignore type byte */
6265  buf->ReadByte();
6266 
6267  /* Skip the sprites of this action */
6268  _cur.skip_sprites = buf->ReadExtendedByte();
6269 
6270  grfmsg(3, "SkipAct5: Skipping %d sprites", _cur.skip_sprites);
6271 }
6272 
6284 bool GetGlobalVariable(byte param, uint32 *value, const GRFFile *grffile)
6285 {
6286  switch (param) {
6287  case 0x00: // current date
6288  *value = std::max(_date - DAYS_TILL_ORIGINAL_BASE_YEAR, 0);
6289  return true;
6290 
6291  case 0x01: // current year
6293  return true;
6294 
6295  case 0x02: { // detailed date information: month of year (bit 0-7), day of month (bit 8-12), leap year (bit 15), day of year (bit 16-24)
6296  YearMonthDay ymd;
6297  ConvertDateToYMD(_date, &ymd);
6298  Date start_of_year = ConvertYMDToDate(ymd.year, 0, 1);
6299  *value = ymd.month | (ymd.day - 1) << 8 | (IsLeapYear(ymd.year) ? 1 << 15 : 0) | (_date - start_of_year) << 16;
6300  return true;
6301  }
6302 
6303  case 0x03: // current climate, 0=temp, 1=arctic, 2=trop, 3=toyland
6305  return true;
6306 
6307  case 0x06: // road traffic side, bit 4 clear=left, set=right
6308  *value = _settings_game.vehicle.road_side << 4;
6309  return true;
6310 
6311  case 0x09: // date fraction
6312  *value = _date_fract * 885;
6313  return true;
6314 
6315  case 0x0A: // animation counter
6316  *value = GB(_tick_counter, 0, 16);
6317  return true;
6318 
6319  case 0x0B: { // TTDPatch version
6320  uint major = 2;
6321  uint minor = 6;
6322  uint revision = 1; // special case: 2.0.1 is 2.0.10
6323  uint build = 1382;
6324  *value = (major << 24) | (minor << 20) | (revision << 16) | build;
6325  return true;
6326  }
6327 
6328  case 0x0D: // TTD Version, 00=DOS, 01=Windows
6329  *value = _cur.grfconfig->palette & GRFP_USE_MASK;
6330  return true;
6331 
6332  case 0x0E: // Y-offset for train sprites
6333  *value = _cur.grffile->traininfo_vehicle_pitch;
6334  return true;
6335 
6336  case 0x0F: // Rail track type cost factors
6337  *value = 0;
6338  SB(*value, 0, 8, GetRailTypeInfo(RAILTYPE_RAIL)->cost_multiplier); // normal rail
6340  /* skip elrail multiplier - disabled */
6341  SB(*value, 8, 8, GetRailTypeInfo(RAILTYPE_MONO)->cost_multiplier); // monorail
6342  } else {
6343  SB(*value, 8, 8, GetRailTypeInfo(RAILTYPE_ELECTRIC)->cost_multiplier); // electified railway
6344  /* Skip monorail multiplier - no space in result */
6345  }
6346  SB(*value, 16, 8, GetRailTypeInfo(RAILTYPE_MAGLEV)->cost_multiplier); // maglev
6347  return true;
6348 
6349  case 0x11: // current rail tool type
6350  *value = 0; // constant fake value to avoid desync
6351  return true;
6352 
6353  case 0x12: // Game mode
6354  *value = _game_mode;
6355  return true;
6356 
6357  /* case 0x13: // Tile refresh offset to left not implemented */
6358  /* case 0x14: // Tile refresh offset to right not implemented */
6359  /* case 0x15: // Tile refresh offset upwards not implemented */
6360  /* case 0x16: // Tile refresh offset downwards not implemented */
6361  /* case 0x17: // temperate snow line not implemented */
6362 
6363  case 0x1A: // Always -1
6364  *value = UINT_MAX;
6365  return true;
6366 
6367  case 0x1B: // Display options
6368  *value = 0x3F; // constant fake value to avoid desync
6369  return true;
6370 
6371  case 0x1D: // TTD Platform, 00=TTDPatch, 01=OpenTTD
6372  *value = 1;
6373  return true;
6374 
6375  case 0x1E: // Miscellaneous GRF features
6376  *value = _misc_grf_features;
6377 
6378  /* Add the local flags */
6379  assert(!HasBit(*value, GMB_TRAIN_WIDTH_32_PIXELS));
6380  if (_cur.grffile->traininfo_vehicle_width == VEHICLEINFO_FULL_VEHICLE_WIDTH) SetBit(*value, GMB_TRAIN_WIDTH_32_PIXELS);
6381  return true;
6382 
6383  /* case 0x1F: // locale dependent settings not implemented to avoid desync */
6384 
6385  case 0x20: { // snow line height
6386  byte snowline = GetSnowLine();
6388  *value = Clamp(snowline * (grffile->grf_version >= 8 ? 1 : TILE_HEIGHT), 0, 0xFE);
6389  } else {
6390  /* No snow */
6391  *value = 0xFF;
6392  }
6393  return true;
6394  }
6395 
6396  case 0x21: // OpenTTD version
6397  *value = _openttd_newgrf_version;
6398  return true;
6399 
6400  case 0x22: // difficulty level
6401  *value = SP_CUSTOM;
6402  return true;
6403 
6404  case 0x23: // long format date
6405  *value = _date;
6406  return true;
6407 
6408  case 0x24: // long format year
6409  *value = _cur_year;
6410  return true;
6411 
6412  default: return false;
6413  }
6414 }
6415 
6416 static uint32 GetParamVal(byte param, uint32 *cond_val)
6417 {
6418  /* First handle variable common with VarAction2 */
6419  uint32 value;
6420  if (GetGlobalVariable(param - 0x80, &value, _cur.grffile)) return value;
6421 
6422  /* Non-common variable */
6423  switch (param) {
6424  case 0x84: { // GRF loading stage
6425  uint32 res = 0;
6426 
6427  if (_cur.stage > GLS_INIT) SetBit(res, 0);
6428  if (_cur.stage == GLS_RESERVE) SetBit(res, 8);
6429  if (_cur.stage == GLS_ACTIVATION) SetBit(res, 9);
6430  return res;
6431  }
6432 
6433  case 0x85: // TTDPatch flags, only for bit tests
6434  if (cond_val == nullptr) {
6435  /* Supported in Action 0x07 and 0x09, not 0x0D */
6436  return 0;
6437  } else {
6438  uint32 index = *cond_val / 0x20;
6439  uint32 param_val = index < lengthof(_ttdpatch_flags) ? _ttdpatch_flags[index] : 0;
6440  *cond_val %= 0x20;
6441  return param_val;
6442  }
6443 
6444  case 0x88: // GRF ID check
6445  return 0;
6446 
6447  /* case 0x99: Global ID offset not implemented */
6448 
6449  default:
6450  /* GRF Parameter */
6451  if (param < 0x80) return _cur.grffile->GetParam(param);
6452 
6453  /* In-game variable. */
6454  grfmsg(1, "Unsupported in-game variable 0x%02X", param);
6455  return UINT_MAX;
6456  }
6457 }
6458 
6459 /* Action 0x06 */
6460 static void CfgApply(ByteReader *buf)
6461 {
6462  /* <06> <param-num> <param-size> <offset> ... <FF>
6463  *
6464  * B param-num Number of parameter to substitute (First = "zero")
6465  * Ignored if that parameter was not specified in newgrf.cfg
6466  * B param-size How many bytes to replace. If larger than 4, the
6467  * bytes of the following parameter are used. In that
6468  * case, nothing is applied unless *all* parameters
6469  * were specified.
6470  * B offset Offset into data from beginning of next sprite
6471  * to place where parameter is to be stored. */
6472 
6473  /* Preload the next sprite */
6474  SpriteFile &file = *_cur.file;
6475  size_t pos = file.GetPos();
6476  uint32 num = file.GetContainerVersion() >= 2 ? file.ReadDword() : file.ReadWord();
6477  uint8 type = file.ReadByte();
6478  byte *preload_sprite = nullptr;
6479 
6480  /* Check if the sprite is a pseudo sprite. We can't operate on real sprites. */
6481  if (type == 0xFF) {
6482  preload_sprite = MallocT<byte>(num);
6483  file.ReadBlock(preload_sprite, num);
6484  }
6485 
6486  /* Reset the file position to the start of the next sprite */
6487  file.SeekTo(pos, SEEK_SET);
6488 
6489  if (type != 0xFF) {
6490  grfmsg(2, "CfgApply: Ignoring (next sprite is real, unsupported)");
6491  free(preload_sprite);
6492  return;
6493  }
6494 
6495  GRFLocation location(_cur.grfconfig->ident.grfid, _cur.nfo_line + 1);
6496  GRFLineToSpriteOverride::iterator it = _grf_line_to_action6_sprite_override.find(location);
6497  if (it != _grf_line_to_action6_sprite_override.end()) {
6498  free(preload_sprite);
6499  preload_sprite = _grf_line_to_action6_sprite_override[location];
6500  } else {
6501  _grf_line_to_action6_sprite_override[location] = preload_sprite;
6502  }
6503 
6504  /* Now perform the Action 0x06 on our data. */
6505 
6506  for (;;) {
6507  uint i;
6508  uint param_num;
6509  uint param_size;
6510  uint offset;
6511  bool add_value;
6512 
6513  /* Read the parameter to apply. 0xFF indicates no more data to change. */
6514  param_num = buf->ReadByte();
6515  if (param_num == 0xFF) break;
6516 
6517  /* Get the size of the parameter to use. If the size covers multiple
6518  * double words, sequential parameter values are used. */
6519  param_size = buf->ReadByte();
6520 
6521  /* Bit 7 of param_size indicates we should add to the original value
6522  * instead of replacing it. */
6523  add_value = HasBit(param_size, 7);
6524  param_size = GB(param_size, 0, 7);
6525 
6526  /* Where to apply the data to within the pseudo sprite data. */
6527  offset = buf->ReadExtendedByte();
6528 
6529  /* If the parameter is a GRF parameter (not an internal variable) check
6530  * if it (and all further sequential parameters) has been defined. */
6531  if (param_num < 0x80 && (param_num + (param_size - 1) / 4) >= _cur.grffile->param_end) {
6532  grfmsg(2, "CfgApply: Ignoring (param %d not set)", (param_num + (param_size - 1) / 4));
6533  break;
6534  }
6535 
6536  grfmsg(8, "CfgApply: Applying %u bytes from parameter 0x%02X at offset 0x%04X", param_size, param_num, offset);
6537 
6538  bool carry = false;
6539  for (i = 0; i < param_size && offset + i < num; i++) {
6540  uint32 value = GetParamVal(param_num + i / 4, nullptr);
6541  /* Reset carry flag for each iteration of the variable (only really
6542  * matters if param_size is greater than 4) */
6543  if (i % 4 == 0) carry = false;
6544 
6545  if (add_value) {
6546  uint new_value = preload_sprite[offset + i] + GB(value, (i % 4) * 8, 8) + (carry ? 1 : 0);
6547  preload_sprite[offset + i] = GB(new_value, 0, 8);
6548  /* Check if the addition overflowed */
6549  carry = new_value >= 256;
6550  } else {
6551  preload_sprite[offset + i] = GB(value, (i % 4) * 8, 8);
6552  }
6553  }
6554  }
6555 }
6556 
6567 {
6568  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_STATIC_GRF_CAUSES_DESYNC, c);
6569  error->data = _cur.grfconfig->GetName();
6570 }
6571 
6572 /* Action 0x07
6573  * Action 0x09 */
6574 static void SkipIf(ByteReader *buf)
6575 {
6576  /* <07/09> <param-num> <param-size> <condition-type> <value> <num-sprites>
6577  *
6578  * B param-num
6579  * B param-size
6580  * B condition-type
6581  * V value
6582  * B num-sprites */
6583  uint32 cond_val = 0;
6584  uint32 mask = 0;
6585  bool result;
6586 
6587  uint8 param = buf->ReadByte();
6588  uint8 paramsize = buf->ReadByte();
6589  uint8 condtype = buf->ReadByte();
6590 
6591  if (condtype < 2) {
6592  /* Always 1 for bit tests, the given value should be ignored. */
6593  paramsize = 1;
6594  }
6595 
6596  switch (paramsize) {
6597  case 8: cond_val = buf->ReadDWord(); mask = buf->ReadDWord(); break;
6598  case 4: cond_val = buf->ReadDWord(); mask = 0xFFFFFFFF; break;
6599  case 2: cond_val = buf->ReadWord(); mask = 0x0000FFFF; break;
6600  case 1: cond_val = buf->ReadByte(); mask = 0x000000FF; break;
6601  default: break;
6602  }
6603 
6604  if (param < 0x80 && _cur.grffile->param_end <= param) {
6605  grfmsg(7, "SkipIf: Param %d undefined, skipping test", param);
6606  return;
6607  }
6608 
6609  grfmsg(7, "SkipIf: Test condtype %d, param 0x%02X, condval 0x%08X", condtype, param, cond_val);
6610 
6611  /* condtypes that do not use 'param' are always valid.
6612  * condtypes that use 'param' are either not valid for param 0x88, or they are only valid for param 0x88.
6613  */
6614  if (condtype >= 0x0B) {
6615  /* Tests that ignore 'param' */
6616  switch (condtype) {
6617  case 0x0B: result = GetCargoIDByLabel(BSWAP32(cond_val)) == CT_INVALID;
6618  break;
6619  case 0x0C: result = GetCargoIDByLabel(BSWAP32(cond_val)) != CT_INVALID;
6620  break;
6621  case 0x0D: result = GetRailTypeByLabel(BSWAP32(cond_val)) == INVALID_RAILTYPE;
6622  break;
6623  case 0x0E: result = GetRailTypeByLabel(BSWAP32(cond_val)) != INVALID_RAILTYPE;
6624  break;
6625  case 0x0F: {
6626  RoadType rt = GetRoadTypeByLabel(BSWAP32(cond_val));
6627  result = rt == INVALID_ROADTYPE || !RoadTypeIsRoad(rt);
6628  break;
6629  }
6630  case 0x10: {
6631  RoadType rt = GetRoadTypeByLabel(BSWAP32(cond_val));
6632  result = rt != INVALID_ROADTYPE && RoadTypeIsRoad(rt);
6633  break;
6634  }
6635  case 0x11: {
6636  RoadType rt = GetRoadTypeByLabel(BSWAP32(cond_val));
6637  result = rt == INVALID_ROADTYPE || !RoadTypeIsTram(rt);
6638  break;
6639  }
6640  case 0x12: {
6641  RoadType rt = GetRoadTypeByLabel(BSWAP32(cond_val));
6642  result = rt != INVALID_ROADTYPE && RoadTypeIsTram(rt);
6643  break;
6644  }
6645  default: grfmsg(1, "SkipIf: Unsupported condition type %02X. Ignoring", condtype); return;
6646  }
6647  } else if (param == 0x88) {
6648  /* GRF ID checks */
6649 
6650  GRFConfig *c = GetGRFConfig(cond_val, mask);
6651 
6652  if (c != nullptr && HasBit(c->flags, GCF_STATIC) && !HasBit(_cur.grfconfig->flags, GCF_STATIC) && _networking) {
6654  c = nullptr;
6655  }
6656 
6657  if (condtype != 10 && c == nullptr) {
6658  grfmsg(7, "SkipIf: GRFID 0x%08X unknown, skipping test", BSWAP32(cond_val));
6659  return;
6660  }
6661 
6662  switch (condtype) {
6663  /* Tests 0x06 to 0x0A are only for param 0x88, GRFID checks */
6664  case 0x06: // Is GRFID active?
6665  result = c->status == GCS_ACTIVATED;
6666  break;
6667 
6668  case 0x07: // Is GRFID non-active?
6669  result = c->status != GCS_ACTIVATED;
6670  break;
6671 
6672  case 0x08: // GRFID is not but will be active?
6673  result = c->status == GCS_INITIALISED;
6674  break;
6675 
6676  case 0x09: // GRFID is or will be active?
6677  result = c->status == GCS_ACTIVATED || c->status == GCS_INITIALISED;
6678  break;
6679 
6680  case 0x0A: // GRFID is not nor will be active
6681  /* This is the only condtype that doesn't get ignored if the GRFID is not found */
6682  result = c == nullptr || c->status == GCS_DISABLED || c->status == GCS_NOT_FOUND;
6683  break;
6684 
6685  default: grfmsg(1, "SkipIf: Unsupported GRF condition type %02X. Ignoring", condtype); return;
6686  }
6687  } else {
6688  /* Tests that use 'param' and are not GRF ID checks. */
6689  uint32 param_val = GetParamVal(param, &cond_val); // cond_val is modified for param == 0x85
6690  switch (condtype) {
6691  case 0x00: result = !!(param_val & (1 << cond_val));
6692  break;
6693  case 0x01: result = !(param_val & (1 << cond_val));
6694  break;
6695  case 0x02: result = (param_val & mask) == cond_val;
6696  break;
6697  case 0x03: result = (param_val & mask) != cond_val;
6698  break;
6699  case 0x04: result = (param_val & mask) < cond_val;
6700  break;
6701  case 0x05: result = (param_val & mask) > cond_val;
6702  break;
6703  default: grfmsg(1, "SkipIf: Unsupported condition type %02X. Ignoring", condtype); return;
6704  }
6705  }
6706 
6707  if (!result) {
6708  grfmsg(2, "SkipIf: Not skipping sprites, test was false");
6709  return;
6710  }
6711 
6712  uint8 numsprites = buf->ReadByte();
6713 
6714  /* numsprites can be a GOTO label if it has been defined in the GRF
6715  * file. The jump will always be the first matching label that follows
6716  * the current nfo_line. If no matching label is found, the first matching
6717  * label in the file is used. */
6718  GRFLabel *choice = nullptr;
6719  for (GRFLabel *label = _cur.grffile->label; label != nullptr; label = label->next) {
6720  if (label->label != numsprites) continue;
6721 
6722  /* Remember a goto before the current line */
6723  if (choice == nullptr) choice = label;
6724  /* If we find a label here, this is definitely good */
6725  if (label->nfo_line > _cur.nfo_line) {
6726  choice = label;
6727  break;
6728  }
6729  }
6730 
6731  if (choice != nullptr) {
6732  grfmsg(2, "SkipIf: Jumping to label 0x%0X at line %d, test was true", choice->label, choice->nfo_line);
6733  _cur.file->SeekTo(choice->pos, SEEK_SET);
6734  _cur.nfo_line = choice->nfo_line;
6735  return;
6736  }
6737 
6738  grfmsg(2, "SkipIf: Skipping %d sprites, test was true", numsprites);
6739  _cur.skip_sprites = numsprites;
6740  if (_cur.skip_sprites == 0) {
6741  /* Zero means there are no sprites to skip, so
6742  * we use -1 to indicate that all further
6743  * sprites should be skipped. */
6744  _cur.skip_sprites = -1;
6745 
6746  /* If an action 8 hasn't been encountered yet, disable the grf. */
6747  if (_cur.grfconfig->status != (_cur.stage < GLS_RESERVE ? GCS_INITIALISED : GCS_ACTIVATED)) {
6748  DisableGrf();
6749  }
6750  }
6751 }
6752 
6753 
6754 /* Action 0x08 (GLS_FILESCAN) */
6755 static void ScanInfo(ByteReader *buf)
6756 {
6757  uint8 grf_version = buf->ReadByte();
6758  uint32 grfid = buf->ReadDWord();
6759  const char *name = buf->ReadString();
6760 
6761  _cur.grfconfig->ident.grfid = grfid;
6762 
6763  if (grf_version < 2 || grf_version > 8) {
6765  Debug(grf, 0, "{}: NewGRF \"{}\" (GRFID {:08X}) uses GRF version {}, which is incompatible with this version of OpenTTD.", _cur.grfconfig->filename, name, BSWAP32(grfid), grf_version);
6766  }
6767 
6768  /* GRF IDs starting with 0xFF are reserved for internal TTDPatch use */
6769  if (GB(grfid, 0, 8) == 0xFF) SetBit(_cur.grfconfig->flags, GCF_SYSTEM);
6770 
6771  AddGRFTextToList(_cur.grfconfig->name, 0x7F, grfid, false, name);
6772 
6773  if (buf->HasData()) {
6774  const char *info = buf->ReadString();
6775  AddGRFTextToList(_cur.grfconfig->info, 0x7F, grfid, true, info);
6776  }
6777 
6778  /* GLS_INFOSCAN only looks for the action 8, so we can skip the rest of the file */
6779  _cur.skip_sprites = -1;
6780 }
6781 
6782 /* Action 0x08 */
6783 static void GRFInfo(ByteReader *buf)
6784 {
6785  /* <08> <version> <grf-id> <name> <info>
6786  *
6787  * B version newgrf version, currently 06
6788  * 4*B grf-id globally unique ID of this .grf file
6789  * S name name of this .grf set
6790  * S info string describing the set, and e.g. author and copyright */
6791 
6792  uint8 version = buf->ReadByte();
6793  uint32 grfid = buf->ReadDWord();
6794  const char *name = buf->ReadString();
6795 
6796  if (_cur.stage < GLS_RESERVE && _cur.grfconfig->status != GCS_UNKNOWN) {
6797  DisableGrf(STR_NEWGRF_ERROR_MULTIPLE_ACTION_8);
6798  return;
6799  }
6800 
6801  if (_cur.grffile->grfid != grfid) {
6802  Debug(grf, 0, "GRFInfo: GRFID {:08X} in FILESCAN stage does not match GRFID {:08X} in INIT/RESERVE/ACTIVATION stage", BSWAP32(_cur.grffile->grfid), BSWAP32(grfid));
6803  _cur.grffile->grfid = grfid;
6804  }
6805 
6806  _cur.grffile->grf_version = version;
6807  _cur.grfconfig->status = _cur.stage < GLS_RESERVE ? GCS_INITIALISED : GCS_ACTIVATED;
6808 
6809  /* Do swap the GRFID for displaying purposes since people expect that */
6810  Debug(grf, 1, "GRFInfo: Loaded GRFv{} set {:08X} - {} (palette: {}, version: {})", version, BSWAP32(grfid), name, (_cur.grfconfig->palette & GRFP_USE_MASK) ? "Windows" : "DOS", _cur.grfconfig->version);
6811 }
6812 
6813 /* Action 0x0A */
6814 static void SpriteReplace(ByteReader *buf)
6815 {
6816  /* <0A> <num-sets> <set1> [<set2> ...]
6817  * <set>: <num-sprites> <first-sprite>
6818  *
6819  * B num-sets How many sets of sprites to replace.
6820  * Each set:
6821  * B num-sprites How many sprites are in this set
6822  * W first-sprite First sprite number to replace */
6823 
6824  uint8 num_sets = buf->ReadByte();
6825 
6826  for (uint i = 0; i < num_sets; i++) {
6827  uint8 num_sprites = buf->ReadByte();
6828  uint16 first_sprite = buf->ReadWord();
6829 
6830  grfmsg(2, "SpriteReplace: [Set %d] Changing %d sprites, beginning with %d",
6831  i, num_sprites, first_sprite
6832  );
6833 
6834  for (uint j = 0; j < num_sprites; j++) {
6835  int load_index = first_sprite + j;
6836  _cur.nfo_line++;
6837  LoadNextSprite(load_index, *_cur.file, _cur.nfo_line); // XXX
6838 
6839  /* Shore sprites now located at different addresses.
6840  * So detect when the old ones get replaced. */
6841  if (IsInsideMM(load_index, SPR_ORIGINALSHORE_START, SPR_ORIGINALSHORE_END + 1)) {
6843  }
6844  }
6845  }
6846 }
6847 
6848 /* Action 0x0A (SKIP) */
6849 static void SkipActA(ByteReader *buf)
6850 {
6851  uint8 num_sets = buf->ReadByte();
6852 
6853  for (uint i = 0; i < num_sets; i++) {
6854  /* Skip the sprites this replaces */
6855  _cur.skip_sprites += buf->ReadByte();
6856  /* But ignore where they go */
6857  buf->ReadWord();
6858  }
6859 
6860  grfmsg(3, "SkipActA: Skipping %d sprites", _cur.skip_sprites);
6861 }
6862 
6863 /* Action 0x0B */
6864 static void GRFLoadError(ByteReader *buf)
6865 {
6866  /* <0B> <severity> <language-id> <message-id> [<message...> 00] [<data...>] 00 [<parnum>]
6867  *
6868  * B severity 00: notice, continue loading grf file
6869  * 01: warning, continue loading grf file
6870  * 02: error, but continue loading grf file, and attempt
6871  * loading grf again when loading or starting next game
6872  * 03: error, abort loading and prevent loading again in
6873  * the future (only when restarting the patch)
6874  * B language-id see action 4, use 1F for built-in error messages
6875  * B message-id message to show, see below
6876  * S message for custom messages (message-id FF), text of the message
6877  * not present for built-in messages.
6878  * V data additional data for built-in (or custom) messages
6879  * B parnum parameter numbers to be shown in the message (maximum of 2) */
6880 
6881  static const StringID msgstr[] = {
6882  STR_NEWGRF_ERROR_VERSION_NUMBER,
6883  STR_NEWGRF_ERROR_DOS_OR_WINDOWS,
6884  STR_NEWGRF_ERROR_UNSET_SWITCH,
6885  STR_NEWGRF_ERROR_INVALID_PARAMETER,
6886  STR_NEWGRF_ERROR_LOAD_BEFORE,
6887  STR_NEWGRF_ERROR_LOAD_AFTER,
6888  STR_NEWGRF_ERROR_OTTD_VERSION_NUMBER,
6889  };
6890 
6891  static const StringID sevstr[] = {
6892  STR_NEWGRF_ERROR_MSG_INFO,
6893  STR_NEWGRF_ERROR_MSG_WARNING,
6894  STR_NEWGRF_ERROR_MSG_ERROR,
6895  STR_NEWGRF_ERROR_MSG_FATAL
6896  };
6897 
6898  byte severity = buf->ReadByte();
6899  byte lang = buf->ReadByte();
6900  byte message_id = buf->ReadByte();
6901 
6902  /* Skip the error if it isn't valid for the current language. */
6903  if (!CheckGrfLangID(lang, _cur.grffile->grf_version)) return;
6904 
6905  /* Skip the error until the activation stage unless bit 7 of the severity
6906  * is set. */
6907  if (!HasBit(severity, 7) && _cur.stage == GLS_INIT) {
6908  grfmsg(7, "GRFLoadError: Skipping non-fatal GRFLoadError in stage %d", _cur.stage);
6909  return;
6910  }
6911  ClrBit(severity, 7);
6912 
6913  if (severity >= lengthof(sevstr)) {
6914  grfmsg(7, "GRFLoadError: Invalid severity id %d. Setting to 2 (non-fatal error).", severity);
6915  severity = 2;
6916  } else if (severity == 3) {
6917  /* This is a fatal error, so make sure the GRF is deactivated and no
6918  * more of it gets loaded. */
6919  DisableGrf();
6920 
6921  /* Make sure we show fatal errors, instead of silly infos from before */
6922  delete _cur.grfconfig->error;
6923  _cur.grfconfig->error = nullptr;
6924  }
6925 
6926  if (message_id >= lengthof(msgstr) && message_id != 0xFF) {
6927  grfmsg(7, "GRFLoadError: Invalid message id.");
6928  return;
6929  }
6930 
6931  if (buf->Remaining() <= 1) {
6932  grfmsg(7, "GRFLoadError: No message data supplied.");
6933  return;
6934  }
6935 
6936  /* For now we can only show one message per newgrf file. */
6937  if (_cur.grfconfig->error != nullptr) return;
6938 
6939  GRFError *error = new GRFError(sevstr[severity]);
6940 
6941  if (message_id == 0xFF) {
6942  /* This is a custom error message. */
6943  if (buf->HasData()) {
6944  const char *message = buf->ReadString();
6945 
6946  error->custom_message = TranslateTTDPatchCodes(_cur.grffile->grfid, lang, true, message, SCC_RAW_STRING_POINTER);
6947  } else {
6948  grfmsg(7, "GRFLoadError: No custom message supplied.");
6949  error->custom_message.clear();
6950  }
6951  } else {
6952  error->message = msgstr[message_id];
6953  }
6954 
6955  if (buf->HasData()) {
6956  const char *data = buf->ReadString();
6957 
6958  error->data = TranslateTTDPatchCodes(_cur.grffile->grfid, lang, true, data);
6959  } else {
6960  grfmsg(7, "GRFLoadError: No message data supplied.");
6961  error->data.clear();
6962  }
6963 
6964  /* Only two parameter numbers can be used in the string. */
6965  for (uint i = 0; i < lengthof(error->param_value) && buf->HasData(); i++) {
6966  uint param_number = buf->ReadByte();
6967  error->param_value[i] = _cur.grffile->GetParam(param_number);
6968  }
6969 
6970  _cur.grfconfig->error = error;
6971 }
6972 
6973 /* Action 0x0C */
6974 static void GRFComment(ByteReader *buf)
6975 {
6976  /* <0C> [<ignored...>]
6977  *
6978  * V ignored Anything following the 0C is ignored */
6979 
6980  if (!buf->HasData()) return;
6981 
6982  const char *text = buf->ReadString();
6983  grfmsg(2, "GRFComment: %s", text);
6984 }
6985 
6986 /* Action 0x0D (GLS_SAFETYSCAN) */
6987 static void SafeParamSet(ByteReader *buf)
6988 {
6989  uint8 target = buf->ReadByte();
6990 
6991  /* Writing GRF parameters and some bits of 'misc GRF features' are safe. */
6992  if (target < 0x80 || target == 0x9E) return;
6993 
6994  /* GRM could be unsafe, but as here it can only happen after other GRFs
6995  * are loaded, it should be okay. If the GRF tried to use the slots it
6996  * reserved, it would be marked unsafe anyway. GRM for (e.g. bridge)
6997  * sprites is considered safe. */
6998 
6999  SetBit(_cur.grfconfig->flags, GCF_UNSAFE);
7000 
7001  /* Skip remainder of GRF */
7002  _cur.skip_sprites = -1;
7003 }
7004 
7005 
7006 static uint32 GetPatchVariable(uint8 param)
7007 {
7008  switch (param) {
7009  /* start year - 1920 */
7011 
7012  /* freight trains weight factor */
7013  case 0x0E: return _settings_game.vehicle.freight_trains;
7014 
7015  /* empty wagon speed increase */
7016  case 0x0F: return 0;
7017 
7018  /* plane speed factor; our patch option is reversed from TTDPatch's,
7019  * the following is good for 1x, 2x and 4x (most common?) and...
7020  * well not really for 3x. */
7021  case 0x10:
7023  default:
7024  case 4: return 1;
7025  case 3: return 2;
7026  case 2: return 2;
7027  case 1: return 4;
7028  }
7029 
7030 
7031  /* 2CC colourmap base sprite */
7032  case 0x11: return SPR_2CCMAP_BASE;
7033 
7034  /* map size: format = -MABXYSS
7035  * M : the type of map
7036  * bit 0 : set : squared map. Bit 1 is now not relevant
7037  * clear : rectangle map. Bit 1 will indicate the bigger edge of the map
7038  * bit 1 : set : Y is the bigger edge. Bit 0 is clear
7039  * clear : X is the bigger edge.
7040  * A : minimum edge(log2) of the map
7041  * B : maximum edge(log2) of the map
7042  * XY : edges(log2) of each side of the map.
7043  * SS : combination of both X and Y, thus giving the size(log2) of the map
7044  */
7045  case 0x13: {
7046  byte map_bits = 0;
7047  byte log_X = MapLogX() - 6; // subtraction is required to make the minimal size (64) zero based
7048  byte log_Y = MapLogY() - 6;
7049  byte max_edge = std::max(log_X, log_Y);
7050 
7051  if (log_X == log_Y) { // we have a squared map, since both edges are identical
7052  SetBit(map_bits, 0);
7053  } else {
7054  if (max_edge == log_Y) SetBit(map_bits, 1); // edge Y been the biggest, mark it
7055  }
7056 
7057  return (map_bits << 24) | (std::min(log_X, log_Y) << 20) | (max_edge << 16) |
7058  (log_X << 12) | (log_Y << 8) | (log_X + log_Y);
7059  }
7060 
7061  /* The maximum height of the map. */
7062  case 0x14:
7064 
7065  /* Extra foundations base sprite */
7066  case 0x15:
7067  return SPR_SLOPES_BASE;
7068 
7069  /* Shore base sprite */
7070  case 0x16:
7071  return SPR_SHORE_BASE;
7072 
7073  /* Game map seed */
7074  case 0x17:
7076 
7077  default:
7078  grfmsg(2, "ParamSet: Unknown Patch variable 0x%02X.", param);
7079  return 0;
7080  }
7081 }
7082 
7083 
7084 static uint32 PerformGRM(uint32 *grm, uint16 num_ids, uint16 count, uint8 op, uint8 target, const char *type)
7085 {
7086  uint start = 0;
7087  uint size = 0;
7088 
7089  if (op == 6) {
7090  /* Return GRFID of set that reserved ID */
7091  return grm[_cur.grffile->GetParam(target)];
7092  }
7093 
7094  /* With an operation of 2 or 3, we want to reserve a specific block of IDs */
7095  if (op == 2 || op == 3) start = _cur.grffile->GetParam(target);
7096 
7097  for (uint i = start; i < num_ids; i++) {
7098  if (grm[i] == 0) {
7099  size++;
7100  } else {
7101  if (op == 2 || op == 3) break;
7102  start = i + 1;
7103  size = 0;
7104  }
7105 
7106  if (size == count) break;
7107  }
7108 
7109  if (size == count) {
7110  /* Got the slot... */
7111  if (op == 0 || op == 3) {
7112  grfmsg(2, "ParamSet: GRM: Reserving %d %s at %d", count, type, start);
7113  for (uint i = 0; i < count; i++) grm[start + i] = _cur.grffile->grfid;
7114  }
7115  return start;
7116  }
7117 
7118  /* Unable to allocate */
7119  if (op != 4 && op != 5) {
7120  /* Deactivate GRF */
7121  grfmsg(0, "ParamSet: GRM: Unable to allocate %d %s, deactivating", count, type);
7122  DisableGrf(STR_NEWGRF_ERROR_GRM_FAILED);
7123  return UINT_MAX;
7124  }
7125 
7126  grfmsg(1, "ParamSet: GRM: Unable to allocate %d %s", count, type);
7127  return UINT_MAX;
7128 }
7129 
7130 
7132 static void ParamSet(ByteReader *buf)
7133 {
7134  /* <0D> <target> <operation> <source1> <source2> [<data>]
7135  *
7136  * B target parameter number where result is stored
7137  * B operation operation to perform, see below
7138  * B source1 first source operand
7139  * B source2 second source operand
7140  * D data data to use in the calculation, not necessary
7141  * if both source1 and source2 refer to actual parameters
7142  *
7143  * Operations
7144  * 00 Set parameter equal to source1
7145  * 01 Addition, source1 + source2
7146  * 02 Subtraction, source1 - source2
7147  * 03 Unsigned multiplication, source1 * source2 (both unsigned)
7148  * 04 Signed multiplication, source1 * source2 (both signed)
7149  * 05 Unsigned bit shift, source1 by source2 (source2 taken to be a
7150  * signed quantity; left shift if positive and right shift if
7151  * negative, source1 is unsigned)
7152  * 06 Signed bit shift, source1 by source2
7153  * (source2 like in 05, and source1 as well)
7154  */
7155 
7156  uint8 target = buf->ReadByte();
7157  uint8 oper = buf->ReadByte();
7158  uint32 src1 = buf->ReadByte();
7159  uint32 src2 = buf->ReadByte();
7160 
7161  uint32 data = 0;
7162  if (buf->Remaining() >= 4) data = buf->ReadDWord();
7163 
7164  /* You can add 80 to the operation to make it apply only if the target
7165  * is not defined yet. In this respect, a parameter is taken to be
7166  * defined if any of the following applies:
7167  * - it has been set to any value in the newgrf(w).cfg parameter list
7168  * - it OR A PARAMETER WITH HIGHER NUMBER has been set to any value by
7169  * an earlier action D */
7170  if (HasBit(oper, 7)) {
7171  if (target < 0x80 && target < _cur.grffile->param_end) {
7172  grfmsg(7, "ParamSet: Param %u already defined, skipping", target);
7173  return;
7174  }
7175 
7176  oper = GB(oper, 0, 7);
7177  }
7178 
7179  if (src2 == 0xFE) {
7180  if (GB(data, 0, 8) == 0xFF) {
7181  if (data == 0x0000FFFF) {
7182  /* Patch variables */
7183  src1 = GetPatchVariable(src1);
7184  } else {
7185  /* GRF Resource Management */
7186  uint8 op = src1;
7187  uint8 feature = GB(data, 8, 8);
7188  uint16 count = GB(data, 16, 16);
7189 
7190  if (_cur.stage == GLS_RESERVE) {
7191  if (feature == 0x08) {
7192  /* General sprites */
7193  if (op == 0) {
7194  /* Check if the allocated sprites will fit below the original sprite limit */
7195  if (_cur.spriteid + count >= 16384) {
7196  grfmsg(0, "ParamSet: GRM: Unable to allocate %d sprites; try changing NewGRF order", count);
7197  DisableGrf(STR_NEWGRF_ERROR_GRM_FAILED);
7198  return;
7199  }
7200 
7201  /* Reserve space at the current sprite ID */
7202  grfmsg(4, "ParamSet: GRM: Allocated %d sprites at %d", count, _cur.spriteid);
7203  _grm_sprites[GRFLocation(_cur.grffile->grfid, _cur.nfo_line)] = _cur.spriteid;
7204  _cur.spriteid += count;
7205  }
7206  }
7207  /* Ignore GRM result during reservation */
7208  src1 = 0;
7209  } else if (_cur.stage == GLS_ACTIVATION) {
7210  switch (feature) {
7211  case 0x00: // Trains
7212  case 0x01: // Road Vehicles
7213  case 0x02: // Ships
7214  case 0x03: // Aircraft
7216  src1 = PerformGRM(&_grm_engines[_engine_offsets[feature]], _engine_counts[feature], count, op, target, "vehicles");
7217  if (_cur.skip_sprites == -1) return;
7218  } else {
7219  /* GRM does not apply for dynamic engine allocation. */
7220  switch (op) {
7221  case 2:
7222  case 3:
7223  src1 = _cur.grffile->GetParam(target);
7224  break;
7225 
7226  default:
7227  src1 = 0;
7228  break;
7229  }
7230  }
7231  break;
7232 
7233  case 0x08: // General sprites
7234  switch (op) {
7235  case 0:
7236  /* Return space reserved during reservation stage */
7237  src1 = _grm_sprites[GRFLocation(_cur.grffile->grfid, _cur.nfo_line)];
7238  grfmsg(4, "ParamSet: GRM: Using pre-allocated sprites at %d", src1);
7239  break;
7240 
7241  case 1:
7242  src1 = _cur.spriteid;
7243  break;
7244 
7245  default:
7246  grfmsg(1, "ParamSet: GRM: Unsupported operation %d for general sprites", op);
7247  return;
7248  }
7249  break;
7250 
7251  case 0x0B: // Cargo
7252  /* There are two ranges: one for cargo IDs and one for cargo bitmasks */
7253  src1 = PerformGRM(_grm_cargoes, NUM_CARGO * 2, count, op, target, "cargoes");
7254  if (_cur.skip_sprites == -1) return;
7255  break;
7256 
7257  default: grfmsg(1, "ParamSet: GRM: Unsupported feature 0x%X", feature); return;
7258  }
7259  } else {
7260  /* Ignore GRM during initialization */
7261  src1 = 0;
7262  }
7263  }
7264  } else {
7265  /* Read another GRF File's parameter */
7266  const GRFFile *file = GetFileByGRFID(data);
7267  GRFConfig *c = GetGRFConfig(data);
7268  if (c != nullptr && HasBit(c->flags, GCF_STATIC) && !HasBit(_cur.grfconfig->flags, GCF_STATIC) && _networking) {
7269  /* Disable the read GRF if it is a static NewGRF. */
7271  src1 = 0;
7272  } else if (file == nullptr || c == nullptr || c->status == GCS_DISABLED) {
7273  src1 = 0;
7274  } else if (src1 == 0xFE) {
7275  src1 = c->version;
7276  } else {
7277  src1 = file->GetParam(src1);
7278  }
7279  }
7280  } else {
7281  /* The source1 and source2 operands refer to the grf parameter number
7282  * like in action 6 and 7. In addition, they can refer to the special
7283  * variables available in action 7, or they can be FF to use the value
7284  * of <data>. If referring to parameters that are undefined, a value
7285  * of 0 is used instead. */
7286  src1 = (src1 == 0xFF) ? data : GetParamVal(src1, nullptr);
7287  src2 = (src2 == 0xFF) ? data : GetParamVal(src2, nullptr);
7288  }
7289 
7290  uint32 res;
7291  switch (oper) {
7292  case 0x00:
7293  res = src1;
7294  break;
7295 
7296  case 0x01:
7297  res = src1 + src2;
7298  break;
7299 
7300  case 0x02:
7301  res = src1 - src2;
7302  break;
7303 
7304  case 0x03:
7305  res = src1 * src2;
7306  break;
7307 
7308  case 0x04:
7309  res = (int32)src1 * (int32)src2;
7310  break;
7311 
7312  case 0x05:
7313  if ((int32)src2 < 0) {
7314  res = src1 >> -(int32)src2;
7315  } else {
7316  res = src1 << (src2 & 0x1F); // Same behaviour as in EvalAdjustT, mask 'value' to 5 bits, which should behave the same on all architectures.
7317  }
7318  break;
7319 
7320  case 0x06:
7321  if ((int32)src2 < 0) {
7322  res = (int32)src1 >> -(int32)src2;
7323  } else {
7324  res = (int32)src1 << (src2 & 0x1F); // Same behaviour as in EvalAdjustT, mask 'value' to 5 bits, which should behave the same on all architectures.
7325  }
7326  break;
7327 
7328  case 0x07: // Bitwise AND
7329  res = src1 & src2;
7330  break;
7331 
7332  case 0x08: // Bitwise OR
7333  res = src1 | src2;
7334  break;
7335 
7336  case 0x09: // Unsigned division
7337  if (src2 == 0) {
7338  res = src1;
7339  } else {
7340  res = src1 / src2;
7341  }
7342  break;
7343 
7344  case 0x0A: // Signed division
7345  if (src2 == 0) {
7346  res = src1;
7347  } else {
7348  res = (int32)src1 / (int32)src2;
7349  }
7350  break;
7351 
7352  case 0x0B: // Unsigned modulo
7353  if (src2 == 0) {
7354  res = src1;
7355  } else {
7356  res = src1 % src2;
7357  }
7358  break;
7359 
7360  case 0x0C: // Signed modulo
7361  if (src2 == 0) {
7362  res = src1;
7363  } else {
7364  res = (int32)src1 % (int32)src2;
7365  }
7366  break;
7367 
7368  default: grfmsg(0, "ParamSet: Unknown operation %d, skipping", oper); return;
7369  }
7370 
7371  switch (target) {
7372  case 0x8E: // Y-Offset for train sprites
7373  _cur.grffile->traininfo_vehicle_pitch = res;
7374  break;
7375 
7376  case 0x8F: { // Rail track type cost factors
7377  extern RailtypeInfo _railtypes[RAILTYPE_END];
7378  _railtypes[RAILTYPE_RAIL].cost_multiplier = GB(res, 0, 8);
7380  _railtypes[RAILTYPE_ELECTRIC].cost_multiplier = GB(res, 0, 8);
7381  _railtypes[RAILTYPE_MONO].cost_multiplier = GB(res, 8, 8);
7382  } else {
7383  _railtypes[RAILTYPE_ELECTRIC].cost_multiplier = GB(res, 8, 8);
7384  _railtypes[RAILTYPE_MONO].cost_multiplier = GB(res, 16, 8);
7385  }
7386  _railtypes[RAILTYPE_MAGLEV].cost_multiplier = GB(res, 16, 8);
7387  break;
7388  }
7389 
7390  /* not implemented */
7391  case 0x93: // Tile refresh offset to left -- Intended to allow support for larger sprites, not necessary for OTTD
7392  case 0x94: // Tile refresh offset to right
7393  case 0x95: // Tile refresh offset upwards
7394  case 0x96: // Tile refresh offset downwards
7395  case 0x97: // Snow line height -- Better supported by feature 8 property 10h (snow line table) TODO: implement by filling the entire snow line table with the given value
7396  case 0x99: // Global ID offset -- Not necessary since IDs are remapped automatically
7397  grfmsg(7, "ParamSet: Skipping unimplemented target 0x%02X", target);
7398  break;
7399 
7400  case 0x9E: // Miscellaneous GRF features
7401  /* Set train list engine width */
7402  _cur.grffile->traininfo_vehicle_width = HasBit(res, GMB_TRAIN_WIDTH_32_PIXELS) ? VEHICLEINFO_FULL_VEHICLE_WIDTH : TRAININFO_DEFAULT_VEHICLE_WIDTH;
7403  /* Remove the local flags from the global flags */
7405 
7406  /* Only copy safe bits for static grfs */
7407  if (HasBit(_cur.grfconfig->flags, GCF_STATIC)) {
7408  uint32 safe_bits = 0;
7409  SetBit(safe_bits, GMB_SECOND_ROCKY_TILE_SET);
7410 
7411  _misc_grf_features = (_misc_grf_features & ~safe_bits) | (res & safe_bits);
7412  } else {
7413  _misc_grf_features = res;
7414  }
7415  break;
7416 
7417  case 0x9F: // locale-dependent settings
7418  grfmsg(7, "ParamSet: Skipping unimplemented target 0x%02X", target);
7419  break;
7420 
7421  default:
7422  if (target < 0x80) {
7423  _cur.grffile->param[target] = res;
7424  /* param is zeroed by default */
7425  if (target + 1U > _cur.grffile->param_end) _cur.grffile->param_end = target + 1;
7426  } else {
7427  grfmsg(7, "ParamSet: Skipping unknown target 0x%02X", target);
7428  }
7429  break;
7430  }
7431 }
7432 
7433 /* Action 0x0E (GLS_SAFETYSCAN) */
7434 static void SafeGRFInhibit(ByteReader *buf)
7435 {
7436  /* <0E> <num> <grfids...>
7437  *
7438  * B num Number of GRFIDs that follow
7439  * D grfids GRFIDs of the files to deactivate */
7440 
7441  uint8 num = buf->ReadByte();
7442 
7443  for (uint i = 0; i < num; i++) {
7444  uint32 grfid = buf->ReadDWord();
7445 
7446  /* GRF is unsafe it if tries to deactivate other GRFs */
7447  if (grfid != _cur.grfconfig->ident.grfid) {
7448  SetBit(_cur.grfconfig->flags, GCF_UNSAFE);
7449 
7450  /* Skip remainder of GRF */
7451  _cur.skip_sprites = -1;
7452 
7453  return;
7454  }
7455  }
7456 }
7457 
7458 /* Action 0x0E */
7459 static void GRFInhibit(ByteReader *buf)
7460 {
7461  /* <0E> <num> <grfids...>
7462  *
7463  * B num Number of GRFIDs that follow
7464  * D grfids GRFIDs of the files to deactivate */
7465 
7466  uint8 num = buf->ReadByte();
7467 
7468  for (uint i = 0; i < num; i++) {
7469  uint32 grfid = buf->ReadDWord();
7470  GRFConfig *file = GetGRFConfig(grfid);
7471 
7472  /* Unset activation flag */
7473  if (file != nullptr && file != _cur.grfconfig) {
7474  grfmsg(2, "GRFInhibit: Deactivating file '%s'", file->filename);
7475  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_FORCEFULLY_DISABLED, file);
7476  error->data = _cur.grfconfig->GetName();
7477  }
7478  }
7479 }
7480 
7482 static void FeatureTownName(ByteReader *buf)
7483 {
7484  /* <0F> <id> <style-name> <num-parts> <parts>
7485  *
7486  * B id ID of this definition in bottom 7 bits (final definition if bit 7 set)
7487  * V style-name Name of the style (only for final definition)
7488  * B num-parts Number of parts in this definition
7489  * V parts The parts */
7490 
7491  uint32 grfid = _cur.grffile->grfid;
7492 
7493  GRFTownName *townname = AddGRFTownName(grfid);
7494 
7495  byte id = buf->ReadByte();
7496  grfmsg(6, "FeatureTownName: definition 0x%02X", id & 0x7F);
7497 
7498  if (HasBit(id, 7)) {
7499  /* Final definition */
7500  ClrBit(id, 7);
7501  bool new_scheme = _cur.grffile->grf_version >= 7;
7502 
7503  byte lang = buf->ReadByte();
7504 
7505  byte nb_gen = townname->nb_gen;
7506  do {
7507  ClrBit(lang, 7);
7508 
7509  const char *name = buf->ReadString();
7510 
7511  std::string lang_name = TranslateTTDPatchCodes(grfid, lang, false, name);
7512  grfmsg(6, "FeatureTownName: lang 0x%X -> '%s'", lang, lang_name.c_str());
7513 
7514  townname->name[nb_gen] = AddGRFString(grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
7515 
7516  lang = buf->ReadByte();
7517  } while (lang != 0);
7518  townname->id[nb_gen] = id;
7519  townname->nb_gen++;
7520  }
7521 
7522  byte nb = buf->ReadByte();
7523  grfmsg(6, "FeatureTownName: %u parts", nb);
7524 
7525  townname->nbparts[id] = nb;
7526  townname->partlist[id] = CallocT<NamePartList>(nb);
7527 
7528  for (int i = 0; i < nb; i++) {
7529  byte nbtext = buf->ReadByte();
7530  townname->partlist[id][i].bitstart = buf->ReadByte();
7531  townname->partlist[id][i].bitcount = buf->ReadByte();
7532  townname->partlist[id][i].maxprob = 0;
7533  townname->partlist[id][i].partcount = nbtext;
7534  townname->partlist[id][i].parts = CallocT<NamePart>(nbtext);
7535  grfmsg(6, "FeatureTownName: part %d contains %d texts and will use GB(seed, %d, %d)", i, nbtext, townname->partlist[id][i].bitstart, townname->partlist[id][i].bitcount);
7536 
7537  for (int j = 0; j < nbtext; j++) {
7538  byte prob = buf->ReadByte();
7539 
7540  if (HasBit(prob, 7)) {
7541  byte ref_id = buf->ReadByte();
7542 
7543  if (townname->nbparts[ref_id] == 0) {
7544  grfmsg(0, "FeatureTownName: definition 0x%02X doesn't exist, deactivating", ref_id);
7545  DelGRFTownName(grfid);
7546  DisableGrf(STR_NEWGRF_ERROR_INVALID_ID);
7547  return;
7548  }
7549 
7550  grfmsg(6, "FeatureTownName: part %d, text %d, uses intermediate definition 0x%02X (with probability %d)", i, j, ref_id, prob & 0x7F);
7551  townname->partlist[id][i].parts[j].data.id = ref_id;
7552  } else {
7553  const char *text = buf->ReadString();
7554  townname->partlist[id][i].parts[j].data.text = stredup(TranslateTTDPatchCodes(grfid, 0, false, text).c_str());
7555  grfmsg(6, "FeatureTownName: part %d, text %d, '%s' (with probability %d)", i, j, townname->partlist[id][i].parts[j].data.text, prob);
7556  }
7557  townname->partlist[id][i].parts[j].prob = prob;
7558  townname->partlist[id][i].maxprob += GB(prob, 0, 7);
7559  }
7560  grfmsg(6, "FeatureTownName: part %d, total probability %d", i, townname->partlist[id][i].maxprob);
7561  }
7562 }
7563 
7565 static void DefineGotoLabel(ByteReader *buf)
7566 {
7567  /* <10> <label> [<comment>]
7568  *
7569  * B label The label to define
7570  * V comment Optional comment - ignored */
7571 
7572  byte nfo_label = buf->ReadByte();
7573 
7574  GRFLabel *label = MallocT<GRFLabel>(1);
7575  label->label = nfo_label;
7576  label->nfo_line = _cur.nfo_line;
7577  label->pos = _cur.file->GetPos();
7578  label->next = nullptr;
7579 
7580  /* Set up a linked list of goto targets which we will search in an Action 0x7/0x9 */
7581  if (_cur.grffile->label == nullptr) {
7582  _cur.grffile->label = label;
7583  } else {
7584  /* Attach the label to the end of the list */
7585  GRFLabel *l;
7586  for (l = _cur.grffile->label; l->next != nullptr; l = l->next) {}
7587  l->next = label;
7588  }
7589 
7590  grfmsg(2, "DefineGotoLabel: GOTO target with label 0x%02X", label->label);
7591 }
7592 
7597 static void ImportGRFSound(SoundEntry *sound)
7598 {
7599  const GRFFile *file;
7600  uint32 grfid = _cur.file->ReadDword();
7601  SoundID sound_id = _cur.file->ReadWord();
7602 
7603  file = GetFileByGRFID(grfid);
7604  if (file == nullptr || file->sound_offset == 0) {
7605  grfmsg(1, "ImportGRFSound: Source file not available");
7606  return;
7607  }
7608 
7609  if (sound_id >= file->num_sounds) {
7610  grfmsg(1, "ImportGRFSound: Sound effect %d is invalid", sound_id);
7611  return;
7612  }
7613 
7614  grfmsg(2, "ImportGRFSound: Copying sound %d (%d) from file %X", sound_id, file->sound_offset + sound_id, grfid);
7615 
7616  *sound = *GetSound(file->sound_offset + sound_id);
7617 
7618  /* Reset volume and priority, which TTDPatch doesn't copy */
7619  sound->volume = 128;
7620  sound->priority = 0;
7621 }
7622 
7628 static void LoadGRFSound(size_t offs, SoundEntry *sound)
7629 {
7630  /* Set default volume and priority */
7631  sound->volume = 0x80;
7632  sound->priority = 0;
7633 
7634  if (offs != SIZE_MAX) {
7635  /* Sound is present in the NewGRF. */
7636  sound->file = _cur.file;
7637  sound->file_offset = offs;
7638  sound->grf_container_ver = _cur.file->GetContainerVersion();
7639  }
7640 }
7641 
7642 /* Action 0x11 */
7643 static void GRFSound(ByteReader *buf)
7644 {
7645  /* <11> <num>
7646  *
7647  * W num Number of sound files that follow */
7648 
7649  uint16 num = buf->ReadWord();
7650  if (num == 0) return;
7651 
7652  SoundEntry *sound;
7653  if (_cur.grffile->sound_offset == 0) {
7654  _cur.grffile->sound_offset = GetNumSounds();
7655  _cur.grffile->num_sounds = num;
7656  sound = AllocateSound(num);
7657  } else {
7658  sound = GetSound(_cur.grffile->sound_offset);
7659  }
7660 
7661  SpriteFile &file = *_cur.file;
7662  byte grf_container_version = file.GetContainerVersion();
7663  for (int i = 0; i < num; i++) {
7664  _cur.nfo_line++;
7665 
7666  /* Check whether the index is in range. This might happen if multiple action 11 are present.
7667  * While this is invalid, we do not check for this. But we should prevent it from causing bigger trouble */
7668  bool invalid = i >= _cur.grffile->num_sounds;
7669 
7670  size_t offs = file.GetPos();
7671 
7672  uint32 len = grf_container_version >= 2 ? file.ReadDword() : file.ReadWord();
7673  byte type = file.ReadByte();
7674 
7675  if (grf_container_version >= 2 && type == 0xFD) {
7676  /* Reference to sprite section. */
7677  if (invalid) {
7678  grfmsg(1, "GRFSound: Sound index out of range (multiple Action 11?)");
7679  file.SkipBytes(len);
7680  } else if (len != 4) {
7681  grfmsg(1, "GRFSound: Invalid sprite section import");
7682  file.SkipBytes(len);
7683  } else {
7684  uint32 id = file.ReadDword();
7685  if (_cur.stage == GLS_INIT) LoadGRFSound(GetGRFSpriteOffset(id), sound + i);
7686  }
7687  continue;
7688  }
7689 
7690  if (type != 0xFF) {
7691  grfmsg(1, "GRFSound: Unexpected RealSprite found, skipping");
7692  file.SkipBytes(7);
7693  SkipSpriteData(*_cur.file, type, len - 8);
7694  continue;
7695  }
7696 
7697  if (invalid) {
7698  grfmsg(1, "GRFSound: Sound index out of range (multiple Action 11?)");
7699  file.SkipBytes(len);
7700  }
7701 
7702  byte action = file.ReadByte();
7703  switch (action) {
7704  case 0xFF:
7705  /* Allocate sound only in init stage. */
7706  if (_cur.stage == GLS_INIT) {
7707  if (grf_container_version >= 2) {
7708  grfmsg(1, "GRFSound: Inline sounds are not supported for container version >= 2");
7709  } else {
7710  LoadGRFSound(offs, sound + i);
7711  }
7712  }
7713  file.SkipBytes(len - 1); // already read <action>
7714  break;
7715 
7716  case 0xFE:
7717  if (_cur.stage == GLS_ACTIVATION) {
7718  /* XXX 'Action 0xFE' isn't really specified. It is only mentioned for
7719  * importing sounds, so this is probably all wrong... */
7720  if (file.ReadByte() != 0) grfmsg(1, "GRFSound: Import type mismatch");
7721  ImportGRFSound(sound + i);
7722  } else {
7723  file.SkipBytes(len - 1); // already read <action>
7724  }
7725  break;
7726 
7727  default:
7728  grfmsg(1, "GRFSound: Unexpected Action %x found, skipping", action);
7729  file.SkipBytes(len - 1); // already read <action>
7730  break;
7731  }
7732  }
7733 }
7734 
7735 /* Action 0x11 (SKIP) */
7736 static void SkipAct11(ByteReader *buf)
7737 {
7738  /* <11> <num>
7739  *
7740  * W num Number of sound files that follow */
7741 
7742  _cur.skip_sprites = buf->ReadWord();
7743 
7744  grfmsg(3, "SkipAct11: Skipping %d sprites", _cur.skip_sprites);
7745 }
7746 
7748 static void LoadFontGlyph(ByteReader *buf)
7749 {
7750  /* <12> <num_def> <font_size> <num_char> <base_char>
7751  *
7752  * B num_def Number of definitions
7753  * B font_size Size of font (0 = normal, 1 = small, 2 = large, 3 = mono)
7754  * B num_char Number of consecutive glyphs
7755  * W base_char First character index */
7756 
7757  uint8 num_def = buf->ReadByte();
7758 
7759  for (uint i = 0; i < num_def; i++) {
7760  FontSize size = (FontSize)buf->ReadByte();
7761  uint8 num_char = buf->ReadByte();
7762  uint16 base_char = buf->ReadWord();
7763 
7764  if (size >= FS_END) {
7765  grfmsg(1, "LoadFontGlyph: Size %u is not supported, ignoring", size);
7766  }
7767 
7768  grfmsg(7, "LoadFontGlyph: Loading %u glyph(s) at 0x%04X for size %u", num_char, base_char, size);
7769 
7770  for (uint c = 0; c < num_char; c++) {
7771  if (size < FS_END) SetUnicodeGlyph(size, base_char + c, _cur.spriteid);
7772  _cur.nfo_line++;
7773  LoadNextSprite(_cur.spriteid++, *_cur.file, _cur.nfo_line);
7774  }
7775  }
7776 }
7777 
7779 static void SkipAct12(ByteReader *buf)
7780 {
7781  /* <12> <num_def> <font_size> <num_char> <base_char>
7782  *
7783  * B num_def Number of definitions
7784  * B font_size Size of font (0 = normal, 1 = small, 2 = large)
7785  * B num_char Number of consecutive glyphs
7786  * W base_char First character index */
7787 
7788  uint8 num_def = buf->ReadByte();
7789 
7790  for (uint i = 0; i < num_def; i++) {
7791  /* Ignore 'size' byte */
7792  buf->ReadByte();
7793 
7794  /* Sum up number of characters */
7795  _cur.skip_sprites += buf->ReadByte();
7796 
7797  /* Ignore 'base_char' word */
7798  buf->ReadWord();
7799  }
7800 
7801  grfmsg(3, "SkipAct12: Skipping %d sprites", _cur.skip_sprites);
7802 }
7803 
7806 {
7807  /* <13> <grfid> <num-ent> <offset> <text...>
7808  *
7809  * 4*B grfid The GRFID of the file whose texts are to be translated
7810  * B num-ent Number of strings
7811  * W offset First text ID
7812  * S text... Zero-terminated strings */
7813 
7814  uint32 grfid = buf->ReadDWord();
7815  const GRFConfig *c = GetGRFConfig(grfid);
7816  if (c == nullptr || (c->status != GCS_INITIALISED && c->status != GCS_ACTIVATED)) {
7817  grfmsg(7, "TranslateGRFStrings: GRFID 0x%08x unknown, skipping action 13", BSWAP32(grfid));
7818  return;
7819  }
7820 
7821  if (c->status == GCS_INITIALISED) {
7822  /* If the file is not active but will be activated later, give an error
7823  * and disable this file. */
7824  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LOAD_AFTER);
7825 
7826  error->data = GetString(STR_NEWGRF_ERROR_AFTER_TRANSLATED_FILE);
7827 
7828  return;
7829  }
7830 
7831  /* Since no language id is supplied for with version 7 and lower NewGRFs, this string has
7832  * to be added as a generic string, thus the language id of 0x7F. For this to work
7833  * new_scheme has to be true as well, which will also be implicitly the case for version 8
7834  * and higher. A language id of 0x7F will be overridden by a non-generic id, so this will
7835  * not change anything if a string has been provided specifically for this language. */
7836  byte language = _cur.grffile->grf_version >= 8 ? buf->ReadByte() : 0x7F;
7837  byte num_strings = buf->ReadByte();
7838  uint16 first_id = buf->ReadWord();
7839 
7840  if (!((first_id >= 0xD000 && first_id + num_strings <= 0xD400) || (first_id >= 0xD800 && first_id + num_strings <= 0xE000))) {
7841  grfmsg(7, "TranslateGRFStrings: Attempting to set out-of-range string IDs in action 13 (first: 0x%4X, number: 0x%2X)", first_id, num_strings);
7842  return;
7843  }
7844 
7845  for (uint i = 0; i < num_strings && buf->HasData(); i++) {
7846  const char *string = buf->ReadString();
7847 
7848  if (StrEmpty(string)) {
7849  grfmsg(7, "TranslateGRFString: Ignoring empty string.");
7850  continue;
7851  }
7852 
7853  AddGRFString(grfid, first_id + i, language, true, true, string, STR_UNDEFINED);
7854  }
7855 }
7856 
7858 static bool ChangeGRFName(byte langid, const char *str)
7859 {
7860  AddGRFTextToList(_cur.grfconfig->name, langid, _cur.grfconfig->ident.grfid, false, str);
7861  return true;
7862 }
7863 
7865 static bool ChangeGRFDescription(byte langid, const char *str)
7866 {
7867  AddGRFTextToList(_cur.grfconfig->info, langid, _cur.grfconfig->ident.grfid, true, str);
7868  return true;
7869 }
7870 
7872 static bool ChangeGRFURL(byte langid, const char *str)
7873 {
7874  AddGRFTextToList(_cur.grfconfig->url, langid, _cur.grfconfig->ident.grfid, false, str);
7875  return true;
7876 }
7877 
7879 static bool ChangeGRFNumUsedParams(size_t len, ByteReader *buf)
7880 {
7881  if (len != 1) {
7882  grfmsg(2, "StaticGRFInfo: expected only 1 byte for 'INFO'->'NPAR' but got " PRINTF_SIZE ", ignoring this field", len);
7883  buf->Skip(len);
7884  } else {
7885  _cur.grfconfig->num_valid_params = std::min<byte>(buf->ReadByte(), lengthof(_cur.grfconfig->param));
7886  }
7887  return true;
7888 }
7889 
7891 static bool ChangeGRFPalette(size_t len, ByteReader *buf)
7892 {
7893  if (len != 1) {
7894  grfmsg(2, "StaticGRFInfo: expected only 1 byte for 'INFO'->'PALS' but got " PRINTF_SIZE ", ignoring this field", len);
7895  buf->Skip(len);
7896  } else {
7897  char data = buf->ReadByte();
7898  GRFPalette pal = GRFP_GRF_UNSET;
7899  switch (data) {
7900  case '*':
7901  case 'A': pal = GRFP_GRF_ANY; break;
7902  case 'W': pal = GRFP_GRF_WINDOWS; break;
7903  case 'D': pal = GRFP_GRF_DOS; break;
7904  default:
7905  grfmsg(2, "StaticGRFInfo: unexpected value '%02x' for 'INFO'->'PALS', ignoring this field", data);
7906  break;
7907  }
7908  if (pal != GRFP_GRF_UNSET) {
7909  _cur.grfconfig->palette &= ~GRFP_GRF_MASK;
7910  _cur.grfconfig->palette |= pal;
7911  }
7912  }
7913  return true;
7914 }
7915 
7917 static bool ChangeGRFBlitter(size_t len, ByteReader *buf)
7918 {
7919  if (len != 1) {
7920  grfmsg(2, "StaticGRFInfo: expected only 1 byte for 'INFO'->'BLTR' but got " PRINTF_SIZE ", ignoring this field", len);
7921  buf->Skip(len);
7922  } else {
7923  char data = buf->ReadByte();
7924  GRFPalette pal = GRFP_BLT_UNSET;
7925  switch (data) {
7926  case '8': pal = GRFP_BLT_UNSET; break;
7927  case '3': pal = GRFP_BLT_32BPP; break;
7928  default:
7929  grfmsg(2, "StaticGRFInfo: unexpected value '%02x' for 'INFO'->'BLTR', ignoring this field", data);
7930  return true;
7931  }
7932  _cur.grfconfig->palette &= ~GRFP_BLT_MASK;
7933  _cur.grfconfig->palette |= pal;
7934  }
7935  return true;
7936 }
7937 
7939 static bool ChangeGRFVersion(size_t len, ByteReader *buf)
7940 {
7941  if (len != 4) {
7942  grfmsg(2, "StaticGRFInfo: expected 4 bytes for 'INFO'->'VRSN' but got " PRINTF_SIZE ", ignoring this field", len);
7943  buf->Skip(len);
7944  } else {
7945  /* Set min_loadable_version as well (default to minimal compatibility) */
7946  _cur.grfconfig->version = _cur.grfconfig->min_loadable_version = buf->ReadDWord();
7947  }
7948  return true;
7949 }
7950 
7952 static bool ChangeGRFMinVersion(size_t len, ByteReader *buf)
7953 {
7954  if (len != 4) {
7955  grfmsg(2, "StaticGRFInfo: expected 4 bytes for 'INFO'->'MINV' but got " PRINTF_SIZE ", ignoring this field", len);
7956  buf->Skip(len);
7957  } else {
7958  _cur.grfconfig->min_loadable_version = buf->ReadDWord();
7959  if (_cur.grfconfig->version == 0) {
7960  grfmsg(2, "StaticGRFInfo: 'MINV' defined before 'VRSN' or 'VRSN' set to 0, ignoring this field");
7961  _cur.grfconfig->min_loadable_version = 0;
7962  }
7963  if (_cur.grfconfig->version < _cur.grfconfig->min_loadable_version) {
7964  grfmsg(2, "StaticGRFInfo: 'MINV' defined as %d, limiting it to 'VRSN'", _cur.grfconfig->min_loadable_version);
7966  }
7967  }
7968  return true;
7969 }
7970 
7972 
7974 static bool ChangeGRFParamName(byte langid, const char *str)
7975 {
7976  AddGRFTextToList(_cur_parameter->name, langid, _cur.grfconfig->ident.grfid, false, str);
7977  return true;
7978 }
7979 
7981 static bool ChangeGRFParamDescription(byte langid, const char *str)
7982 {
7983  AddGRFTextToList(_cur_parameter->desc, langid, _cur.grfconfig->ident.grfid, true, str);
7984  return true;
7985 }
7986 
7988 static bool ChangeGRFParamType(size_t len, ByteReader *buf)
7989 {
7990  if (len != 1) {
7991  grfmsg(2, "StaticGRFInfo: expected 1 byte for 'INFO'->'PARA'->'TYPE' but got " PRINTF_SIZE ", ignoring this field", len);
7992  buf->Skip(len);
7993  } else {
7994  GRFParameterType type = (GRFParameterType)buf->ReadByte();
7995  if (type < PTYPE_END) {
7996  _cur_parameter->type = type;
7997  } else {
7998  grfmsg(3, "StaticGRFInfo: unknown parameter type %d, ignoring this field", type);
7999  }
8000  }
8001  return true;
8002 }
8003 
8005 static bool ChangeGRFParamLimits(size_t len, ByteReader *buf)
8006 {
8008  grfmsg(2, "StaticGRFInfo: 'INFO'->'PARA'->'LIMI' is only valid for parameters with type uint/enum, ignoring this field");
8009  buf->Skip(len);
8010  } else if (len != 8) {
8011  grfmsg(2, "StaticGRFInfo: expected 8 bytes for 'INFO'->'PARA'->'LIMI' but got " PRINTF_SIZE ", ignoring this field", len);
8012  buf->Skip(len);
8013  } else {
8014  uint32 min_value = buf->ReadDWord();
8015  uint32 max_value = buf->ReadDWord();
8016  if (min_value <= max_value) {
8017  _cur_parameter->min_value = min_value;
8018  _cur_parameter->max_value = max_value;
8019  } else {
8020  grfmsg(2, "StaticGRFInfo: 'INFO'->'PARA'->'LIMI' values are incoherent, ignoring this field");
8021  }
8022  }
8023  return true;
8024 }
8025 
8027 static bool ChangeGRFParamMask(size_t len, ByteReader *buf)
8028 {
8029  if (len < 1 || len > 3) {
8030  grfmsg(2, "StaticGRFInfo: expected 1 to 3 bytes for 'INFO'->'PARA'->'MASK' but got " PRINTF_SIZE ", ignoring this field", len);
8031  buf->Skip(len);
8032  } else {
8033  byte param_nr = buf->ReadByte();
8034  if (param_nr >= lengthof(_cur.grfconfig->param)) {
8035  grfmsg(2, "StaticGRFInfo: invalid parameter number in 'INFO'->'PARA'->'MASK', param %d, ignoring this field", param_nr);
8036  buf->Skip(len - 1);
8037  } else {
8038  _cur_parameter->param_nr = param_nr;
8039  if (len >= 2) _cur_parameter->first_bit = std::min<byte>(buf->ReadByte(), 31);
8040  if (len >= 3) _cur_parameter->num_bit = std::min<byte>(buf->ReadByte(), 32 - _cur_parameter->first_bit);
8041  }
8042  }
8043 
8044  return true;
8045 }
8046 
8048 static bool ChangeGRFParamDefault(size_t len, ByteReader *buf)
8049 {
8050  if (len != 4) {
8051  grfmsg(2, "StaticGRFInfo: expected 4 bytes for 'INFO'->'PARA'->'DEFA' but got " PRINTF_SIZE ", ignoring this field", len);
8052  buf->Skip(len);
8053  } else {
8054  _cur_parameter->def_value = buf->ReadDWord();
8055  }
8056  _cur.grfconfig->has_param_defaults = true;
8057  return true;
8058 }
8059 
8060 typedef bool (*DataHandler)(size_t, ByteReader *);
8061 typedef bool (*TextHandler)(byte, const char *str);
8062 typedef bool (*BranchHandler)(ByteReader *);
8063 
8074  id(0),
8075  type(0)
8076  {}
8077 
8083  AllowedSubtags(uint32 id, DataHandler handler) :
8084  id(id),
8085  type('B')
8086  {
8087  this->handler.data = handler;
8088  }
8089 
8095  AllowedSubtags(uint32 id, TextHandler handler) :
8096  id(id),
8097  type('T')
8098  {
8099  this->handler.text = handler;
8100  }
8101 
8107  AllowedSubtags(uint32 id, BranchHandler handler) :
8108  id(id),
8109  type('C')
8110  {
8111  this->handler.call_handler = true;
8112  this->handler.u.branch = handler;
8113  }
8114 
8121  id(id),
8122  type('C')
8123  {
8124  this->handler.call_handler = false;
8125  this->handler.u.subtags = subtags;
8126  }
8127 
8128  uint32 id;
8129  byte type;
8130  union {
8133  struct {
8134  union {
8137  } u;
8139  };
8140  } handler;
8141 };
8142 
8143 static bool SkipUnknownInfo(ByteReader *buf, byte type);
8144 static bool HandleNodes(ByteReader *buf, AllowedSubtags *tags);
8145 
8153 {
8154  byte type = buf->ReadByte();
8155  while (type != 0) {
8156  uint32 id = buf->ReadDWord();
8157  if (type != 'T' || id > _cur_parameter->max_value) {
8158  grfmsg(2, "StaticGRFInfo: all child nodes of 'INFO'->'PARA'->param_num->'VALU' should have type 't' and the value/bit number as id");
8159  if (!SkipUnknownInfo(buf, type)) return false;
8160  type = buf->ReadByte();
8161  continue;
8162  }
8163 
8164  byte langid = buf->ReadByte();
8165  const char *name_string = buf->ReadString();
8166 
8167  std::pair<uint32, GRFTextList> *val_name = _cur_parameter->value_names.Find(id);
8168  if (val_name != _cur_parameter->value_names.End()) {
8169  AddGRFTextToList(val_name->second, langid, _cur.grfconfig->ident.grfid, false, name_string);
8170  } else {
8171  GRFTextList list;
8172  AddGRFTextToList(list, langid, _cur.grfconfig->ident.grfid, false, name_string);
8173  _cur_parameter->value_names.Insert(id, list);
8174  }
8175 
8176  type = buf->ReadByte();
8177  }
8178  return true;
8179 }
8180 
8190  AllowedSubtags()
8191 };
8192 
8200 {
8201  byte type = buf->ReadByte();
8202  while (type != 0) {
8203  uint32 id = buf->ReadDWord();
8204  if (type != 'C' || id >= _cur.grfconfig->num_valid_params) {
8205  grfmsg(2, "StaticGRFInfo: all child nodes of 'INFO'->'PARA' should have type 'C' and their parameter number as id");
8206  if (!SkipUnknownInfo(buf, type)) return false;
8207  type = buf->ReadByte();
8208  continue;
8209  }
8210 
8211  if (id >= _cur.grfconfig->param_info.size()) {
8212  _cur.grfconfig->param_info.resize(id + 1);
8213  }
8214  if (_cur.grfconfig->param_info[id] == nullptr) {
8215  _cur.grfconfig->param_info[id] = new GRFParameterInfo(id);
8216  }
8217  _cur_parameter = _cur.grfconfig->param_info[id];
8218  /* Read all parameter-data and process each node. */
8219  if (!HandleNodes(buf, _tags_parameters)) return false;
8220  type = buf->ReadByte();
8221  }
8222  return true;
8223 }
8224 
8227  AllowedSubtags('NAME', ChangeGRFName),
8229  AllowedSubtags('URL_', ChangeGRFURL),
8236  AllowedSubtags()
8237 };
8238 
8241  AllowedSubtags('INFO', _tags_info),
8242  AllowedSubtags()
8243 };
8244 
8245 
8252 static bool SkipUnknownInfo(ByteReader *buf, byte type)
8253 {
8254  /* type and id are already read */
8255  switch (type) {
8256  case 'C': {
8257  byte new_type = buf->ReadByte();
8258  while (new_type != 0) {
8259  buf->ReadDWord(); // skip the id
8260  if (!SkipUnknownInfo(buf, new_type)) return false;
8261  new_type = buf->ReadByte();
8262  }
8263  break;
8264  }
8265 
8266  case 'T':
8267  buf->ReadByte(); // lang
8268  buf->ReadString(); // actual text
8269  break;
8270 
8271  case 'B': {
8272  uint16 size = buf->ReadWord();
8273  buf->Skip(size);
8274  break;
8275  }
8276 
8277  default:
8278  return false;
8279  }
8280 
8281  return true;
8282 }
8283 
8292 static bool HandleNode(byte type, uint32 id, ByteReader *buf, AllowedSubtags subtags[])
8293 {
8294  uint i = 0;
8295  AllowedSubtags *tag;
8296  while ((tag = &subtags[i++])->type != 0) {
8297  if (tag->id != BSWAP32(id) || tag->type != type) continue;
8298  switch (type) {
8299  default: NOT_REACHED();
8300 
8301  case 'T': {
8302  byte langid = buf->ReadByte();
8303  return tag->handler.text(langid, buf->ReadString());
8304  }
8305 
8306  case 'B': {
8307  size_t len = buf->ReadWord();
8308  if (buf->Remaining() < len) return false;
8309  return tag->handler.data(len, buf);
8310  }
8311 
8312  case 'C': {
8313  if (tag->handler.call_handler) {
8314  return tag->handler.u.branch(buf);
8315  }
8316  return HandleNodes(buf, tag->handler.u.subtags);
8317  }
8318  }
8319  }
8320  grfmsg(2, "StaticGRFInfo: unknown type/id combination found, type=%c, id=%x", type, id);
8321  return SkipUnknownInfo(buf, type);
8322 }
8323 
8330 static bool HandleNodes(ByteReader *buf, AllowedSubtags subtags[])
8331 {
8332  byte type = buf->ReadByte();
8333  while (type != 0) {
8334  uint32 id = buf->ReadDWord();
8335  if (!HandleNode(type, id, buf, subtags)) return false;
8336  type = buf->ReadByte();
8337  }
8338  return true;
8339 }
8340 
8345 static void StaticGRFInfo(ByteReader *buf)
8346 {
8347  /* <14> <type> <id> <text/data...> */
8348  HandleNodes(buf, _tags_root);
8349 }
8350 
8356 static void GRFUnsafe(ByteReader *buf)
8357 {
8358  SetBit(_cur.grfconfig->flags, GCF_UNSAFE);
8359 
8360  /* Skip remainder of GRF */
8361  _cur.skip_sprites = -1;
8362 }
8363 
8364 
8367 {
8368  _ttdpatch_flags[0] = ((_settings_game.station.never_expire_airports ? 1U : 0U) << 0x0C) // keepsmallairport
8369  | (1U << 0x0D) // newairports
8370  | (1U << 0x0E) // largestations
8371  | ((_settings_game.construction.max_bridge_length > 16 ? 1U : 0U) << 0x0F) // longbridges
8372  | (0U << 0x10) // loadtime
8373  | (1U << 0x12) // presignals
8374  | (1U << 0x13) // extpresignals
8375  | ((_settings_game.vehicle.never_expire_vehicles ? 1U : 0U) << 0x16) // enginespersist
8376  | (1U << 0x1B) // multihead
8377  | (1U << 0x1D) // lowmemory
8378  | (1U << 0x1E); // generalfixes
8379 
8380  _ttdpatch_flags[1] = ((_settings_game.economy.station_noise_level ? 1U : 0U) << 0x07) // moreairports - based on units of noise
8381  | (1U << 0x08) // mammothtrains
8382  | (1U << 0x09) // trainrefit
8383  | (0U << 0x0B) // subsidiaries
8384  | ((_settings_game.order.gradual_loading ? 1U : 0U) << 0x0C) // gradualloading
8385  | (1U << 0x12) // unifiedmaglevmode - set bit 0 mode. Not revelant to OTTD
8386  | (1U << 0x13) // unifiedmaglevmode - set bit 1 mode
8387  | (1U << 0x14) // bridgespeedlimits
8388  | (1U << 0x16) // eternalgame
8389  | (1U << 0x17) // newtrains
8390  | (1U << 0x18) // newrvs
8391  | (1U << 0x19) // newships
8392  | (1U << 0x1A) // newplanes
8393  | ((_settings_game.construction.train_signal_side == 1 ? 1U : 0U) << 0x1B) // signalsontrafficside
8394  | ((_settings_game.vehicle.disable_elrails ? 0U : 1U) << 0x1C); // electrifiedrailway
8395 
8396  _ttdpatch_flags[2] = (1U << 0x01) // loadallgraphics - obsolote
8397  | (1U << 0x03) // semaphores
8398  | (1U << 0x0A) // newobjects
8399  | (0U << 0x0B) // enhancedgui
8400  | (0U << 0x0C) // newagerating
8401  | ((_settings_game.construction.build_on_slopes ? 1U : 0U) << 0x0D) // buildonslopes
8402  | (1U << 0x0E) // fullloadany
8403  | (1U << 0x0F) // planespeed
8404  | (0U << 0x10) // moreindustriesperclimate - obsolete
8405  | (0U << 0x11) // moretoylandfeatures
8406  | (1U << 0x12) // newstations
8407  | (1U << 0x13) // tracktypecostdiff
8408  | (1U << 0x14) // manualconvert
8409  | ((_settings_game.construction.build_on_slopes ? 1U : 0U) << 0x15) // buildoncoasts
8410  | (1U << 0x16) // canals
8411  | (1U << 0x17) // newstartyear
8412  | ((_settings_game.vehicle.freight_trains > 1 ? 1U : 0U) << 0x18) // freighttrains
8413  | (1U << 0x19) // newhouses
8414  | (1U << 0x1A) // newbridges
8415  | (1U << 0x1B) // newtownnames
8416  | (1U << 0x1C) // moreanimation
8417  | ((_settings_game.vehicle.wagon_speed_limits ? 1U : 0U) << 0x1D) // wagonspeedlimits
8418  | (1U << 0x1E) // newshistory
8419  | (0U << 0x1F); // custombridgeheads
8420 
8421  _ttdpatch_flags[3] = (0U << 0x00) // newcargodistribution
8422  | (1U << 0x01) // windowsnap
8423  | ((_settings_game.economy.allow_town_roads || _generating_world ? 0U : 1U) << 0x02) // townbuildnoroad
8424  | (1U << 0x03) // pathbasedsignalling
8425  | (0U << 0x04) // aichoosechance
8426  | (1U << 0x05) // resolutionwidth
8427  | (1U << 0x06) // resolutionheight
8428  | (1U << 0x07) // newindustries
8429  | ((_settings_game.order.improved_load ? 1U : 0U) << 0x08) // fifoloading
8430  | (0U << 0x09) // townroadbranchprob
8431  | (0U << 0x0A) // tempsnowline
8432  | (1U << 0x0B) // newcargo
8433  | (1U << 0x0C) // enhancemultiplayer
8434  | (1U << 0x0D) // onewayroads
8435  | (1U << 0x0E) // irregularstations
8436  | (1U << 0x0F) // statistics
8437  | (1U << 0x10) // newsounds
8438  | (1U << 0x11) // autoreplace
8439  | (1U << 0x12) // autoslope
8440  | (0U << 0x13) // followvehicle
8441  | (1U << 0x14) // trams
8442  | (0U << 0x15) // enhancetunnels
8443  | (1U << 0x16) // shortrvs
8444  | (1U << 0x17) // articulatedrvs
8445  | ((_settings_game.vehicle.dynamic_engines ? 1U : 0U) << 0x18) // dynamic engines
8446  | (1U << 0x1E) // variablerunningcosts
8447  | (1U << 0x1F); // any switch is on
8448 
8449  _ttdpatch_flags[4] = (1U << 0x00) // larger persistent storage
8450  | ((_settings_game.economy.inflation ? 1U : 0U) << 0x01); // inflation is on
8451 }
8452 
8454 static void ResetCustomStations()
8455 {
8456  for (GRFFile * const file : _grf_files) {
8457  StationSpec **&stations = file->stations;
8458  if (stations == nullptr) continue;
8459  for (uint i = 0; i < NUM_STATIONS_PER_GRF; i++) {
8460  if (stations[i] == nullptr) continue;
8461  StationSpec *statspec = stations[i];
8462 
8463  /* Release this station */
8464  delete statspec;
8465  }
8466 
8467  /* Free and reset the station data */
8468  free(stations);
8469  stations = nullptr;
8470  }
8471 }
8472 
8474 static void ResetCustomHouses()
8475 {
8476  for (GRFFile * const file : _grf_files) {
8477  HouseSpec **&housespec = file->housespec;
8478  if (housespec == nullptr) continue;
8479  for (uint i = 0; i < NUM_HOUSES_PER_GRF; i++) {
8480  free(housespec[i]);
8481  }
8482 
8483  free(housespec);
8484  housespec = nullptr;
8485  }
8486 }
8487 
8489 static void ResetCustomAirports()
8490 {
8491  for (GRFFile * const file : _grf_files) {
8492  AirportSpec **aslist = file->airportspec;
8493  if (aslist != nullptr) {
8494  for (uint i = 0; i < NUM_AIRPORTS_PER_GRF; i++) {
8495  AirportSpec *as = aslist[i];
8496 
8497  if (as != nullptr) {
8498  /* We need to remove the tiles layouts */
8499  for (int j = 0; j < as->num_table; j++) {
8500  /* remove the individual layouts */
8501  free(as->table[j]);
8502  }
8503  free(as->table);
8504  free(as->depot_table);
8505  free(as->rotation);
8506 
8507  free(as);
8508  }
8509  }
8510  free(aslist);
8511  file->airportspec = nullptr;
8512  }
8513 
8514  AirportTileSpec **&airporttilespec = file->airtspec;
8515  if (airporttilespec != nullptr) {
8516  for (uint i = 0; i < NUM_AIRPORTTILES_PER_GRF; i++) {
8517  free(airporttilespec[i]);
8518  }
8519  free(airporttilespec);
8520  airporttilespec = nullptr;
8521  }
8522  }
8523 }
8524 
8527 {
8528  for (GRFFile * const file : _grf_files) {
8529  IndustrySpec **&industryspec = file->industryspec;
8530  IndustryTileSpec **&indtspec = file->indtspec;
8531 
8532  /* We are verifiying both tiles and industries specs loaded from the grf file
8533  * First, let's deal with industryspec */
8534  if (industryspec != nullptr) {
8535  for (uint i = 0; i < NUM_INDUSTRYTYPES_PER_GRF; i++) {
8536  IndustrySpec *ind = industryspec[i];
8537  delete ind;
8538  }
8539 
8540  free(industryspec);
8541  industryspec = nullptr;
8542  }
8543 
8544  if (indtspec == nullptr) continue;
8545  for (uint i = 0; i < NUM_INDUSTRYTILES_PER_GRF; i++) {
8546  free(indtspec[i]);
8547  }
8548 
8549  free(indtspec);
8550  indtspec = nullptr;
8551  }
8552 }
8553 
8555 static void ResetCustomObjects()
8556 {
8557  for (GRFFile * const file : _grf_files) {
8558  ObjectSpec **&objectspec = file->objectspec;
8559  if (objectspec == nullptr) continue;
8560  for (uint i = 0; i < NUM_OBJECTS_PER_GRF; i++) {
8561  free(objectspec[i]);
8562  }
8563 
8564  free(objectspec);
8565  objectspec = nullptr;
8566  }
8567 }
8568 
8570 static void ResetNewGRF()
8571 {
8572  for (GRFFile * const file : _grf_files) {
8573  delete file;
8574  }
8575 
8576  _grf_files.clear();
8577  _cur.grffile = nullptr;
8578 }
8579 
8581 static void ResetNewGRFErrors()
8582 {
8583  for (GRFConfig *c = _grfconfig; c != nullptr; c = c->next) {
8584  if (!HasBit(c->flags, GCF_COPY) && c->error != nullptr) {
8585  delete c->error;
8586  c->error = nullptr;
8587  }
8588  }
8589 }
8590 
8595 {
8596  CleanUpStrings();
8597  CleanUpGRFTownNames();
8598 
8599  /* Copy/reset original engine info data */
8600  SetupEngines();
8601 
8602  /* Copy/reset original bridge info data */
8603  ResetBridges();
8604 
8605  /* Reset rail type information */
8606  ResetRailTypes();
8607 
8608  /* Copy/reset original road type info data */
8609  ResetRoadTypes();
8610 
8611  /* Allocate temporary refit/cargo class data */
8612  _gted = CallocT<GRFTempEngineData>(Engine::GetPoolSize());
8613 
8614  /* Fill rail type label temporary data for default trains */
8615  for (const Engine *e : Engine::IterateType(VEH_TRAIN)) {
8616  _gted[e->index].railtypelabel = GetRailTypeInfo(e->u.rail.railtype)->label;
8617  }
8618 
8619  /* Reset GRM reservations */
8620  memset(&_grm_engines, 0, sizeof(_grm_engines));
8621  memset(&_grm_cargoes, 0, sizeof(_grm_cargoes));
8622 
8623  /* Reset generic feature callback lists */
8625 
8626  /* Reset price base data */
8628 
8629  /* Reset the curencies array */
8630  ResetCurrencies();
8631 
8632  /* Reset the house array */
8634  ResetHouses();
8635 
8636  /* Reset the industries structures*/
8638  ResetIndustries();
8639 
8640  /* Reset the objects. */
8641  ObjectClass::Reset();
8643  ResetObjects();
8644 
8645  /* Reset station classes */
8646  StationClass::Reset();
8648 
8649  /* Reset airport-related structures */
8650  AirportClass::Reset();
8654 
8655  /* Reset canal sprite groups and flags */
8656  memset(_water_feature, 0, sizeof(_water_feature));
8657 
8658  /* Reset the snowline table. */
8659  ClearSnowLine();
8660 
8661  /* Reset NewGRF files */
8662  ResetNewGRF();
8663 
8664  /* Reset NewGRF errors. */
8666 
8667  /* Set up the default cargo types */
8669 
8670  /* Reset misc GRF features and train list display variables */
8671  _misc_grf_features = 0;
8672 
8674  _loaded_newgrf_features.used_liveries = 1 << LS_DEFAULT;
8677 
8678  /* Clear all GRF overrides */
8679  _grf_id_overrides.clear();
8680 
8681  InitializeSoundPool();
8682  _spritegroup_pool.CleanPool();
8683 }
8684 
8689 {
8690  /* Reset override managers */
8691  _engine_mngr.ResetToDefaultMapping();
8692  _house_mngr.ResetMapping();
8693  _industry_mngr.ResetMapping();
8694  _industile_mngr.ResetMapping();
8695  _airport_mngr.ResetMapping();
8696  _airporttile_mngr.ResetMapping();
8697 }
8698 
8704 {
8705  memset(_cur.grffile->cargo_map, 0xFF, sizeof(_cur.grffile->cargo_map));
8706 
8707  for (CargoID c = 0; c < NUM_CARGO; c++) {
8708  const CargoSpec *cs = CargoSpec::Get(c);
8709  if (!cs->IsValid()) continue;
8710 
8711  if (_cur.grffile->cargo_list.size() == 0) {
8712  /* Default translation table, so just a straight mapping to bitnum */
8713  _cur.grffile->cargo_map[c] = cs->bitnum;
8714  } else {
8715  /* Check the translation table for this cargo's label */
8716  int idx = find_index(_cur.grffile->cargo_list, {cs->label});
8717  if (idx >= 0) _cur.grffile->cargo_map[c] = idx;
8718  }
8719  }
8720 }
8721 
8726 static void InitNewGRFFile(const GRFConfig *config)
8727 {
8728  GRFFile *newfile = GetFileByFilename(config->filename);
8729  if (newfile != nullptr) {
8730  /* We already loaded it once. */
8731  _cur.grffile = newfile;
8732  return;
8733  }
8734 
8735  newfile = new GRFFile(config);
8736  _grf_files.push_back(_cur.grffile = newfile);
8737 }
8738 
8744 {
8745  this->filename = stredup(config->filename);
8746  this->grfid = config->ident.grfid;
8747 
8748  /* Initialise local settings to defaults */
8749  this->traininfo_vehicle_pitch = 0;
8750  this->traininfo_vehicle_width = TRAININFO_DEFAULT_VEHICLE_WIDTH;
8751 
8752  /* Mark price_base_multipliers as 'not set' */
8753  for (Price i = PR_BEGIN; i < PR_END; i++) {
8754  this->price_base_multipliers[i] = INVALID_PRICE_MODIFIER;
8755  }
8756 
8757  /* Initialise rail type map with default rail types */
8758  std::fill(std::begin(this->railtype_map), std::end(this->railtype_map), INVALID_RAILTYPE);
8759  this->railtype_map[0] = RAILTYPE_RAIL;
8760  this->railtype_map[1] = RAILTYPE_ELECTRIC;
8761  this->railtype_map[2] = RAILTYPE_MONO;
8762  this->railtype_map[3] = RAILTYPE_MAGLEV;
8763 
8764  /* Initialise road type map with default road types */
8765  std::fill(std::begin(this->roadtype_map), std::end(this->roadtype_map), INVALID_ROADTYPE);
8766  this->roadtype_map[0] = ROADTYPE_ROAD;
8767 
8768  /* Initialise tram type map with default tram types */
8769  std::fill(std::begin(this->tramtype_map), std::end(this->tramtype_map), INVALID_ROADTYPE);
8770  this->tramtype_map[0] = ROADTYPE_TRAM;
8771 
8772  /* Copy the initial parameter list
8773  * 'Uninitialised' parameters are zeroed as that is their default value when dynamically creating them. */
8774  static_assert(lengthof(this->param) == lengthof(config->param) && lengthof(this->param) == 0x80);
8775 
8776  assert(config->num_params <= lengthof(config->param));
8777  this->param_end = config->num_params;
8778  if (this->param_end > 0) {
8779  MemCpyT(this->param, config->param, this->param_end);
8780  }
8781 }
8782 
8783 GRFFile::~GRFFile()
8784 {
8785  free(this->filename);
8786  delete[] this->language_map;
8787 }
8788 
8789 
8793 static void CalculateRefitMasks()
8794 {
8795  CargoTypes original_known_cargoes = 0;
8796  for (int ct = 0; ct != NUM_ORIGINAL_CARGO; ++ct) {
8798  if (cid != CT_INVALID) SetBit(original_known_cargoes, cid);
8799  }
8800 
8801  for (Engine *e : Engine::Iterate()) {
8802  EngineID engine = e->index;
8803  EngineInfo *ei = &e->info;
8804  bool only_defaultcargo;
8805 
8806  /* If the NewGRF did not set any cargo properties, we apply default values. */
8807  if (_gted[engine].defaultcargo_grf == nullptr) {
8808  /* If the vehicle has any capacity, apply the default refit masks */
8809  if (e->type != VEH_TRAIN || e->u.rail.capacity != 0) {
8810  static constexpr byte T = 1 << LT_TEMPERATE;
8811  static constexpr byte A = 1 << LT_ARCTIC;
8812  static constexpr byte S = 1 << LT_TROPIC;
8813  static constexpr byte Y = 1 << LT_TOYLAND;
8814  static const struct DefaultRefitMasks {
8815  byte climate;
8816  CargoType cargo_type;
8817  CargoTypes cargo_allowed;
8818  CargoTypes cargo_disallowed;
8819  } _default_refit_masks[] = {
8820  {T | A | S | Y, CT_PASSENGERS, CC_PASSENGERS, 0},
8821  {T | A | S , CT_MAIL, CC_MAIL, 0},
8822  {T | A | S , CT_VALUABLES, CC_ARMOURED, CC_LIQUID},
8823  { Y, CT_MAIL, CC_MAIL | CC_ARMOURED, CC_LIQUID},
8824  {T | A , CT_COAL, CC_BULK, 0},
8825  { S , CT_COPPER_ORE, CC_BULK, 0},
8826  { Y, CT_SUGAR, CC_BULK, 0},
8827  {T | A | S , CT_OIL, CC_LIQUID, 0},
8828  { Y, CT_COLA, CC_LIQUID, 0},
8829  {T , CT_GOODS, CC_PIECE_GOODS | CC_EXPRESS, CC_LIQUID | CC_PASSENGERS},
8830  { A | S , CT_GOODS, CC_PIECE_GOODS | CC_EXPRESS, CC_LIQUID | CC_PASSENGERS | CC_REFRIGERATED},
8831  { A | S , CT_FOOD, CC_REFRIGERATED, 0},
8832  { Y, CT_CANDY, CC_PIECE_GOODS | CC_EXPRESS, CC_LIQUID | CC_PASSENGERS},
8833  };
8834 
8835  if (e->type == VEH_AIRCRAFT) {
8836  /* Aircraft default to "light" cargoes */
8837  _gted[engine].cargo_allowed = CC_PASSENGERS | CC_MAIL | CC_ARMOURED | CC_EXPRESS;
8838  _gted[engine].cargo_disallowed = CC_LIQUID;
8839  } else if (e->type == VEH_SHIP) {
8840  switch (ei->cargo_type) {
8841  case CT_PASSENGERS:
8842  /* Ferries */
8843  _gted[engine].cargo_allowed = CC_PASSENGERS;
8844  _gted[engine].cargo_disallowed = 0;
8845  break;
8846  case CT_OIL:
8847  /* Tankers */
8848  _gted[engine].cargo_allowed = CC_LIQUID;
8849  _gted[engine].cargo_disallowed = 0;
8850  break;
8851  default:
8852  /* Cargo ships */
8853  if (_settings_game.game_creation.landscape == LT_TOYLAND) {
8854  /* No tanker in toyland :( */
8855  _gted[engine].cargo_allowed = CC_MAIL | CC_ARMOURED | CC_EXPRESS | CC_BULK | CC_PIECE_GOODS | CC_LIQUID;
8856  _gted[engine].cargo_disallowed = CC_PASSENGERS;
8857  } else {
8858  _gted[engine].cargo_allowed = CC_MAIL | CC_ARMOURED | CC_EXPRESS | CC_BULK | CC_PIECE_GOODS;
8859  _gted[engine].cargo_disallowed = CC_LIQUID | CC_PASSENGERS;
8860  }
8861  break;
8862  }
8863  e->u.ship.old_refittable = true;
8864  } else if (e->type == VEH_TRAIN && e->u.rail.railveh_type != RAILVEH_WAGON) {
8865  /* Train engines default to all cargoes, so you can build single-cargo consists with fast engines.
8866  * Trains loading multiple cargoes may start stations accepting unwanted cargoes. */
8867  _gted[engine].cargo_allowed = CC_PASSENGERS | CC_MAIL | CC_ARMOURED | CC_EXPRESS | CC_BULK | CC_PIECE_GOODS | CC_LIQUID;
8868  _gted[engine].cargo_disallowed = 0;
8869  } else {
8870  /* Train wagons and road vehicles are classified by their default cargo type */
8871  for (const auto &drm : _default_refit_masks) {
8872  if (!HasBit(drm.climate, _settings_game.game_creation.landscape)) continue;
8873  if (drm.cargo_type != ei->cargo_type) continue;
8874 
8875  _gted[engine].cargo_allowed = drm.cargo_allowed;
8876  _gted[engine].cargo_disallowed = drm.cargo_disallowed;
8877  break;
8878  }
8879 
8880  /* All original cargoes have specialised vehicles, so exclude them */
8881  _gted[engine].ctt_exclude_mask = original_known_cargoes;
8882  }
8883  }
8884  _gted[engine].UpdateRefittability(_gted[engine].cargo_allowed != 0);
8885 
8886  /* Translate cargo_type using the original climate-specific cargo table. */
8887  ei->cargo_type = GetDefaultCargoID(_settings_game.game_creation.landscape, static_cast<CargoType>(ei->cargo_type));
8888  if (ei->cargo_type != CT_INVALID) ClrBit(_gted[engine].ctt_exclude_mask, ei->cargo_type);
8889  }
8890 
8891  /* Compute refittability */
8892  {
8893  CargoTypes mask = 0;
8894  CargoTypes not_mask = 0;
8895  CargoTypes xor_mask = ei->refit_mask;
8896 
8897  /* If the original masks set by the grf are zero, the vehicle shall only carry the default cargo.
8898  * Note: After applying the translations, the vehicle may end up carrying no defined cargo. It becomes unavailable in that case. */
8899  only_defaultcargo = _gted[engine].refittability != GRFTempEngineData::NONEMPTY;
8900 
8901  if (_gted[engine].cargo_allowed != 0) {
8902  /* Build up the list of cargo types from the set cargo classes. */
8903  for (const CargoSpec *cs : CargoSpec::Iterate()) {
8904  if (_gted[engine].cargo_allowed & cs->classes) SetBit(mask, cs->Index());
8905  if (_gted[engine].cargo_disallowed & cs->classes) SetBit(not_mask, cs->Index());
8906  }
8907  }
8908 
8909  ei->refit_mask = ((mask & ~not_mask) ^ xor_mask) & _cargo_mask;
8910 
8911  /* Apply explicit refit includes/excludes. */
8912  ei->refit_mask |= _gted[engine].ctt_include_mask;
8913  ei->refit_mask &= ~_gted[engine].ctt_exclude_mask;
8914  }
8915 
8916  /* Clear invalid cargoslots (from default vehicles or pre-NewCargo GRFs) */
8917  if (ei->cargo_type != CT_INVALID && !HasBit(_cargo_mask, ei->cargo_type)) ei->cargo_type = CT_INVALID;
8918 
8919  /* Ensure that the vehicle is either not refittable, or that the default cargo is one of the refittable cargoes.
8920  * Note: Vehicles refittable to no cargo are handle differently to vehicle refittable to a single cargo. The latter might have subtypes. */
8921  if (!only_defaultcargo && (e->type != VEH_SHIP || e->u.ship.old_refittable) && ei->cargo_type != CT_INVALID && !HasBit(ei->refit_mask, ei->cargo_type)) {
8922  ei->cargo_type = CT_INVALID;
8923  }
8924 
8925  /* Check if this engine's cargo type is valid. If not, set to the first refittable
8926  * cargo type. Finally disable the vehicle, if there is still no cargo. */
8927  if (ei->cargo_type == CT_INVALID && ei->refit_mask != 0) {
8928  /* Figure out which CTT to use for the default cargo, if it is 'first refittable'. */
8929  const uint8 *cargo_map_for_first_refittable = nullptr;
8930  {
8931  const GRFFile *file = _gted[engine].defaultcargo_grf;
8932  if (file == nullptr) file = e->GetGRF();
8933  if (file != nullptr && file->grf_version >= 8 && file->cargo_list.size() != 0) {
8934  cargo_map_for_first_refittable = file->cargo_map;
8935  }
8936  }
8937 
8938  if (cargo_map_for_first_refittable != nullptr) {
8939  /* Use first refittable cargo from cargo translation table */
8940  byte best_local_slot = 0xFF;
8941  for (CargoID cargo_type : SetCargoBitIterator(ei->refit_mask)) {
8942  byte local_slot = cargo_map_for_first_refittable[cargo_type];
8943  if (local_slot < best_local_slot) {
8944  best_local_slot = local_slot;
8945  ei->cargo_type = cargo_type;
8946  }
8947  }
8948  }
8949 
8950  if (ei->cargo_type == CT_INVALID) {
8951  /* Use first refittable cargo slot */
8952  ei->cargo_type = (CargoID)FindFirstBit(ei->refit_mask);
8953  }
8954  }
8955  if (ei->cargo_type == CT_INVALID) ei->climates = 0;
8956 
8957  /* Clear refit_mask for not refittable ships */
8958  if (e->type == VEH_SHIP && !e->u.ship.old_refittable) {
8959  ei->refit_mask = 0;
8960  }
8961  }
8962 }
8963 
8965 static void FinaliseCanals()
8966 {
8967  for (uint i = 0; i < CF_END; i++) {
8968  if (_water_feature[i].grffile != nullptr) {
8971  }
8972  }
8973 }
8974 
8976 static void FinaliseEngineArray()
8977 {
8978  for (Engine *e : Engine::Iterate()) {
8979  if (e->GetGRF() == nullptr) {
8980  const EngineIDMapping &eid = _engine_mngr[e->index];
8981  if (eid.grfid != INVALID_GRFID || eid.internal_id != eid.substitute_id) {
8982  e->info.string_id = STR_NEWGRF_INVALID_ENGINE;
8983  }
8984  }
8985 
8986  if (!HasBit(e->info.climates, _settings_game.game_creation.landscape)) continue;
8987 
8988  /* When the train does not set property 27 (misc flags), but it
8989  * is overridden by a NewGRF graphically we want to disable the
8990  * flipping possibility. */
8991  if (e->type == VEH_TRAIN && !_gted[e->index].prop27_set && e->GetGRF() != nullptr && is_custom_sprite(e->u.rail.image_index)) {
8992  ClrBit(e->info.misc_flags, EF_RAIL_FLIPS);
8993  }
8994 
8995  /* Skip wagons, there livery is defined via the engine */
8996  if (e->type != VEH_TRAIN || e->u.rail.railveh_type != RAILVEH_WAGON) {
8999  /* Note: For ships and roadvehicles we assume that they cannot be refitted between passenger and freight */
9000 
9001  if (e->type == VEH_TRAIN) {
9002  SetBit(_loaded_newgrf_features.used_liveries, LS_FREIGHT_WAGON);
9003  switch (ls) {
9004  case LS_STEAM:
9005  case LS_DIESEL:
9006  case LS_ELECTRIC:
9007  case LS_MONORAIL:
9008  case LS_MAGLEV:
9009  SetBit(_loaded_newgrf_features.used_liveries, LS_PASSENGER_WAGON_STEAM + ls - LS_STEAM);
9010  break;
9011 
9012  case LS_DMU:
9013  case LS_EMU:
9014  SetBit(_loaded_newgrf_features.used_liveries, LS_PASSENGER_WAGON_DIESEL + ls - LS_DMU);
9015  break;
9016 
9017  default: NOT_REACHED();
9018  }
9019  }
9020  }
9021  }
9022 }
9023 
9025 static void FinaliseCargoArray()
9026 {
9027  for (CargoID c = 0; c < NUM_CARGO; c++) {
9028  CargoSpec *cs = CargoSpec::Get(c);
9029  if (!cs->IsValid()) {
9030  cs->name = cs->name_single = cs->units_volume = STR_NEWGRF_INVALID_CARGO;
9031  cs->quantifier = STR_NEWGRF_INVALID_CARGO_QUANTITY;
9032  cs->abbrev = STR_NEWGRF_INVALID_CARGO_ABBREV;
9033  }
9034  }
9035 }
9036 
9048 static bool IsHouseSpecValid(HouseSpec *hs, const HouseSpec *next1, const HouseSpec *next2, const HouseSpec *next3, const char *filename)
9049 {
9050  if (((hs->building_flags & BUILDING_HAS_2_TILES) != 0 &&
9051  (next1 == nullptr || !next1->enabled || (next1->building_flags & BUILDING_HAS_1_TILE) != 0)) ||
9052  ((hs->building_flags & BUILDING_HAS_4_TILES) != 0 &&
9053  (next2 == nullptr || !next2->enabled || (next2->building_flags & BUILDING_HAS_1_TILE) != 0 ||
9054  next3 == nullptr || !next3->enabled || (next3->building_flags & BUILDING_HAS_1_TILE) != 0))) {
9055  hs->enabled = false;
9056  if (filename != nullptr) Debug(grf, 1, "FinaliseHouseArray: {} defines house {} as multitile, but no suitable tiles follow. Disabling house.", filename, hs->grf_prop.local_id);
9057  return false;
9058  }
9059 
9060  /* Some places sum population by only counting north tiles. Other places use all tiles causing desyncs.
9061  * As the newgrf specs define population to be zero for non-north tiles, we just disable the offending house.
9062  * If you want to allow non-zero populations somewhen, make sure to sum the population of all tiles in all places. */
9063  if (((hs->building_flags & BUILDING_HAS_2_TILES) != 0 && next1->population != 0) ||
9064  ((hs->building_flags & BUILDING_HAS_4_TILES) != 0 && (next2->population != 0 || next3->population != 0))) {
9065  hs->enabled = false;
9066  if (filename != nullptr) Debug(grf, 1, "FinaliseHouseArray: {} defines multitile house {} with non-zero population on additional tiles. Disabling house.", filename, hs->grf_prop.local_id);
9067  return false;
9068  }
9069 
9070  /* Substitute type is also used for override, and having an override with a different size causes crashes.
9071  * This check should only be done for NewGRF houses because grf_prop.subst_id is not set for original houses.*/
9072  if (filename != nullptr && (hs->building_flags & BUILDING_HAS_1_TILE) != (HouseSpec::Get(hs->grf_prop.subst_id)->building_flags & BUILDING_HAS_1_TILE)) {
9073  hs->enabled = false;
9074  Debug(grf, 1, "FinaliseHouseArray: {} defines house {} with different house size then it's substitute type. Disabling house.", filename, hs->grf_prop.local_id);
9075  return false;
9076  }
9077 
9078  /* Make sure that additional parts of multitile houses are not available. */
9079  if ((hs->building_flags & BUILDING_HAS_1_TILE) == 0 && (hs->building_availability & HZ_ZONALL) != 0 && (hs->building_availability & HZ_CLIMALL) != 0) {
9080  hs->enabled = false;
9081  if (filename != nullptr) Debug(grf, 1, "FinaliseHouseArray: {} defines house {} without a size but marked it as available. Disabling house.", filename, hs->grf_prop.local_id);
9082  return false;
9083  }
9084 
9085  return true;
9086 }
9087 
9094 static void EnsureEarlyHouse(HouseZones bitmask)
9095 {
9096  Year min_year = MAX_YEAR;
9097 
9098  for (int i = 0; i < NUM_HOUSES; i++) {
9099  HouseSpec *hs = HouseSpec::Get(i);
9100  if (hs == nullptr || !hs->enabled) continue;
9101  if ((hs->building_availability & bitmask) != bitmask) continue;
9102  if (hs->min_year < min_year) min_year = hs->min_year;
9103  }
9104 
9105  if (min_year == 0) return;
9106 
9107  for (int i = 0; i < NUM_HOUSES; i++) {
9108  HouseSpec *hs = HouseSpec::Get(i);
9109  if (hs == nullptr || !hs->enabled) continue;
9110  if ((hs->building_availability & bitmask) != bitmask) continue;
9111  if (hs->min_year == min_year) hs->min_year = 0;
9112  }
9113 }
9114 
9121 static void FinaliseHouseArray()
9122 {
9123  /* If there are no houses with start dates before 1930, then all houses
9124  * with start dates of 1930 have them reset to 0. This is in order to be
9125  * compatible with TTDPatch, where if no houses have start dates before
9126  * 1930 and the date is before 1930, the game pretends that this is 1930.
9127  * If there have been any houses defined with start dates before 1930 then
9128  * the dates are left alone.
9129  * On the other hand, why 1930? Just 'fix' the houses with the lowest
9130  * minimum introduction date to 0.
9131  */
9132  for (GRFFile * const file : _grf_files) {
9133  HouseSpec **&housespec = file->housespec;
9134  if (housespec == nullptr) continue;
9135 
9136  for (int i = 0; i < NUM_HOUSES_PER_GRF; i++) {
9137  HouseSpec *hs = housespec[i];
9138 
9139  if (hs == nullptr) continue;
9140 
9141  const HouseSpec *next1 = (i + 1 < NUM_HOUSES_PER_GRF ? housespec[i + 1] : nullptr);
9142  const HouseSpec *next2 = (i + 2 < NUM_HOUSES_PER_GRF ? housespec[i + 2] : nullptr);
9143  const HouseSpec *next3 = (i + 3 < NUM_HOUSES_PER_GRF ? housespec[i + 3] : nullptr);
9144 
9145  if (!IsHouseSpecValid(hs, next1, next2, next3, file->filename)) continue;
9146 
9147  _house_mngr.SetEntitySpec(hs);
9148  }
9149  }
9150 
9151  for (int i = 0; i < NUM_HOUSES; i++) {
9152  HouseSpec *hs = HouseSpec::Get(i);
9153  const HouseSpec *next1 = (i + 1 < NUM_HOUSES ? HouseSpec::Get(i + 1) : nullptr);
9154  const HouseSpec *next2 = (i + 2 < NUM_HOUSES ? HouseSpec::Get(i + 2) : nullptr);
9155  const HouseSpec *next3 = (i + 3 < NUM_HOUSES ? HouseSpec::Get(i + 3) : nullptr);
9156 
9157  /* We need to check all houses again to we are sure that multitile houses
9158  * did get consecutive IDs and none of the parts are missing. */
9159  if (!IsHouseSpecValid(hs, next1, next2, next3, nullptr)) {
9160  /* GetHouseNorthPart checks 3 houses that are directly before
9161  * it in the house pool. If any of those houses have multi-tile
9162  * flags set it assumes it's part of a multitile house. Since
9163  * we can have invalid houses in the pool marked as disabled, we
9164  * don't want to have them influencing valid tiles. As such set
9165  * building_flags to zero here to make sure any house following
9166  * this one in the pool is properly handled as 1x1 house. */
9167  hs->building_flags = TILE_NO_FLAG;
9168  }
9169  }
9170 
9171  HouseZones climate_mask = (HouseZones)(1 << (_settings_game.game_creation.landscape + 12));
9172  EnsureEarlyHouse(HZ_ZON1 | climate_mask);
9173  EnsureEarlyHouse(HZ_ZON2 | climate_mask);
9174  EnsureEarlyHouse(HZ_ZON3 | climate_mask);
9175  EnsureEarlyHouse(HZ_ZON4 | climate_mask);
9176  EnsureEarlyHouse(HZ_ZON5 | climate_mask);
9177 
9178  if (_settings_game.game_creation.landscape == LT_ARCTIC) {
9184  }
9185 }
9186 
9193 {
9194  for (GRFFile * const file : _grf_files) {
9195  IndustrySpec **&industryspec = file->industryspec;
9196  IndustryTileSpec **&indtspec = file->indtspec;
9197  if (industryspec != nullptr) {
9198  for (int i = 0; i < NUM_INDUSTRYTYPES_PER_GRF; i++) {
9199  IndustrySpec *indsp = industryspec[i];
9200 
9201  if (indsp != nullptr && indsp->enabled) {
9202  StringID strid;
9203  /* process the conversion of text at the end, so to be sure everything will be fine
9204  * and available. Check if it does not return undefind marker, which is a very good sign of a
9205  * substitute industry who has not changed the string been examined, thus using it as such */
9206  strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->name);
9207  if (strid != STR_UNDEFINED) indsp->name = strid;
9208 
9209  strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->closure_text);
9210  if (strid != STR_UNDEFINED) indsp->closure_text = strid;
9211 
9212  strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->production_up_text);
9213  if (strid != STR_UNDEFINED) indsp->production_up_text = strid;
9214 
9215  strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->production_down_text);
9216  if (strid != STR_UNDEFINED) indsp->production_down_text = strid;
9217 
9218  strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->new_industry_text);
9219  if (strid != STR_UNDEFINED) indsp->new_industry_text = strid;
9220 
9221  if (indsp->station_name != STR_NULL) {
9222  /* STR_NULL (0) can be set by grf. It has a meaning regarding assignation of the
9223  * station's name. Don't want to lose the value, therefore, do not process. */
9224  strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->station_name);
9225  if (strid != STR_UNDEFINED) indsp->station_name = strid;
9226  }
9227 
9228  _industry_mngr.SetEntitySpec(indsp);
9229  }
9230  }
9231  }
9232 
9233  if (indtspec != nullptr) {
9234  for (int i = 0; i < NUM_INDUSTRYTILES_PER_GRF; i++) {
9235  IndustryTileSpec *indtsp = indtspec[i];
9236  if (indtsp != nullptr) {
9237  _industile_mngr.SetEntitySpec(indtsp);
9238  }
9239  }
9240  }
9241  }
9242 
9243  for (uint j = 0; j < NUM_INDUSTRYTYPES; j++) {
9244  IndustrySpec *indsp = &_industry_specs[j];
9245  if (indsp->enabled && indsp->grf_prop.grffile != nullptr) {
9246  for (uint i = 0; i < 3; i++) {
9247  indsp->conflicting[i] = MapNewGRFIndustryType(indsp->conflicting[i], indsp->grf_prop.grffile->grfid);
9248  }
9249  }
9250  if (!indsp->enabled) {
9251  indsp->name = STR_NEWGRF_INVALID_INDUSTRYTYPE;
9252  }
9253  }
9254 }
9255 
9262 {
9263  for (GRFFile * const file : _grf_files) {
9264  ObjectSpec **&objectspec = file->objectspec;
9265  if (objectspec != nullptr) {
9266  for (int i = 0; i < NUM_OBJECTS_PER_GRF; i++) {
9267  if (objectspec[i] != nullptr && objectspec[i]->grf_prop.grffile != nullptr && objectspec[i]->enabled) {
9268  _object_mngr.SetEntitySpec(objectspec[i]);
9269  }
9270  }
9271  }
9272  }
9273 }
9274 
9281 {
9282  for (GRFFile * const file : _grf_files) {
9283  AirportSpec **&airportspec = file->airportspec;
9284  if (airportspec != nullptr) {
9285  for (int i = 0; i < NUM_AIRPORTS_PER_GRF; i++) {
9286  if (airportspec[i] != nullptr && airportspec[i]->enabled) {
9287  _airport_mngr.SetEntitySpec(airportspec[i]);
9288  }
9289  }
9290  }
9291 
9292  AirportTileSpec **&airporttilespec = file->airtspec;
9293  if (airporttilespec != nullptr) {
9294  for (uint i = 0; i < NUM_AIRPORTTILES_PER_GRF; i++) {
9295  if (airporttilespec[i] != nullptr && airporttilespec[i]->enabled) {
9296  _airporttile_mngr.SetEntitySpec(airporttilespec[i]);
9297  }
9298  }
9299  }
9300  }
9301 }
9302 
9303 /* Here we perform initial decoding of some special sprites (as are they
9304  * described at http://www.ttdpatch.net/src/newgrf.txt, but this is only a very
9305  * partial implementation yet).
9306  * XXX: We consider GRF files trusted. It would be trivial to exploit OTTD by
9307  * a crafted invalid GRF file. We should tell that to the user somehow, or
9308  * better make this more robust in the future. */
9309 static void DecodeSpecialSprite(byte *buf, uint num, GrfLoadingStage stage)
9310 {
9311  /* XXX: There is a difference between staged loading in TTDPatch and
9312  * here. In TTDPatch, for some reason actions 1 and 2 are carried out
9313  * during stage 1, whilst action 3 is carried out during stage 2 (to
9314  * "resolve" cargo IDs... wtf). This is a little problem, because cargo
9315  * IDs are valid only within a given set (action 1) block, and may be
9316  * overwritten after action 3 associates them. But overwriting happens
9317  * in an earlier stage than associating, so... We just process actions
9318  * 1 and 2 in stage 2 now, let's hope that won't get us into problems.
9319  * --pasky
9320  * We need a pre-stage to set up GOTO labels of Action 0x10 because the grf
9321  * is not in memory and scanning the file every time would be too expensive.
9322  * In other stages we skip action 0x10 since it's already dealt with. */
9323  static const SpecialSpriteHandler handlers[][GLS_END] = {
9324  /* 0x00 */ { nullptr, SafeChangeInfo, nullptr, nullptr, ReserveChangeInfo, FeatureChangeInfo, },
9325  /* 0x01 */ { SkipAct1, SkipAct1, SkipAct1, SkipAct1, SkipAct1, NewSpriteSet, },
9326  /* 0x02 */ { nullptr, nullptr, nullptr, nullptr, nullptr, NewSpriteGroup, },
9327  /* 0x03 */ { nullptr, GRFUnsafe, nullptr, nullptr, nullptr, FeatureMapSpriteGroup, },
9328  /* 0x04 */ { nullptr, nullptr, nullptr, nullptr, nullptr, FeatureNewName, },
9329  /* 0x05 */ { SkipAct5, SkipAct5, SkipAct5, SkipAct5, SkipAct5, GraphicsNew, },
9330  /* 0x06 */ { nullptr, nullptr, nullptr, CfgApply, CfgApply, CfgApply, },
9331  /* 0x07 */ { nullptr, nullptr, nullptr, nullptr, SkipIf, SkipIf, },
9332  /* 0x08 */ { ScanInfo, nullptr, nullptr, GRFInfo, GRFInfo, GRFInfo, },
9333  /* 0x09 */ { nullptr, nullptr, nullptr, SkipIf, SkipIf, SkipIf, },
9334  /* 0x0A */ { SkipActA, SkipActA, SkipActA, SkipActA, SkipActA, SpriteReplace, },
9335  /* 0x0B */ { nullptr, nullptr, nullptr, GRFLoadError, GRFLoadError, GRFLoadError, },
9336  /* 0x0C */ { nullptr, nullptr, nullptr, GRFComment, nullptr, GRFComment, },
9337  /* 0x0D */ { nullptr, SafeParamSet, nullptr, ParamSet, ParamSet, ParamSet, },
9338  /* 0x0E */ { nullptr, SafeGRFInhibit, nullptr, GRFInhibit, GRFInhibit, GRFInhibit, },
9339  /* 0x0F */ { nullptr, GRFUnsafe, nullptr, FeatureTownName, nullptr, nullptr, },
9340  /* 0x10 */ { nullptr, nullptr, DefineGotoLabel, nullptr, nullptr, nullptr, },
9341  /* 0x11 */ { SkipAct11, GRFUnsafe, SkipAct11, GRFSound, SkipAct11, GRFSound, },
9343  /* 0x13 */ { nullptr, nullptr, nullptr, nullptr, nullptr, TranslateGRFStrings, },
9344  /* 0x14 */ { StaticGRFInfo, nullptr, nullptr, nullptr, nullptr, nullptr, },
9345  };
9346 
9347  GRFLocation location(_cur.grfconfig->ident.grfid, _cur.nfo_line);
9348 
9349  GRFLineToSpriteOverride::iterator it = _grf_line_to_action6_sprite_override.find(location);
9350  if (it == _grf_line_to_action6_sprite_override.end()) {
9351  /* No preloaded sprite to work with; read the
9352  * pseudo sprite content. */
9353  _cur.file->ReadBlock(buf, num);
9354  } else {
9355  /* Use the preloaded sprite data. */
9356  buf = _grf_line_to_action6_sprite_override[location];
9357  grfmsg(7, "DecodeSpecialSprite: Using preloaded pseudo sprite data");
9358 
9359  /* Skip the real (original) content of this action. */
9360  _cur.file->SeekTo(num, SEEK_CUR);
9361  }
9362 
9363  ByteReader br(buf, buf + num);
9364  ByteReader *bufp = &br;
9365 
9366  try {
9367  byte action = bufp->ReadByte();
9368 
9369  if (action == 0xFF) {
9370  grfmsg(2, "DecodeSpecialSprite: Unexpected data block, skipping");
9371  } else if (action == 0xFE) {
9372  grfmsg(2, "DecodeSpecialSprite: Unexpected import block, skipping");
9373  } else if (action >= lengthof(handlers)) {
9374  grfmsg(7, "DecodeSpecialSprite: Skipping unknown action 0x%02X", action);
9375  } else if (handlers[action][stage] == nullptr) {
9376  grfmsg(7, "DecodeSpecialSprite: Skipping action 0x%02X in stage %d", action, stage);
9377  } else {
9378  grfmsg(7, "DecodeSpecialSprite: Handling action 0x%02X in stage %d", action, stage);
9379  handlers[action][stage](bufp);
9380  }
9381  } catch (...) {
9382  grfmsg(1, "DecodeSpecialSprite: Tried to read past end of pseudo-sprite data");
9383  DisableGrf(STR_NEWGRF_ERROR_READ_BOUNDS);
9384  }
9385 }
9386 
9393 static void LoadNewGRFFileFromFile(GRFConfig *config, GrfLoadingStage stage, SpriteFile &file)
9394 {
9395  _cur.file = &file;
9396  _cur.grfconfig = config;
9397 
9398  Debug(grf, 2, "LoadNewGRFFile: Reading NewGRF-file '{}'", config->filename);
9399 
9400  byte grf_container_version = file.GetContainerVersion();
9401  if (grf_container_version == 0) {
9402  Debug(grf, 7, "LoadNewGRFFile: Custom .grf has invalid format");
9403  return;
9404  }
9405 
9406  if (stage == GLS_INIT || stage == GLS_ACTIVATION) {
9407  /* We need the sprite offsets in the init stage for NewGRF sounds
9408  * and in the activation stage for real sprites. */
9409  ReadGRFSpriteOffsets(file);
9410  } else {
9411  /* Skip sprite section offset if present. */
9412  if (grf_container_version >= 2) file.ReadDword();
9413  }
9414 
9415  if (grf_container_version >= 2) {
9416  /* Read compression value. */
9417  byte compression = file.ReadByte();
9418  if (compression != 0) {
9419  Debug(grf, 7, "LoadNewGRFFile: Unsupported compression format");
9420  return;
9421  }
9422  }
9423 
9424  /* Skip the first sprite; we don't care about how many sprites this
9425  * does contain; newest TTDPatches and George's longvehicles don't
9426  * neither, apparently. */
9427  uint32 num = grf_container_version >= 2 ? file.ReadDword() : file.ReadWord();
9428  if (num == 4 && file.ReadByte() == 0xFF) {
9429  file.ReadDword();
9430  } else {
9431  Debug(grf, 7, "LoadNewGRFFile: Custom .grf has invalid format");
9432  return;
9433  }
9434 
9435  _cur.ClearDataForNextFile();
9436 
9438 
9439  while ((num = (grf_container_version >= 2 ? file.ReadDword() : file.ReadWord())) != 0) {
9440  byte type = file.ReadByte();
9441  _cur.nfo_line++;
9442 
9443  if (type == 0xFF) {
9444  if (_cur.skip_sprites == 0) {
9445  DecodeSpecialSprite(buf.Allocate(num), num, stage);
9446 
9447  /* Stop all processing if we are to skip the remaining sprites */
9448  if (_cur.skip_sprites == -1) break;
9449 
9450  continue;
9451  } else {
9452  file.SkipBytes(num);
9453  }
9454  } else {
9455  if (_cur.skip_sprites == 0) {
9456  grfmsg(0, "LoadNewGRFFile: Unexpected sprite, disabling");
9457  DisableGrf(STR_NEWGRF_ERROR_UNEXPECTED_SPRITE);
9458  break;
9459  }
9460 
9461  if (grf_container_version >= 2 && type == 0xFD) {
9462  /* Reference to data section. Container version >= 2 only. */
9463  file.SkipBytes(num);
9464  } else {
9465  file.SkipBytes(7);
9466  SkipSpriteData(file, type, num - 8);
9467  }
9468  }
9469 
9470  if (_cur.skip_sprites > 0) _cur.skip_sprites--;
9471  }
9472 }
9473 
9482 void LoadNewGRFFile(GRFConfig *config, GrfLoadingStage stage, Subdirectory subdir, bool temporary)
9483 {
9484  const char *filename = config->filename;
9485 
9486  /* A .grf file is activated only if it was active when the game was
9487  * started. If a game is loaded, only its active .grfs will be
9488  * reactivated, unless "loadallgraphics on" is used. A .grf file is
9489  * considered active if its action 8 has been processed, i.e. its
9490  * action 8 hasn't been skipped using an action 7.
9491  *
9492  * During activation, only actions 0, 1, 2, 3, 4, 5, 7, 8, 9, 0A and 0B are
9493  * carried out. All others are ignored, because they only need to be
9494  * processed once at initialization. */
9495  if (stage != GLS_FILESCAN && stage != GLS_SAFETYSCAN && stage != GLS_LABELSCAN) {
9496  _cur.grffile = GetFileByFilename(filename);
9497  if (_cur.grffile == nullptr) usererror("File '%s' lost in cache.\n", filename);
9498  if (stage == GLS_RESERVE && config->status != GCS_INITIALISED) return;
9499  if (stage == GLS_ACTIVATION && !HasBit(config->flags, GCF_RESERVED)) return;
9500  }
9501 
9502  bool needs_palette_remap = config->palette & GRFP_USE_MASK;
9503  if (temporary) {
9504  SpriteFile temporarySpriteFile(filename, subdir, needs_palette_remap);
9505  LoadNewGRFFileFromFile(config, stage, temporarySpriteFile);
9506  } else {
9507  LoadNewGRFFileFromFile(config, stage, OpenCachedSpriteFile(filename, subdir, needs_palette_remap));
9508  }
9509 }
9510 
9518 static void ActivateOldShore()
9519 {
9520  /* Use default graphics, if no shore sprites were loaded.
9521  * Should not happen, as the base set's extra grf should include some. */
9523 
9525  DupSprite(SPR_ORIGINALSHORE_START + 1, SPR_SHORE_BASE + 1); // SLOPE_W
9526  DupSprite(SPR_ORIGINALSHORE_START + 2, SPR_SHORE_BASE + 2); // SLOPE_S
9527  DupSprite(SPR_ORIGINALSHORE_START + 6, SPR_SHORE_BASE + 3); // SLOPE_SW
9528  DupSprite(SPR_ORIGINALSHORE_START + 0, SPR_SHORE_BASE + 4); // SLOPE_E
9529  DupSprite(SPR_ORIGINALSHORE_START + 4, SPR_SHORE_BASE + 6); // SLOPE_SE
9530  DupSprite(SPR_ORIGINALSHORE_START + 3, SPR_SHORE_BASE + 8); // SLOPE_N
9531  DupSprite(SPR_ORIGINALSHORE_START + 7, SPR_SHORE_BASE + 9); // SLOPE_NW
9532  DupSprite(SPR_ORIGINALSHORE_START + 5, SPR_SHORE_BASE + 12); // SLOPE_NE
9533  }
9534 
9536  DupSprite(SPR_FLAT_GRASS_TILE + 16, SPR_SHORE_BASE + 0); // SLOPE_STEEP_S
9537  DupSprite(SPR_FLAT_GRASS_TILE + 17, SPR_SHORE_BASE + 5); // SLOPE_STEEP_W
9538  DupSprite(SPR_FLAT_GRASS_TILE + 7, SPR_SHORE_BASE + 7); // SLOPE_WSE
9539  DupSprite(SPR_FLAT_GRASS_TILE + 15, SPR_SHORE_BASE + 10); // SLOPE_STEEP_N
9540  DupSprite(SPR_FLAT_GRASS_TILE + 11, SPR_SHORE_BASE + 11); // SLOPE_NWS
9541  DupSprite(SPR_FLAT_GRASS_TILE + 13, SPR_SHORE_BASE + 13); // SLOPE_ENW
9542  DupSprite(SPR_FLAT_GRASS_TILE + 14, SPR_SHORE_BASE + 14); // SLOPE_SEN
9543  DupSprite(SPR_FLAT_GRASS_TILE + 18, SPR_SHORE_BASE + 15); // SLOPE_STEEP_E
9544 
9545  /* XXX - SLOPE_EW, SLOPE_NS are currently not used.
9546  * If they would be used somewhen, then these grass tiles will most like not look as needed */
9547  DupSprite(SPR_FLAT_GRASS_TILE + 5, SPR_SHORE_BASE + 16); // SLOPE_EW
9548  DupSprite(SPR_FLAT_GRASS_TILE + 10, SPR_SHORE_BASE + 17); // SLOPE_NS
9549  }
9550 }
9551 
9556 {
9558  DupSprite(SPR_ROAD_DEPOT + 0, SPR_TRAMWAY_DEPOT_NO_TRACK + 0); // use road depot graphics for "no tracks"
9559  DupSprite(SPR_TRAMWAY_DEPOT_WITH_TRACK + 1, SPR_TRAMWAY_DEPOT_NO_TRACK + 1);
9560  DupSprite(SPR_ROAD_DEPOT + 2, SPR_TRAMWAY_DEPOT_NO_TRACK + 2); // use road depot graphics for "no tracks"
9561  DupSprite(SPR_TRAMWAY_DEPOT_WITH_TRACK + 3, SPR_TRAMWAY_DEPOT_NO_TRACK + 3);
9562  DupSprite(SPR_TRAMWAY_DEPOT_WITH_TRACK + 4, SPR_TRAMWAY_DEPOT_NO_TRACK + 4);
9563  DupSprite(SPR_TRAMWAY_DEPOT_WITH_TRACK + 5, SPR_TRAMWAY_DEPOT_NO_TRACK + 5);
9564  }
9565 }
9566 
9571 {
9572  extern const PriceBaseSpec _price_base_specs[];
9574  static const uint32 override_features = (1 << GSF_TRAINS) | (1 << GSF_ROADVEHICLES) | (1 << GSF_SHIPS) | (1 << GSF_AIRCRAFT);
9575 
9576  /* Evaluate grf overrides */
9577  int num_grfs = (uint)_grf_files.size();
9578  int *grf_overrides = AllocaM(int, num_grfs);
9579  for (int i = 0; i < num_grfs; i++) {
9580  grf_overrides[i] = -1;
9581 
9582  GRFFile *source = _grf_files[i];
9583  uint32 override = _grf_id_overrides[source->grfid];
9584  if (override == 0) continue;
9585 
9586  GRFFile *dest = GetFileByGRFID(override);
9587  if (dest == nullptr) continue;
9588 
9589  grf_overrides[i] = find_index(_grf_files, dest);
9590  assert(grf_overrides[i] >= 0);
9591  }
9592 
9593  /* Override features and price base multipliers of earlier loaded grfs */
9594  for (int i = 0; i < num_grfs; i++) {
9595  if (grf_overrides[i] < 0 || grf_overrides[i] >= i) continue;
9596  GRFFile *source = _grf_files[i];
9597  GRFFile *dest = _grf_files[grf_overrides[i]];
9598 
9599  uint32 features = (source->grf_features | dest->grf_features) & override_features;
9600  source->grf_features |= features;
9601  dest->grf_features |= features;
9602 
9603  for (Price p = PR_BEGIN; p < PR_END; p++) {
9604  /* No price defined -> nothing to do */
9605  if (!HasBit(features, _price_base_specs[p].grf_feature) || source->price_base_multipliers[p] == INVALID_PRICE_MODIFIER) continue;
9606  Debug(grf, 3, "'{}' overrides price base multiplier {} of '{}'", source->filename, p, dest->filename);
9607  dest->price_base_multipliers[p] = source->price_base_multipliers[p];
9608  }
9609  }
9610 
9611  /* Propagate features and price base multipliers of afterwards loaded grfs, if none is present yet */
9612  for (int i = num_grfs - 1; i >= 0; i--) {
9613  if (grf_overrides[i] < 0 || grf_overrides[i] <= i) continue;
9614  GRFFile *source = _grf_files[i];
9615  GRFFile *dest = _grf_files[grf_overrides[i]];
9616 
9617  uint32 features = (source->grf_features | dest->grf_features) & override_features;
9618  source->grf_features |= features;
9619  dest->grf_features |= features;
9620 
9621  for (Price p = PR_BEGIN; p < PR_END; p++) {
9622  /* Already a price defined -> nothing to do */
9623  if (!HasBit(features, _price_base_specs[p].grf_feature) || dest->price_base_multipliers[p] != INVALID_PRICE_MODIFIER) continue;
9624  Debug(grf, 3, "Price base multiplier {} from '{}' propagated to '{}'", p, source->filename, dest->filename);
9625  dest->price_base_multipliers[p] = source->price_base_multipliers[p];
9626  }
9627  }
9628 
9629  /* The 'master grf' now have the correct multipliers. Assign them to the 'addon grfs' to make everything consistent. */
9630  for (int i = 0; i < num_grfs; i++) {
9631  if (grf_overrides[i] < 0) continue;
9632  GRFFile *source = _grf_files[i];
9633  GRFFile *dest = _grf_files[grf_overrides[i]];
9634 
9635  uint32 features = (source->grf_features | dest->grf_features) & override_features;
9636  source->grf_features |= features;
9637  dest->grf_features |= features;
9638 
9639  for (Price p = PR_BEGIN; p < PR_END; p++) {
9640  if (!HasBit(features, _price_base_specs[p].grf_feature)) continue;
9641  if (source->price_base_multipliers[p] != dest->price_base_multipliers[p]) {
9642  Debug(grf, 3, "Price base multiplier {} from '{}' propagated to '{}'", p, dest->filename, source->filename);
9643  }
9644  source->price_base_multipliers[p] = dest->price_base_multipliers[p];
9645  }
9646  }
9647 
9648  /* Apply fallback prices for grf version < 8 */
9649  for (GRFFile * const file : _grf_files) {
9650  if (file->grf_version >= 8) continue;
9651  PriceMultipliers &price_base_multipliers = file->price_base_multipliers;
9652  for (Price p = PR_BEGIN; p < PR_END; p++) {
9653  Price fallback_price = _price_base_specs[p].fallback_price;
9654  if (fallback_price != INVALID_PRICE && price_base_multipliers[p] == INVALID_PRICE_MODIFIER) {
9655  /* No price multiplier has been set.
9656  * So copy the multiplier from the fallback price, maybe a multiplier was set there. */
9657  price_base_multipliers[p] = price_base_multipliers[fallback_price];
9658  }
9659  }
9660  }
9661 
9662  /* Decide local/global scope of price base multipliers */
9663  for (GRFFile * const file : _grf_files) {
9664  PriceMultipliers &price_base_multipliers = file->price_base_multipliers;
9665  for (Price p = PR_BEGIN; p < PR_END; p++) {
9666  if (price_base_multipliers[p] == INVALID_PRICE_MODIFIER) {
9667  /* No multiplier was set; set it to a neutral value */
9668  price_base_multipliers[p] = 0;
9669  } else {
9670  if (!HasBit(file->grf_features, _price_base_specs[p].grf_feature)) {
9671  /* The grf does not define any objects of the feature,
9672  * so it must be a difficulty setting. Apply it globally */
9673  Debug(grf, 3, "'{}' sets global price base multiplier {}", file->filename, p);
9674  SetPriceBaseMultiplier(p, price_base_multipliers[p]);
9675  price_base_multipliers[p] = 0;
9676  } else {
9677  Debug(grf, 3, "'{}' sets local price base multiplier {}", file->filename, p);
9678  }
9679  }
9680  }
9681  }
9682 }
9683 
9684 extern void InitGRFTownGeneratorNames();
9685 
9687 static void AfterLoadGRFs()
9688 {
9689  for (StringIDMapping &it : _string_to_grf_mapping) {
9690  *it.target = MapGRFStringID(it.grfid, it.source);
9691  }
9692  _string_to_grf_mapping.clear();
9693 
9694  /* Free the action 6 override sprites. */
9695  for (GRFLineToSpriteOverride::iterator it = _grf_line_to_action6_sprite_override.begin(); it != _grf_line_to_action6_sprite_override.end(); it++) {
9696  free((*it).second);
9697  }
9698  _grf_line_to_action6_sprite_override.clear();
9699 
9700  /* Polish cargoes */
9702 
9703  /* Pre-calculate all refit masks after loading GRF files. */
9705 
9706  /* Polish engines */
9708 
9709  /* Set the actually used Canal properties */
9710  FinaliseCanals();
9711 
9712  /* Add all new houses to the house array. */
9714 
9715  /* Add all new industries to the industry array. */
9717 
9718  /* Add all new objects to the object array. */
9720 
9722 
9723  /* Sort the list of industry types. */
9725 
9726  /* Create dynamic list of industry legends for smallmap_gui.cpp */
9728 
9729  /* Build the routemap legend, based on the available cargos */
9731 
9732  /* Add all new airports to the airports array. */
9734  BindAirportSpecs();
9735 
9736  /* Update the townname generators list */
9738 
9739  /* Run all queued vehicle list order changes */
9741 
9742  /* Load old shore sprites in new position, if they were replaced by ActionA */
9743  ActivateOldShore();
9744 
9745  /* Load old tram depot sprites in new position, if no new ones are present */
9747 
9748  /* Set up custom rail types */
9749  InitRailTypes();
9750  InitRoadTypes();
9751 
9752  for (Engine *e : Engine::IterateType(VEH_ROAD)) {
9753  if (_gted[e->index].rv_max_speed != 0) {
9754  /* Set RV maximum speed from the mph/0.8 unit value */
9755  e->u.road.max_speed = _gted[e->index].rv_max_speed * 4;
9756  }
9757 
9758  RoadTramType rtt = HasBit(e->info.misc_flags, EF_ROAD_TRAM) ? RTT_TRAM : RTT_ROAD;
9759 
9760  const GRFFile *file = e->GetGRF();
9761  if (file == nullptr || _gted[e->index].roadtramtype == 0) {
9762  e->u.road.roadtype = (rtt == RTT_TRAM) ? ROADTYPE_TRAM : ROADTYPE_ROAD;
9763  continue;
9764  }
9765 
9766  /* Remove +1 offset. */
9767  _gted[e->index].roadtramtype--;
9768 
9769  const std::vector<RoadTypeLabel> *list = (rtt == RTT_TRAM) ? &file->tramtype_list : &file->roadtype_list;
9770  if (_gted[e->index].roadtramtype < list->size())
9771  {
9772  RoadTypeLabel rtl = (*list)[_gted[e->index].roadtramtype];
9773  RoadType rt = GetRoadTypeByLabel(rtl);
9774  if (rt != INVALID_ROADTYPE && GetRoadTramType(rt) == rtt) {
9775  e->u.road.roadtype = rt;
9776  continue;
9777  }
9778  }
9779 
9780  /* Road type is not available, so disable this engine */
9781  e->info.climates = 0;
9782  }
9783 
9784  for (Engine *e : Engine::IterateType(VEH_TRAIN)) {
9785  RailType railtype = GetRailTypeByLabel(_gted[e->index].railtypelabel);
9786  if (railtype == INVALID_RAILTYPE) {
9787  /* Rail type is not available, so disable this engine */
9788  e->info.climates = 0;
9789  } else {
9790  e->u.rail.railtype = railtype;
9791  }
9792  }
9793 
9795 
9797 
9798  /* Deallocate temporary loading data */
9799  free(_gted);
9800  _grm_sprites.clear();
9801 }
9802 
9808 void LoadNewGRF(uint load_index, uint num_baseset)
9809 {
9810  /* In case of networking we need to "sync" the start values
9811  * so all NewGRFs are loaded equally. For this we use the
9812  * start date of the game and we set the counters, etc. to
9813  * 0 so they're the same too. */
9814  Date date = _date;
9815  Year year = _cur_year;
9816  DateFract date_fract = _date_fract;
9817  uint64 tick_counter = _tick_counter;
9818  byte display_opt = _display_opt;
9819 
9820  if (_networking) {
9822  _date = ConvertYMDToDate(_cur_year, 0, 1);
9823  _date_fract = 0;
9824  _tick_counter = 0;
9825  _display_opt = 0;
9826  }
9827 
9829 
9830  ResetNewGRFData();
9831 
9832  /*
9833  * Reset the status of all files, so we can 'retry' to load them.
9834  * This is needed when one for example rearranges the NewGRFs in-game
9835  * and a previously disabled NewGRF becomes usable. If it would not
9836  * be reset, the NewGRF would remain disabled even though it should
9837  * have been enabled.
9838  */
9839  for (GRFConfig *c = _grfconfig; c != nullptr; c = c->next) {
9840  if (c->status != GCS_NOT_FOUND) c->status = GCS_UNKNOWN;
9841  }
9842 
9843  _cur.spriteid = load_index;
9844 
9845  /* Load newgrf sprites
9846  * in each loading stage, (try to) open each file specified in the config
9847  * and load information from it. */
9848  for (GrfLoadingStage stage = GLS_LABELSCAN; stage <= GLS_ACTIVATION; stage++) {
9849  /* Set activated grfs back to will-be-activated between reservation- and activation-stage.
9850  * This ensures that action7/9 conditions 0x06 - 0x0A work correctly. */
9851  for (GRFConfig *c = _grfconfig; c != nullptr; c = c->next) {
9852  if (c->status == GCS_ACTIVATED) c->status = GCS_INITIALISED;
9853  }
9854 
9855  if (stage == GLS_RESERVE) {
9856  static const uint32 overrides[][2] = {
9857  { 0x44442202, 0x44440111 }, // UKRS addons modifies UKRS
9858  { 0x6D620402, 0x6D620401 }, // DBSetXL ECS extension modifies DBSetXL
9859  { 0x4D656f20, 0x4D656F17 }, // LV4cut modifies LV4
9860  };
9861  for (size_t i = 0; i < lengthof(overrides); i++) {
9862  SetNewGRFOverride(BSWAP32(overrides[i][0]), BSWAP32(overrides[i][1]));
9863  }
9864  }
9865 
9866  uint num_grfs = 0;
9867  uint num_non_static = 0;
9868 
9869  _cur.stage = stage;
9870  for (GRFConfig *c = _grfconfig; c != nullptr; c = c->next) {
9871  if (c->status == GCS_DISABLED || c->status == GCS_NOT_FOUND) continue;
9872  if (stage > GLS_INIT && HasBit(c->flags, GCF_INIT_ONLY)) continue;
9873 
9874  Subdirectory subdir = num_grfs < num_baseset ? BASESET_DIR : NEWGRF_DIR;
9875  if (!FioCheckFileExists(c->filename, subdir)) {
9876  Debug(grf, 0, "NewGRF file is missing '{}'; disabling", c->filename);
9877  c->status = GCS_NOT_FOUND;
9878  continue;
9879  }
9880 
9881  if (stage == GLS_LABELSCAN) InitNewGRFFile(c);
9882 
9883  if (!HasBit(c->flags, GCF_STATIC) && !HasBit(c->flags, GCF_SYSTEM)) {
9884  if (num_non_static == NETWORK_MAX_GRF_COUNT) {
9885  Debug(grf, 0, "'{}' is not loaded as the maximum number of non-static GRFs has been reached", c->filename);
9886  c->status = GCS_DISABLED;
9887  c->error = new GRFError(STR_NEWGRF_ERROR_MSG_FATAL, STR_NEWGRF_ERROR_TOO_MANY_NEWGRFS_LOADED);
9888  continue;
9889  }
9890  num_non_static++;
9891  }
9892 
9893  num_grfs++;
9894 
9895  LoadNewGRFFile(c, stage, subdir, false);
9896  if (stage == GLS_RESERVE) {
9897  SetBit(c->flags, GCF_RESERVED);
9898  } else if (stage == GLS_ACTIVATION) {
9899  ClrBit(c->flags, GCF_RESERVED);
9900  assert(GetFileByGRFID(c->ident.grfid) == _cur.grffile);
9903  Debug(sprite, 2, "LoadNewGRF: Currently {} sprites are loaded", _cur.spriteid);
9904  } else if (stage == GLS_INIT && HasBit(c->flags, GCF_INIT_ONLY)) {
9905  /* We're not going to activate this, so free whatever data we allocated */
9907  }
9908  }
9909  }
9910 
9911  /* Pseudo sprite processing is finished; free temporary stuff */
9912  _cur.ClearDataForNextFile();
9913 
9914  /* Call any functions that should be run after GRFs have been loaded. */
9915  AfterLoadGRFs();
9916 
9917  /* Now revert back to the original situation */
9918  _cur_year = year;
9919  _date = date;
9920  _date_fract = date_fract;
9921  _tick_counter = tick_counter;
9922  _display_opt = display_opt;
9923 }
VEH_AIRCRAFT
@ VEH_AIRCRAFT
Aircraft vehicle type.
Definition: vehicle_type.h:27
MapLogX
static uint MapLogX()
Logarithm of the map size along the X side.
Definition: map_func.h:51
GRFConfig::version
uint32 version
NOSAVE: Version a NewGRF can set so only the newest NewGRF is shown.
Definition: newgrf_config.h:171
ResetCustomHouses
static void ResetCustomHouses()
Reset and clear all NewGRF houses.
Definition: newgrf.cpp:8474
AirportSpec::min_year
Year min_year
first year the airport is available
Definition: newgrf_airport.h:109
RoadTypeInfo::flags
RoadTypeFlags flags
Bit mask of road type flags.
Definition: road.h:124
ChangeGRFName
static bool ChangeGRFName(byte langid, const char *str)
Callback function for 'INFO'->'NAME' to add a translation to the newgrf name.
Definition: newgrf.cpp:7858
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:8138
RoadTypeInfo::new_engine
StringID new_engine
Name of an engine for this type of road in the engine preview GUI.
Definition: road.h:105
StationChangeInfo
static ChangeInfoResult StationChangeInfo(uint stid, int numinfo, int prop, ByteReader *buf)
Define properties for stations.
Definition: newgrf.cpp:1876
ParamSet
static void ParamSet(ByteReader *buf)
Action 0x0D: Set parameter.
Definition: newgrf.cpp:7132
GRFLocation
Definition: newgrf.cpp:361
CalculateRefitMasks
static void CalculateRefitMasks()
Precalculate refit masks from cargo classes for all vehicles.
Definition: newgrf.cpp:8793
GRFP_USE_MASK
@ GRFP_USE_MASK
Bitmask to get only the use palette use states.
Definition: newgrf_config.h:68
RoadTypeInfo::toolbar_caption
StringID toolbar_caption
Caption in the construction toolbar GUI for this rail type.
Definition: road.h:101
HouseSpec::removal_cost
byte removal_cost
cost multiplier for removing it
Definition: house.h:103
CargoType
CargoType
Available types of cargo.
Definition: cargo_type.h:23
AllocateSound
SoundEntry * AllocateSound(uint num)
Allocate sound slots.
Definition: newgrf_sound.cpp:31
GRFTempEngineData::UpdateRefittability
void UpdateRefittability(bool non_empty)
Update the summary refittability on setting a refittability property.
Definition: newgrf.cpp:340
INVALID_ENGINE
static const EngineID INVALID_ENGINE
Constant denoting an invalid engine.
Definition: engine_type.h:175
EngineInfo::base_life
Year base_life
Basic duration of engine availability (without random parts). 0xFF means infinite life.
Definition: engine_type.h:136
YearMonthDay::day
Day day
Day (1..31)
Definition: date_type.h:107
Action5Type::sprite_base
SpriteID sprite_base
Load the sprites starting from this sprite.
Definition: newgrf.cpp:6144
OrderSettings::improved_load
bool improved_load
improved loading algorithm
Definition: settings_type.h:475
MAX_NUM_GENDERS
static const uint8 MAX_NUM_GENDERS
Maximum number of supported genders.
Definition: language.h:20
INVALID_AIRPORTTILE
static const uint INVALID_AIRPORTTILE
id for an invalid airport tile
Definition: airport.h:25
RoadTypeInfo
Definition: road.h:75
GRFConfig::num_valid_params
uint8 num_valid_params
NOSAVE: Number of valid parameters (action 0x14)
Definition: newgrf_config.h:178
DuplicateTileTable
static void DuplicateTileTable(AirportSpec *as)
Create a copy of the tile table so it can be freed later without problems.
Definition: newgrf.cpp:3800
IsInsideMM
static 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:204
NUM_STATIONS_PER_GRF
static const uint NUM_STATIONS_PER_GRF
Number of StationSpecs per NewGRF; limited to 255 to allow extending Action3 with an extended byte la...
Definition: newgrf.cpp:314
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:167
CargoSpec::callback_mask
uint8 callback_mask
Bitmask of cargo callbacks that have to be called.
Definition: cargotype.h:69
AllowedSubtags::AllowedSubtags
AllowedSubtags()
Create empty subtags object used to identify the end of a list.
Definition: newgrf.cpp:8073
GameCreationSettings::generation_seed
uint32 generation_seed
noise seed for world generation
Definition: settings_type.h:310
GRFFileProps::override
uint16 override
id of the entity been replaced by
Definition: newgrf_commons.h:333
NUM_INDUSTRYTYPES
static const IndustryType NUM_INDUSTRYTYPES
total number of industry types, new and old; limited to 240 because we need some special ids like INV...
Definition: industry_type.h:26
ROADTYPE_END
@ ROADTYPE_END
Used for iterations.
Definition: road_type.h:26
RAILTYPE_MAGLEV
@ RAILTYPE_MAGLEV
Maglev.
Definition: rail_type.h:32
ResetCustomObjects
static void ResetCustomObjects()
Reset and clear all NewObjects.
Definition: newgrf.cpp:8555
RailVehicleInfo::pow_wag_weight
byte pow_wag_weight
Extra weight applied to consist if wagon should be powered.
Definition: engine_type.h:56
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:161
IndustrySpec::map_colour
byte map_colour
colour used for the small map
Definition: industrytype.h:126
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:92
RailtypeInfo::max_speed
uint16 max_speed
Maximum speed for vehicles travelling on this rail type.
Definition: rail.h:228
newgrf_station.h
newgrf_house.h
GRFFile::language_map
struct LanguageMap * language_map
Mappings related to the languages.
Definition: newgrf.h:140
GRFFile::roadtype_list
std::vector< RoadTypeLabel > roadtype_list
Roadtype translation table (road)
Definition: newgrf.h:132
Pool::PoolItem<&_engine_pool >::Get
static Titem * Get(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:337
EngineOverrideManager::ResetToDefaultMapping
void ResetToDefaultMapping()
Initializes the EngineOverrideManager with the default engines.
Definition: engine.cpp:476
CargoSpec::label
CargoLabel label
Unique label of the cargo type.
Definition: cargotype.h:59
StationSpec::flags
byte flags
Bitmask of flags, bit 0: use different sprite set; bit 1: divide cargo about by station size.
Definition: newgrf_station.h:160
LanguageMap::case_map
std::vector< Mapping > case_map
Mapping of NewGRF and OpenTTD IDs for cases.
Definition: newgrf_text.h:72
PROP_TRAIN_CARGO_CAPACITY
@ PROP_TRAIN_CARGO_CAPACITY
Capacity (if dualheaded: for each single vehicle)
Definition: newgrf_properties.h:24
Direction
Direction
Defines the 8 directions on the map.
Definition: direction_type.h:24
AllowedSubtags::AllowedSubtags
AllowedSubtags(uint32 id, AllowedSubtags *subtags)
Create a branch node with a list of sub-nodes.
Definition: newgrf.cpp:8120
GRFConfig::error
GRFError * error
NOSAVE: Error/Warning during GRF loading (Action 0x0B)
Definition: newgrf_config.h:169
GameSettings::station
StationSettings station
settings related to station management
Definition: settings_type.h:595
WChar
char32_t WChar
Type for wide characters, i.e.
Definition: string_type.h:36
ResetCustomAirports
static void ResetCustomAirports()
Reset and clear all NewGRF airports.
Definition: newgrf.cpp:8489
GRFTextList
std::vector< GRFText > GRFTextList
A GRF text with a list of translations.
Definition: newgrf_text.h:31
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
ObjectChangeInfo
static ChangeInfoResult ObjectChangeInfo(uint id, int numinfo, int prop, ByteReader *buf)
Define properties for objects.
Definition: newgrf.cpp:4054
EngineIDMapping::grfid
uint32 grfid
The GRF ID of the file the entity belongs to.
Definition: engine_base.h:168
RoadTypeInfo::menu_text
StringID menu_text
Name of this rail type in the main toolbar dropdown.
Definition: road.h:102
IndustryProductionSpriteGroup::subtract_input
int16 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:273
usererror
void CDECL usererror(const char *s,...)
Error handling for fatal user errors.
Definition: openttd.cpp:105
DeterministicSpriteGroupRange
Definition: newgrf_spritegroup.h:160
StationSpec::renderdata
std::vector< NewGRFSpriteLayout > renderdata
Number of tile layouts.
Definition: newgrf_station.h:148
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
GB
static uint GB(const T x, const uint8 s, const uint8 n)
Fetch n bits from x, started at bit s.
Definition: bitmath_func.hpp:32
SPR_SHORE_BASE
static const SpriteID SPR_SHORE_BASE
shore tiles - action 05-0D
Definition: sprites.h:224
TLF_DODRAW
@ TLF_DODRAW
Only draw sprite if value of register TileLayoutRegisters::dodraw is non-zero.
Definition: newgrf_commons.h:36
ReusableBuffer
A reusable buffer that can be used for places that temporary allocate a bit of memory and do that ver...
Definition: alloc_type.hpp:24
AircraftVehicleInfo::subtype
byte subtype
Type of aircraft.
Definition: engine_type.h:102
OBJECT_FLAG_2CC_COLOUR
@ OBJECT_FLAG_2CC_COLOUR
Object wants 2CC colour mapping.
Definition: newgrf_object.h:34
ShipVehicleChangeInfo
static ChangeInfoResult ShipVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader *buf)
Define properties for ships.
Definition: newgrf.cpp:1550
GetRoadTypeByLabel
RoadType GetRoadTypeByLabel(RoadTypeLabel label, bool allow_alternate_labels)
Get the road type for a given label.
Definition: road.cpp:243
HouseSpec::random_colour
byte random_colour[4]
4 "random" colours
Definition: house.h:116
PROP_ROADVEH_COST_FACTOR
@ PROP_ROADVEH_COST_FACTOR
Purchase cost.
Definition: newgrf_properties.h:35
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
CanalProperties::callback_mask
uint8 callback_mask
Bitmask of canal callbacks that have to be called.
Definition: newgrf.h:40
RailtypeInfo::menu_text
StringID menu_text
Name of this rail type in the main toolbar dropdown.
Definition: rail.h:175
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:104
ObjectFlags
ObjectFlags
Various object behaviours.
Definition: newgrf_object.h:24
DrawTileSeqStruct::IsParentSprite
bool IsParentSprite() const
Check whether this is a parent sprite with a boundingbox.
Definition: sprite.h:47
BridgeSpec::flags
byte flags
bit 0 set: disable drawing of far pillars.
Definition: bridge.h:52
ObjectSpec::build_cost_multiplier
uint8 build_cost_multiplier
Build cost multiplier per tile.
Definition: newgrf_object.h:68
BridgeSpec::avail_year
Year avail_year
the year where it becomes available
Definition: bridge.h:42
ResetCustomIndustries
static void ResetCustomIndustries()
Reset and clear all NewGRF industries.
Definition: newgrf.cpp:8526
PROP_TRAIN_RUNNING_COST_FACTOR
@ PROP_TRAIN_RUNNING_COST_FACTOR
Yearly runningcost (if dualheaded: sum of both vehicles)
Definition: newgrf_properties.h:23
smallmap_gui.h
_grf_files
static std::vector< GRFFile * > _grf_files
List of all loaded GRF files.
Definition: newgrf.cpp:67
SPRITE_WIDTH
@ SPRITE_WIDTH
number of bits for the sprite number
Definition: sprites.h:1521
GameCreationSettings::landscape
byte landscape
the landscape we're currently in
Definition: settings_type.h:326
StringIDMapping::grfid
uint32 grfid
Source NewGRF.
Definition: newgrf.cpp:475
ShipVehicleInfo::canal_speed_frac
byte canal_speed_frac
Fraction of maximum speed for canal/river tiles.
Definition: engine_type.h:76
TLF_CHILD_X_OFFSET
@ TLF_CHILD_X_OFFSET
Add signed offset to child sprite X positions from register TileLayoutRegisters::delta....
Definition: newgrf_commons.h:44
RoadTypeInfo::introduces_roadtypes
RoadTypes introduces_roadtypes
Bitmask of which other roadtypes are introduced when this roadtype is introduced.
Definition: road.h:174
TE_GOODS
@ TE_GOODS
Cargo behaves goods/candy-like.
Definition: cargotype.h:31
_engine_counts
const uint8 _engine_counts[4]
Number of engines of each vehicle type in original engine data.
Definition: engine.cpp:51
AllowedSubtags::AllowedSubtags
AllowedSubtags(uint32 id, DataHandler handler)
Create a binary leaf node.
Definition: newgrf.cpp:8083
GRFFile::price_base_multipliers
PriceMultipliers price_base_multipliers
Price base multipliers as set by the grf.
Definition: newgrf.h:146
FeatureTownName
static void FeatureTownName(ByteReader *buf)
Action 0x0F - Define Town names.
Definition: newgrf.cpp:7482
grfmsg
void CDECL grfmsg(int severity, const char *str,...)
Debug() function dedicated to newGRF debugging messages Function is essentially the same as Debug(grf...
Definition: newgrf.cpp:392
_cur_year
Year _cur_year
Current year, starting at 0.
Definition: date.cpp:26
IndustriesChangeInfo
static ChangeInfoResult IndustriesChangeInfo(uint indid, int numinfo, int prop, ByteReader *buf)
Define properties for industries.
Definition: newgrf.cpp:3420
DeterministicSpriteGroup
Definition: newgrf_spritegroup.h:167
TileLayoutRegisters::sprite
uint8 sprite
Register specifying a signed offset for the sprite.
Definition: newgrf_commons.h:94
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:8135
HandleNodes
static bool HandleNodes(ByteReader *buf, AllowedSubtags subtags[])
Handle the contents of a 'C' choice of an Action14.
Definition: newgrf.cpp:8330
HouseSpec::accepts_cargo
CargoID accepts_cargo[HOUSE_NUM_ACCEPTS]
input cargo slots
Definition: house.h:108
RoadTypeInfo::sorting_order
byte sorting_order
The sorting order of this roadtype for the toolbar dropdown.
Definition: road.h:179
CargoSpec::initial_payment
int32 initial_payment
Initial payment rate before inflation is applied.
Definition: cargotype.h:64
AirportSpec::size_y
byte size_y
size of airport in y direction
Definition: newgrf_airport.h:106
CargoSpec::town_effect
TownEffect town_effect
The effect that delivering this cargo type has on towns. Also affects destination of subsidies.
Definition: cargotype.h:68
NewGRFSpriteLayout::AllocateRegisters
void AllocateRegisters()
Allocate memory for register modifiers.
Definition: newgrf_commons.cpp:636
Pool::CleanPool
virtual void CleanPool()
Virtual method that deletes all items in the pool.
PALETTE_MODIFIER_COLOUR
@ PALETTE_MODIFIER_COLOUR
this bit is set when a recolouring process is in action
Definition: sprites.h:1536
BASESET_DIR
@ BASESET_DIR
Subdirectory for all base data (base sets, intro game)
Definition: fileio_type.h:116
currency.h
GRFConfig::num_params
uint8 num_params
Number of used parameters.
Definition: newgrf_config.h:177
GetNewEngine
static Engine * GetNewEngine(const GRFFile *file, VehicleType type, uint16 internal_id, bool static_access=false)
Returns the engine associated to a certain internal_id, resp.
Definition: newgrf.cpp:612
_date_fract
DateFract _date_fract
Fractional part of the day.
Definition: date.cpp:29
TileLayoutRegisters::parent
uint8 parent[3]
Registers for signed offsets for the bounding box position of parent sprites.
Definition: newgrf_commons.h:99
NamePart::prob
byte prob
The relative probability of the following name to appear in the bottom 7 bits.
Definition: newgrf_townname.h:20
Price
Price
Enumeration of all base prices for use with Prices.
Definition: economy_type.h:74
PROP_AIRCRAFT_MAIL_CAPACITY
@ PROP_AIRCRAFT_MAIL_CAPACITY
Mail Capacity.
Definition: newgrf_properties.h:53
AirportSpec::name
StringID name
name of this airport
Definition: newgrf_airport.h:111
CC_EXPRESS
@ CC_EXPRESS
Express cargo (Goods, Food, Candy, but also possible for passengers)
Definition: cargotype.h:43
FinaliseCanals
static void FinaliseCanals()
Set to use the correct action0 properties for each canal feature.
Definition: newgrf.cpp:8965
RailtypeInfo::replace_text
StringID replace_text
Text used in the autoreplace GUI.
Definition: rail.h:177
GRFFile::grf_features
uint32 grf_features
Bitset of GrfSpecFeature the grf uses.
Definition: newgrf.h:145
LanguageMap::plural_form
int plural_form
The plural form used for this language.
Definition: newgrf_text.h:73
ConstructionSettings::map_height_limit
uint8 map_height_limit
the maximum allowed heightlevel
Definition: settings_type.h:339
CurrencySpec::symbol_pos
byte symbol_pos
The currency symbol is represented by two possible values, prefix and suffix Usage of one or the othe...
Definition: currency.h:87
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:193
AircraftVehicleInfo::passenger_capacity
uint16 passenger_capacity
Passenger capacity (persons).
Definition: engine_type.h:107
IndustrySpec::removal_cost_multiplier
uint32 removal_cost_multiplier
Base removal cost multiplier.
Definition: industrytype.h:110
RandomizedSpriteGroup::cmp_mode
RandomizedSpriteGroupCompareMode cmp_mode
Check for these triggers:
Definition: newgrf_spritegroup.h:195
DeterministicSpriteGroupAdjust::parameter
byte parameter
Used for variables between 0x60 and 0x7F inclusive.
Definition: newgrf_spritegroup.h:151
VE_DEFAULT
@ VE_DEFAULT
Default value to indicate that visual effect should be based on engine class.
Definition: vehicle_base.h:96
A5BLOCK_INVALID
@ A5BLOCK_INVALID
unknown/not-implemented type
Definition: newgrf.cpp:6139
Action5BlockType
Action5BlockType
The type of action 5 type.
Definition: newgrf.cpp:6136
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:8005
Pool::PoolItem::index
Tindex index
Index of this pool item.
Definition: pool_type.hpp:235
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:51
IsValidNewGRFImageIndex
static bool IsValidNewGRFImageIndex(uint8 image_index)
Helper to check whether an image index is valid for a particular NewGRF vehicle.
Definition: newgrf.cpp:205
AirportSpec::max_year
Year max_year
last year the airport is available
Definition: newgrf_airport.h:110
CargoSpec::Get
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo ID.
Definition: cargotype.h:118
IndustryProductionSpriteGroup::num_input
uint8 num_input
How many subtract_input values are valid.
Definition: newgrf_spritegroup.h:272
ResetPersistentNewGRFData
void ResetPersistentNewGRFData()
Reset NewGRF data which is stored persistently in savegames.
Definition: newgrf.cpp:8688
PROP_SHIP_CARGO_CAPACITY
@ PROP_SHIP_CARGO_CAPACITY
Capacity.
Definition: newgrf_properties.h:45
TileLayoutRegisters::palette_var10
uint8 palette_var10
Value for variable 10 when resolving the palette.
Definition: newgrf_commons.h:103
HouseExtraFlags
HouseExtraFlags
Definition: house.h:88
_bridge
BridgeSpec _bridge[MAX_BRIDGES]
The specification of all bridges.
Definition: tunnelbridge_cmd.cpp:51
PalSpriteID::sprite
SpriteID sprite
The 'real' sprite.
Definition: gfx_type.h:23
GrfProcessingState::ClearDataForNextFile
void ClearDataForNextFile()
Clear temporary data before processing the next file in the current loading stage.
Definition: newgrf.cpp:115
PROP_AIRCRAFT_RUNNING_COST_FACTOR
@ PROP_AIRCRAFT_RUNNING_COST_FACTOR
Yearly runningcost.
Definition: newgrf_properties.h:51
RAILTYPE_MONO
@ RAILTYPE_MONO
Monorail.
Definition: rail_type.h:31
HouseSpec::enabled
bool enabled
the house is available to build (true by default, but can be disabled by newgrf)
Definition: house.h:111
AirportSpec::noise_level
byte noise_level
noise that this airport generates
Definition: newgrf_airport.h:107
ChangeGRFVersion
static bool ChangeGRFVersion(size_t len, ByteReader *buf)
Callback function for 'INFO'->'VRSN' to the version of the NewGRF.
Definition: newgrf.cpp:7939
SortIndustryTypes
void SortIndustryTypes()
Initialize the list of sorted industry types.
Definition: industry_gui.cpp:209
FindFirstBit
uint8 FindFirstBit(uint64 x)
Search the first set bit in a 64 bit variable.
Definition: bitmath_func.cpp:37
HasBit
static bool HasBit(const T x, const uint8 y)
Checks if a bit in a value is set.
Definition: bitmath_func.hpp:103
ResetPriceBaseMultipliers
void ResetPriceBaseMultipliers()
Reset changes to the price base multipliers.
Definition: economy.cpp:882
ChangeGRFParamName
static bool ChangeGRFParamName(byte langid, const char *str)
Callback function for 'INFO'->'PARAM'->param_num->'NAME' to set the name of a parameter.
Definition: newgrf.cpp:7974
ResetRailTypes
void ResetRailTypes()
Reset all rail type information to its default values.
Definition: rail_cmd.cpp:64
GrfProcessingState::spritesets
std::map< uint, SpriteSet > spritesets[GSF_END]
Currently referenceable spritesets.
Definition: newgrf.cpp:95
GrfProcessingState::spriteid
SpriteID spriteid
First available SpriteID for loading realsprites.
Definition: newgrf.cpp:100
RailtypeInfo
This struct contains all the info that is needed to draw and construct tracks.
Definition: rail.h:124
WaterFeature::callback_mask
uint8 callback_mask
Bitmask of canal callbacks that have to be called.
Definition: newgrf_canal.h:25
ClrBit
static T ClrBit(T &x, const uint8 y)
Clears a bit in a variable.
Definition: bitmath_func.hpp:151
VehicleSettings::wagon_speed_limits
bool wagon_speed_limits
enable wagon speed limits
Definition: settings_type.h:490
CIR_INVALID_ID
@ CIR_INVALID_ID
Attempt to modify an invalid ID.
Definition: newgrf.cpp:1003
GRFParameterInfo::param_nr
byte param_nr
GRF parameter to store content in.
Definition: newgrf_config.h:143
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:39
RailtypeInfo::grffile
const GRFFile * grffile[RTSG_END]
NewGRF providing the Action3 for the railtype.
Definition: rail.h:273
SetNewGRFOverride
static void SetNewGRFOverride(uint32 source_grfid, uint32 target_grfid)
Set the override for a NewGRF.
Definition: newgrf.cpp:598
_tags_info
AllowedSubtags _tags_info[]
Action14 tags for the INFO node.
Definition: newgrf.cpp:8226
Year
int32 Year
Type for the year, note: 0 based, i.e. starts at the year 0.
Definition: date_type.h:18
vehicle_base.h
GRFUnsafe
static void GRFUnsafe(ByteReader *buf)
Set the current NewGRF as unsafe for static use.
Definition: newgrf.cpp:8356
GRFParameterInfo::def_value
uint32 def_value
Default value of this parameter.
Definition: newgrf_config.h:142
fileio_func.h
GCS_NOT_FOUND
@ GCS_NOT_FOUND
GRF file was not found in the local cache.
Definition: newgrf_config.h:37
ConvertTTDBasePrice
static void ConvertTTDBasePrice(uint32 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:978
newgrf_airport.h
SetupCargoForClimate
void SetupCargoForClimate(LandscapeID l)
Set up the default cargo types for the given landscape type.
Definition: cargotype.cpp:40
build_industry.h
GRFTempEngineData::ctt_include_mask
CargoTypes ctt_include_mask
Cargo types always included in the refit mask.
Definition: newgrf.cpp:333
HouseSpec::building_name
StringID building_name
building name
Definition: house.h:104
ObjectSpec::end_of_life_date
Date end_of_life_date
When can't this object be built anymore.
Definition: newgrf_object.h:71
CargoSpec::Iterate
static IterateWrapper Iterate(size_t from=0)
Returns an iterable ensemble of all valid CargoSpec.
Definition: cargotype.h:174
SetupEngines
void SetupEngines()
Initialise the engine pool with the data from the original vehicles.
Definition: engine.cpp:532
OverrideManagerBase::GetID
virtual uint16 GetID(uint8 grf_local_id, uint32 grfid) const
Return the ID (if ever available) of a previously inserted entity.
Definition: newgrf_commons.cpp:102
GRFConfig::ident
GRFIdentifier ident
grfid and md5sum to uniquely identify newgrfs
Definition: newgrf_config.h:163
newgrf_townname.h
AircraftVehicleInfo::max_speed
uint16 max_speed
Maximum speed (1 unit = 8 mph = 12.8 km-ish/h)
Definition: engine_type.h:105
LiveryScheme
LiveryScheme
List of different livery schemes.
Definition: livery.h:20
AirportSpec::ResetAirports
static void ResetAirports()
This function initializes the airportspec array.
Definition: newgrf_airport.cpp:153
GCF_COPY
@ GCF_COPY
The data is copied from a grf in _all_grfs.
Definition: newgrf_config.h:27
CargoSpec
Specification of a cargo type.
Definition: cargotype.h:57
AllowedSubtags::AllowedSubtags
AllowedSubtags(uint32 id, TextHandler handler)
Create a text leaf node.
Definition: newgrf.cpp:8095
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:174
GetNewGRFSoundID
SoundID GetNewGRFSoundID(const GRFFile *file, SoundID sound_id)
Resolve NewGRF sound ID.
Definition: newgrf_sound.cpp:169
VE_TYPE_COUNT
@ VE_TYPE_COUNT
Number of bits used for the effect type.
Definition: vehicle_base.h:86
town.h
ORIGINAL_BASE_YEAR
static const Year ORIGINAL_BASE_YEAR
The minimum starting year/base year of the original TTD.
Definition: date_type.h:50
NUM_OBJECTS_PER_GRF
static const ObjectType NUM_OBJECTS_PER_GRF
Number of supported objects per NewGRF; limited to 255 to allow extending Action3 with an extended by...
Definition: object_type.h:22
RailVehicleInfo::power
uint16 power
Power of engine (hp); For multiheaded engines the sum of both engine powers.
Definition: engine_type.h:48
CC_LIQUID
@ CC_LIQUID
Liquids (Oil, Water, Rubber)
Definition: cargotype.h:47
GRFP_GRF_UNSET
@ GRFP_GRF_UNSET
The NewGRF provided no information.
Definition: newgrf_config.h:70
EngineInfo
Information about a vehicle.
Definition: engine_type.h:133
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:7988
DSGA_OP_ADD
@ DSGA_OP_ADD
a + b
Definition: newgrf_spritegroup.h:121
GrfProcessingState::file
SpriteFile * file
File of currently processed GRF file.
Definition: newgrf.cpp:103
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:60
IndustrySpec::station_name
StringID station_name
Default name for nearby station.
Definition: industrytype.h:132
CreateGroupFromGroupID
static const SpriteGroup * CreateGroupFromGroupID(byte feature, byte setid, byte type, uint16 spriteid)
Helper function to either create a callback or a result sprite group.
Definition: newgrf.cpp:4976
DIR_W
@ DIR_W
West.
Definition: direction_type.h:32
_display_opt
byte _display_opt
What do we want to draw/do?
Definition: transparency_gui.cpp:26
OverrideManagerBase::Add
void Add(uint8 local_id, uint32 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:72
EngineInfo::base_intro
Date base_intro
Basic date of engine introduction (without random parts).
Definition: engine_type.h:134
CIR_SUCCESS
@ CIR_SUCCESS
Variable was parsed and read.
Definition: newgrf.cpp:999
MAX_SPRITEGROUP
static const uint MAX_SPRITEGROUP
Maximum GRF-local ID for a spritegroup.
Definition: newgrf.cpp:83
GRFLoadedFeatures::used_liveries
uint64 used_liveries
Bitmask of LiveryScheme used by the defined engines.
Definition: newgrf.h:176
HouseSpec::max_year
Year max_year
last year it can be built
Definition: house.h:101
VehicleSettings::road_side
byte road_side
the side of the road vehicles drive on
Definition: settings_type.h:501
RoadTypeInfo::replace_text
StringID replace_text
Text used in the autoreplace GUI.
Definition: road.h:104
AllowedSubtags::text
TextHandler text
Callback function for a text node, only valid if type == 'T'.
Definition: newgrf.cpp:8132
VSG_SCOPE_PARENT
@ VSG_SCOPE_PARENT
Related object of the resolved one.
Definition: newgrf_spritegroup.h:101
RailtypeInfo::fallback_railtype
byte fallback_railtype
Original railtype number to use when drawing non-newgrf railtypes, or when drawing stations.
Definition: rail.h:198
Engine
Definition: engine_base.h:27
VEH_ROAD
@ VEH_ROAD
Road vehicle type.
Definition: vehicle_type.h:25
CC_PASSENGERS
@ CC_PASSENGERS
Passengers.
Definition: cargotype.h:41
EngineIDMapping::internal_id
uint16 internal_id
The internal ID within the GRF file.
Definition: engine_base.h:169
GRFParameterInfo::type
GRFParameterType type
The type of this parameter.
Definition: newgrf_config.h:139
SoundEffectChangeInfo
static ChangeInfoResult SoundEffectChangeInfo(uint sid, int numinfo, int prop, ByteReader *buf)
Define properties for sound effects.
Definition: newgrf.cpp:3064
_tags_parameters
AllowedSubtags _tags_parameters[]
Action14 parameter tags.
Definition: newgrf.cpp:8182
RoadVehicleInfo::roadtype
RoadType roadtype
Road type.
Definition: engine_type.h:126
SpriteFile::GetContainerVersion
byte GetContainerVersion() const
Get the version number of container type used by the file.
Definition: sprite_file_type.hpp:38
RoadTypeInfo::introduction_date
Date introduction_date
Introduction date.
Definition: road.h:163
SoundEntry::grf_container_ver
byte grf_container_ver
NewGRF container version if the sound is from a NewGRF.
Definition: sound_type.h:22
fios.h
TranslateGRFStrings
static void TranslateGRFStrings(ByteReader *buf)
Action 0x13.
Definition: newgrf.cpp:7805
SmallMap::Insert
bool Insert(const T &key, const U &data)
Adds new item to this map.
Definition: smallmap_type.hpp:127
BridgeSpec::speed
uint16 speed
maximum travel speed (1 unit = 1/1.6 mph = 1 km-ish/h)
Definition: bridge.h:46
FinalisePriceBaseMultipliers
static void FinalisePriceBaseMultipliers()
Decide whether price base multipliers of grfs shall apply globally or only to the grf specifying them...
Definition: newgrf.cpp:9570
RandomAccessFile::ReadBlock
void ReadBlock(void *ptr, size_t size)
Read a block.
Definition: random_access_file.cpp:138
TranslateTTDPatchCodes
std::string TranslateTTDPatchCodes(uint32 grfid, uint8 language_id, bool allow_newlines, const std::string &str, StringControlCode byte80)
Translate TTDPatch string codes into something OpenTTD can handle (better).
Definition: newgrf_text.cpp:241
MemCpyT
static void MemCpyT(T *destination, const T *source, size_t num=1)
Type-safe version of memcpy().
Definition: mem_func.hpp:23
TLF_BB_Z_OFFSET
@ TLF_BB_Z_OFFSET
Add signed offset to bounding box Z positions from register TileLayoutRegisters::delta....
Definition: newgrf_commons.h:42
GFX_WATERTILE_SPECIALCHECK
@ GFX_WATERTILE_SPECIALCHECK
not really a tile, but rather a very special check
Definition: industry_map.h:54
GRFTempEngineData::rv_max_speed
uint8 rv_max_speed
Temporary storage of RV prop 15, maximum speed in mph/0.8.
Definition: newgrf.cpp:332
ObjectSpec::size
uint8 size
The size of this objects; low nibble for X, high nibble for Y.
Definition: newgrf_object.h:67
GRFFile::GetParam
uint32 GetParam(uint number) const
Get GRF Parameter with range checking.
Definition: newgrf.h:152
AirportSpec
Defines the data structure for an airport.
Definition: newgrf_airport.h:98
EngineOverrideManager::GetID
EngineID GetID(VehicleType type, uint16 grf_local_id, uint32 grfid)
Looks up an EngineID in the EngineOverrideManager.
Definition: engine.cpp:499
ObjectSpec::callback_mask
uint16 callback_mask
Bitmask of requested/allowed callbacks.
Definition: newgrf_object.h:74
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
INVALID_ROADTYPE
@ INVALID_ROADTYPE
flag for invalid roadtype
Definition: road_type.h:27
genworld.h
RailtypeInfo::sorting_order
byte sorting_order
The sorting order of this railtype for the toolbar dropdown.
Definition: rail.h:268
TileLayoutRegisters
Additional modifiers for items in sprite layouts.
Definition: newgrf_commons.h:91
AnimationInfo::speed
uint8 speed
The speed, i.e. the amount of time between frames.
Definition: newgrf_animation_type.h:21
TileLayoutRegisters::dodraw
uint8 dodraw
Register deciding whether the sprite shall be drawn at all. Non-zero means drawing.
Definition: newgrf_commons.h:93
GRFIdentifier::grfid
uint32 grfid
GRF ID (defined by Action 0x08)
Definition: newgrf_config.h:84
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
RandomAccessFile::ReadByte
byte ReadByte()
Read a byte from the file.
Definition: random_access_file.cpp:100
CargoLabel
uint32 CargoLabel
Globally unique label of a cargo type.
Definition: cargotype.h:23
ObjectSpec::animation
AnimationInfo animation
Information about the animation.
Definition: newgrf_object.h:73
CIR_UNHANDLED
@ CIR_UNHANDLED
Variable was parsed but unread.
Definition: newgrf.cpp:1001
RoadVehicleInfo::air_drag
uint8 air_drag
Coefficient of air drag.
Definition: engine_type.h:123
AirportSpec::maintenance_cost
uint16 maintenance_cost
maintenance cost multiplier
Definition: newgrf_airport.h:115
VSG_SCOPE_SELF
@ VSG_SCOPE_SELF
Resolved object itself.
Definition: newgrf_spritegroup.h:100
CargoSpec::bitnum
uint8 bitnum
Cargo bit number, is INVALID_CARGO for a non-used spec.
Definition: cargotype.h:58
SPR_AQUEDUCT_BASE
static const SpriteID SPR_AQUEDUCT_BASE
Sprites for the Aqueduct.
Definition: sprites.h:186
RailVehicleInfo::cost_factor
byte cost_factor
Purchase cost factor; For multiheaded engines the sum of both engine prices.
Definition: engine_type.h:45
industry_map.h
DeterministicSpriteGroupAdjustOperation
DeterministicSpriteGroupAdjustOperation
Definition: newgrf_spritegroup.h:120
GameSettings::game_creation
GameCreationSettings game_creation
settings used during the creation of a game (map)
Definition: settings_type.h:584
GRFParameterInfo::num_bit
byte num_bit
Number of bits to use for this parameter.
Definition: newgrf_config.h:145
RAILTYPE_ELECTRIC
@ RAILTYPE_ELECTRIC
Electric rails.
Definition: rail_type.h:30
RandomizedSpriteGroup::var_scope
VarSpriteGroupScope var_scope
Take this object:
Definition: newgrf_spritegroup.h:193
GCF_INVALID
@ GCF_INVALID
GRF is unusable with this version of OpenTTD.
Definition: newgrf_config.h:30
AllocateRoadType
RoadType AllocateRoadType(RoadTypeLabel label, RoadTramType rtt)
Allocate a new road type label.
Definition: road_cmd.cpp:140
AirportChangeInfo
static ChangeInfoResult AirportChangeInfo(uint airport, int numinfo, int prop, ByteReader *buf)
Define properties for airports.
Definition: newgrf.cpp:3829
IndustryTileLayout
std::vector< IndustryTileLayoutTile > IndustryTileLayout
A complete tile layout for an industry is a list of tiles.
Definition: industrytype.h:102
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
AddGRFString
StringID AddGRFString(uint32 grfid, uint16 stringid, byte langid_to_add, bool new_scheme, bool allow_newlines, const char *text_to_add, StringID def_string)
Add the new read string into our structure.
Definition: newgrf_text.cpp:551
GetFileByGRFID
static GRFFile * GetFileByGRFID(uint32 grfid)
Obtain a NewGRF file by its grfID.
Definition: newgrf.cpp:409
SpriteID
uint32 SpriteID
The number of a sprite, without mapping bits and colourtables.
Definition: gfx_type.h:17
ObjectSpec::introduction_date
Date introduction_date
From when can this object be built.
Definition: newgrf_object.h:70
StringIDMapping::target
StringID * target
Destination for mapping result.
Definition: newgrf.cpp:477
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:258
RandomAccessFile::SkipBytes
void SkipBytes(int n)
Skip n bytes ahead in the file.
Definition: random_access_file.cpp:148
BridgeSpec
Struct containing information about a single bridge type.
Definition: bridge.h:41
RailtypeInfo::name
StringID name
Name of this rail type.
Definition: rail.h:173
IndustrySpec::closure_text
StringID closure_text
Message appearing when the industry closes.
Definition: industrytype.h:129
EngineInfo::lifelength
Year lifelength
Lifetime of a single vehicle.
Definition: engine_type.h:135
Engine::GetGRF
const GRFFile * GetGRF() const
Retrieve the NewGRF the engine is tied to.
Definition: engine_base.h:142
GrfProcessingState::SpriteSet::sprite
SpriteID sprite
SpriteID of the first sprite of the set.
Definition: newgrf.cpp:90
GRFFile::traininfo_vehicle_pitch
int traininfo_vehicle_pitch
Vertical offset for drawing train images in depot GUI and vehicle details.
Definition: newgrf.h:142
AirportTileSpec::ResetAirportTiles
static void ResetAirportTiles()
This function initializes the tile array of AirportTileSpec.
Definition: newgrf_airporttiles.cpp:57
TLF_KNOWN_FLAGS
@ TLF_KNOWN_FLAGS
Known flags. Any unknown set flag will disable the GRF.
Definition: newgrf_commons.h:50
ShipVehicleInfo::visual_effect
byte visual_effect
Bitstuffed NewGRF visual effect data.
Definition: engine_type.h:74
RoadVehicleInfo::max_speed
uint16 max_speed
Maximum speed (1 unit = 1/3.2 mph = 0.5 km-ish/h)
Definition: engine_type.h:118
DrawTileSprites::ground
PalSpriteID ground
Palette and sprite for the ground.
Definition: sprite.h:59
HouseSpec::extra_flags
HouseExtraFlags extra_flags
some more flags
Definition: house.h:118
GetRailTypeInfo
static const RailtypeInfo * GetRailTypeInfo(RailType railtype)
Returns a pointer to the Railtype information for a given railtype.
Definition: rail.h:304
AirportTileSpec
Defines the data structure of each individual tile of an airport.
Definition: newgrf_airporttiles.h:66
HouseSpec::probability
byte probability
Relative probability of appearing (16 is the standard value)
Definition: house.h:117
NETWORK_MAX_GRF_COUNT
static const uint NETWORK_MAX_GRF_COUNT
Maximum number of GRFs that can be sent.
Definition: config.h:95
IndustryTileSpec::special_flags
IndustryTileSpecialFlags special_flags
Bitmask of extra flags used by the tile.
Definition: industrytype.h:170
StationSpec::cls_id
StationClassID cls_id
The class to which this spec belongs.
Definition: newgrf_station.h:126
EC_MAGLEV
@ EC_MAGLEV
Maglev engine.
Definition: engine_type.h:38
GRFTempEngineData::Refittability
Refittability
Summary state of refittability properties.
Definition: newgrf.cpp:319
NFO_UTF8_IDENTIFIER
static const WChar NFO_UTF8_IDENTIFIER
This character, the thorn ('þ'), indicates a unicode string to NFO.
Definition: newgrf_text.h:22
IndustryProductionSpriteGroup::num_output
uint8 num_output
How many add_output values are valid.
Definition: newgrf_spritegroup.h:275
newgrf_airporttiles.h
GameSettings::order
OrderSettings order
settings related to orders
Definition: settings_type.h:591
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:358
Slope
Slope
Enumeration for the slope-type.
Definition: slope_type.h:48
InitGRFTownGeneratorNames
void InitGRFTownGeneratorNames()
Allocate memory for the NewGRF town names.
Definition: newgrf_townname.cpp:109
GRFP_GRF_DOS
@ GRFP_GRF_DOS
The NewGRF says the DOS palette can be used.
Definition: newgrf_config.h:71
_grm_engines
static uint32 _grm_engines[256]
Contains the GRF ID of the owner of a vehicle if it has been reserved.
Definition: newgrf.cpp:356
MAX_CATCHMENT
@ MAX_CATCHMENT
Maximum catchment for airports with "modified catchment" enabled.
Definition: station_type.h:85
AnimationInfo::frames
uint8 frames
The number of frames.
Definition: newgrf_animation_type.h:19
DrawTileSeqStruct::delta_x
int8 delta_x
0x80 is sequence terminator
Definition: sprite.h:26
GRFLoadedFeatures::has_2CC
bool has_2CC
Set if any vehicle is loaded which uses 2cc (two company colours).
Definition: newgrf.h:175
PROP_ROADVEH_SPEED
@ PROP_ROADVEH_SPEED
Max. speed: 1 unit = 1/0.8 mph = 2 km-ish/h.
Definition: newgrf_properties.h:38
RailVehicleInfo::visual_effect
byte visual_effect
Bitstuffed NewGRF visual effect data.
Definition: engine_type.h:57
TileIndexDiffC::y
int16 y
The y value of the coordinate.
Definition: map_type.h:59
GrfProcessingState::HasValidSpriteSets
bool HasValidSpriteSets(byte feature) const
Check whether there are any valid spritesets for a feature.
Definition: newgrf.cpp:151
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:6566
LoadNewGRF
void LoadNewGRF(uint load_index, uint num_baseset)
Load all the NewGRFs.
Definition: newgrf.cpp:9808
AirportSpec::rotation
const Direction * rotation
the rotation of each tiletable
Definition: newgrf_airport.h:101
EngineID
uint16 EngineID
Unique identification number of an engine.
Definition: engine_type.h:21
LoadNewGRFFile
void LoadNewGRFFile(GRFConfig *config, GrfLoadingStage stage, Subdirectory subdir, bool temporary)
Load a particular NewGRF.
Definition: newgrf.cpp:9482
SHORE_REPLACE_NONE
@ SHORE_REPLACE_NONE
No shore sprites were replaced.
Definition: newgrf.h:162
RailVehicleInfo::ai_passenger_only
byte ai_passenger_only
Bit value to tell AI that this engine is for passenger use only.
Definition: engine_type.h:54
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:527
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:177
_gted
static GRFTempEngineData * _gted
Temporary engine data used during NewGRF loading.
Definition: newgrf.cpp:350
TE_NONE
@ TE_NONE
Cargo has no effect.
Definition: cargotype.h:28
RoadTypeInfo::powered_roadtypes
RoadTypes powered_roadtypes
bitmask to the OTHER roadtypes on which a vehicle of THIS roadtype generates power
Definition: road.h:119
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:52
IndustryTileSpec::acceptance
int8 acceptance[INDUSTRY_NUM_INPUTS]
Level of acceptance per cargo type (signed, may be negative!)
Definition: industrytype.h:158
BindAirportSpecs
void BindAirportSpecs()
Tie all airportspecs to their class.
Definition: newgrf_airport.cpp:165
LoadNextSprite
bool LoadNextSprite(int load_index, SpriteFile &file, uint file_sprite_id)
Load a real or recolour sprite.
Definition: spritecache.cpp:611
VE_TYPE_START
@ VE_TYPE_START
First bit used for the type of effect.
Definition: vehicle_base.h:85
RailType
RailType
Enumeration for all possible railtypes.
Definition: rail_type.h:27
GRFFile::tramtype_list
std::vector< RoadTypeLabel > tramtype_list
Roadtype translation table (tram)
Definition: newgrf.h:135
GetSnowLine
byte GetSnowLine()
Get the current snow line, either variable or static.
Definition: landscape.cpp:650
SetBitIterator
Iterable ensemble of each set bit in a value.
Definition: bitmath_func.hpp:329
_date
Date _date
Current date in days (day counter)
Definition: date.cpp:28
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
RailVehicleInfo::air_drag
byte air_drag
Coefficient of air drag.
Definition: engine_type.h:60
LanguageMap::GetLanguageMap
static const LanguageMap * GetLanguageMap(uint32 grfid, uint8 language_id)
Get the language map associated with a given NewGRF and language.
Definition: newgrf.cpp:2572
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:155
NUM_HOUSES
static const HouseID NUM_HOUSES
Total number of houses.
Definition: house.h:29
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
HasExactlyOneBit
static bool HasExactlyOneBit(T value)
Test whether value has exactly 1 bit set.
Definition: bitmath_func.hpp:274
MAX_BRIDGES
static const uint MAX_BRIDGES
Maximal number of available bridge specs.
Definition: bridge.h:34
DrawTileSeqStruct::delta_z
int8 delta_z
0x80 identifies child sprites
Definition: sprite.h:28
StringIDMapping::source
StringID source
Source StringID (GRF local).
Definition: newgrf.cpp:476
AirportSpec::num_table
byte num_table
number of elements in the table
Definition: newgrf_airport.h:102
SetPriceBaseMultiplier
void SetPriceBaseMultiplier(Price price, int factor)
Change a price base by the given factor.
Definition: economy.cpp:894
IndustrySpec::conflicting
IndustryType conflicting[3]
Industries this industry cannot be close to.
Definition: industrytype.h:112
EngineInfo::callback_mask
byte callback_mask
Bitmask of vehicle callbacks that have to be called.
Definition: engine_type.h:144
CurrencySpec::suffix
std::string suffix
Suffix to apply when formatting money in this currency.
Definition: currency.h:77
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:41
DIR_E
@ DIR_E
East.
Definition: direction_type.h:28
MIN_YEAR
static const Year MIN_YEAR
The absolute minimum & maximum years in OTTD.
Definition: date_type.h:84
StationSpec::layouts
std::vector< std::vector< std::vector< byte > > > layouts
Custom platform layouts.
Definition: newgrf_station.h:176
OverrideManagerBase::ResetMapping
void ResetMapping()
Resets the mapping, which is used while initializing game.
Definition: newgrf_commons.cpp:82
FinaliseIndustriesArray
static void FinaliseIndustriesArray()
Add all new industries to the industry array.
Definition: newgrf.cpp:9192
TLF_CHILD_Y_OFFSET
@ TLF_CHILD_Y_OFFSET
Add signed offset to child sprite Y positions from register TileLayoutRegisters::delta....
Definition: newgrf_commons.h:45
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
YearMonthDay::month
Month month
Month (0..11)
Definition: date_type.h:106
NEW_HOUSE_OFFSET
static const HouseID NEW_HOUSE_OFFSET
Offset for new houses.
Definition: house.h:28
HandleParameterInfo
static bool HandleParameterInfo(ByteReader *buf)
Callback function for 'INFO'->'PARA' to set extra information about the parameters.
Definition: newgrf.cpp:8199
StationSpec::pylons
byte pylons
Bitmask of base tiles (0 - 7) which should contain elrail pylons.
Definition: newgrf_station.h:162
AirportTileTable::gfx
StationGfx gfx
AirportTile to use for this tile.
Definition: newgrf_airport.h:25
StrMakeValidInPlace
void StrMakeValidInPlace(char *str, const char *last, StringValidationSettings settings)
Scans the string for invalid characters and replaces then with a question mark '?' (if not ignored).
Definition: string.cpp:273
CallbackResultSpriteGroup
Definition: newgrf_spritegroup.h:210
CargoSpec::units_volume
StringID units_volume
Name of a single unit of cargo of this type.
Definition: cargotype.h:73
CargoSpec::IsValid
bool IsValid() const
Tests for validity of this cargospec.
Definition: cargotype.h:99
RailtypeInfo::alternate_labels
RailTypeLabelList alternate_labels
Rail type labels this type provides in addition to the main label.
Definition: rail.h:238
HouseSpec::building_flags
BuildingFlags building_flags
some flags that describe the house (size, stadium etc...)
Definition: house.h:109
RoadVehicleInfo
Information about a road vehicle.
Definition: engine_type.h:112
CC_PIECE_GOODS
@ CC_PIECE_GOODS
Piece goods (Livestock, Wood, Steel, Paper)
Definition: cargotype.h:46
GRFConfig::flags
uint8 flags
NOSAVE: GCF_Flags, bitset.
Definition: newgrf_config.h:173
BranchHandler
bool(* BranchHandler)(ByteReader *)
Type of callback function for branch nodes.
Definition: newgrf.cpp:8062
LanguageMap::Mapping::openttd_id
byte openttd_id
OpenTTD's internal ID for a case/gender.
Definition: newgrf_text.h:62
SB
static T SB(T &x, const uint8 s, const uint8 n, const U d)
Set n bits in x starting at bit s to d.
Definition: bitmath_func.hpp:58
RoadVehicleInfo::visual_effect
byte visual_effect
Bitstuffed NewGRF visual effect data.
Definition: engine_type.h:124
IndustryProductionSpriteGroup
Definition: newgrf_spritegroup.h:268
ConvertYMDToDate
Date ConvertYMDToDate(Year year, Month month, Day day)
Converts a tuple of Year, Month and Day to a Date.
Definition: date.cpp:149
IndustrySpec::layouts
std::vector< IndustryTileLayout > layouts
List of possible tile layouts for the industry.
Definition: industrytype.h:108
SPRITE_MODIFIER_OPAQUE
@ SPRITE_MODIFIER_OPAQUE
Set when a sprite must not ever be displayed transparently.
Definition: sprites.h:1534
IndustrySpec::accepts_cargo
CargoID accepts_cargo[INDUSTRY_NUM_INPUTS]
16 accepted cargoes.
Definition: industrytype.h:121
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
GetGRFSpriteOffset
size_t GetGRFSpriteOffset(uint32 id)
Get the file offset for a specific sprite in the sprite section of a GRF.
Definition: spritecache.cpp:546
EF_USES_2CC
@ EF_USES_2CC
Vehicle uses two company colours.
Definition: engine_type.h:156
SHORE_REPLACE_ONLY_NEW
@ SHORE_REPLACE_ONLY_NEW
Only corner-shores were loaded by Action5 (openttd(w/d).grf only).
Definition: newgrf.h:165
IndustrySpec::number_of_sounds
uint8 number_of_sounds
Number of sounds available in the sounds array.
Definition: industrytype.h:135
find_index
int find_index(std::vector< T > const &vec, T const &item)
Helper function to get the index of an item Consider using std::set, std::unordered_set or std::flat_...
Definition: smallvec_type.hpp:44
BridgeSpec::transport_name
StringID transport_name[2]
description of the bridge, when built for road or rail
Definition: bridge.h:50
CC_BULK
@ CC_BULK
Bulk cargo (Coal, Grain etc., Ores, Fruit)
Definition: cargotype.h:45
_cargo_mask
CargoTypes _cargo_mask
Bitmask of cargo types available.
Definition: cargotype.cpp:29
AircraftVehicleInfo::max_range
uint16 max_range
Maximum range of this aircraft.
Definition: engine_type.h:108
AddGenericCallback
void AddGenericCallback(uint8 feature, const GRFFile *file, const SpriteGroup *group)
Add a generic feature callback sprite group to the appropriate feature list.
Definition: newgrf_generic.cpp:109
SP_CUSTOM
@ SP_CUSTOM
No profile, special "custom" highscore.
Definition: settings_type.h:45
NUM_AIRPORTS_PER_GRF
@ NUM_AIRPORTS_PER_GRF
Maximal number of airports per NewGRF.
Definition: airport.h:40
IndustrySpec::production_up_text
StringID production_up_text
Message appearing when the industry's production is increasing.
Definition: industrytype.h:130
CleanUpStrings
void CleanUpStrings()
House cleaning.
Definition: newgrf_text.cpp:695
Date
int32 Date
The type to store our dates in.
Definition: date_type.h:14
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:9094
GrfProcessingState::SpriteSet
Definition of a single Action1 spriteset.
Definition: newgrf.cpp:89
LoadNewGRFFileFromFile
static void LoadNewGRFFileFromFile(GRFConfig *config, GrfLoadingStage stage, SpriteFile &file)
Load a particular NewGRF from a SpriteFile.
Definition: newgrf.cpp:9393
IndustrySpec::input_cargo_multiplier
uint16 input_cargo_multiplier[INDUSTRY_NUM_INPUTS][INDUSTRY_NUM_OUTPUTS]
Input cargo multipliers (multiply amount of incoming cargo for the produced cargoes)
Definition: industrytype.h:122
CargoSpec::grffile
const struct GRFFile * grffile
NewGRF where #group belongs to.
Definition: cargotype.h:80
StaticGRFInfo
static void StaticGRFInfo(ByteReader *buf)
Handle Action 0x14.
Definition: newgrf.cpp:8345
EC_DIESEL
@ EC_DIESEL
Diesel rail engine.
Definition: engine_type.h:35
HZ_ZONALL
@ HZ_ZONALL
1F This is just to englobe all above types at once
Definition: house.h:78
NewGRFClass
Struct containing information relating to NewGRF classes for stations and airports.
Definition: newgrf_class.h:19
StationSettings::never_expire_airports
bool never_expire_airports
never expire airports
Definition: settings_type.h:559
AfterLoadGRFs
static void AfterLoadGRFs()
Finish loading NewGRFs and execute needed post-processing.
Definition: newgrf.cpp:9687
_cur_parameter
static GRFParameterInfo * _cur_parameter
The parameter which info is currently changed by the newgrf.
Definition: newgrf.cpp:7971
IndustrySpec::minimal_cargo
byte minimal_cargo
minimum amount of cargo transported to the stations.
Definition: industrytype.h:120
RoadTypeInfo::group
const SpriteGroup * group[ROTSG_END]
Sprite groups for resolving sprites.
Definition: road.h:189
LanguageMap::gender_map
std::vector< Mapping > gender_map
Mapping of NewGRF and OpenTTD IDs for genders.
Definition: newgrf_text.h:71
SHORE_REPLACE_ACTION_5
@ SHORE_REPLACE_ACTION_5
Shore sprites were replaced by Action5.
Definition: newgrf.h:163
StringIDMapping
Information for mapping static StringIDs.
Definition: newgrf.cpp:474
RailtypeInfo::introduction_date
Date introduction_date
Introduction date.
Definition: rail.h:252
_settings_game
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition: settings.cpp:54
HouseSpec::animation
AnimationInfo animation
information about the animation.
Definition: house.h:120
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
ANIM_STATUS_NO_ANIMATION
static const uint8 ANIM_STATUS_NO_ANIMATION
There is no animation.
Definition: newgrf_animation_type.h:15
ValidateIndustryLayout
static bool ValidateIndustryLayout(const IndustryTileLayout &layout)
Validate the industry layout; e.g.
Definition: newgrf.cpp:3387
RoadTypeInfo::alternate_labels
RoadTypeLabelList alternate_labels
Road type labels this type provides in addition to the main label.
Definition: road.h:149
MapNewGRFIndustryType
IndustryType MapNewGRFIndustryType(IndustryType grf_type, uint32 grf_id)
Map the GRF local type to an industry type.
Definition: newgrf_industries.cpp:39
ChangeGRFURL
static bool ChangeGRFURL(byte langid, const char *str)
Callback function for 'INFO'->'URL_' to set the newgrf url.
Definition: newgrf.cpp:7872
_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:194
GRFParameterInfo
Information about one grf parameter.
Definition: newgrf_config.h:134
CargoSpec::sprite
SpriteID sprite
Icon to display this cargo type, may be 0xFFF (which means to resolve an action123 chain).
Definition: cargotype.h:77
ConvertDateToYMD
void ConvertDateToYMD(Date date, YearMonthDay *ymd)
Converts a Date to a Year, Month & Day.
Definition: date.cpp:94
GameSettings::economy
EconomySettings economy
settings to change the economy
Definition: settings_type.h:593
DrawTileSeqStruct::IsTerminator
bool IsTerminator() const
Check whether this is a sequence terminator.
Definition: sprite.h:41
AirportSpec::ttd_airport_type
TTDPAirportType ttd_airport_type
ttdpatch airport type (Small/Large/Helipad/Oilrig)
Definition: newgrf_airport.h:112
PROP_SHIP_CARGO_AGE_PERIOD
@ PROP_SHIP_CARGO_AGE_PERIOD
Number of ticks before carried cargo is aged.
Definition: newgrf_properties.h:47
HandleNode
static bool HandleNode(byte type, uint32 id, ByteReader *buf, AllowedSubtags subtags[])
Handle the nodes of an Action14.
Definition: newgrf.cpp:8292
TileLayoutRegisters::child
uint8 child[2]
Registers for signed offsets for the position of child sprites.
Definition: newgrf_commons.h:100
_action5_types
static const Action5Type _action5_types[]
The information about action 5 types.
Definition: newgrf.cpp:6151
NewGRFSpriteLayout
NewGRF supplied spritelayout.
Definition: newgrf_commons.h:113
MAX_LANG
static const uint MAX_LANG
Maximum number of languages supported by the game, and the NewGRF specs.
Definition: strings_type.h:19
safeguards.h
GRFFile::label
GRFLabel * label
Pointer to the first label. This is a linked list, not an array.
Definition: newgrf.h:124
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:8027
StationSpec::name
StringID name
Name of this station.
Definition: newgrf_station.h:127
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:315
GRFP_BLT_32BPP
@ GRFP_BLT_32BPP
The NewGRF prefers a 32 bpp blitter.
Definition: newgrf_config.h:77
HouseSpec::callback_mask
uint16 callback_mask
Bitmask of house callbacks that have to be called.
Definition: house.h:115
IndustryTileSpec::slopes_refused
Slope slopes_refused
slope pattern on which this tile cannot be built
Definition: industrytype.h:159
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:8152
ImportGRFSound
static void ImportGRFSound(SoundEntry *sound)
Process a sound import from another GRF file.
Definition: newgrf.cpp:7597
GRFConfig::has_param_defaults
bool has_param_defaults
NOSAVE: did this newgrf specify any defaults for it's parameters.
Definition: newgrf_config.h:181
GRFFile::param_end
uint param_end
one more than the highest set parameter
Definition: newgrf.h:122
TLR_MAX_VAR10
static const uint TLR_MAX_VAR10
Maximum value for var 10.
Definition: newgrf_commons.h:106
GetGRFStringID
StringID GetGRFStringID(uint32 grfid, StringID stringid)
Returns the index for this stringid associated with its grfID.
Definition: newgrf_text.cpp:601
ttd_strnlen
static size_t ttd_strnlen(const char *str, size_t maxlen)
Get the length of a string, within a limited buffer.
Definition: string_func.h:79
GrfProcessingState
Temporary data during loading of GRFs.
Definition: newgrf.cpp:86
SPRITE_MODIFIER_CUSTOM_SPRITE
@ SPRITE_MODIFIER_CUSTOM_SPRITE
Set when a sprite originates from an Action 1.
Definition: sprites.h:1533
IndustryTileSpec::enabled
bool enabled
entity still available (by default true).newgrf can disable it, though
Definition: industrytype.h:171
StrEmpty
static bool StrEmpty(const char *s)
Check if a string buffer is empty.
Definition: string_func.h:67
_tags_root
AllowedSubtags _tags_root[]
Action14 root tags.
Definition: newgrf.cpp:8240
CargoSpec::weight
uint8 weight
Weight of a single unit of this cargo type in 1/16 ton (62.5 kg).
Definition: cargotype.h:62
FinaliseObjectsArray
static void FinaliseObjectsArray()
Add all new objects to the object array.
Definition: newgrf.cpp:9261
GRFTempEngineData::EMPTY
@ EMPTY
GRF defined vehicle as not-refittable. The vehicle shall only carry the default cargo.
Definition: newgrf.cpp:321
TranslateRefitMask
static CargoTypes TranslateRefitMask(uint32 refit_mask)
Translate the refit mask.
Definition: newgrf.cpp:961
ObjectSpec::height
uint8 height
The height of this structure, in heightlevels; max MAX_TILE_HEIGHT.
Definition: newgrf_object.h:75
WaterFeature::flags
uint8 flags
Flags controlling display.
Definition: newgrf_canal.h:26
NamePart::text
char * text
If probability bit 7 is clear.
Definition: newgrf_townname.h:22
DrawTileSprites
Ground palette sprite of a tile, together with its sprite layout.
Definition: sprite.h:58
HouseSpec::minimum_life
byte minimum_life
The minimum number of years this house will survive before the town rebuilds it.
Definition: house.h:122
_networking
bool _networking
are we in networking mode?
Definition: network.cpp:58
ROADTYPE_ROAD
@ ROADTYPE_ROAD
Basic road type.
Definition: road_type.h:24
TTDPAirportType
TTDPAirportType
Allow incrementing of AirportClassID variables.
Definition: newgrf_airport.h:81
CanalChangeInfo
static ChangeInfoResult CanalChangeInfo(uint id, int numinfo, int prop, ByteReader *buf)
Define properties for water features.
Definition: newgrf.cpp:2105
LoadTranslationTable
static ChangeInfoResult LoadTranslationTable(uint gvid, int numinfo, ByteReader *buf, T &translation_table, const char *name)
Load a cargo- or railtype-translation table.
Definition: newgrf.cpp:2589
GlobalVarChangeInfo
static ChangeInfoResult GlobalVarChangeInfo(uint gvid, int numinfo, int prop, ByteReader *buf)
Define properties for global variables.
Definition: newgrf.cpp:2629
newgrf_text.h
road.h
vseprintf
int CDECL vseprintf(char *str, const char *last, const char *format, va_list ap)
Safer implementation of vsnprintf; same as vsnprintf except:
Definition: string.cpp:62
RoadTypeInfo::name
StringID name
Name of this rail type.
Definition: road.h:100
error.h
GrfProcessingState::GetSprite
SpriteID GetSprite(byte feature, uint set) const
Returns the first sprite of a spriteset.
Definition: newgrf.cpp:176
RailVehicleChangeInfo
static ChangeInfoResult RailVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader *buf)
Define properties for rail vehicles.
Definition: newgrf.cpp:1058
CargoSpec::is_freight
bool is_freight
Cargo type is considered to be freight (affects train freight multiplier).
Definition: cargotype.h:67
HZ_ZON5
@ HZ_ZON5
center of town
Definition: house.h:77
GRFTempEngineData::ctt_exclude_mask
CargoTypes ctt_exclude_mask
Cargo types always excluded from the refit mask.
Definition: newgrf.cpp:334
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:329
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:157
EngineIDMapping
Definition: engine_base.h:167
AirportTileTable
Tile-offset / AirportTileID pair.
Definition: newgrf_airport.h:23
IndustrySpec::appear_creation
byte appear_creation[NUM_LANDSCAPE]
Probability of appearance during map creation.
Definition: industrytype.h:134
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:81
language.h
IndustryTileSpec::anim_production
byte anim_production
Animation frame to start when goods are produced.
Definition: industrytype.h:160
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:27
EngineInfo::retire_early
int8 retire_early
Number of years early to retire vehicle.
Definition: engine_type.h:145
GetNewEngineID
EngineID GetNewEngineID(const GRFFile *file, VehicleType type, uint16 internal_id)
Return the ID of a new engine.
Definition: newgrf.cpp:708
RailVehicleInfo::tractive_effort
byte tractive_effort
Tractive effort coefficient.
Definition: engine_type.h:59
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:143
EngineIDMapping::substitute_id
uint8 substitute_id
The (original) entity ID to use if this GRF is not available (currently not used)
Definition: engine_base.h:171
CargoChangeInfo
static ChangeInfoResult CargoChangeInfo(uint cid, int numinfo, int prop, ByteReader *buf)
Define properties for cargoes.
Definition: newgrf.cpp:2925
date_func.h
SoundEntry
Definition: sound_type.h:13
StationSpec::disallowed_platforms
byte disallowed_platforms
Bitmask of number of platforms available for the station.
Definition: newgrf_station.h:133
stdafx.h
GrfProcessingState::grfconfig
GRFConfig * grfconfig
Config of the currently processed GRF file.
Definition: newgrf.cpp:105
TLF_NON_GROUND_FLAGS
@ TLF_NON_GROUND_FLAGS
Flags which do not work for the (first) ground sprite.
Definition: newgrf_commons.h:56
VehicleType
VehicleType
Available vehicle types.
Definition: vehicle_type.h:21
IsLeapYear
static bool IsLeapYear(Year yr)
Checks whether the given year is a leap year or not.
Definition: date_func.h:30
landscape.h
ObjectSpec::enabled
bool enabled
Is this spec enabled?
Definition: newgrf_object.h:78
RailVehicleInfo::pow_wag_power
uint16 pow_wag_power
Extra power applied to consist if wagon should be powered.
Definition: engine_type.h:55
RailtypeInfo::toolbar_caption
StringID toolbar_caption
Caption in the construction toolbar GUI for this rail type.
Definition: rail.h:174
OTTDByteReaderSignal
Definition: newgrf.cpp:210
PROP_AIRCRAFT_COST_FACTOR
@ PROP_AIRCRAFT_COST_FACTOR
Purchase cost.
Definition: newgrf_properties.h:49
IndustrySpec
Defines the data structure for constructing industry.
Definition: industrytype.h:107
RailVehicleInfo::weight
uint16 weight
Weight of vehicle (tons); For multiheaded engines the weight of each single engine.
Definition: engine_type.h:49
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:172
BSWAP32
static uint32 BSWAP32(uint32 x)
Perform a 32 bits endianness bitswap on x.
Definition: bitmath_func.hpp:390
SPR_RAILTYPE_TUNNEL_BASE
static const SpriteID SPR_RAILTYPE_TUNNEL_BASE
Tunnel sprites with grass only for custom railtype tunnel.
Definition: sprites.h:297
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:1535
NEWGRF_DIR
@ NEWGRF_DIR
Subdirectory for all NewGRFs.
Definition: fileio_type.h:117
IgnoreIndustryProperty
static ChangeInfoResult IgnoreIndustryProperty(int prop, ByteReader *buf)
Ignore an industry property.
Definition: newgrf.cpp:3297
GRFTempEngineData::refittability
Refittability refittability
Did the newgrf set any refittability property? If not, default refittability will be applied.
Definition: newgrf.cpp:330
EngineInfo::misc_flags
byte misc_flags
Miscellaneous flags.
Definition: engine_type.h:143
HouseSpec::mail_generation
byte mail_generation
mail generation multiplier (tile based, as the acceptances below)
Definition: house.h:106
A5BLOCK_FIXED
@ A5BLOCK_FIXED
Only allow replacing a whole block of sprites. (TTDP compatible)
Definition: newgrf.cpp:6137
GRFTownName
Definition: newgrf_townname.h:35
RandomAccessFile::ReadWord
uint16 ReadWord()
Read a word (16 bits) from the file (in low endian format).
Definition: random_access_file.cpp:117
A5BLOCK_ALLOW_OFFSET
@ A5BLOCK_ALLOW_OFFSET
Allow replacing any subset by specifiing an offset.
Definition: newgrf.cpp:6138
HouseSpec::population
byte population
population (Zero on other tiles in multi tile house.)
Definition: house.h:102
PROP_SHIP_RUNNING_COST_FACTOR
@ PROP_SHIP_RUNNING_COST_FACTOR
Yearly runningcost.
Definition: newgrf_properties.h:46
RailtypeInfo::powered_railtypes
RailTypes powered_railtypes
bitmask to the OTHER railtypes on which an engine of THIS railtype generates power
Definition: rail.h:185
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.h:60
RandomAccessFile::ReadDword
uint32 ReadDword()
Read a double word (32 bits) from the file (in low endian format).
Definition: random_access_file.cpp:127
BuildCargoTranslationMap
static void BuildCargoTranslationMap()
Construct the Cargo Mapping.
Definition: newgrf.cpp:8703
Utf8Decode
size_t Utf8Decode(WChar *c, const char *s)
Decode and consume the next UTF-8 encoded character.
Definition: string.cpp:593
HouseSpec::cargo_acceptance
byte cargo_acceptance[HOUSE_NUM_ACCEPTS]
acceptance level for the cargo slots
Definition: house.h:107
RailtypeInfo::map_colour
byte map_colour
Colour on mini-map.
Definition: rail.h:243
WaterFeature::grffile
const GRFFile * grffile
NewGRF where 'group' belongs to.
Definition: newgrf_canal.h:24
_engine_offsets
const uint8 _engine_offsets[4]
Offset of the first engine of each vehicle type in original engine data.
Definition: engine.cpp:59
ShipVehicleInfo::old_refittable
bool old_refittable
Is ship refittable; only used during initialisation. Later use EngineInfo::refit_mask.
Definition: engine_type.h:73
AllowedSubtags::type
byte type
The type of the node, must be one of 'C', 'B' or 'T'.
Definition: newgrf.cpp:8129
GRFParameterInfo::first_bit
byte first_bit
First bit to use in the GRF parameter.
Definition: newgrf_config.h:144
BuildIndustriesLegend
void BuildIndustriesLegend()
Fills an array for the industries legends.
Definition: smallmap_gui.cpp:169
SetSnowLine
void SetSnowLine(byte table[SNOW_LINE_MONTHS][SNOW_LINE_DAYS])
Set a variable snow line, as loaded from a newgrf file.
Definition: landscape.cpp:631
newgrf_object.h
BridgeSpec::min_length
byte min_length
the minimum length (not counting start and end tile)
Definition: bridge.h:43
IndustryProductionSpriteGroup::add_output
uint16 add_output[INDUSTRY_NUM_OUTPUTS]
Add this much output cargo when successful (unsigned, is indirect in cb version 1+)
Definition: newgrf_spritegroup.h:276
ObjectSpec::name
StringID name
The name for this object.
Definition: newgrf_object.h:64
ChangeGRFBlitter
static bool ChangeGRFBlitter(size_t len, ByteReader *buf)
Callback function for 'INFO'->'BLTR' to set the blitter info.
Definition: newgrf.cpp:7917
RandomAccessFile::GetPos
size_t GetPos() const
Get position in the file.
Definition: random_access_file.cpp:73
AirportSpec::size_x
byte size_x
size of airport in x direction
Definition: newgrf_airport.h:105
FinaliseEngineArray
static void FinaliseEngineArray()
Check for invalid engines.
Definition: newgrf.cpp:8976
GRFParameterType
GRFParameterType
The possible types of a newgrf parameter.
Definition: newgrf_config.h:127
ChangeGRFNumUsedParams
static bool ChangeGRFNumUsedParams(size_t len, ByteReader *buf)
Callback function for 'INFO'->'NPAR' to set the number of valid parameters.
Definition: newgrf.cpp:7879
GRFTempEngineData::UNSET
@ UNSET
No properties assigned. Default refit masks shall be activated.
Definition: newgrf.cpp:320
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:7952
TileLayoutRegisters::sprite_var10
uint8 sprite_var10
Value for variable 10 when resolving the sprite.
Definition: newgrf_commons.h:102
RAILTYPE_RAIL
@ RAILTYPE_RAIL
Standard non-electric rails.
Definition: rail_type.h:29
_generating_world
bool _generating_world
Whether we are generating the map or not.
Definition: genworld.cpp:61
GCS_UNKNOWN
@ GCS_UNKNOWN
The status of this grf file is unknown.
Definition: newgrf_config.h:35
ConstructionSettings::max_bridge_length
uint16 max_bridge_length
maximum length of bridges
Definition: settings_type.h:342
ObjectSpec::clear_cost_multiplier
uint8 clear_cost_multiplier
Clear cost multiplier per tile.
Definition: newgrf_object.h:69
SpriteFile
RandomAccessFile with some extra information specific for sprite files.
Definition: sprite_file_type.hpp:19
LanguagePackHeader::GetGenderIndex
uint8 GetGenderIndex(const char *gender_str) const
Get the index for the given gender.
Definition: language.h:68
DeterministicSpriteGroupAdjust
Definition: newgrf_spritegroup.h:147
PriceBaseSpec
Describes properties of price bases.
Definition: economy_type.h:190
IndustryTileSpec::accepts_cargo
CargoID accepts_cargo[INDUSTRY_NUM_INPUTS]
Cargo accepted by this tile.
Definition: industrytype.h:157
YearMonthDay::year
Year year
Year (0...)
Definition: date_type.h:105
string_func.h
IndustrySpec::enabled
bool enabled
entity still available (by default true).newgrf can disable it, though
Definition: industrytype.h:140
ObjectSpec::generate_amount
uint8 generate_amount
Number of objects which are attempted to be generated per 256^2 map during world generation.
Definition: newgrf_object.h:77
GRFFile::canal_local_properties
CanalProperties canal_local_properties[CF_END]
Canal properties as set by this NewGRF.
Definition: newgrf.h:138
GRFError
Information about why GRF had problems during initialisation.
Definition: newgrf_config.h:112
RoadTypeInfo::grffile
const GRFFile * grffile[ROTSG_END]
NewGRF providing the Action3 for the roadtype.
Definition: road.h:184
RailtypeInfo::acceleration_type
uint8 acceleration_type
Acceleration type of this rail type.
Definition: rail.h:223
ChangeGRFDescription
static bool ChangeGRFDescription(byte langid, const char *str)
Callback function for 'INFO'->'DESC' to add a translation to the newgrf description.
Definition: newgrf.cpp:7865
GCS_DISABLED
@ GCS_DISABLED
GRF file is disabled.
Definition: newgrf_config.h:36
StringID
uint32 StringID
Numeric value that represents a string, independent of the selected language.
Definition: strings_type.h:16
SetUnicodeGlyph
static void SetUnicodeGlyph(FontSize size, WChar key, SpriteID sprite)
Map a SpriteID to the font size and key.
Definition: fontcache.h:163
CIR_DISABLED
@ CIR_DISABLED
GRF was disabled due to error.
Definition: newgrf.cpp:1000
GRFParameterInfo::max_value
uint32 max_value
The maximal value of this parameter.
Definition: newgrf_config.h:141
AllocateRailType
RailType AllocateRailType(RailTypeLabel label)
Allocate a new rail type label.
Definition: rail_cmd.cpp:159
ORIGINAL_MAX_YEAR
static const Year ORIGINAL_MAX_YEAR
The maximum year of the original TTD.
Definition: date_type.h:54
vehicle_func.h
rev.h
CURRENCY_END
@ CURRENCY_END
always the last item
Definition: currency.h:68
LanguagePackHeader::GetCaseIndex
uint8 GetCaseIndex(const char *case_str) const
Get the index for the given case.
Definition: language.h:81
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:8743
RailtypeInfo::flags
RailTypeFlags flags
Bit mask of rail type flags.
Definition: rail.h:208
VehicleSettings::dynamic_engines
bool dynamic_engines
enable dynamic allocation of engine data
Definition: settings_type.h:498
newgrf_sound.h
Clamp
static T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Definition: math_func.hpp:77
RoadVehicleInfo::shorten_factor
byte shorten_factor
length on main map for this type is 8 - shorten_factor
Definition: engine_type.h:125
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:386
GRFFilePropsBase::spritegroup
const struct SpriteGroup * spritegroup[Tcnt]
pointer to the different sprites of the entity
Definition: newgrf_commons.h:321
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:59
StationSpec
Station specification.
Definition: newgrf_station.h:113
CLEAN_RANDOMSOUNDS
@ CLEAN_RANDOMSOUNDS
Free the dynamically allocated sounds table.
Definition: industrytype.h:24
AirportSpec::enabled
bool enabled
Entity still available (by default true). Newgrf can disable it, though.
Definition: newgrf_airport.h:117
LanguageMap
Mapping of language data between a NewGRF and OpenTTD.
Definition: newgrf_text.h:58
PROP_TRAIN_SHORTEN_FACTOR
@ PROP_TRAIN_SHORTEN_FACTOR
Shorter vehicles.
Definition: newgrf_properties.h:28
IsHouseSpecValid
static bool IsHouseSpecValid(HouseSpec *hs, const HouseSpec *next1, const HouseSpec *next2, const HouseSpec *next3, const char *filename)
Check if a given housespec is valid and disable it if it's not.
Definition: newgrf.cpp:9048
IndustrytilesChangeInfo
static ChangeInfoResult IndustrytilesChangeInfo(uint indtid, int numinfo, int prop, ByteReader *buf)
Define properties for industry tiles.
Definition: newgrf.cpp:3159
RailVehicleInfo::max_speed
uint16 max_speed
Maximum speed (1 unit = 1/1.6 mph = 1 km-ish/h)
Definition: engine_type.h:47
FioCheckFileExists
bool FioCheckFileExists(const std::string &filename, Subdirectory subdir)
Check whether the given file exists.
Definition: fileio.cpp:108
GRFParameterInfo::value_names
SmallMap< uint32, GRFTextList > value_names
Names for each value.
Definition: newgrf_config.h:146
bridge.h
NEW_AIRPORT_OFFSET
@ NEW_AIRPORT_OFFSET
Number of the first newgrf airport.
Definition: airport.h:39
TileLayoutRegisters::palette
uint8 palette
Register specifying a signed offset for the palette.
Definition: newgrf_commons.h:95
GRFTempEngineData
Temporary engine data used when loading only.
Definition: newgrf.cpp:317
CC_ARMOURED
@ CC_ARMOURED
Armoured cargo (Valuables, Gold, Diamonds)
Definition: cargotype.h:44
ResetNewGRFErrors
static void ResetNewGRFErrors()
Clear all NewGRF errors.
Definition: newgrf.cpp:8581
GRFConfig::name
GRFTextWrapper name
NOSAVE: GRF name (Action 0x08)
Definition: newgrf_config.h:166
ResetNewGRF
static void ResetNewGRF()
Reset and clear all NewGRFs.
Definition: newgrf.cpp:8570
GRFLoadedFeatures::tram
TramReplacement tram
In which way tram depots were replaced.
Definition: newgrf.h:178
TileLayoutRegisters::max_palette_offset
uint16 max_palette_offset
Maximum offset to add to the palette. (limited by size of the spriteset)
Definition: newgrf_commons.h:97
BridgeSpec::max_length
uint16 max_length
the maximum length (not counting start and end tile)
Definition: bridge.h:44
GRFParameterInfo::desc
GRFTextList desc
The description of this parameter.
Definition: newgrf_config.h:138
AllowedSubtags
Data structure to store the allowed id/type combinations for action 14.
Definition: newgrf.cpp:8071
FinaliseAirportsArray
static void FinaliseAirportsArray()
Add all new airports to the airport array.
Definition: newgrf.cpp:9280
IndustrySpec::cost_multiplier
uint8 cost_multiplier
Base construction cost multiplier.
Definition: industrytype.h:109
SHORE_REPLACE_ACTION_A
@ SHORE_REPLACE_ACTION_A
Shore sprites were replaced by ActionA (using grass tiles for the corner-shores).
Definition: newgrf.h:164
GCF_RESERVED
@ GCF_RESERVED
GRF file passed GLS_RESERVE stage.
Definition: newgrf_config.h:29
BridgeSpec::price
uint16 price
the price multiplier
Definition: bridge.h:45
SanitizeSpriteOffset
static uint16 SanitizeSpriteOffset(uint16 &num, uint16 offset, int max_sprites, const char *name)
Sanitize incoming sprite offsets for Action 5 graphics replacements.
Definition: newgrf.cpp:6114
GRFConfig::min_loadable_version
uint32 min_loadable_version
NOSAVE: Minimum compatible version a NewGRF can define.
Definition: newgrf_config.h:172
ObjectSpec::views
uint8 views
The number of views.
Definition: newgrf_object.h:76
TRAMWAY_REPLACE_DEPOT_WITH_TRACK
@ TRAMWAY_REPLACE_DEPOT_WITH_TRACK
Electrified depot graphics with tram track were loaded.
Definition: newgrf.h:170
IndustryTileSpec::animation
AnimationInfo animation
Information about the animation (is it looping, how many loops etc)
Definition: industrytype.h:169
AirportTileSpec::callback_mask
uint8 callback_mask
Bitmask telling which grf callback is set.
Definition: newgrf_airporttiles.h:69
MapSpriteMappingRecolour
static void MapSpriteMappingRecolour(PalSpriteID *grf_sprite)
Map the colour modifiers of TTDPatch to those that Open is using.
Definition: newgrf.cpp:724
GetGlobalVariable
bool GetGlobalVariable(byte param, uint32 *value, const GRFFile *grffile)
Reads a variable common to VarAction2 and Action7/9/D.
Definition: newgrf.cpp:6284
RAILTYPE_END
@ RAILTYPE_END
Used for iterations.
Definition: rail_type.h:33
CC_REFRIGERATED
@ CC_REFRIGERATED
Refrigerated cargo (Food, Fruit)
Definition: cargotype.h:48
CanalProperties::flags
uint8 flags
Flags controlling display.
Definition: newgrf.h:41
PaletteID
uint32 PaletteID
The number of the palette.
Definition: gfx_type.h:18
CommonVehicleChangeInfo
static ChangeInfoResult CommonVehicleChangeInfo(EngineInfo *ei, int prop, ByteReader *buf)
Define properties common to all vehicles.
Definition: newgrf.cpp:1015
ConstructionSettings::build_on_slopes
bool build_on_slopes
allow building on slopes
Definition: settings_type.h:340
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:8136
HZ_SUBARTC_ABOVE
@ HZ_SUBARTC_ABOVE
11 800 can appear in sub-arctic climate above the snow line
Definition: house.h:79
TextHandler
bool(* TextHandler)(byte, const char *str)
Type of callback function for text nodes.
Definition: newgrf.cpp:8061
Action5Type::block_type
Action5BlockType block_type
How is this Action5 type processed?
Definition: newgrf.cpp:6143
AirportSpec::grf_prop
struct GRFFileProps grf_prop
Properties related to the grf file.
Definition: newgrf_airport.h:118
CargoSpec::quantifier
StringID quantifier
Text for multiple units of cargo of this type.
Definition: cargotype.h:74
SPR_AIRPORT_PREVIEW_BASE
static const SpriteID SPR_AIRPORT_PREVIEW_BASE
Airport preview sprites.
Definition: sprites.h:248
Action5Type::min_sprites
uint16 min_sprites
If the Action5 contains less sprites, the whole block will be ignored.
Definition: newgrf.cpp:6145
GRFConfig::next
struct GRFConfig * next
NOSAVE: Next item in the linked list.
Definition: newgrf_config.h:183
industrytype.h
RAILVEH_MULTIHEAD
@ RAILVEH_MULTIHEAD
indicates a combination of two locomotives
Definition: engine_type.h:28
GetEngineLiveryScheme
LiveryScheme GetEngineLiveryScheme(EngineID engine_type, EngineID parent_engine_type, const Vehicle *v)
Determines the LiveryScheme for a vehicle.
Definition: vehicle.cpp:1883
GetDefaultCargoID
CargoID GetDefaultCargoID(LandscapeID l, CargoType ct)
Get the cargo ID of a default cargo, if present.
Definition: cargotype.cpp:87
InitializeSortedCargoSpecs
void InitializeSortedCargoSpecs()
Initialize the list of sorted cargo specifications.
Definition: cargotype.cpp:189
GrfProcessingState::AddSpriteSets
void AddSpriteSets(byte feature, SpriteID first_sprite, uint first_set, uint numsets, uint numents)
Records new spritesets.
Definition: newgrf.cpp:135
CurrencySpec::rate
uint16 rate
The conversion rate compared to the base currency.
Definition: currency.h:73
SPR_OPENTTD_BASE
static const SpriteID SPR_OPENTTD_BASE
Extra graphic spritenumbers.
Definition: sprites.h:56
IndustrySpec::production_down_text
StringID production_down_text
Message appearing when the industry's production is decreasing.
Definition: industrytype.h:131
TRAMWAY_REPLACE_DEPOT_NONE
@ TRAMWAY_REPLACE_DEPOT_NONE
No tram depot graphics were loaded.
Definition: newgrf.h:169
RailVehicleInfo::user_def_data
byte user_def_data
Property 0x25: "User-defined bit mask" Used only for (very few) NewGRF vehicles.
Definition: engine_type.h:61
AlterVehicleListOrder
void AlterVehicleListOrder(EngineID engine, uint target)
Record a vehicle ListOrderChange.
Definition: newgrf_engine.cpp:1296
CargoSpec::classes
uint16 classes
Classes of this cargo type.
Definition: cargotype.h:79
RoadVehicleChangeInfo
static ChangeInfoResult RoadVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader *buf)
Define properties for road vehicles.
Definition: newgrf.cpp:1356
AirportTileSpec::enabled
bool enabled
entity still available (by default true). newgrf can disable it, though
Definition: newgrf_airporttiles.h:71
IndustrySpec::cleanup_flag
uint8 cleanup_flag
flags indicating which data should be freed upon cleaning up
Definition: industrytype.h:139
IndustrySpec::appear_ingame
byte appear_ingame[NUM_LANDSCAPE]
Probability of appearance in game.
Definition: industrytype.h:133
IndustrySpec::grf_prop
GRFFileProps grf_prop
properties related to the grf file
Definition: industrytype.h:141
TRAMWAY_REPLACE_DEPOT_NO_TRACK
@ TRAMWAY_REPLACE_DEPOT_NO_TRACK
Electrified depot graphics without tram track were loaded.
Definition: newgrf.h:171
RoadTypeInfo::map_colour
byte map_colour
Colour on mini-map.
Definition: road.h:154
NewGRFSpriteLayout::consistent_max_offset
uint consistent_max_offset
Number of sprites in all referenced spritesets.
Definition: newgrf_commons.h:120
HouseSpec::watched_cargoes
CargoTypes watched_cargoes
Cargo types watched for acceptance.
Definition: house.h:123
NUM_CARGO
@ NUM_CARGO
Maximal number of cargo types in a game.
Definition: cargo_type.h:65
IsSnowLineSet
bool IsSnowLineSet()
Has a snow line table already been loaded.
Definition: landscape.cpp:621
RailTypeFlags
RailTypeFlags
Railtype flags.
Definition: rail.h:25
RailtypeInfo::label
RailTypeLabel label
Unique 32 bit rail type identifier.
Definition: rail.h:233
StationClassID
StationClassID
Definition: newgrf_station.h:83
GetCargoTranslation
CargoID GetCargoTranslation(uint8 cargo, const GRFFile *grffile, bool usebit)
Translate a GRF-local cargo slot/bitnum into a CargoID.
Definition: newgrf_cargo.cpp:79
IndustrySpec::prospecting_chance
uint32 prospecting_chance
Chance prospecting succeeds.
Definition: industrytype.h:111
ConstructionSettings::train_signal_side
byte train_signal_side
show signals on left / driving / right side
Definition: settings_type.h:345
HouseSpec::class_id
HouseClassID class_id
defines the class this house has (not grf file based)
Definition: house.h:119
GRFParameterInfo::name
GRFTextList name
The name of this parameter.
Definition: newgrf_config.h:137
GRFFile::cargo_map
uint8 cargo_map[NUM_CARGO]
Inverse cargo translation table (CargoID -> local ID)
Definition: newgrf.h:127
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:307
IndustryTileLayoutTile
Definition of one tile in an industry tile layout.
Definition: industrytype.h:96
RailtypeInfo::build_caption
StringID build_caption
Caption of the build vehicle GUI for this rail type.
Definition: rail.h:176
VehicleSettings::disable_elrails
bool disable_elrails
when true, the elrails are disabled
Definition: settings_type.h:491
InitNewGRFFile
static void InitNewGRFFile(const GRFConfig *config)
Prepare loading a NewGRF file with its config.
Definition: newgrf.cpp:8726
CommitVehicleListOrderChanges
void CommitVehicleListOrderChanges()
Deternine default engine sorting and execute recorded ListOrderChanges from AlterVehicleListOrder.
Definition: newgrf_engine.cpp:1326
ShipVehicleInfo
Information about a ship vehicle.
Definition: engine_type.h:66
HouseSpec::building_availability
HouseZones building_availability
where can it be built (climates, zones)
Definition: house.h:110
NewGRFClass::name
StringID name
Name of this class.
Definition: newgrf_class.h:39
RoadType
RoadType
The different roadtypes we support.
Definition: road_type.h:22
Subdirectory
Subdirectory
The different kinds of subdirectories OpenTTD uses.
Definition: fileio_type.h:108
IndustryProductionSpriteGroup::version
uint8 version
Production callback version used, or 0xFF if marked invalid.
Definition: newgrf_spritegroup.h:271
AirportSpec::GetWithoutOverride
static AirportSpec * GetWithoutOverride(byte type)
Retrieve airport spec for the given airport.
Definition: newgrf_airport.cpp:117
TileLayoutFlags
TileLayoutFlags
Flags to enable register usage in sprite layouts.
Definition: newgrf_commons.h:33
CargoSpec::name
StringID name
Name of this type of cargo.
Definition: cargotype.h:71
PROP_ROADVEH_CARGO_CAPACITY
@ PROP_ROADVEH_CARGO_CAPACITY
Capacity.
Definition: newgrf_properties.h:34
ResetNewGRFData
void ResetNewGRFData()
Reset all NewGRF loaded data.
Definition: newgrf.cpp:8594
AircraftVehicleChangeInfo
static ChangeInfoResult AircraftVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader *buf)
Define properties for aircraft.
Definition: newgrf.cpp:1722
GRFFile::cargo_list
std::vector< CargoLabel > cargo_list
Cargo translation table (local ID -> label)
Definition: newgrf.h:126
GameCreationSettings::starting_year
Year starting_year
starting date
Definition: settings_type.h:311
TE_MAIL
@ TE_MAIL
Cargo behaves mail-like.
Definition: cargotype.h:30
PalSpriteID
Combination of a palette sprite and a 'real' sprite.
Definition: gfx_type.h:22
GRFConfig::url
GRFTextWrapper url
NOSAVE: URL belonging to this GRF.
Definition: newgrf_config.h:168
VSG_SCOPE_RELATIVE
@ VSG_SCOPE_RELATIVE
Relative position (vehicles only)
Definition: newgrf_spritegroup.h:102
ActivateOldTramDepot
static void ActivateOldTramDepot()
Replocate the old tram depot sprites to the new position, if no new ones were loaded.
Definition: newgrf.cpp:9555
HZ_CLIMALL
@ HZ_CLIMALL
Bitmask of all climate bits.
Definition: house.h:84
RoadVehicleInfo::tractive_effort
uint8 tractive_effort
Coefficient of tractive effort.
Definition: engine_type.h:122
GrfProcessingState::stage
GrfLoadingStage stage
Current loading stage.
Definition: newgrf.cpp:99
ORIGINAL_SAMPLE_COUNT
static const uint ORIGINAL_SAMPLE_COUNT
The number of sounds in the original sample.cat.
Definition: sound_type.h:116
IndustrySpec::callback_mask
uint16 callback_mask
Bitmask of industry callbacks that have to be called.
Definition: industrytype.h:138
AnimationInfo::triggers
uint16 triggers
The triggers that trigger animation.
Definition: newgrf_animation_type.h:22
IgnoreObjectProperty
static ChangeInfoResult IgnoreObjectProperty(uint prop, ByteReader *buf)
Ignore properties for objects.
Definition: newgrf.cpp:4008
CHECK_NOTHING
@ CHECK_NOTHING
Always succeeds.
Definition: industrytype.h:40
AircraftVehicleInfo::mail_capacity
byte mail_capacity
Mail capacity (bags).
Definition: engine_type.h:106
CargoSpec::name_single
StringID name_single
Name of a single entity of this type of cargo.
Definition: cargotype.h:72
PTYPE_END
@ PTYPE_END
Invalid parameter type.
Definition: newgrf_config.h:130
IndustrySpec::random_sounds
const uint8 * random_sounds
array of random sounds.
Definition: industrytype.h:136
GrfProcessingState::GetNumEnts
uint GetNumEnts(byte feature, uint set) const
Returns the number of sprites in a spriteset.
Definition: newgrf.cpp:188
CargoSpec::abbrev
StringID abbrev
Two letter abbreviation for this cargo type.
Definition: cargotype.h:75
ReallocT
static T * ReallocT(T *t_ptr, size_t num_elements)
Simplified reallocation function that allocates the specified number of elements of the given type.
Definition: alloc_func.hpp:111
HouseSpec::processing_time
byte processing_time
Periodic refresh multiplier.
Definition: house.h:121
IndustrySpec::life_type
IndustryLifeType life_type
This is also known as Industry production flag, in newgrf specs.
Definition: industrytype.h:123
RoadVehicleInfo::weight
uint8 weight
Weight in 1/4t units.
Definition: engine_type.h:120
Action5Type::name
const char * name
Name for error messages.
Definition: newgrf.cpp:6147
SkipSpriteData
bool SkipSpriteData(SpriteFile &file, byte type, uint16 num)
Skip the given amount of sprite graphics data.
Definition: spritecache.cpp:126
abs
static T abs(const T a)
Returns the absolute value of (scalar) variable.
Definition: math_func.hpp:21
stredup
char * stredup(const char *s, const char *last)
Create a duplicate of the given string.
Definition: string.cpp:138
FinaliseHouseArray
static void FinaliseHouseArray()
Add all new houses to the house array.
Definition: newgrf.cpp:9121
GRFConfig::palette
uint8 palette
GRFPalette, bitset.
Definition: newgrf_config.h:179
CargoSpec::multiplier
uint16 multiplier
Capacity multiplier for vehicles. (8 fractional bits)
Definition: cargotype.h:63
IndustryTileSpec::callback_mask
uint8 callback_mask
Bitmask of industry tile callbacks that have to be called.
Definition: industrytype.h:168
_grm_cargoes
static uint32 _grm_cargoes[NUM_CARGO *2]
Contains the GRF ID of the owner of a cargo if it has been reserved.
Definition: newgrf.cpp:359
NewGRFSpriteLayout::Clone
void Clone(const DrawTileSeqStruct *source)
Clone the building sprites of a spritelayout.
Definition: newgrf_commons.cpp:586
error
void CDECL error(const char *s,...)
Error handling for fatal non-user errors.
Definition: openttd.cpp:134
StationSpec::cargo_threshold
uint16 cargo_threshold
Cargo threshold for choosing between little and lots of cargo.
Definition: newgrf_station.h:154
RandomAccessFile::SeekTo
void SeekTo(size_t pos, int mode)
Seek in the current file.
Definition: random_access_file.cpp:83
RailVehicleInfo::shorten_factor
byte shorten_factor
length on main map for this type is 8 - shorten_factor
Definition: engine_type.h:58
_grfconfig
GRFConfig * _grfconfig
First item in list of current GRF set up.
Definition: newgrf_config.cpp:171
RoadTypeInfo::cost_multiplier
uint16 cost_multiplier
Cost multiplier for building this road type.
Definition: road.h:129
SmallMap::Find
std::vector< Pair >::const_iterator Find(const T &key) const
Finds given key in this map.
Definition: smallmap_type.hpp:41
CurrencySpec::to_euro
Year to_euro
Year of switching to the Euro. May also be CF_NOEURO or CF_ISEURO.
Definition: currency.h:75
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:1002
GRFTempEngineData::NONEMPTY
@ NONEMPTY
GRF defined the vehicle as refittable. If the refitmask is empty after translation (cargotypes not av...
Definition: newgrf.cpp:322
AllowedSubtags::id
uint32 id
The identifier for this node.
Definition: newgrf.cpp:8128
IndustrySpec::behaviour
IndustryBehaviour behaviour
How this industry will behave, and how others entities can use it.
Definition: industrytype.h:125
Debug
#define Debug(name, level, format_string,...)
Ouptut a line of debugging information.
Definition: debug.h:37
AnimationInfo::status
uint8 status
Status; 0: no looping, 1: looping, 0xFF: no animation.
Definition: newgrf_animation_type.h:20
ResetObjects
void ResetObjects()
This function initialize the spec arrays of objects.
Definition: newgrf_object.cpp:94
SetBit
static T SetBit(T &x, const uint8 y)
Set a bit in a variable.
Definition: bitmath_func.hpp:121
TE_WATER
@ TE_WATER
Cargo behaves water-like.
Definition: cargotype.h:32
lengthof
#define lengthof(x)
Return the length of an fixed size array.
Definition: stdafx.h:386
HouseSpec::min_year
Year min_year
introduction year of the house
Definition: house.h:100
CurrencySpec::separator
std::string separator
The thousands separator for this currency.
Definition: currency.h:74
YearMonthDay
Data structure to convert between Date and triplet (year, month, and day).
Definition: date_type.h:104
StationSpec::grf_prop
GRFFilePropsBase< NUM_CARGO+3 > grf_prop
Properties related the the grf file.
Definition: newgrf_station.h:125
NewGRFClass::Get
static NewGRFClass * Get(Tid cls_id)
Get a particular class.
Definition: newgrf_class_func.h:103
RoadTypeInfo::max_speed
uint16 max_speed
Maximum speed for vehicles travelling on this road type.
Definition: road.h:139
InitializeGRFSpecial
static void InitializeGRFSpecial()
Initialize the TTDPatch flags.
Definition: newgrf.cpp:8366
DataHandler
bool(* DataHandler)(size_t, ByteReader *)
Type of callback function for binary nodes.
Definition: newgrf.cpp:8060
RandomizedSpriteGroup::lowest_randbit
byte lowest_randbit
Look for this in the per-object randomized bitmask:
Definition: newgrf_spritegroup.h:199
RailtypeInfo::new_loco
StringID new_loco
Name of an engine for this type of rail in the engine preview GUI.
Definition: rail.h:178
ActivateOldShore
static void ActivateOldShore()
Relocates the old shore sprites at new positions.
Definition: newgrf.cpp:9518
BridgeSpec::material
StringID material
the string that contains the bridge description
Definition: bridge.h:49
RoadVehicleInfo::power
uint8 power
Power in 10hp units.
Definition: engine_type.h:121
TileLayoutRegisters::flags
TileLayoutFlags flags
Flags defining which members are valid and to be used.
Definition: newgrf_commons.h:92
AirportSpec::depot_table
const HangarTileTable * depot_table
gives the position of the depots on the airports
Definition: newgrf_airport.h:103
SkipUnknownInfo
static bool SkipUnknownInfo(ByteReader *buf, byte type)
Try to skip the current node and all subnodes (if it's a branch node).
Definition: newgrf.cpp:8252
RailtypeInfo::compatible_railtypes
RailTypes compatible_railtypes
bitmask to the OTHER railtypes on which an engine of THIS railtype can physically travel
Definition: rail.h:188
CT_PURCHASE_OBJECT
static const CargoID CT_PURCHASE_OBJECT
Mapping of purchase for objects.
Definition: newgrf_object.h:161
newgrf_canal.h
TILE_HEIGHT
static const uint TILE_HEIGHT
Height of a height level in world coordinate AND in pixels in #ZOOM_LVL_BASE.
Definition: tile_type.h:18
IgnoreTownHouseProperty
static ChangeInfoResult IgnoreTownHouseProperty(int prop, ByteReader *buf)
Ignore a house property.
Definition: newgrf.cpp:2253
CargoID
byte CargoID
Cargo slots to indicate a cargo type within a game.
Definition: cargo_type.h:20
ROADTYPE_TRAM
@ ROADTYPE_TRAM
Trams.
Definition: road_type.h:25
MemSetT
static void MemSetT(T *ptr, byte value, size_t num=1)
Type-safe version of memset().
Definition: mem_func.hpp:49
VehicleSettings::never_expire_vehicles
bool never_expire_vehicles
never expire vehicles
Definition: settings_type.h:499
HouseSpec
Definition: house.h:98
config.h
GetNewgrfCurrencyIdConverted
byte GetNewgrfCurrencyIdConverted(byte grfcurr_id)
Will return the ottd's index correspondence to the ttdpatch's id.
Definition: currency.cpp:113
EF_RAIL_FLIPS
@ EF_RAIL_FLIPS
Rail vehicle can be flipped in the depot.
Definition: engine_type.h:158
GrfProcessingState::SpriteSet::num_sprites
uint num_sprites
Number of sprites in the set.
Definition: newgrf.cpp:91
NEW_AIRPORTTILE_OFFSET
static const uint NEW_AIRPORTTILE_OFFSET
offset of first newgrf airport tile
Definition: airport.h:24
RoadTypeFlags
RoadTypeFlags
Roadtype flags.
Definition: road.h:38
OverrideManagerBase::AddEntityID
virtual uint16 AddEntityID(byte grf_local_id, uint32 grfid, byte substitute_id)
Reserves a place in the mapping array for an entity to be installed.
Definition: newgrf_commons.cpp:123
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:998
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:277
BridgeChangeInfo
static ChangeInfoResult BridgeChangeInfo(uint brid, int numinfo, int prop, ByteReader *buf)
Define properties for bridges.
Definition: newgrf.cpp:2143
fontcache.h
_object_mngr
ObjectOverrideManager _object_mngr
The override manager for our objects.
HouseZones
HouseZones
Definition: house.h:71
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:2611
VehicleSettings::plane_speed
uint8 plane_speed
divisor for speed of aircraft
Definition: settings_type.h:496
RailtypeInfo::maintenance_multiplier
uint16 maintenance_multiplier
Cost multiplier for maintenance of this rail type.
Definition: rail.h:218
RailTypeChangeInfo
static ChangeInfoResult RailTypeChangeInfo(uint id, int numinfo, int prop, ByteReader *buf)
Define properties for railtypes.
Definition: newgrf.cpp:4190
Engine::grf_prop
GRFFilePropsBase< NUM_CARGO+2 > grf_prop
Properties related the the grf file.
Definition: engine_base.h:64
RAILVEH_SINGLEHEAD
@ RAILVEH_SINGLEHEAD
indicates a "standalone" locomotive
Definition: engine_type.h:27
IndustryTileSpecialFlags
IndustryTileSpecialFlags
Flags for miscellaneous industry tile specialities.
Definition: industrytype.h:88
IndustrySpec::check_proc
byte check_proc
Index to a procedure to check for conflicting circumstances.
Definition: industrytype.h:113
ReadGRFSpriteOffsets
void ReadGRFSpriteOffsets(SpriteFile &file)
Parse the sprite section of GRFs.
Definition: spritecache.cpp:555
ShipVehicleInfo::max_speed
uint16 max_speed
Maximum speed (1 unit = 1/3.2 mph = 0.5 km-ish/h)
Definition: engine_type.h:69
GRFTempEngineData::prop27_set
bool prop27_set
Did the NewGRF set property 27 (misc flags)?
Definition: newgrf.cpp:331
RailVehicleInfo::running_cost
byte running_cost
Running cost of engine; For multiheaded engines the sum of both running costs.
Definition: engine_type.h:50
EF_ROAD_TRAM
@ EF_ROAD_TRAM
Road vehicle is a tram/light rail vehicle.
Definition: engine_type.h:155
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
GRFFilePropsBase::local_id
uint16 local_id
id defined by the grf file for this entity
Definition: newgrf_commons.h:319
newgrf_industries.h
PalSpriteID::pal
PaletteID pal
The palette (use PAL_NONE) if not needed)
Definition: gfx_type.h:24
EconomySettings::inflation
bool inflation
disable inflation
Definition: settings_type.h:507
FinaliseCargoArray
static void FinaliseCargoArray()
Check for invalid cargoes.
Definition: newgrf.cpp:9025
GameSettings::construction
ConstructionSettings construction
construction of things in-game
Definition: settings_type.h:585
GrfProcessingState::IsValidSpriteSet
bool IsValidSpriteSet(byte feature, uint set) const
Check whether a specific set is defined.
Definition: newgrf.cpp:164
GameSettings::vehicle
VehicleSettings vehicle
options for vehicles
Definition: settings_type.h:592
FontSize
FontSize
Available font sizes.
Definition: gfx_type.h:206
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:65
TLF_SPRITE
@ TLF_SPRITE
Add signed offset to sprite from register TileLayoutRegisters::sprite.
Definition: newgrf_commons.h:37
ClearTemporaryNewGRFData
static void ClearTemporaryNewGRFData(GRFFile *gf)
Reset all NewGRFData that was used only while processing data.
Definition: newgrf.cpp:431
EngineInfo::climates
byte climates
Climates supported by the engine.
Definition: engine_type.h:139
TLF_PALETTE
@ TLF_PALETTE
Add signed offset to palette from register TileLayoutRegisters::palette.
Definition: newgrf_commons.h:38
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:128
AirportSpec::nof_depots
byte nof_depots
the number of hangar tiles in this airport
Definition: newgrf_airport.h:104
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:683
ResetRoadTypes
void ResetRoadTypes()
Reset all road type information to its default values.
Definition: road_cmd.cpp:64
GRFPalette
GRFPalette
Information that can/has to be stored about a GRF's palette.
Definition: newgrf_config.h:59
StationSpec::callback_mask
byte callback_mask
Bitmask of station callbacks that have to be called.
Definition: newgrf_station.h:158
PROP_ROADVEH_POWER
@ PROP_ROADVEH_POWER
Power in 10 HP.
Definition: newgrf_properties.h:36
TE_FOOD
@ TE_FOOD
Cargo behaves food/fizzy-drinks-like.
Definition: cargotype.h:33
VEH_TRAIN
@ VEH_TRAIN
Train vehicle type.
Definition: vehicle_type.h:24
RandomizedSpriteGroup
Definition: newgrf_spritegroup.h:190
RailtypeInfo::group
const SpriteGroup * group[RTSG_END]
Sprite groups for resolving sprites.
Definition: rail.h:278
IndustrySpec::name
StringID name
Displayed name of the industry.
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:8048
IndustryBehaviour
IndustryBehaviour
Various industry behaviours mostly to represent original TTD specialities.
Definition: industrytype.h:61
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:128
StationSpec::disallowed_lengths
byte disallowed_lengths
Bitmask of platform lengths available for the station.
Definition: newgrf_station.h:138
_misc_grf_features
byte _misc_grf_features
Miscellaneous GRF features, set by Action 0x0D, parameter 0x9E.
Definition: newgrf.cpp:75
RailtypeInfo::strings
struct RailtypeInfo::@39 strings
Strings associated with the rail type.
RailVehicleInfo::capacity
byte capacity
Cargo capacity of vehicle; For multiheaded engines the capacity of each single engine.
Definition: engine_type.h:53
IndustryProductionSpriteGroup::cargo_input
CargoID cargo_input[INDUSTRY_NUM_INPUTS]
Which input cargoes to take from (only cb version 2)
Definition: newgrf_spritegroup.h:274
DefineGotoLabel
static void DefineGotoLabel(ByteReader *buf)
Action 0x10 - Define goto label.
Definition: newgrf.cpp:7565
ByteReader
Class to read from a NewGRF file.
Definition: newgrf.cpp:213
LoadGRFSound
static void LoadGRFSound(size_t offs, SoundEntry *sound)
Load a sound from a file.
Definition: newgrf.cpp:7628
AllowedSubtags::AllowedSubtags
AllowedSubtags(uint32 id, BranchHandler handler)
Create a branch node with a callback handler.
Definition: newgrf.cpp:8107
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:500
GRFFilePropsBase::grffile
const struct GRFFile * grffile
grf file that introduced this entity
Definition: newgrf_commons.h:320
PROP_AIRCRAFT_SPEED
@ PROP_AIRCRAFT_SPEED
Max. speed: 1 unit = 8 mph = 12.8 km-ish/h.
Definition: newgrf_properties.h:50
AirportTileSpec::name
StringID name
Tile Subname string, land information on this tile will give you "AirportName (TileSubname)".
Definition: newgrf_airporttiles.h:68
CanalProperties
Canal properties local to the NewGRF.
Definition: newgrf.h:39
ResetBridges
void ResetBridges()
Reset the data been eventually changed by the grf loaded.
Definition: tunnelbridge_cmd.cpp:85
RailtypeInfo::cost_multiplier
uint16 cost_multiplier
Cost multiplier for building this rail type.
Definition: rail.h:213
DateFract
uint16 DateFract
The fraction of a date we're in, i.e. the number of ticks since the last date changeover.
Definition: date_type.h:15
AllowedSubtags::data
DataHandler data
Callback function for a binary node, only valid if type == 'B'.
Definition: newgrf.cpp:8131
OBJECT_SIZE_1X1
static const uint8 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
AirportTileTable::ti
TileIndexDiffC ti
Tile offset from the top-most airport tile.
Definition: newgrf_airport.h:24
GRFConfig::filename
char * filename
Filename - either with or without full path.
Definition: newgrf_config.h:165
EngineInfo::string_id
StringID string_id
Default name of engine.
Definition: engine_type.h:146
AircraftVehicleInfo
Information about a aircraft vehicle.
Definition: engine_type.h:98
GetLanguage
const LanguageMetadata * GetLanguage(byte newgrflangid)
Get the language with the given NewGRF language ID.
Definition: strings.cpp:1911
ObjectSpec::climate
uint8 climate
In which climates is this object available?
Definition: newgrf_object.h:66
free
static void free(const void *ptr)
Version of the standard free that accepts const pointers.
Definition: stdafx.h:470
AirportSpec::table
const AirportTileTable *const * table
list of the tiles composing the airport
Definition: newgrf_airport.h:100
HangarTileTable
A list of all hangar tiles in an airport.
Definition: newgrf_airport.h:89
CT_INVALID
@ CT_INVALID
Invalid cargo type.
Definition: cargo_type.h:69
_tick_counter
uint64 _tick_counter
Ever incrementing tick counter for setting off various events.
Definition: date.cpp:30
MapGRFStringID
StringID MapGRFStringID(uint32 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:564
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:36
TownHouseChangeInfo
static ChangeInfoResult TownHouseChangeInfo(uint hid, int numinfo, int prop, ByteReader *buf)
Define properties for houses.
Definition: newgrf.cpp:2320
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:260
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:75
VEH_SHIP
@ VEH_SHIP
Ship vehicle type.
Definition: vehicle_type.h:26
VehicleSettings::freight_trains
uint8 freight_trains
value to multiply the weight of cargo by
Definition: settings_type.h:497
ChangeGRFPalette
static bool ChangeGRFPalette(size_t len, ByteReader *buf)
Callback function for 'INFO'->'PALS' to set the number of valid parameters.
Definition: newgrf.cpp:7891
LoadFontGlyph
static void LoadFontGlyph(ByteReader *buf)
Action 0x12.
Definition: newgrf.cpp:7748
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
IndustryTileSpec::anim_next
byte anim_next
Next frame in an animation.
Definition: industrytype.h:161
IndustryTileSpec
Defines the data structure of each individual tile of an industry.
Definition: industrytype.h:156
GRFLoadedFeatures
Definition: newgrf.h:174
TLF_DRAWING_FLAGS
@ TLF_DRAWING_FLAGS
Flags which are still required after loading the GRF.
Definition: newgrf_commons.h:53
TLF_PALETTE_VAR10
@ TLF_PALETTE_VAR10
Resolve palette with a specific value in variable 10.
Definition: newgrf_commons.h:48
InitRailTypes
void InitRailTypes()
Resolve sprites of custom rail types.
Definition: rail_cmd.cpp:139
CurrencySpec::prefix
std::string prefix
Prefix to apply when formatting money in this currency.
Definition: currency.h:76
CC_MAIL
@ CC_MAIL
Mail.
Definition: cargotype.h:42
HouseSpec::remove_rating_decrease
uint16 remove_rating_decrease
rating decrease if removed
Definition: house.h:105
DisableGrf
static GRFError * DisableGrf(StringID message=STR_NULL, GRFConfig *config=nullptr)
Disable a GRF.
Definition: newgrf.cpp:448
AirportTileSpec::grf_prop
GRFFileProps grf_prop
properties related the the grf file
Definition: newgrf_airporttiles.h:72
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:62
InitRoadTypes
void InitRoadTypes()
Resolve sprites of custom road types.
Definition: road_cmd.cpp:120
RoadTypeInfo::build_caption
StringID build_caption
Caption of the build vehicle GUI for this rail type.
Definition: road.h:103
GetFileByFilename
static GRFFile * GetFileByFilename(const char *filename)
Obtain a NewGRF file by its filename.
Definition: newgrf.cpp:422
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:109
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:96
ResetCustomStations
static void ResetCustomStations()
Reset and clear all NewGRF stations.
Definition: newgrf.cpp:8454
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:73
TLF_SPRITE_VAR10
@ TLF_SPRITE_VAR10
Resolve sprite with a specific value in variable 10.
Definition: newgrf_commons.h:47
lastof
#define lastof(x)
Get the last element of an fixed size array.
Definition: stdafx.h:402
PROP_AIRCRAFT_RANGE
@ PROP_AIRCRAFT_RANGE
Aircraft range.
Definition: newgrf_properties.h:55
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:525
MAX_NUM_CASES
static const uint8 MAX_NUM_CASES
Maximum number of supported cases.
Definition: language.h:21
_ttdpatch_flags
static uint32 _ttdpatch_flags[8]
32 * 8 = 256 flags.
Definition: newgrf.cpp:78
BuildLinkStatsLegend
void BuildLinkStatsLegend()
Populate legend table for the link stat view.
Definition: smallmap_gui.cpp:199
ChangeGRFParamDescription
static bool ChangeGRFParamDescription(byte langid, const char *str)
Callback function for 'INFO'->'PARAM'->param_num->'DESC' to set the description of a parameter.
Definition: newgrf.cpp:7981
EngineInfo::cargo_age_period
uint16 cargo_age_period
Number of ticks before carried cargo is aged.
Definition: engine_type.h:147
GrfProcessingState::nfo_line
uint32 nfo_line
Currently processed pseudo sprite number in the GRF.
Definition: newgrf.cpp:106
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:169
ReadSpriteLayout
static bool ReadSpriteLayout(ByteReader *buf, uint num_building_sprites, bool use_cur_spritesets, byte feature, bool allow_var10, bool no_z_position, NewGRFSpriteLayout *dts)
Read a spritelayout from the GRF.
Definition: newgrf.cpp:866
GetCargoIDByLabel
CargoID GetCargoIDByLabel(CargoLabel cl)
Get the cargo ID by cargo label.
Definition: cargotype.cpp:108
newgrf_cargo.h
SetYearEngineAgingStops
void SetYearEngineAgingStops()
Compute the value for _year_engine_aging_stops.
Definition: engine.cpp:604
RailtypeInfo::curve_speed
byte curve_speed
Multiplier for curve maximum speed advantage.
Definition: rail.h:203
MapLogY
static uint MapLogY()
Logarithm of the map size along the y side.
Definition: map_func.h:62
GRFFile::railtype_list
std::vector< RailTypeLabel > railtype_list
Railtype translation table.
Definition: newgrf.h:129
AirportSpec::catchment
byte catchment
catchment area of this airport
Definition: newgrf_airport.h:108
RandomizedSpriteGroup::groups
std::vector< const SpriteGroup * > groups
Take the group with appropriate index:
Definition: newgrf_spritegroup.h:201
ReadSpriteLayoutSprite
static TileLayoutFlags ReadSpriteLayoutSprite(ByteReader *buf, bool read_flags, bool invert_action1_flag, bool use_cur_spritesets, int feature, PalSpriteID *grf_sprite, uint16 *max_sprite_offset=nullptr, uint16 *max_palette_offset=nullptr)
Read a sprite and a palette from the GRF and convert them into a format suitable to OpenTTD.
Definition: newgrf.cpp:755
StationSpec::cargo_triggers
CargoTypes cargo_triggers
Bitmask of cargo types which cause trigger re-randomizing.
Definition: newgrf_station.h:156
SpriteGroup
Definition: newgrf_spritegroup.h:57
GRFLabel
Definition: newgrf.h:97
SkipAct12
static void SkipAct12(ByteReader *buf)
Action 0x12 (SKIP)
Definition: newgrf.cpp:7779
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:114
AddStringForMapping
static void AddStringForMapping(StringID source, StringID *target)
Record a static StringID for getting translated later.
Definition: newgrf.cpp:487
GetGRFConfig
GRFConfig * GetGRFConfig(uint32 grfid, uint32 mask)
Retrieve a NewGRF from the current config by its grfid.
Definition: newgrf_config.cpp:771
ResetGenericCallbacks
void ResetGenericCallbacks()
Reset all generic feature callback sprite groups.
Definition: newgrf_generic.cpp:95
Action5Type
Information about a single action 5 type.
Definition: newgrf.cpp:6142
_currency_specs
CurrencySpec _currency_specs[CURRENCY_END]
Array of currencies used by the system.
Definition: currency.cpp:74
NamePart::id
byte id
If probability bit 7 is set.
Definition: newgrf_townname.h:23
LanguageMap::Mapping::newgrf_id
byte newgrf_id
NewGRF's internal ID for a case/gender.
Definition: newgrf_text.h:61
RailVehicleInfo::curve_speed_mod
int16 curve_speed_mod
Modifier to maximum speed in curves (fixed-point binary with 8 fractional bits)
Definition: engine_type.h:62
StationSpec::wires
byte wires
Bitmask of base tiles (0 - 7) which should contain elrail wires.
Definition: newgrf_station.h:163
AddGRFTextToList
static void AddGRFTextToList(GRFTextList &list, byte langid, const std::string &text_to_add)
Add a new text to a GRFText list.
Definition: newgrf_text.cpp:493
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:70
OrderSettings::gradual_loading
bool gradual_loading
load vehicles gradually
Definition: settings_type.h:476
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:624
Action5Type::max_sprites
uint16 max_sprites
If the Action5 contains more sprites, only the first max_sprites sprites will be used.
Definition: newgrf.cpp:6146
GRFConfig::param_info
std::vector< GRFParameterInfo * > param_info
NOSAVE: extra information about the parameters.
Definition: newgrf_config.h:180
IndustryLifeType
IndustryLifeType
Available types of industry lifetimes.
Definition: industrytype.h:28
GRFFile
Dynamic data of a loaded NewGRF.
Definition: newgrf.h:105
ObjectSpec::cls_id
ObjectClassID cls_id
The class to which this spec belongs.
Definition: newgrf_object.h:63
PROP_TRAIN_USER_DATA
@ PROP_TRAIN_USER_DATA
User defined data for vehicle variable 0x42.
Definition: newgrf_properties.h:29
ShipVehicleInfo::ocean_speed_frac
byte ocean_speed_frac
Fraction of maximum speed for ocean tiles.
Definition: engine_type.h:75
Engine::type
VehicleType type
Vehicle type, ie VEH_ROAD, VEH_TRAIN, etc.
Definition: engine_base.h:46
TE_PASSENGERS
@ TE_PASSENGERS
Cargo behaves passenger-like.
Definition: cargotype.h:29
IgnoreIndustryTileProperty
static ChangeInfoResult IgnoreIndustryTileProperty(int prop, ByteReader *buf)
Ignore an industry tile property.
Definition: newgrf.cpp:3119
StationSpec::blocked
byte blocked
Bitmask of base tiles (0 - 7) which are blocked to trains.
Definition: newgrf_station.h:164
debug.h
GRFConfig::param
uint32 param[0x80]
GRF parameters.
Definition: newgrf_config.h:176
DAYS_TILL_ORIGINAL_BASE_YEAR
#define DAYS_TILL_ORIGINAL_BASE_YEAR
The offset in days from the '_date == 0' till 'ConvertYMDToDate(ORIGINAL_BASE_YEAR,...
Definition: date_type.h:81
GRFParameterInfo::min_value
uint32 min_value
The minimal value this parameter can have.
Definition: newgrf_config.h:140
TileLayoutSpriteGroup
Action 2 sprite layout for houses, industry tiles, objects and airport tiles.
Definition: newgrf_spritegroup.h:259
GRFConfig::GetName
const char * GetName() const
Get the name of this grf.
Definition: newgrf_config.cpp:105
RoadTypeInfo::maintenance_multiplier
uint16 maintenance_multiplier
Cost multiplier for maintenance of this road type.
Definition: road.h:134
PROP_ROADVEH_WEIGHT
@ PROP_ROADVEH_WEIGHT
Weight in 1/4 t.
Definition: newgrf_properties.h:37
TileLayoutRegisters::max_sprite_offset
uint16 max_sprite_offset
Maximum offset to add to the sprite. (limited by size of the spriteset)
Definition: newgrf_commons.h:96
SPR_TRAMWAY_BASE
static const SpriteID SPR_TRAMWAY_BASE
Tramway sprites.
Definition: sprites.h:272
engine_func.h
AirportTileSpec::animation
AnimationInfo animation
Information about the animation.
Definition: newgrf_airporttiles.h:67
RoadTypeInfo::strings
struct RoadTypeInfo::@42 strings
Strings associated with the rail type.
EC_MONORAIL
@ EC_MONORAIL
Mono rail engine.
Definition: engine_type.h:37
WaterFeature::group
const SpriteGroup * group
Sprite group to start resolving.
Definition: newgrf_canal.h:23
INVALID_RAILTYPE
@ INVALID_RAILTYPE
Flag for invalid railtype.
Definition: rail_type.h:34
DrawTileSeqStruct
A tile child sprite and palette to draw for stations etc, with 3D bounding box.
Definition: sprite.h:25
ObjectSpec::flags
ObjectFlags flags
Flags/settings related to the object.
Definition: newgrf_object.h:72
RoadTypeChangeInfo
static ChangeInfoResult RoadTypeChangeInfo(uint id, int numinfo, int prop, ByteReader *buf, RoadTramType rtt)
Define properties for roadtypes.
Definition: newgrf.cpp:4408
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:176
RailtypeInfo::introduces_railtypes
RailTypes introduces_railtypes
Bitmask of which other railtypes are introduced when this railtype is introduced.
Definition: rail.h:263
MAX_YEAR
static const Year MAX_YEAR
MAX_YEAR, nicely rounded value of the number of years that can be encoded in a single 32 bits date,...
Definition: date_type.h:95
AllocaM
#define AllocaM(T, num_elements)
alloca() has to be called in the parent function, so define AllocaM() as a macro
Definition: alloc_func.hpp:132
SNOW_LINE_MONTHS
static const uint SNOW_LINE_MONTHS
Number of months in the snow line table.
Definition: landscape.h:16
CanalFeature
CanalFeature
List of different canal 'features'.
Definition: newgrf.h:25
TileIndexDiffC::x
int16 x
The x value of the coordinate.
Definition: map_type.h:58
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:813
GRFP_BLT_MASK
@ GRFP_BLT_MASK
Bitmask to only get the blitter information.
Definition: newgrf_config.h:78