OpenTTD
newgrf.cpp
Go to the documentation of this file.
1 /* $Id$ */
2 
3 /*
4  * This file is part of OpenTTD.
5  * 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.
6  * 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.
7  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8  */
9 
12 #include "stdafx.h"
13 
14 #include <stdarg.h>
15 #include <algorithm>
16 
17 #include "debug.h"
18 #include "fileio_func.h"
19 #include "engine_func.h"
20 #include "engine_base.h"
21 #include "bridge.h"
22 #include "town.h"
23 #include "newgrf_engine.h"
24 #include "newgrf_text.h"
25 #include "fontcache.h"
26 #include "currency.h"
27 #include "landscape.h"
28 #include "newgrf_cargo.h"
29 #include "newgrf_house.h"
30 #include "newgrf_sound.h"
31 #include "newgrf_station.h"
32 #include "industrytype.h"
33 #include "newgrf_canal.h"
34 #include "newgrf_townname.h"
35 #include "newgrf_industries.h"
36 #include "newgrf_airporttiles.h"
37 #include "newgrf_airport.h"
38 #include "newgrf_object.h"
39 #include "rev.h"
40 #include "fios.h"
41 #include "strings_func.h"
42 #include "date_func.h"
43 #include "string_func.h"
44 #include "network/network.h"
45 #include <map>
46 #include "smallmap_gui.h"
47 #include "genworld.h"
48 #include "error.h"
49 #include "vehicle_func.h"
50 #include "language.h"
51 #include "vehicle_base.h"
52 
53 #include "table/strings.h"
54 #include "table/build_industry.h"
55 
56 #include "safeguards.h"
57 
58 /* TTDPatch extended GRF format codec
59  * (c) Petr Baudis 2004 (GPL'd)
60  * Changes by Florian octo Forster are (c) by the OpenTTD development team.
61  *
62  * Contains portions of documentation by TTDPatch team.
63  * Thanks especially to Josef Drexler for the documentation as well as a lot
64  * of help at #tycoon. Also thanks to Michael Blunck for his GRF files which
65  * served as subject to the initial testing of this codec. */
66 
69 
72 
74 static uint32 _ttdpatch_flags[8];
75 
78 
79 static const uint MAX_SPRITEGROUP = UINT8_MAX;
80 
83 private:
85  struct SpriteSet {
87  uint num_sprites;
88  };
89 
91  std::map<uint, SpriteSet> spritesets[GSF_END];
92 
93 public:
94  /* Global state */
95  GrfLoadingStage stage;
97 
98  /* Local state in the file */
99  uint file_index;
102  uint32 nfo_line;
104 
105  /* Kind of return values when processing certain actions */
107 
108  /* Currently referenceable spritegroups */
109  SpriteGroup *spritegroups[MAX_SPRITEGROUP + 1];
110 
113  {
114  this->nfo_line = 0;
115  this->skip_sprites = 0;
116 
117  for (uint i = 0; i < GSF_END; i++) {
118  this->spritesets[i].clear();
119  }
120 
121  memset(this->spritegroups, 0, sizeof(this->spritegroups));
122  }
123 
132  void AddSpriteSets(byte feature, SpriteID first_sprite, uint first_set, uint numsets, uint numents)
133  {
134  assert(feature < GSF_END);
135  for (uint i = 0; i < numsets; i++) {
136  SpriteSet &set = this->spritesets[feature][first_set + i];
137  set.sprite = first_sprite + i * numents;
138  set.num_sprites = numents;
139  }
140  }
141 
148  bool HasValidSpriteSets(byte feature) const
149  {
150  assert(feature < GSF_END);
151  return !this->spritesets[feature].empty();
152  }
153 
161  bool IsValidSpriteSet(byte feature, uint set) const
162  {
163  assert(feature < GSF_END);
164  return this->spritesets[feature].find(set) != this->spritesets[feature].end();
165  }
166 
173  SpriteID GetSprite(byte feature, uint set) const
174  {
175  assert(IsValidSpriteSet(feature, set));
176  return this->spritesets[feature].find(set)->second.sprite;
177  }
178 
185  uint GetNumEnts(byte feature, uint set) const
186  {
187  assert(IsValidSpriteSet(feature, set));
188  return this->spritesets[feature].find(set)->second.num_sprites;
189  }
190 };
191 
192 static GrfProcessingState _cur;
193 
194 
201 template <VehicleType T>
202 static inline bool IsValidNewGRFImageIndex(uint8 image_index)
203 {
204  return image_index == 0xFD || IsValidImageIndex<T>(image_index);
205 }
206 
208 
210 class ByteReader {
211 protected:
212  byte *data;
213  byte *end;
214 
215 public:
216  ByteReader(byte *data, byte *end) : data(data), end(end) { }
217 
218  inline byte ReadByte()
219  {
220  if (data < end) return *(data)++;
221  throw OTTDByteReaderSignal();
222  }
223 
224  uint16 ReadWord()
225  {
226  uint16 val = ReadByte();
227  return val | (ReadByte() << 8);
228  }
229 
230  uint16 ReadExtendedByte()
231  {
232  uint16 val = ReadByte();
233  return val == 0xFF ? ReadWord() : val;
234  }
235 
236  uint32 ReadDWord()
237  {
238  uint32 val = ReadWord();
239  return val | (ReadWord() << 16);
240  }
241 
242  uint32 ReadVarSize(byte size)
243  {
244  switch (size) {
245  case 1: return ReadByte();
246  case 2: return ReadWord();
247  case 4: return ReadDWord();
248  default:
249  NOT_REACHED();
250  return 0;
251  }
252  }
253 
254  const char *ReadString()
255  {
256  char *string = reinterpret_cast<char *>(data);
257  size_t string_length = ttd_strnlen(string, Remaining());
258 
259  if (string_length == Remaining()) {
260  /* String was not NUL terminated, so make sure it is now. */
261  string[string_length - 1] = '\0';
262  grfmsg(7, "String was not terminated with a zero byte.");
263  } else {
264  /* Increase the string length to include the NUL byte. */
265  string_length++;
266  }
267  Skip(string_length);
268 
269  return string;
270  }
271 
272  inline size_t Remaining() const
273  {
274  return end - data;
275  }
276 
277  inline bool HasData(size_t count = 1) const
278  {
279  return data + count <= end;
280  }
281 
282  inline byte *Data()
283  {
284  return data;
285  }
286 
287  inline void Skip(size_t len)
288  {
289  data += len;
290  /* It is valid to move the buffer to exactly the end of the data,
291  * as there may not be any more data read. */
292  if (data > end) throw OTTDByteReaderSignal();
293  }
294 };
295 
296 typedef void (*SpecialSpriteHandler)(ByteReader *buf);
297 
298 static const uint NUM_STATIONS_PER_GRF = 255;
299 
304  UNSET = 0,
307  };
308 
309  uint16 cargo_allowed;
310  uint16 cargo_disallowed;
311  RailTypeLabel railtypelabel;
314  bool prop27_set;
315  uint8 rv_max_speed;
316  CargoTypes ctt_include_mask;
317  CargoTypes ctt_exclude_mask;
318 
323  void UpdateRefittability(bool non_empty)
324  {
325  if (non_empty) {
326  this->refittability = NONEMPTY;
327  } else if (this->refittability == UNSET) {
328  this->refittability = EMPTY;
329  }
330  }
331 };
332 
334 
339 static uint32 _grm_engines[256];
340 
342 static uint32 _grm_cargoes[NUM_CARGO * 2];
343 
344 struct GRFLocation {
345  uint32 grfid;
346  uint32 nfoline;
347 
348  GRFLocation(uint32 grfid, uint32 nfoline) : grfid(grfid), nfoline(nfoline) { }
349 
350  bool operator<(const GRFLocation &other) const
351  {
352  return this->grfid < other.grfid || (this->grfid == other.grfid && this->nfoline < other.nfoline);
353  }
354 
355  bool operator == (const GRFLocation &other) const
356  {
357  return this->grfid == other.grfid && this->nfoline == other.nfoline;
358  }
359 };
360 
361 static std::map<GRFLocation, SpriteID> _grm_sprites;
362 typedef std::map<GRFLocation, byte*> GRFLineToSpriteOverride;
363 static GRFLineToSpriteOverride _grf_line_to_action6_sprite_override;
364 
375 void CDECL grfmsg(int severity, const char *str, ...)
376 {
377  char buf[1024];
378  va_list va;
379 
380  va_start(va, str);
381  vseprintf(buf, lastof(buf), str, va);
382  va_end(va);
383 
384  DEBUG(grf, severity, "[%s:%d] %s", _cur.grfconfig->filename, _cur.nfo_line, buf);
385 }
386 
392 static GRFFile *GetFileByGRFID(uint32 grfid)
393 {
394  const GRFFile * const *end = _grf_files.End();
395  for (GRFFile * const *file = _grf_files.Begin(); file != end; file++) {
396  if ((*file)->grfid == grfid) return *file;
397  }
398  return NULL;
399 }
400 
406 static GRFFile *GetFileByFilename(const char *filename)
407 {
408  const GRFFile * const *end = _grf_files.End();
409  for (GRFFile * const *file = _grf_files.Begin(); file != end; file++) {
410  if (strcmp((*file)->filename, filename) == 0) return *file;
411  }
412  return NULL;
413 }
414 
417 {
418  /* Clear the GOTO labels used for GRF processing */
419  for (GRFLabel *l = gf->label; l != NULL;) {
420  GRFLabel *l2 = l->next;
421  free(l);
422  l = l2;
423  }
424  gf->label = NULL;
425 }
426 
433 static GRFError *DisableGrf(StringID message = STR_NULL, GRFConfig *config = NULL)
434 {
435  GRFFile *file;
436  if (config != NULL) {
437  file = GetFileByGRFID(config->ident.grfid);
438  } else {
439  config = _cur.grfconfig;
440  file = _cur.grffile;
441  }
442 
443  config->status = GCS_DISABLED;
444  if (file != NULL) ClearTemporaryNewGRFData(file);
445  if (config == _cur.grfconfig) _cur.skip_sprites = -1;
446 
447  if (message != STR_NULL) {
448  delete config->error;
449  config->error = new GRFError(STR_NEWGRF_ERROR_MSG_FATAL, message);
450  if (config == _cur.grfconfig) config->error->param_value[0] = _cur.nfo_line;
451  }
452 
453  return config->error;
454 }
455 
460  uint32 grfid;
463 };
465 static StringIDMappingVector _string_to_grf_mapping;
466 
472 static void AddStringForMapping(StringID source, StringID *target)
473 {
474  *target = STR_UNDEFINED;
475  StringIDMapping *item = _string_to_grf_mapping.Append();
476  item->grfid = _cur.grffile->grfid;
477  item->source = source;
478  item->target = target;
479 }
480 
489 {
490  /* StringID table for TextIDs 0x4E->0x6D */
491  static const StringID units_volume[] = {
492  STR_ITEMS, STR_PASSENGERS, STR_TONS, STR_BAGS,
493  STR_LITERS, STR_ITEMS, STR_CRATES, STR_TONS,
494  STR_TONS, STR_TONS, STR_TONS, STR_BAGS,
495  STR_TONS, STR_TONS, STR_TONS, STR_BAGS,
496  STR_TONS, STR_TONS, STR_BAGS, STR_LITERS,
497  STR_TONS, STR_LITERS, STR_TONS, STR_ITEMS,
498  STR_BAGS, STR_LITERS, STR_TONS, STR_ITEMS,
499  STR_TONS, STR_ITEMS, STR_LITERS, STR_ITEMS
500  };
501 
502  /* A string straight from a NewGRF; this was already translated by MapGRFStringID(). */
503  assert(!IsInsideMM(str, 0xD000, 0xD7FF));
504 
505 #define TEXTID_TO_STRINGID(begin, end, stringid, stringend) \
506  assert_compile(stringend - stringid == end - begin); \
507  if (str >= begin && str <= end) return str + (stringid - begin)
508 
509  /* We have some changes in our cargo strings, resulting in some missing. */
510  TEXTID_TO_STRINGID(0x000E, 0x002D, STR_CARGO_PLURAL_NOTHING, STR_CARGO_PLURAL_FIZZY_DRINKS);
511  TEXTID_TO_STRINGID(0x002E, 0x004D, STR_CARGO_SINGULAR_NOTHING, STR_CARGO_SINGULAR_FIZZY_DRINK);
512  if (str >= 0x004E && str <= 0x006D) return units_volume[str - 0x004E];
513  TEXTID_TO_STRINGID(0x006E, 0x008D, STR_QUANTITY_NOTHING, STR_QUANTITY_FIZZY_DRINKS);
514  TEXTID_TO_STRINGID(0x008E, 0x00AD, STR_ABBREV_NOTHING, STR_ABBREV_FIZZY_DRINKS);
515  TEXTID_TO_STRINGID(0x00D1, 0x00E0, STR_COLOUR_DARK_BLUE, STR_COLOUR_WHITE);
516 
517  /* Map building names according to our lang file changes. There are several
518  * ranges of house ids, all of which need to be remapped to allow newgrfs
519  * to use original house names. */
520  TEXTID_TO_STRINGID(0x200F, 0x201F, STR_TOWN_BUILDING_NAME_TALL_OFFICE_BLOCK_1, STR_TOWN_BUILDING_NAME_OLD_HOUSES_1);
521  TEXTID_TO_STRINGID(0x2036, 0x2041, STR_TOWN_BUILDING_NAME_COTTAGES_1, STR_TOWN_BUILDING_NAME_SHOPPING_MALL_1);
522  TEXTID_TO_STRINGID(0x2059, 0x205C, STR_TOWN_BUILDING_NAME_IGLOO_1, STR_TOWN_BUILDING_NAME_PIGGY_BANK_1);
523 
524  /* Same thing for industries */
525  TEXTID_TO_STRINGID(0x4802, 0x4826, STR_INDUSTRY_NAME_COAL_MINE, STR_INDUSTRY_NAME_SUGAR_MINE);
526  TEXTID_TO_STRINGID(0x482D, 0x482E, STR_NEWS_INDUSTRY_CONSTRUCTION, STR_NEWS_INDUSTRY_PLANTED);
527  TEXTID_TO_STRINGID(0x4832, 0x4834, STR_NEWS_INDUSTRY_CLOSURE_GENERAL, STR_NEWS_INDUSTRY_CLOSURE_LACK_OF_TREES);
528  TEXTID_TO_STRINGID(0x4835, 0x4838, STR_NEWS_INDUSTRY_PRODUCTION_INCREASE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_INCREASE_FARM);
529  TEXTID_TO_STRINGID(0x4839, 0x483A, STR_NEWS_INDUSTRY_PRODUCTION_DECREASE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_DECREASE_FARM);
530 
531  switch (str) {
532  case 0x4830: return STR_ERROR_CAN_T_CONSTRUCT_THIS_INDUSTRY;
533  case 0x4831: return STR_ERROR_FOREST_CAN_ONLY_BE_PLANTED;
534  case 0x483B: return STR_ERROR_CAN_ONLY_BE_POSITIONED;
535  }
536 #undef TEXTID_TO_STRINGID
537 
538  if (str == STR_NULL) return STR_EMPTY;
539 
540  DEBUG(grf, 0, "Unknown StringID 0x%04X remapped to STR_EMPTY. Please open a Feature Request if you need it", str);
541 
542  return STR_EMPTY;
543 }
544 
552 StringID MapGRFStringID(uint32 grfid, StringID str)
553 {
554  if (IsInsideMM(str, 0xD800, 0xE000)) {
555  /* General text provided by NewGRF.
556  * In the specs this is called the 0xDCxx range (misc presistent texts),
557  * but we meanwhile extended the range to 0xD800-0xDFFF.
558  * Note: We are not involved in the "persistent" business, since we do not store
559  * any NewGRF strings in savegames. */
560  return GetGRFStringID(grfid, str);
561  } else if (IsInsideMM(str, 0xD000, 0xD800)) {
562  /* Callback text provided by NewGRF.
563  * In the specs this is called the 0xD0xx range (misc graphics texts).
564  * These texts can be returned by various callbacks.
565  *
566  * Due to how TTDP implements the GRF-local- to global-textid translation
567  * texts included via 0x80 or 0x81 control codes have to add 0x400 to the textid.
568  * We do not care about that difference and just mask out the 0x400 bit.
569  */
570  str &= ~0x400;
571  return GetGRFStringID(grfid, str);
572  } else {
573  /* The NewGRF wants to include/reference an original TTD string.
574  * Try our best to find an equivalent one. */
576  }
577 }
578 
579 static std::map<uint32, uint32> _grf_id_overrides;
580 
586 static void SetNewGRFOverride(uint32 source_grfid, uint32 target_grfid)
587 {
588  _grf_id_overrides[source_grfid] = target_grfid;
589  grfmsg(5, "SetNewGRFOverride: Added override of 0x%X to 0x%X", BSWAP32(source_grfid), BSWAP32(target_grfid));
590 }
591 
600 static Engine *GetNewEngine(const GRFFile *file, VehicleType type, uint16 internal_id, bool static_access = false)
601 {
602  /* Hack for add-on GRFs that need to modify another GRF's engines. This lets
603  * them use the same engine slots. */
604  uint32 scope_grfid = INVALID_GRFID; // If not using dynamic_engines, all newgrfs share their ID range
606  /* If dynamic_engies is enabled, there can be multiple independent ID ranges. */
607  scope_grfid = file->grfid;
608  uint32 override = _grf_id_overrides[file->grfid];
609  if (override != 0) {
610  scope_grfid = override;
611  const GRFFile *grf_match = GetFileByGRFID(override);
612  if (grf_match == NULL) {
613  grfmsg(5, "Tried mapping from GRFID %x to %x but target is not loaded", BSWAP32(file->grfid), BSWAP32(override));
614  } else {
615  grfmsg(5, "Mapping from GRFID %x to %x", BSWAP32(file->grfid), BSWAP32(override));
616  }
617  }
618 
619  /* Check if the engine is registered in the override manager */
620  EngineID engine = _engine_mngr.GetID(type, internal_id, scope_grfid);
621  if (engine != INVALID_ENGINE) {
622  Engine *e = Engine::Get(engine);
623  if (e->grf_prop.grffile == NULL) e->grf_prop.grffile = file;
624  return e;
625  }
626  }
627 
628  /* Check if there is an unreserved slot */
629  EngineID engine = _engine_mngr.GetID(type, internal_id, INVALID_GRFID);
630  if (engine != INVALID_ENGINE) {
631  Engine *e = Engine::Get(engine);
632 
633  if (e->grf_prop.grffile == NULL) {
634  e->grf_prop.grffile = file;
635  grfmsg(5, "Replaced engine at index %d for GRFID %x, type %d, index %d", e->index, BSWAP32(file->grfid), type, internal_id);
636  }
637 
638  /* Reserve the engine slot */
639  if (!static_access) {
640  EngineIDMapping *eid = _engine_mngr.Get(engine);
641  eid->grfid = scope_grfid; // Note: this is INVALID_GRFID if dynamic_engines is disabled, so no reservation
642  }
643 
644  return e;
645  }
646 
647  if (static_access) return NULL;
648 
649  if (!Engine::CanAllocateItem()) {
650  grfmsg(0, "Can't allocate any more engines");
651  return NULL;
652  }
653 
654  size_t engine_pool_size = Engine::GetPoolSize();
655 
656  /* ... it's not, so create a new one based off an existing engine */
657  Engine *e = new Engine(type, internal_id);
658  e->grf_prop.grffile = file;
659 
660  /* Reserve the engine slot */
661  assert(_engine_mngr.Length() == e->index);
662  EngineIDMapping *eid = _engine_mngr.Append();
663  eid->type = type;
664  eid->grfid = scope_grfid; // Note: this is INVALID_GRFID if dynamic_engines is disabled, so no reservation
665  eid->internal_id = internal_id;
666  eid->substitute_id = min(internal_id, _engine_counts[type]); // substitute_id == _engine_counts[subtype] means "no substitute"
667 
668  if (engine_pool_size != Engine::GetPoolSize()) {
669  /* Resize temporary engine data ... */
670  _gted = ReallocT(_gted, Engine::GetPoolSize());
671 
672  /* and blank the new block. */
673  size_t len = (Engine::GetPoolSize() - engine_pool_size) * sizeof(*_gted);
674  memset(_gted + engine_pool_size, 0, len);
675  }
676  if (type == VEH_TRAIN) {
677  _gted[e->index].railtypelabel = GetRailTypeInfo(e->u.rail.railtype)->label;
678  }
679 
680  grfmsg(5, "Created new engine at index %d for GRFID %x, type %d, index %d", e->index, BSWAP32(file->grfid), type, internal_id);
681 
682  return e;
683 }
684 
695 EngineID GetNewEngineID(const GRFFile *file, VehicleType type, uint16 internal_id)
696 {
697  uint32 scope_grfid = INVALID_GRFID; // If not using dynamic_engines, all newgrfs share their ID range
699  scope_grfid = file->grfid;
700  uint32 override = _grf_id_overrides[file->grfid];
701  if (override != 0) scope_grfid = override;
702  }
703 
704  return _engine_mngr.GetID(type, internal_id, scope_grfid);
705 }
706 
711 static void MapSpriteMappingRecolour(PalSpriteID *grf_sprite)
712 {
713  if (HasBit(grf_sprite->pal, 14)) {
714  ClrBit(grf_sprite->pal, 14);
715  SetBit(grf_sprite->sprite, SPRITE_MODIFIER_OPAQUE);
716  }
717 
718  if (HasBit(grf_sprite->sprite, 14)) {
719  ClrBit(grf_sprite->sprite, 14);
721  }
722 
723  if (HasBit(grf_sprite->sprite, 15)) {
724  ClrBit(grf_sprite->sprite, 15);
725  SetBit(grf_sprite->sprite, PALETTE_MODIFIER_COLOUR);
726  }
727 }
728 
742 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 = NULL, uint16 *max_palette_offset = NULL)
743 {
744  grf_sprite->sprite = buf->ReadWord();
745  grf_sprite->pal = buf->ReadWord();
746  TileLayoutFlags flags = read_flags ? (TileLayoutFlags)buf->ReadWord() : TLF_NOTHING;
747 
748  MapSpriteMappingRecolour(grf_sprite);
749 
750  bool custom_sprite = HasBit(grf_sprite->pal, 15) != invert_action1_flag;
751  ClrBit(grf_sprite->pal, 15);
752  if (custom_sprite) {
753  /* Use sprite from Action 1 */
754  uint index = GB(grf_sprite->sprite, 0, 14);
755  if (use_cur_spritesets && (!_cur.IsValidSpriteSet(feature, index) || _cur.GetNumEnts(feature, index) == 0)) {
756  grfmsg(1, "ReadSpriteLayoutSprite: Spritelayout uses undefined custom spriteset %d", index);
757  grf_sprite->sprite = SPR_IMG_QUERY;
758  grf_sprite->pal = PAL_NONE;
759  } else {
760  SpriteID sprite = use_cur_spritesets ? _cur.GetSprite(feature, index) : index;
761  if (max_sprite_offset != NULL) *max_sprite_offset = use_cur_spritesets ? _cur.GetNumEnts(feature, index) : UINT16_MAX;
762  SB(grf_sprite->sprite, 0, SPRITE_WIDTH, sprite);
764  }
765  } else if ((flags & TLF_SPRITE_VAR10) && !(flags & TLF_SPRITE_REG_FLAGS)) {
766  grfmsg(1, "ReadSpriteLayoutSprite: Spritelayout specifies var10 value for non-action-1 sprite");
767  DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
768  return flags;
769  }
770 
771  if (flags & TLF_CUSTOM_PALETTE) {
772  /* Use palette from Action 1 */
773  uint index = GB(grf_sprite->pal, 0, 14);
774  if (use_cur_spritesets && (!_cur.IsValidSpriteSet(feature, index) || _cur.GetNumEnts(feature, index) == 0)) {
775  grfmsg(1, "ReadSpriteLayoutSprite: Spritelayout uses undefined custom spriteset %d for 'palette'", index);
776  grf_sprite->pal = PAL_NONE;
777  } else {
778  SpriteID sprite = use_cur_spritesets ? _cur.GetSprite(feature, index) : index;
779  if (max_palette_offset != NULL) *max_palette_offset = use_cur_spritesets ? _cur.GetNumEnts(feature, index) : UINT16_MAX;
780  SB(grf_sprite->pal, 0, SPRITE_WIDTH, sprite);
782  }
783  } else if ((flags & TLF_PALETTE_VAR10) && !(flags & TLF_PALETTE_REG_FLAGS)) {
784  grfmsg(1, "ReadSpriteLayoutRegisters: Spritelayout specifies var10 value for non-action-1 palette");
785  DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
786  return flags;
787  }
788 
789  return flags;
790 }
791 
800 static void ReadSpriteLayoutRegisters(ByteReader *buf, TileLayoutFlags flags, bool is_parent, NewGRFSpriteLayout *dts, uint index)
801 {
802  if (!(flags & TLF_DRAWING_FLAGS)) return;
803 
804  if (dts->registers == NULL) dts->AllocateRegisters();
805  TileLayoutRegisters &regs = const_cast<TileLayoutRegisters&>(dts->registers[index]);
806  regs.flags = flags & TLF_DRAWING_FLAGS;
807 
808  if (flags & TLF_DODRAW) regs.dodraw = buf->ReadByte();
809  if (flags & TLF_SPRITE) regs.sprite = buf->ReadByte();
810  if (flags & TLF_PALETTE) regs.palette = buf->ReadByte();
811 
812  if (is_parent) {
813  if (flags & TLF_BB_XY_OFFSET) {
814  regs.delta.parent[0] = buf->ReadByte();
815  regs.delta.parent[1] = buf->ReadByte();
816  }
817  if (flags & TLF_BB_Z_OFFSET) regs.delta.parent[2] = buf->ReadByte();
818  } else {
819  if (flags & TLF_CHILD_X_OFFSET) regs.delta.child[0] = buf->ReadByte();
820  if (flags & TLF_CHILD_Y_OFFSET) regs.delta.child[1] = buf->ReadByte();
821  }
822 
823  if (flags & TLF_SPRITE_VAR10) {
824  regs.sprite_var10 = buf->ReadByte();
825  if (regs.sprite_var10 > TLR_MAX_VAR10) {
826  grfmsg(1, "ReadSpriteLayoutRegisters: Spritelayout specifies var10 (%d) exceeding the maximal allowed value %d", regs.sprite_var10, TLR_MAX_VAR10);
827  DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
828  return;
829  }
830  }
831 
832  if (flags & TLF_PALETTE_VAR10) {
833  regs.palette_var10 = buf->ReadByte();
834  if (regs.palette_var10 > TLR_MAX_VAR10) {
835  grfmsg(1, "ReadSpriteLayoutRegisters: Spritelayout specifies var10 (%d) exceeding the maximal allowed value %d", regs.palette_var10, TLR_MAX_VAR10);
836  DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
837  return;
838  }
839  }
840 }
841 
853 static bool ReadSpriteLayout(ByteReader *buf, uint num_building_sprites, bool use_cur_spritesets, byte feature, bool allow_var10, bool no_z_position, NewGRFSpriteLayout *dts)
854 {
855  bool has_flags = HasBit(num_building_sprites, 6);
856  ClrBit(num_building_sprites, 6);
857  TileLayoutFlags valid_flags = TLF_KNOWN_FLAGS;
858  if (!allow_var10) valid_flags &= ~TLF_VAR10_FLAGS;
859  dts->Allocate(num_building_sprites); // allocate before reading groundsprite flags
860 
861  uint16 *max_sprite_offset = AllocaM(uint16, num_building_sprites + 1);
862  uint16 *max_palette_offset = AllocaM(uint16, num_building_sprites + 1);
863  MemSetT(max_sprite_offset, 0, num_building_sprites + 1);
864  MemSetT(max_palette_offset, 0, num_building_sprites + 1);
865 
866  /* Groundsprite */
867  TileLayoutFlags flags = ReadSpriteLayoutSprite(buf, has_flags, false, use_cur_spritesets, feature, &dts->ground, max_sprite_offset, max_palette_offset);
868  if (_cur.skip_sprites < 0) return true;
869 
870  if (flags & ~(valid_flags & ~TLF_NON_GROUND_FLAGS)) {
871  grfmsg(1, "ReadSpriteLayout: Spritelayout uses invalid flag 0x%x for ground sprite", flags & ~(valid_flags & ~TLF_NON_GROUND_FLAGS));
872  DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
873  return true;
874  }
875 
876  ReadSpriteLayoutRegisters(buf, flags, false, dts, 0);
877  if (_cur.skip_sprites < 0) return true;
878 
879  for (uint i = 0; i < num_building_sprites; i++) {
880  DrawTileSeqStruct *seq = const_cast<DrawTileSeqStruct*>(&dts->seq[i]);
881 
882  flags = ReadSpriteLayoutSprite(buf, has_flags, false, use_cur_spritesets, feature, &seq->image, max_sprite_offset + i + 1, max_palette_offset + i + 1);
883  if (_cur.skip_sprites < 0) return true;
884 
885  if (flags & ~valid_flags) {
886  grfmsg(1, "ReadSpriteLayout: Spritelayout uses unknown flag 0x%x", flags & ~valid_flags);
887  DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
888  return true;
889  }
890 
891  seq->delta_x = buf->ReadByte();
892  seq->delta_y = buf->ReadByte();
893 
894  if (!no_z_position) seq->delta_z = buf->ReadByte();
895 
896  if (seq->IsParentSprite()) {
897  seq->size_x = buf->ReadByte();
898  seq->size_y = buf->ReadByte();
899  seq->size_z = buf->ReadByte();
900  }
901 
902  ReadSpriteLayoutRegisters(buf, flags, seq->IsParentSprite(), dts, i + 1);
903  if (_cur.skip_sprites < 0) return true;
904  }
905 
906  /* Check if the number of sprites per spriteset is consistent */
907  bool is_consistent = true;
908  dts->consistent_max_offset = 0;
909  for (uint i = 0; i < num_building_sprites + 1; i++) {
910  if (max_sprite_offset[i] > 0) {
911  if (dts->consistent_max_offset == 0) {
912  dts->consistent_max_offset = max_sprite_offset[i];
913  } else if (dts->consistent_max_offset != max_sprite_offset[i]) {
914  is_consistent = false;
915  break;
916  }
917  }
918  if (max_palette_offset[i] > 0) {
919  if (dts->consistent_max_offset == 0) {
920  dts->consistent_max_offset = max_palette_offset[i];
921  } else if (dts->consistent_max_offset != max_palette_offset[i]) {
922  is_consistent = false;
923  break;
924  }
925  }
926  }
927 
928  /* When the Action1 sets are unknown, everything should be 0 (no spriteset usage) or UINT16_MAX (some spriteset usage) */
929  assert(use_cur_spritesets || (is_consistent && (dts->consistent_max_offset == 0 || dts->consistent_max_offset == UINT16_MAX)));
930 
931  if (!is_consistent || dts->registers != NULL) {
932  dts->consistent_max_offset = 0;
933  if (dts->registers == NULL) dts->AllocateRegisters();
934 
935  for (uint i = 0; i < num_building_sprites + 1; i++) {
936  TileLayoutRegisters &regs = const_cast<TileLayoutRegisters&>(dts->registers[i]);
937  regs.max_sprite_offset = max_sprite_offset[i];
938  regs.max_palette_offset = max_palette_offset[i];
939  }
940  }
941 
942  return false;
943 }
944 
948 static CargoTypes TranslateRefitMask(uint32 refit_mask)
949 {
950  CargoTypes result = 0;
951  uint8 bit;
952  FOR_EACH_SET_BIT(bit, refit_mask) {
953  CargoID cargo = GetCargoTranslation(bit, _cur.grffile, true);
954  if (cargo != CT_INVALID) SetBit(result, cargo);
955  }
956  return result;
957 }
958 
966 static void ConvertTTDBasePrice(uint32 base_pointer, const char *error_location, Price *index)
967 {
968  /* Special value for 'none' */
969  if (base_pointer == 0) {
970  *index = INVALID_PRICE;
971  return;
972  }
973 
974  static const uint32 start = 0x4B34;
975  static const uint32 size = 6;
976 
977  if (base_pointer < start || (base_pointer - start) % size != 0 || (base_pointer - start) / size >= PR_END) {
978  grfmsg(1, "%s: Unsupported running cost base 0x%04X, ignoring", error_location, base_pointer);
979  return;
980  }
981 
982  *index = (Price)((base_pointer - start) / size);
983 }
984 
992 };
993 
994 typedef ChangeInfoResult (*VCI_Handler)(uint engine, int numinfo, int prop, ByteReader *buf);
995 
1004 {
1005  switch (prop) {
1006  case 0x00: // Introduction date
1007  ei->base_intro = buf->ReadWord() + DAYS_TILL_ORIGINAL_BASE_YEAR;
1008  break;
1009 
1010  case 0x02: // Decay speed
1011  ei->decay_speed = buf->ReadByte();
1012  break;
1013 
1014  case 0x03: // Vehicle life
1015  ei->lifelength = buf->ReadByte();
1016  break;
1017 
1018  case 0x04: // Model life
1019  ei->base_life = buf->ReadByte();
1020  break;
1021 
1022  case 0x06: // Climates available
1023  ei->climates = buf->ReadByte();
1024  break;
1025 
1026  case PROP_VEHICLE_LOAD_AMOUNT: // 0x07 Loading speed
1027  /* Amount of cargo loaded during a vehicle's "loading tick" */
1028  ei->load_amount = buf->ReadByte();
1029  break;
1030 
1031  default:
1032  return CIR_UNKNOWN;
1033  }
1034 
1035  return CIR_SUCCESS;
1036 }
1037 
1046 static ChangeInfoResult RailVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader *buf)
1047 {
1049 
1050  for (int i = 0; i < numinfo; i++) {
1051  Engine *e = GetNewEngine(_cur.grffile, VEH_TRAIN, engine + i);
1052  if (e == NULL) return CIR_INVALID_ID; // No engine could be allocated, so neither can any next vehicles
1053 
1054  EngineInfo *ei = &e->info;
1055  RailVehicleInfo *rvi = &e->u.rail;
1056 
1057  switch (prop) {
1058  case 0x05: { // Track type
1059  uint8 tracktype = buf->ReadByte();
1060 
1061  if (tracktype < _cur.grffile->railtype_list.Length()) {
1062  _gted[e->index].railtypelabel = _cur.grffile->railtype_list[tracktype];
1063  break;
1064  }
1065 
1066  switch (tracktype) {
1067  case 0: _gted[e->index].railtypelabel = rvi->engclass >= 2 ? RAILTYPE_ELECTRIC_LABEL : RAILTYPE_RAIL_LABEL; break;
1068  case 1: _gted[e->index].railtypelabel = RAILTYPE_MONO_LABEL; break;
1069  case 2: _gted[e->index].railtypelabel = RAILTYPE_MAGLEV_LABEL; break;
1070  default:
1071  grfmsg(1, "RailVehicleChangeInfo: Invalid track type %d specified, ignoring", tracktype);
1072  break;
1073  }
1074  break;
1075  }
1076 
1077  case 0x08: // AI passenger service
1078  /* Tells the AI that this engine is designed for
1079  * passenger services and shouldn't be used for freight. */
1080  rvi->ai_passenger_only = buf->ReadByte();
1081  break;
1082 
1083  case PROP_TRAIN_SPEED: { // 0x09 Speed (1 unit is 1 km-ish/h)
1084  uint16 speed = buf->ReadWord();
1085  if (speed == 0xFFFF) speed = 0;
1086 
1087  rvi->max_speed = speed;
1088  break;
1089  }
1090 
1091  case PROP_TRAIN_POWER: // 0x0B Power
1092  rvi->power = buf->ReadWord();
1093 
1094  /* Set engine / wagon state based on power */
1095  if (rvi->power != 0) {
1096  if (rvi->railveh_type == RAILVEH_WAGON) {
1097  rvi->railveh_type = RAILVEH_SINGLEHEAD;
1098  }
1099  } else {
1100  rvi->railveh_type = RAILVEH_WAGON;
1101  }
1102  break;
1103 
1104  case PROP_TRAIN_RUNNING_COST_FACTOR: // 0x0D Running cost factor
1105  rvi->running_cost = buf->ReadByte();
1106  break;
1107 
1108  case 0x0E: // Running cost base
1109  ConvertTTDBasePrice(buf->ReadDWord(), "RailVehicleChangeInfo", &rvi->running_cost_class);
1110  break;
1111 
1112  case 0x12: { // Sprite ID
1113  uint8 spriteid = buf->ReadByte();
1114  uint8 orig_spriteid = spriteid;
1115 
1116  /* TTD sprite IDs point to a location in a 16bit array, but we use it
1117  * as an array index, so we need it to be half the original value. */
1118  if (spriteid < 0xFD) spriteid >>= 1;
1119 
1120  if (IsValidNewGRFImageIndex<VEH_TRAIN>(spriteid)) {
1121  rvi->image_index = spriteid;
1122  } else {
1123  grfmsg(1, "RailVehicleChangeInfo: Invalid Sprite %d specified, ignoring", orig_spriteid);
1124  rvi->image_index = 0;
1125  }
1126  break;
1127  }
1128 
1129  case 0x13: { // Dual-headed
1130  uint8 dual = buf->ReadByte();
1131 
1132  if (dual != 0) {
1133  rvi->railveh_type = RAILVEH_MULTIHEAD;
1134  } else {
1135  rvi->railveh_type = rvi->power == 0 ?
1137  }
1138  break;
1139  }
1140 
1141  case PROP_TRAIN_CARGO_CAPACITY: // 0x14 Cargo capacity
1142  rvi->capacity = buf->ReadByte();
1143  break;
1144 
1145  case 0x15: { // Cargo type
1146  _gted[e->index].defaultcargo_grf = _cur.grffile;
1147  uint8 ctype = buf->ReadByte();
1148 
1149  if (ctype == 0xFF) {
1150  /* 0xFF is specified as 'use first refittable' */
1151  ei->cargo_type = CT_INVALID;
1152  } else if (_cur.grffile->grf_version >= 8) {
1153  /* Use translated cargo. Might result in CT_INVALID (first refittable), if cargo is not defined. */
1154  ei->cargo_type = GetCargoTranslation(ctype, _cur.grffile);
1155  } else if (ctype < NUM_CARGO) {
1156  /* Use untranslated cargo. */
1157  ei->cargo_type = ctype;
1158  } else {
1159  ei->cargo_type = CT_INVALID;
1160  grfmsg(2, "RailVehicleChangeInfo: Invalid cargo type %d, using first refittable", ctype);
1161  }
1162  break;
1163  }
1164 
1165  case PROP_TRAIN_WEIGHT: // 0x16 Weight
1166  SB(rvi->weight, 0, 8, buf->ReadByte());
1167  break;
1168 
1169  case PROP_TRAIN_COST_FACTOR: // 0x17 Cost factor
1170  rvi->cost_factor = buf->ReadByte();
1171  break;
1172 
1173  case 0x18: // AI rank
1174  grfmsg(2, "RailVehicleChangeInfo: Property 0x18 'AI rank' not used by NoAI, ignored.");
1175  buf->ReadByte();
1176  break;
1177 
1178  case 0x19: { // Engine traction type
1179  /* What do the individual numbers mean?
1180  * 0x00 .. 0x07: Steam
1181  * 0x08 .. 0x27: Diesel
1182  * 0x28 .. 0x31: Electric
1183  * 0x32 .. 0x37: Monorail
1184  * 0x38 .. 0x41: Maglev
1185  */
1186  uint8 traction = buf->ReadByte();
1187  EngineClass engclass;
1188 
1189  if (traction <= 0x07) {
1190  engclass = EC_STEAM;
1191  } else if (traction <= 0x27) {
1192  engclass = EC_DIESEL;
1193  } else if (traction <= 0x31) {
1194  engclass = EC_ELECTRIC;
1195  } else if (traction <= 0x37) {
1196  engclass = EC_MONORAIL;
1197  } else if (traction <= 0x41) {
1198  engclass = EC_MAGLEV;
1199  } else {
1200  break;
1201  }
1202 
1203  if (_cur.grffile->railtype_list.Length() == 0) {
1204  /* Use traction type to select between normal and electrified
1205  * rail only when no translation list is in place. */
1206  if (_gted[e->index].railtypelabel == RAILTYPE_RAIL_LABEL && engclass >= EC_ELECTRIC) _gted[e->index].railtypelabel = RAILTYPE_ELECTRIC_LABEL;
1207  if (_gted[e->index].railtypelabel == RAILTYPE_ELECTRIC_LABEL && engclass < EC_ELECTRIC) _gted[e->index].railtypelabel = RAILTYPE_RAIL_LABEL;
1208  }
1209 
1210  rvi->engclass = engclass;
1211  break;
1212  }
1213 
1214  case 0x1A: // Alter purchase list sort order
1215  AlterVehicleListOrder(e->index, buf->ReadExtendedByte());
1216  break;
1217 
1218  case 0x1B: // Powered wagons power bonus
1219  rvi->pow_wag_power = buf->ReadWord();
1220  break;
1221 
1222  case 0x1C: // Refit cost
1223  ei->refit_cost = buf->ReadByte();
1224  break;
1225 
1226  case 0x1D: { // Refit cargo
1227  uint32 mask = buf->ReadDWord();
1228  _gted[e->index].UpdateRefittability(mask != 0);
1229  ei->refit_mask = TranslateRefitMask(mask);
1230  _gted[e->index].defaultcargo_grf = _cur.grffile;
1231  break;
1232  }
1233 
1234  case 0x1E: // Callback
1235  ei->callback_mask = buf->ReadByte();
1236  break;
1237 
1238  case PROP_TRAIN_TRACTIVE_EFFORT: // 0x1F Tractive effort coefficient
1239  rvi->tractive_effort = buf->ReadByte();
1240  break;
1241 
1242  case 0x20: // Air drag
1243  rvi->air_drag = buf->ReadByte();
1244  break;
1245 
1246  case PROP_TRAIN_SHORTEN_FACTOR: // 0x21 Shorter vehicle
1247  rvi->shorten_factor = buf->ReadByte();
1248  break;
1249 
1250  case 0x22: // Visual effect
1251  rvi->visual_effect = buf->ReadByte();
1252  /* Avoid accidentally setting visual_effect to the default value
1253  * Since bit 6 (disable effects) is set anyways, we can safely erase some bits. */
1254  if (rvi->visual_effect == VE_DEFAULT) {
1255  assert(HasBit(rvi->visual_effect, VE_DISABLE_EFFECT));
1257  }
1258  break;
1259 
1260  case 0x23: // Powered wagons weight bonus
1261  rvi->pow_wag_weight = buf->ReadByte();
1262  break;
1263 
1264  case 0x24: { // High byte of vehicle weight
1265  byte weight = buf->ReadByte();
1266 
1267  if (weight > 4) {
1268  grfmsg(2, "RailVehicleChangeInfo: Nonsensical weight of %d tons, ignoring", weight << 8);
1269  } else {
1270  SB(rvi->weight, 8, 8, weight);
1271  }
1272  break;
1273  }
1274 
1275  case PROP_TRAIN_USER_DATA: // 0x25 User-defined bit mask to set when checking veh. var. 42
1276  rvi->user_def_data = buf->ReadByte();
1277  break;
1278 
1279  case 0x26: // Retire vehicle early
1280  ei->retire_early = buf->ReadByte();
1281  break;
1282 
1283  case 0x27: // Miscellaneous flags
1284  ei->misc_flags = buf->ReadByte();
1285  _loaded_newgrf_features.has_2CC |= HasBit(ei->misc_flags, EF_USES_2CC);
1286  _gted[e->index].prop27_set = true;
1287  break;
1288 
1289  case 0x28: // Cargo classes allowed
1290  _gted[e->index].cargo_allowed = buf->ReadWord();
1291  _gted[e->index].UpdateRefittability(_gted[e->index].cargo_allowed != 0);
1292  _gted[e->index].defaultcargo_grf = _cur.grffile;
1293  break;
1294 
1295  case 0x29: // Cargo classes disallowed
1296  _gted[e->index].cargo_disallowed = buf->ReadWord();
1297  _gted[e->index].UpdateRefittability(false);
1298  break;
1299 
1300  case 0x2A: // Long format introduction date (days since year 0)
1301  ei->base_intro = buf->ReadDWord();
1302  break;
1303 
1304  case PROP_TRAIN_CARGO_AGE_PERIOD: // 0x2B Cargo aging period
1305  ei->cargo_age_period = buf->ReadWord();
1306  break;
1307 
1308  case 0x2C: // CTT refit include list
1309  case 0x2D: { // CTT refit exclude list
1310  uint8 count = buf->ReadByte();
1311  _gted[e->index].UpdateRefittability(prop == 0x2C && count != 0);
1312  if (prop == 0x2C) _gted[e->index].defaultcargo_grf = _cur.grffile;
1313  CargoTypes &ctt = prop == 0x2C ? _gted[e->index].ctt_include_mask : _gted[e->index].ctt_exclude_mask;
1314  ctt = 0;
1315  while (count--) {
1316  CargoID ctype = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
1317  if (ctype == CT_INVALID) continue;
1318  SetBit(ctt, ctype);
1319  }
1320  break;
1321  }
1322 
1323  default:
1324  ret = CommonVehicleChangeInfo(ei, prop, buf);
1325  break;
1326  }
1327  }
1328 
1329  return ret;
1330 }
1331 
1340 static ChangeInfoResult RoadVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader *buf)
1341 {
1343 
1344  for (int i = 0; i < numinfo; i++) {
1345  Engine *e = GetNewEngine(_cur.grffile, VEH_ROAD, engine + i);
1346  if (e == NULL) return CIR_INVALID_ID; // No engine could be allocated, so neither can any next vehicles
1347 
1348  EngineInfo *ei = &e->info;
1349  RoadVehicleInfo *rvi = &e->u.road;
1350 
1351  switch (prop) {
1352  case 0x08: // Speed (1 unit is 0.5 kmh)
1353  rvi->max_speed = buf->ReadByte();
1354  break;
1355 
1356  case PROP_ROADVEH_RUNNING_COST_FACTOR: // 0x09 Running cost factor
1357  rvi->running_cost = buf->ReadByte();
1358  break;
1359 
1360  case 0x0A: // Running cost base
1361  ConvertTTDBasePrice(buf->ReadDWord(), "RoadVehicleChangeInfo", &rvi->running_cost_class);
1362  break;
1363 
1364  case 0x0E: { // Sprite ID
1365  uint8 spriteid = buf->ReadByte();
1366  uint8 orig_spriteid = spriteid;
1367 
1368  /* cars have different custom id in the GRF file */
1369  if (spriteid == 0xFF) spriteid = 0xFD;
1370 
1371  if (spriteid < 0xFD) spriteid >>= 1;
1372 
1373  if (IsValidNewGRFImageIndex<VEH_ROAD>(spriteid)) {
1374  rvi->image_index = spriteid;
1375  } else {
1376  grfmsg(1, "RoadVehicleChangeInfo: Invalid Sprite %d specified, ignoring", orig_spriteid);
1377  rvi->image_index = 0;
1378  }
1379  break;
1380  }
1381 
1382  case PROP_ROADVEH_CARGO_CAPACITY: // 0x0F Cargo capacity
1383  rvi->capacity = buf->ReadByte();
1384  break;
1385 
1386  case 0x10: { // Cargo type
1387  _gted[e->index].defaultcargo_grf = _cur.grffile;
1388  uint8 ctype = buf->ReadByte();
1389 
1390  if (ctype == 0xFF) {
1391  /* 0xFF is specified as 'use first refittable' */
1392  ei->cargo_type = CT_INVALID;
1393  } else if (_cur.grffile->grf_version >= 8) {
1394  /* Use translated cargo. Might result in CT_INVALID (first refittable), if cargo is not defined. */
1395  ei->cargo_type = GetCargoTranslation(ctype, _cur.grffile);
1396  } else if (ctype < NUM_CARGO) {
1397  /* Use untranslated cargo. */
1398  ei->cargo_type = ctype;
1399  } else {
1400  ei->cargo_type = CT_INVALID;
1401  grfmsg(2, "RailVehicleChangeInfo: Invalid cargo type %d, using first refittable", ctype);
1402  }
1403  break;
1404  }
1405 
1406  case PROP_ROADVEH_COST_FACTOR: // 0x11 Cost factor
1407  rvi->cost_factor = buf->ReadByte();
1408  break;
1409 
1410  case 0x12: // SFX
1411  rvi->sfx = GetNewGRFSoundID(_cur.grffile, buf->ReadByte());
1412  break;
1413 
1414  case PROP_ROADVEH_POWER: // Power in units of 10 HP.
1415  rvi->power = buf->ReadByte();
1416  break;
1417 
1418  case PROP_ROADVEH_WEIGHT: // Weight in units of 1/4 tons.
1419  rvi->weight = buf->ReadByte();
1420  break;
1421 
1422  case PROP_ROADVEH_SPEED: // Speed in mph/0.8
1423  _gted[e->index].rv_max_speed = buf->ReadByte();
1424  break;
1425 
1426  case 0x16: { // Cargoes available for refitting
1427  uint32 mask = buf->ReadDWord();
1428  _gted[e->index].UpdateRefittability(mask != 0);
1429  ei->refit_mask = TranslateRefitMask(mask);
1430  _gted[e->index].defaultcargo_grf = _cur.grffile;
1431  break;
1432  }
1433 
1434  case 0x17: // Callback mask
1435  ei->callback_mask = buf->ReadByte();
1436  break;
1437 
1438  case PROP_ROADVEH_TRACTIVE_EFFORT: // Tractive effort coefficient in 1/256.
1439  rvi->tractive_effort = buf->ReadByte();
1440  break;
1441 
1442  case 0x19: // Air drag
1443  rvi->air_drag = buf->ReadByte();
1444  break;
1445 
1446  case 0x1A: // Refit cost
1447  ei->refit_cost = buf->ReadByte();
1448  break;
1449 
1450  case 0x1B: // Retire vehicle early
1451  ei->retire_early = buf->ReadByte();
1452  break;
1453 
1454  case 0x1C: // Miscellaneous flags
1455  ei->misc_flags = buf->ReadByte();
1456  _loaded_newgrf_features.has_2CC |= HasBit(ei->misc_flags, EF_USES_2CC);
1457  break;
1458 
1459  case 0x1D: // Cargo classes allowed
1460  _gted[e->index].cargo_allowed = buf->ReadWord();
1461  _gted[e->index].UpdateRefittability(_gted[e->index].cargo_allowed != 0);
1462  _gted[e->index].defaultcargo_grf = _cur.grffile;
1463  break;
1464 
1465  case 0x1E: // Cargo classes disallowed
1466  _gted[e->index].cargo_disallowed = buf->ReadWord();
1467  _gted[e->index].UpdateRefittability(false);
1468  break;
1469 
1470  case 0x1F: // Long format introduction date (days since year 0)
1471  ei->base_intro = buf->ReadDWord();
1472  break;
1473 
1474  case 0x20: // Alter purchase list sort order
1475  AlterVehicleListOrder(e->index, buf->ReadExtendedByte());
1476  break;
1477 
1478  case 0x21: // Visual effect
1479  rvi->visual_effect = buf->ReadByte();
1480  /* Avoid accidentally setting visual_effect to the default value
1481  * Since bit 6 (disable effects) is set anyways, we can safely erase some bits. */
1482  if (rvi->visual_effect == VE_DEFAULT) {
1483  assert(HasBit(rvi->visual_effect, VE_DISABLE_EFFECT));
1485  }
1486  break;
1487 
1488  case PROP_ROADVEH_CARGO_AGE_PERIOD: // 0x22 Cargo aging period
1489  ei->cargo_age_period = buf->ReadWord();
1490  break;
1491 
1492  case PROP_ROADVEH_SHORTEN_FACTOR: // 0x23 Shorter vehicle
1493  rvi->shorten_factor = buf->ReadByte();
1494  break;
1495 
1496  case 0x24: // CTT refit include list
1497  case 0x25: { // CTT refit exclude list
1498  uint8 count = buf->ReadByte();
1499  _gted[e->index].UpdateRefittability(prop == 0x24 && count != 0);
1500  if (prop == 0x24) _gted[e->index].defaultcargo_grf = _cur.grffile;
1501  CargoTypes &ctt = prop == 0x24 ? _gted[e->index].ctt_include_mask : _gted[e->index].ctt_exclude_mask;
1502  ctt = 0;
1503  while (count--) {
1504  CargoID ctype = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
1505  if (ctype == CT_INVALID) continue;
1506  SetBit(ctt, ctype);
1507  }
1508  break;
1509  }
1510 
1511  default:
1512  ret = CommonVehicleChangeInfo(ei, prop, buf);
1513  break;
1514  }
1515  }
1516 
1517  return ret;
1518 }
1519 
1528 static ChangeInfoResult ShipVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader *buf)
1529 {
1531 
1532  for (int i = 0; i < numinfo; i++) {
1533  Engine *e = GetNewEngine(_cur.grffile, VEH_SHIP, engine + i);
1534  if (e == NULL) return CIR_INVALID_ID; // No engine could be allocated, so neither can any next vehicles
1535 
1536  EngineInfo *ei = &e->info;
1537  ShipVehicleInfo *svi = &e->u.ship;
1538 
1539  switch (prop) {
1540  case 0x08: { // Sprite ID
1541  uint8 spriteid = buf->ReadByte();
1542  uint8 orig_spriteid = spriteid;
1543 
1544  /* ships have different custom id in the GRF file */
1545  if (spriteid == 0xFF) spriteid = 0xFD;
1546 
1547  if (spriteid < 0xFD) spriteid >>= 1;
1548 
1549  if (IsValidNewGRFImageIndex<VEH_SHIP>(spriteid)) {
1550  svi->image_index = spriteid;
1551  } else {
1552  grfmsg(1, "ShipVehicleChangeInfo: Invalid Sprite %d specified, ignoring", orig_spriteid);
1553  svi->image_index = 0;
1554  }
1555  break;
1556  }
1557 
1558  case 0x09: // Refittable
1559  svi->old_refittable = (buf->ReadByte() != 0);
1560  break;
1561 
1562  case PROP_SHIP_COST_FACTOR: // 0x0A Cost factor
1563  svi->cost_factor = buf->ReadByte();
1564  break;
1565 
1566  case PROP_SHIP_SPEED: // 0x0B Speed (1 unit is 0.5 km-ish/h)
1567  svi->max_speed = buf->ReadByte();
1568  break;
1569 
1570  case 0x0C: { // Cargo type
1571  _gted[e->index].defaultcargo_grf = _cur.grffile;
1572  uint8 ctype = buf->ReadByte();
1573 
1574  if (ctype == 0xFF) {
1575  /* 0xFF is specified as 'use first refittable' */
1576  ei->cargo_type = CT_INVALID;
1577  } else if (_cur.grffile->grf_version >= 8) {
1578  /* Use translated cargo. Might result in CT_INVALID (first refittable), if cargo is not defined. */
1579  ei->cargo_type = GetCargoTranslation(ctype, _cur.grffile);
1580  } else if (ctype < NUM_CARGO) {
1581  /* Use untranslated cargo. */
1582  ei->cargo_type = ctype;
1583  } else {
1584  ei->cargo_type = CT_INVALID;
1585  grfmsg(2, "RailVehicleChangeInfo: Invalid cargo type %d, using first refittable", ctype);
1586  }
1587  break;
1588  }
1589 
1590  case PROP_SHIP_CARGO_CAPACITY: // 0x0D Cargo capacity
1591  svi->capacity = buf->ReadWord();
1592  break;
1593 
1594  case PROP_SHIP_RUNNING_COST_FACTOR: // 0x0F Running cost factor
1595  svi->running_cost = buf->ReadByte();
1596  break;
1597 
1598  case 0x10: // SFX
1599  svi->sfx = GetNewGRFSoundID(_cur.grffile, buf->ReadByte());
1600  break;
1601 
1602  case 0x11: { // Cargoes available for refitting
1603  uint32 mask = buf->ReadDWord();
1604  _gted[e->index].UpdateRefittability(mask != 0);
1605  ei->refit_mask = TranslateRefitMask(mask);
1606  _gted[e->index].defaultcargo_grf = _cur.grffile;
1607  break;
1608  }
1609 
1610  case 0x12: // Callback mask
1611  ei->callback_mask = buf->ReadByte();
1612  break;
1613 
1614  case 0x13: // Refit cost
1615  ei->refit_cost = buf->ReadByte();
1616  break;
1617 
1618  case 0x14: // Ocean speed fraction
1619  svi->ocean_speed_frac = buf->ReadByte();
1620  break;
1621 
1622  case 0x15: // Canal speed fraction
1623  svi->canal_speed_frac = buf->ReadByte();
1624  break;
1625 
1626  case 0x16: // Retire vehicle early
1627  ei->retire_early = buf->ReadByte();
1628  break;
1629 
1630  case 0x17: // Miscellaneous flags
1631  ei->misc_flags = buf->ReadByte();
1632  _loaded_newgrf_features.has_2CC |= HasBit(ei->misc_flags, EF_USES_2CC);
1633  break;
1634 
1635  case 0x18: // Cargo classes allowed
1636  _gted[e->index].cargo_allowed = buf->ReadWord();
1637  _gted[e->index].UpdateRefittability(_gted[e->index].cargo_allowed != 0);
1638  _gted[e->index].defaultcargo_grf = _cur.grffile;
1639  break;
1640 
1641  case 0x19: // Cargo classes disallowed
1642  _gted[e->index].cargo_disallowed = buf->ReadWord();
1643  _gted[e->index].UpdateRefittability(false);
1644  break;
1645 
1646  case 0x1A: // Long format introduction date (days since year 0)
1647  ei->base_intro = buf->ReadDWord();
1648  break;
1649 
1650  case 0x1B: // Alter purchase list sort order
1651  AlterVehicleListOrder(e->index, buf->ReadExtendedByte());
1652  break;
1653 
1654  case 0x1C: // Visual effect
1655  svi->visual_effect = buf->ReadByte();
1656  /* Avoid accidentally setting visual_effect to the default value
1657  * Since bit 6 (disable effects) is set anyways, we can safely erase some bits. */
1658  if (svi->visual_effect == VE_DEFAULT) {
1659  assert(HasBit(svi->visual_effect, VE_DISABLE_EFFECT));
1661  }
1662  break;
1663 
1664  case PROP_SHIP_CARGO_AGE_PERIOD: // 0x1D Cargo aging period
1665  ei->cargo_age_period = buf->ReadWord();
1666  break;
1667 
1668  case 0x1E: // CTT refit include list
1669  case 0x1F: { // CTT refit exclude list
1670  uint8 count = buf->ReadByte();
1671  _gted[e->index].UpdateRefittability(prop == 0x1E && count != 0);
1672  if (prop == 0x1E) _gted[e->index].defaultcargo_grf = _cur.grffile;
1673  CargoTypes &ctt = prop == 0x1E ? _gted[e->index].ctt_include_mask : _gted[e->index].ctt_exclude_mask;
1674  ctt = 0;
1675  while (count--) {
1676  CargoID ctype = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
1677  if (ctype == CT_INVALID) continue;
1678  SetBit(ctt, ctype);
1679  }
1680  break;
1681  }
1682 
1683  default:
1684  ret = CommonVehicleChangeInfo(ei, prop, buf);
1685  break;
1686  }
1687  }
1688 
1689  return ret;
1690 }
1691 
1700 static ChangeInfoResult AircraftVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader *buf)
1701 {
1703 
1704  for (int i = 0; i < numinfo; i++) {
1705  Engine *e = GetNewEngine(_cur.grffile, VEH_AIRCRAFT, engine + i);
1706  if (e == NULL) return CIR_INVALID_ID; // No engine could be allocated, so neither can any next vehicles
1707 
1708  EngineInfo *ei = &e->info;
1709  AircraftVehicleInfo *avi = &e->u.air;
1710 
1711  switch (prop) {
1712  case 0x08: { // Sprite ID
1713  uint8 spriteid = buf->ReadByte();
1714  uint8 orig_spriteid = spriteid;
1715 
1716  /* aircraft have different custom id in the GRF file */
1717  if (spriteid == 0xFF) spriteid = 0xFD;
1718 
1719  if (spriteid < 0xFD) spriteid >>= 1;
1720 
1721  if (IsValidNewGRFImageIndex<VEH_AIRCRAFT>(spriteid)) {
1722  avi->image_index = spriteid;
1723  } else {
1724  grfmsg(1, "AircraftVehicleChangeInfo: Invalid Sprite %d specified, ignoring", orig_spriteid);
1725  avi->image_index = 0;
1726  }
1727  break;
1728  }
1729 
1730  case 0x09: // Helicopter
1731  if (buf->ReadByte() == 0) {
1732  avi->subtype = AIR_HELI;
1733  } else {
1734  SB(avi->subtype, 0, 1, 1); // AIR_CTOL
1735  }
1736  break;
1737 
1738  case 0x0A: // Large
1739  SB(avi->subtype, 1, 1, (buf->ReadByte() != 0 ? 1 : 0)); // AIR_FAST
1740  break;
1741 
1742  case PROP_AIRCRAFT_COST_FACTOR: // 0x0B Cost factor
1743  avi->cost_factor = buf->ReadByte();
1744  break;
1745 
1746  case PROP_AIRCRAFT_SPEED: // 0x0C Speed (1 unit is 8 mph, we translate to 1 unit is 1 km-ish/h)
1747  avi->max_speed = (buf->ReadByte() * 128) / 10;
1748  break;
1749 
1750  case 0x0D: // Acceleration
1751  avi->acceleration = buf->ReadByte();
1752  break;
1753 
1754  case PROP_AIRCRAFT_RUNNING_COST_FACTOR: // 0x0E Running cost factor
1755  avi->running_cost = buf->ReadByte();
1756  break;
1757 
1758  case PROP_AIRCRAFT_PASSENGER_CAPACITY: // 0x0F Passenger capacity
1759  avi->passenger_capacity = buf->ReadWord();
1760  break;
1761 
1762  case PROP_AIRCRAFT_MAIL_CAPACITY: // 0x11 Mail capacity
1763  avi->mail_capacity = buf->ReadByte();
1764  break;
1765 
1766  case 0x12: // SFX
1767  avi->sfx = GetNewGRFSoundID(_cur.grffile, buf->ReadByte());
1768  break;
1769 
1770  case 0x13: { // Cargoes available for refitting
1771  uint32 mask = buf->ReadDWord();
1772  _gted[e->index].UpdateRefittability(mask != 0);
1773  ei->refit_mask = TranslateRefitMask(mask);
1774  _gted[e->index].defaultcargo_grf = _cur.grffile;
1775  break;
1776  }
1777 
1778  case 0x14: // Callback mask
1779  ei->callback_mask = buf->ReadByte();
1780  break;
1781 
1782  case 0x15: // Refit cost
1783  ei->refit_cost = buf->ReadByte();
1784  break;
1785 
1786  case 0x16: // Retire vehicle early
1787  ei->retire_early = buf->ReadByte();
1788  break;
1789 
1790  case 0x17: // Miscellaneous flags
1791  ei->misc_flags = buf->ReadByte();
1792  _loaded_newgrf_features.has_2CC |= HasBit(ei->misc_flags, EF_USES_2CC);
1793  break;
1794 
1795  case 0x18: // Cargo classes allowed
1796  _gted[e->index].cargo_allowed = buf->ReadWord();
1797  _gted[e->index].UpdateRefittability(_gted[e->index].cargo_allowed != 0);
1798  _gted[e->index].defaultcargo_grf = _cur.grffile;
1799  break;
1800 
1801  case 0x19: // Cargo classes disallowed
1802  _gted[e->index].cargo_disallowed = buf->ReadWord();
1803  _gted[e->index].UpdateRefittability(false);
1804  break;
1805 
1806  case 0x1A: // Long format introduction date (days since year 0)
1807  ei->base_intro = buf->ReadDWord();
1808  break;
1809 
1810  case 0x1B: // Alter purchase list sort order
1811  AlterVehicleListOrder(e->index, buf->ReadExtendedByte());
1812  break;
1813 
1814  case PROP_AIRCRAFT_CARGO_AGE_PERIOD: // 0x1C Cargo aging period
1815  ei->cargo_age_period = buf->ReadWord();
1816  break;
1817 
1818  case 0x1D: // CTT refit include list
1819  case 0x1E: { // CTT refit exclude list
1820  uint8 count = buf->ReadByte();
1821  _gted[e->index].UpdateRefittability(prop == 0x1D && count != 0);
1822  if (prop == 0x1D) _gted[e->index].defaultcargo_grf = _cur.grffile;
1823  CargoTypes &ctt = prop == 0x1D ? _gted[e->index].ctt_include_mask : _gted[e->index].ctt_exclude_mask;
1824  ctt = 0;
1825  while (count--) {
1826  CargoID ctype = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
1827  if (ctype == CT_INVALID) continue;
1828  SetBit(ctt, ctype);
1829  }
1830  break;
1831  }
1832 
1833  case PROP_AIRCRAFT_RANGE: // 0x1F Max aircraft range
1834  avi->max_range = buf->ReadWord();
1835  break;
1836 
1837  default:
1838  ret = CommonVehicleChangeInfo(ei, prop, buf);
1839  break;
1840  }
1841  }
1842 
1843  return ret;
1844 }
1845 
1854 static ChangeInfoResult StationChangeInfo(uint stid, int numinfo, int prop, ByteReader *buf)
1855 {
1857 
1858  if (stid + numinfo > NUM_STATIONS_PER_GRF) {
1859  grfmsg(1, "StationChangeInfo: Station %u is invalid, max %u, ignoring", stid + numinfo, NUM_STATIONS_PER_GRF);
1860  return CIR_INVALID_ID;
1861  }
1862 
1863  /* Allocate station specs if necessary */
1864  if (_cur.grffile->stations == NULL) _cur.grffile->stations = CallocT<StationSpec*>(NUM_STATIONS_PER_GRF);
1865 
1866  for (int i = 0; i < numinfo; i++) {
1867  StationSpec *statspec = _cur.grffile->stations[stid + i];
1868 
1869  /* Check that the station we are modifying is defined. */
1870  if (statspec == NULL && prop != 0x08) {
1871  grfmsg(2, "StationChangeInfo: Attempt to modify undefined station %u, ignoring", stid + i);
1872  return CIR_INVALID_ID;
1873  }
1874 
1875  switch (prop) {
1876  case 0x08: { // Class ID
1877  StationSpec **spec = &_cur.grffile->stations[stid + i];
1878 
1879  /* Property 0x08 is special; it is where the station is allocated */
1880  if (*spec == NULL) *spec = CallocT<StationSpec>(1);
1881 
1882  /* Swap classid because we read it in BE meaning WAYP or DFLT */
1883  uint32 classid = buf->ReadDWord();
1884  (*spec)->cls_id = StationClass::Allocate(BSWAP32(classid));
1885  break;
1886  }
1887 
1888  case 0x09: // Define sprite layout
1889  statspec->tiles = buf->ReadExtendedByte();
1890  delete[] statspec->renderdata; // delete earlier loaded stuff
1891  statspec->renderdata = new NewGRFSpriteLayout[statspec->tiles];
1892 
1893  for (uint t = 0; t < statspec->tiles; t++) {
1894  NewGRFSpriteLayout *dts = &statspec->renderdata[t];
1895  dts->consistent_max_offset = UINT16_MAX; // Spritesets are unknown, so no limit.
1896 
1897  if (buf->HasData(4) && *(uint32*)buf->Data() == 0) {
1898  buf->Skip(4);
1899  extern const DrawTileSprites _station_display_datas_rail[8];
1900  dts->Clone(&_station_display_datas_rail[t % 8]);
1901  continue;
1902  }
1903 
1904  ReadSpriteLayoutSprite(buf, false, false, false, GSF_STATIONS, &dts->ground);
1905  /* On error, bail out immediately. Temporary GRF data was already freed */
1906  if (_cur.skip_sprites < 0) return CIR_DISABLED;
1907 
1908  static SmallVector<DrawTileSeqStruct, 8> tmp_layout;
1909  tmp_layout.Clear();
1910  for (;;) {
1911  /* no relative bounding box support */
1912  DrawTileSeqStruct *dtss = tmp_layout.Append();
1913  MemSetT(dtss, 0);
1914 
1915  dtss->delta_x = buf->ReadByte();
1916  if (dtss->IsTerminator()) break;
1917  dtss->delta_y = buf->ReadByte();
1918  dtss->delta_z = buf->ReadByte();
1919  dtss->size_x = buf->ReadByte();
1920  dtss->size_y = buf->ReadByte();
1921  dtss->size_z = buf->ReadByte();
1922 
1923  ReadSpriteLayoutSprite(buf, false, true, false, GSF_STATIONS, &dtss->image);
1924  /* On error, bail out immediately. Temporary GRF data was already freed */
1925  if (_cur.skip_sprites < 0) return CIR_DISABLED;
1926  }
1927  dts->Clone(tmp_layout.Begin());
1928  }
1929  break;
1930 
1931  case 0x0A: { // Copy sprite layout
1932  byte srcid = buf->ReadByte();
1933  const StationSpec *srcstatspec = _cur.grffile->stations[srcid];
1934 
1935  if (srcstatspec == NULL) {
1936  grfmsg(1, "StationChangeInfo: Station %u is not defined, cannot copy sprite layout to %u.", srcid, stid + i);
1937  continue;
1938  }
1939 
1940  delete[] statspec->renderdata; // delete earlier loaded stuff
1941 
1942  statspec->tiles = srcstatspec->tiles;
1943  statspec->renderdata = new NewGRFSpriteLayout[statspec->tiles];
1944  for (uint t = 0; t < statspec->tiles; t++) {
1945  statspec->renderdata[t].Clone(&srcstatspec->renderdata[t]);
1946  }
1947  break;
1948  }
1949 
1950  case 0x0B: // Callback mask
1951  statspec->callback_mask = buf->ReadByte();
1952  break;
1953 
1954  case 0x0C: // Disallowed number of platforms
1955  statspec->disallowed_platforms = buf->ReadByte();
1956  break;
1957 
1958  case 0x0D: // Disallowed platform lengths
1959  statspec->disallowed_lengths = buf->ReadByte();
1960  break;
1961 
1962  case 0x0E: // Define custom layout
1963  statspec->copied_layouts = false;
1964 
1965  while (buf->HasData()) {
1966  byte length = buf->ReadByte();
1967  byte number = buf->ReadByte();
1968  StationLayout layout;
1969  uint l, p;
1970 
1971  if (length == 0 || number == 0) break;
1972 
1973  if (length > statspec->lengths) {
1974  byte diff_length = length - statspec->lengths;
1975  statspec->platforms = ReallocT(statspec->platforms, length);
1976  memset(statspec->platforms + statspec->lengths, 0, diff_length);
1977 
1978  statspec->layouts = ReallocT(statspec->layouts, length);
1979  memset(statspec->layouts + statspec->lengths, 0, diff_length * sizeof(*statspec->layouts));
1980 
1981  statspec->lengths = length;
1982  }
1983  l = length - 1; // index is zero-based
1984 
1985  if (number > statspec->platforms[l]) {
1986  statspec->layouts[l] = ReallocT(statspec->layouts[l], number);
1987  /* We expect NULL being 0 here, but C99 guarantees that. */
1988  memset(statspec->layouts[l] + statspec->platforms[l], 0,
1989  (number - statspec->platforms[l]) * sizeof(**statspec->layouts));
1990 
1991  statspec->platforms[l] = number;
1992  }
1993 
1994  p = 0;
1995  layout = MallocT<byte>(length * number);
1996  try {
1997  for (l = 0; l < length; l++) {
1998  for (p = 0; p < number; p++) {
1999  layout[l * number + p] = buf->ReadByte();
2000  }
2001  }
2002  } catch (...) {
2003  free(layout);
2004  throw;
2005  }
2006 
2007  l--;
2008  p--;
2009  free(statspec->layouts[l][p]);
2010  statspec->layouts[l][p] = layout;
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 == NULL) {
2019  grfmsg(1, "StationChangeInfo: Station %u is not defined, cannot copy tile layout to %u.", srcid, stid + i);
2020  continue;
2021  }
2022 
2023  statspec->lengths = srcstatspec->lengths;
2024  statspec->platforms = srcstatspec->platforms;
2025  statspec->layouts = srcstatspec->layouts;
2026  statspec->copied_layouts = true;
2027  break;
2028  }
2029 
2030  case 0x10: // Little/lots cargo threshold
2031  statspec->cargo_threshold = buf->ReadWord();
2032  break;
2033 
2034  case 0x11: // Pylon placement
2035  statspec->pylons = buf->ReadByte();
2036  break;
2037 
2038  case 0x12: // Cargo types for random triggers
2039  if (_cur.grffile->grf_version >= 7) {
2040  statspec->cargo_triggers = TranslateRefitMask(buf->ReadDWord());
2041  } else {
2042  statspec->cargo_triggers = (CargoTypes)buf->ReadDWord();
2043  }
2044  break;
2045 
2046  case 0x13: // General flags
2047  statspec->flags = buf->ReadByte();
2048  break;
2049 
2050  case 0x14: // Overhead wire placement
2051  statspec->wires = buf->ReadByte();
2052  break;
2053 
2054  case 0x15: // Blocked tiles
2055  statspec->blocked = buf->ReadByte();
2056  break;
2057 
2058  case 0x16: // Animation info
2059  statspec->animation.frames = buf->ReadByte();
2060  statspec->animation.status = buf->ReadByte();
2061  break;
2062 
2063  case 0x17: // Animation speed
2064  statspec->animation.speed = buf->ReadByte();
2065  break;
2066 
2067  case 0x18: // Animation triggers
2068  statspec->animation.triggers = buf->ReadWord();
2069  break;
2070 
2071  case 0x1A: // Advanced sprite layout
2072  statspec->tiles = buf->ReadExtendedByte();
2073  delete[] statspec->renderdata; // delete earlier loaded stuff
2074  statspec->renderdata = new NewGRFSpriteLayout[statspec->tiles];
2075 
2076  for (uint t = 0; t < statspec->tiles; t++) {
2077  NewGRFSpriteLayout *dts = &statspec->renderdata[t];
2078  uint num_building_sprites = buf->ReadByte();
2079  /* On error, bail out immediately. Temporary GRF data was already freed */
2080  if (ReadSpriteLayout(buf, num_building_sprites, false, GSF_STATIONS, true, false, dts)) return CIR_DISABLED;
2081  }
2082  break;
2083 
2084  default:
2085  ret = CIR_UNKNOWN;
2086  break;
2087  }
2088  }
2089 
2090  return ret;
2091 }
2092 
2101 static ChangeInfoResult CanalChangeInfo(uint id, int numinfo, int prop, ByteReader *buf)
2102 {
2104 
2105  if (id + numinfo > CF_END) {
2106  grfmsg(1, "CanalChangeInfo: Canal feature %u is invalid, max %u, ignoring", id + numinfo, CF_END);
2107  return CIR_INVALID_ID;
2108  }
2109 
2110  for (int i = 0; i < numinfo; i++) {
2111  CanalProperties *cp = &_cur.grffile->canal_local_properties[id + i];
2112 
2113  switch (prop) {
2114  case 0x08:
2115  cp->callback_mask = buf->ReadByte();
2116  break;
2117 
2118  case 0x09:
2119  cp->flags = buf->ReadByte();
2120  break;
2121 
2122  default:
2123  ret = CIR_UNKNOWN;
2124  break;
2125  }
2126  }
2127 
2128  return ret;
2129 }
2130 
2139 static ChangeInfoResult BridgeChangeInfo(uint brid, int numinfo, int prop, ByteReader *buf)
2140 {
2142 
2143  if (brid + numinfo > MAX_BRIDGES) {
2144  grfmsg(1, "BridgeChangeInfo: Bridge %u is invalid, max %u, ignoring", brid + numinfo, MAX_BRIDGES);
2145  return CIR_INVALID_ID;
2146  }
2147 
2148  for (int i = 0; i < numinfo; i++) {
2149  BridgeSpec *bridge = &_bridge[brid + i];
2150 
2151  switch (prop) {
2152  case 0x08: { // Year of availability
2153  /* We treat '0' as always available */
2154  byte year = buf->ReadByte();
2155  bridge->avail_year = (year > 0 ? ORIGINAL_BASE_YEAR + year : 0);
2156  break;
2157  }
2158 
2159  case 0x09: // Minimum length
2160  bridge->min_length = buf->ReadByte();
2161  break;
2162 
2163  case 0x0A: // Maximum length
2164  bridge->max_length = buf->ReadByte();
2165  if (bridge->max_length > 16) bridge->max_length = 0xFFFF;
2166  break;
2167 
2168  case 0x0B: // Cost factor
2169  bridge->price = buf->ReadByte();
2170  break;
2171 
2172  case 0x0C: // Maximum speed
2173  bridge->speed = buf->ReadWord();
2174  break;
2175 
2176  case 0x0D: { // Bridge sprite tables
2177  byte tableid = buf->ReadByte();
2178  byte numtables = buf->ReadByte();
2179 
2180  if (bridge->sprite_table == NULL) {
2181  /* Allocate memory for sprite table pointers and zero out */
2182  bridge->sprite_table = CallocT<PalSpriteID*>(7);
2183  }
2184 
2185  for (; numtables-- != 0; tableid++) {
2186  if (tableid >= 7) { // skip invalid data
2187  grfmsg(1, "BridgeChangeInfo: Table %d >= 7, skipping", tableid);
2188  for (byte sprite = 0; sprite < 32; sprite++) buf->ReadDWord();
2189  continue;
2190  }
2191 
2192  if (bridge->sprite_table[tableid] == NULL) {
2193  bridge->sprite_table[tableid] = MallocT<PalSpriteID>(32);
2194  }
2195 
2196  for (byte sprite = 0; sprite < 32; sprite++) {
2197  SpriteID image = buf->ReadWord();
2198  PaletteID pal = buf->ReadWord();
2199 
2200  bridge->sprite_table[tableid][sprite].sprite = image;
2201  bridge->sprite_table[tableid][sprite].pal = pal;
2202 
2203  MapSpriteMappingRecolour(&bridge->sprite_table[tableid][sprite]);
2204  }
2205  }
2206  break;
2207  }
2208 
2209  case 0x0E: // Flags; bit 0 - disable far pillars
2210  bridge->flags = buf->ReadByte();
2211  break;
2212 
2213  case 0x0F: // Long format year of availability (year since year 0)
2214  bridge->avail_year = Clamp(buf->ReadDWord(), MIN_YEAR, MAX_YEAR);
2215  break;
2216 
2217  case 0x10: { // purchase string
2218  StringID newone = GetGRFStringID(_cur.grffile->grfid, buf->ReadWord());
2219  if (newone != STR_UNDEFINED) bridge->material = newone;
2220  break;
2221  }
2222 
2223  case 0x11: // description of bridge with rails or roads
2224  case 0x12: {
2225  StringID newone = GetGRFStringID(_cur.grffile->grfid, buf->ReadWord());
2226  if (newone != STR_UNDEFINED) bridge->transport_name[prop - 0x11] = newone;
2227  break;
2228  }
2229 
2230  case 0x13: // 16 bits cost multiplier
2231  bridge->price = buf->ReadWord();
2232  break;
2233 
2234  default:
2235  ret = CIR_UNKNOWN;
2236  break;
2237  }
2238  }
2239 
2240  return ret;
2241 }
2242 
2250 {
2252 
2253  switch (prop) {
2254  case 0x09:
2255  case 0x0B:
2256  case 0x0C:
2257  case 0x0D:
2258  case 0x0E:
2259  case 0x0F:
2260  case 0x11:
2261  case 0x14:
2262  case 0x15:
2263  case 0x16:
2264  case 0x18:
2265  case 0x19:
2266  case 0x1A:
2267  case 0x1B:
2268  case 0x1C:
2269  case 0x1D:
2270  case 0x1F:
2271  buf->ReadByte();
2272  break;
2273 
2274  case 0x0A:
2275  case 0x10:
2276  case 0x12:
2277  case 0x13:
2278  case 0x21:
2279  case 0x22:
2280  buf->ReadWord();
2281  break;
2282 
2283  case 0x1E:
2284  buf->ReadDWord();
2285  break;
2286 
2287  case 0x17:
2288  for (uint j = 0; j < 4; j++) buf->ReadByte();
2289  break;
2290 
2291  case 0x20: {
2292  byte count = buf->ReadByte();
2293  for (byte j = 0; j < count; j++) buf->ReadByte();
2294  break;
2295  }
2296 
2297  case 0x23:
2298  buf->Skip(buf->ReadByte() * 2);
2299  break;
2300 
2301  default:
2302  ret = CIR_UNKNOWN;
2303  break;
2304  }
2305  return ret;
2306 }
2307 
2316 static ChangeInfoResult TownHouseChangeInfo(uint hid, int numinfo, int prop, ByteReader *buf)
2317 {
2319 
2320  if (hid + numinfo > NUM_HOUSES_PER_GRF) {
2321  grfmsg(1, "TownHouseChangeInfo: Too many houses loaded (%u), max (%u). Ignoring.", hid + numinfo, NUM_HOUSES_PER_GRF);
2322  return CIR_INVALID_ID;
2323  }
2324 
2325  /* Allocate house specs if they haven't been allocated already. */
2326  if (_cur.grffile->housespec == NULL) {
2327  _cur.grffile->housespec = CallocT<HouseSpec*>(NUM_HOUSES_PER_GRF);
2328  }
2329 
2330  for (int i = 0; i < numinfo; i++) {
2331  HouseSpec *housespec = _cur.grffile->housespec[hid + i];
2332 
2333  if (prop != 0x08 && housespec == NULL) {
2334  /* If the house property 08 is not yet set, ignore this property */
2335  ChangeInfoResult cir = IgnoreTownHouseProperty(prop, buf);
2336  if (cir > ret) ret = cir;
2337  continue;
2338  }
2339 
2340  switch (prop) {
2341  case 0x08: { // Substitute building type, and definition of a new house
2342  HouseSpec **house = &_cur.grffile->housespec[hid + i];
2343  byte subs_id = buf->ReadByte();
2344 
2345  if (subs_id == 0xFF) {
2346  /* Instead of defining a new house, a substitute house id
2347  * of 0xFF disables the old house with the current id. */
2348  HouseSpec::Get(hid + i)->enabled = false;
2349  continue;
2350  } else if (subs_id >= NEW_HOUSE_OFFSET) {
2351  /* The substitute id must be one of the original houses. */
2352  grfmsg(2, "TownHouseChangeInfo: Attempt to use new house %u as substitute house for %u. Ignoring.", subs_id, hid + i);
2353  continue;
2354  }
2355 
2356  /* Allocate space for this house. */
2357  if (*house == NULL) *house = CallocT<HouseSpec>(1);
2358 
2359  housespec = *house;
2360 
2361  MemCpyT(housespec, HouseSpec::Get(subs_id));
2362 
2363  housespec->enabled = true;
2364  housespec->grf_prop.local_id = hid + i;
2365  housespec->grf_prop.subst_id = subs_id;
2366  housespec->grf_prop.grffile = _cur.grffile;
2367  housespec->random_colour[0] = 0x04; // those 4 random colours are the base colour
2368  housespec->random_colour[1] = 0x08; // for all new houses
2369  housespec->random_colour[2] = 0x0C; // they stand for red, blue, orange and green
2370  housespec->random_colour[3] = 0x06;
2371 
2372  /* Make sure that the third cargo type is valid in this
2373  * climate. This can cause problems when copying the properties
2374  * of a house that accepts food, where the new house is valid
2375  * in the temperate climate. */
2376  if (!CargoSpec::Get(housespec->accepts_cargo[2])->IsValid()) {
2377  housespec->cargo_acceptance[2] = 0;
2378  }
2379 
2380  _loaded_newgrf_features.has_newhouses = true;
2381  break;
2382  }
2383 
2384  case 0x09: // Building flags
2385  housespec->building_flags = (BuildingFlags)buf->ReadByte();
2386  break;
2387 
2388  case 0x0A: { // Availability years
2389  uint16 years = buf->ReadWord();
2390  housespec->min_year = GB(years, 0, 8) > 150 ? MAX_YEAR : ORIGINAL_BASE_YEAR + GB(years, 0, 8);
2391  housespec->max_year = GB(years, 8, 8) > 150 ? MAX_YEAR : ORIGINAL_BASE_YEAR + GB(years, 8, 8);
2392  break;
2393  }
2394 
2395  case 0x0B: // Population
2396  housespec->population = buf->ReadByte();
2397  break;
2398 
2399  case 0x0C: // Mail generation multiplier
2400  housespec->mail_generation = buf->ReadByte();
2401  break;
2402 
2403  case 0x0D: // Passenger acceptance
2404  case 0x0E: // Mail acceptance
2405  housespec->cargo_acceptance[prop - 0x0D] = buf->ReadByte();
2406  break;
2407 
2408  case 0x0F: { // Goods/candy, food/fizzy drinks acceptance
2409  int8 goods = buf->ReadByte();
2410 
2411  /* If value of goods is negative, it means in fact food or, if in toyland, fizzy_drink acceptance.
2412  * Else, we have "standard" 3rd cargo type, goods or candy, for toyland once more */
2413  CargoID cid = (goods >= 0) ? ((_settings_game.game_creation.landscape == LT_TOYLAND) ? CT_CANDY : CT_GOODS) :
2414  ((_settings_game.game_creation.landscape == LT_TOYLAND) ? CT_FIZZY_DRINKS : CT_FOOD);
2415 
2416  /* Make sure the cargo type is valid in this climate. */
2417  if (!CargoSpec::Get(cid)->IsValid()) goods = 0;
2418 
2419  housespec->accepts_cargo[2] = cid;
2420  housespec->cargo_acceptance[2] = abs(goods); // but we do need positive value here
2421  break;
2422  }
2423 
2424  case 0x10: // Local authority rating decrease on removal
2425  housespec->remove_rating_decrease = buf->ReadWord();
2426  break;
2427 
2428  case 0x11: // Removal cost multiplier
2429  housespec->removal_cost = buf->ReadByte();
2430  break;
2431 
2432  case 0x12: // Building name ID
2433  AddStringForMapping(buf->ReadWord(), &housespec->building_name);
2434  break;
2435 
2436  case 0x13: // Building availability mask
2437  housespec->building_availability = (HouseZones)buf->ReadWord();
2438  break;
2439 
2440  case 0x14: // House callback mask
2441  housespec->callback_mask |= buf->ReadByte();
2442  break;
2443 
2444  case 0x15: { // House override byte
2445  byte override = buf->ReadByte();
2446 
2447  /* The house being overridden must be an original house. */
2448  if (override >= NEW_HOUSE_OFFSET) {
2449  grfmsg(2, "TownHouseChangeInfo: Attempt to override new house %u with house id %u. Ignoring.", override, hid + i);
2450  continue;
2451  }
2452 
2453  _house_mngr.Add(hid + i, _cur.grffile->grfid, override);
2454  break;
2455  }
2456 
2457  case 0x16: // Periodic refresh multiplier
2458  housespec->processing_time = min(buf->ReadByte(), 63);
2459  break;
2460 
2461  case 0x17: // Four random colours to use
2462  for (uint j = 0; j < 4; j++) housespec->random_colour[j] = buf->ReadByte();
2463  break;
2464 
2465  case 0x18: // Relative probability of appearing
2466  housespec->probability = buf->ReadByte();
2467  break;
2468 
2469  case 0x19: // Extra flags
2470  housespec->extra_flags = (HouseExtraFlags)buf->ReadByte();
2471  break;
2472 
2473  case 0x1A: // Animation frames
2474  housespec->animation.frames = buf->ReadByte();
2475  housespec->animation.status = GB(housespec->animation.frames, 7, 1);
2476  SB(housespec->animation.frames, 7, 1, 0);
2477  break;
2478 
2479  case 0x1B: // Animation speed
2480  housespec->animation.speed = Clamp(buf->ReadByte(), 2, 16);
2481  break;
2482 
2483  case 0x1C: // Class of the building type
2484  housespec->class_id = AllocateHouseClassID(buf->ReadByte(), _cur.grffile->grfid);
2485  break;
2486 
2487  case 0x1D: // Callback mask part 2
2488  housespec->callback_mask |= (buf->ReadByte() << 8);
2489  break;
2490 
2491  case 0x1E: { // Accepted cargo types
2492  uint32 cargotypes = buf->ReadDWord();
2493 
2494  /* Check if the cargo types should not be changed */
2495  if (cargotypes == 0xFFFFFFFF) break;
2496 
2497  for (uint j = 0; j < 3; j++) {
2498  /* Get the cargo number from the 'list' */
2499  uint8 cargo_part = GB(cargotypes, 8 * j, 8);
2500  CargoID cargo = GetCargoTranslation(cargo_part, _cur.grffile);
2501 
2502  if (cargo == CT_INVALID) {
2503  /* Disable acceptance of invalid cargo type */
2504  housespec->cargo_acceptance[j] = 0;
2505  } else {
2506  housespec->accepts_cargo[j] = cargo;
2507  }
2508  }
2509  break;
2510  }
2511 
2512  case 0x1F: // Minimum life span
2513  housespec->minimum_life = buf->ReadByte();
2514  break;
2515 
2516  case 0x20: { // Cargo acceptance watch list
2517  byte count = buf->ReadByte();
2518  for (byte j = 0; j < count; j++) {
2519  CargoID cargo = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
2520  if (cargo != CT_INVALID) SetBit(housespec->watched_cargoes, cargo);
2521  }
2522  break;
2523  }
2524 
2525  case 0x21: // long introduction year
2526  housespec->min_year = buf->ReadWord();
2527  break;
2528 
2529  case 0x22: // long maximum year
2530  housespec->max_year = buf->ReadWord();
2531  break;
2532 
2533  case 0x23: { // variable length cargo types accepted
2534  uint count = buf->ReadByte();
2535  if (count > lengthof(housespec->accepts_cargo)) {
2536  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
2537  error->param_value[1] = prop;
2538  return CIR_DISABLED;
2539  }
2540  /* Always write the full accepts_cargo array, and check each index for being inside the
2541  * provided data. This ensures all values are properly initialized, and also avoids
2542  * any risks of array overrun. */
2543  for (uint i = 0; i < lengthof(housespec->accepts_cargo); i++) {
2544  if (i < count) {
2545  housespec->accepts_cargo[i] = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
2546  housespec->cargo_acceptance[i] = buf->ReadByte();
2547  } else {
2548  housespec->accepts_cargo[i] = CT_INVALID;
2549  housespec->cargo_acceptance[i] = 0;
2550  }
2551  }
2552  break;
2553  }
2554 
2555  default:
2556  ret = CIR_UNKNOWN;
2557  break;
2558  }
2559  }
2560 
2561  return ret;
2562 }
2563 
2570 /* static */ const LanguageMap *LanguageMap::GetLanguageMap(uint32 grfid, uint8 language_id)
2571 {
2572  /* LanguageID "MAX_LANG", i.e. 7F is any. This language can't have a gender/case mapping, but has to be handled gracefully. */
2573  const GRFFile *grffile = GetFileByGRFID(grfid);
2574  return (grffile != NULL && grffile->language_map != NULL && language_id < MAX_LANG) ? &grffile->language_map[language_id] : NULL;
2575 }
2576 
2586 template <typename T>
2587 static ChangeInfoResult LoadTranslationTable(uint gvid, int numinfo, ByteReader *buf, T &translation_table, const char *name)
2588 {
2589  if (gvid != 0) {
2590  grfmsg(1, "LoadTranslationTable: %s translation table must start at zero", name);
2591  return CIR_INVALID_ID;
2592  }
2593 
2594  translation_table.Clear();
2595  for (int i = 0; i < numinfo; i++) {
2596  uint32 item = buf->ReadDWord();
2597  *translation_table.Append() = BSWAP32(item);
2598  }
2599 
2600  return CIR_SUCCESS;
2601 }
2602 
2611 static ChangeInfoResult GlobalVarChangeInfo(uint gvid, int numinfo, int prop, ByteReader *buf)
2612 {
2613  /* Properties which are handled as a whole */
2614  switch (prop) {
2615  case 0x09: // Cargo Translation Table; loading during both reservation and activation stage (in case it is selected depending on defined cargos)
2616  return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->cargo_list, "Cargo");
2617 
2618  case 0x12: // Rail type translation table; loading during both reservation and activation stage (in case it is selected depending on defined railtypes)
2619  return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->railtype_list, "Rail type");
2620 
2621  default:
2622  break;
2623  }
2624 
2625  /* Properties which are handled per item */
2627  for (int i = 0; i < numinfo; i++) {
2628  switch (prop) {
2629  case 0x08: { // Cost base factor
2630  int factor = buf->ReadByte();
2631  uint price = gvid + i;
2632 
2633  if (price < PR_END) {
2634  _cur.grffile->price_base_multipliers[price] = min<int>(factor - 8, MAX_PRICE_MODIFIER);
2635  } else {
2636  grfmsg(1, "GlobalVarChangeInfo: Price %d out of range, ignoring", price);
2637  }
2638  break;
2639  }
2640 
2641  case 0x0A: { // Currency display names
2642  uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
2643  StringID newone = GetGRFStringID(_cur.grffile->grfid, buf->ReadWord());
2644 
2645  if ((newone != STR_UNDEFINED) && (curidx < CURRENCY_END)) {
2646  _currency_specs[curidx].name = newone;
2647  }
2648  break;
2649  }
2650 
2651  case 0x0B: { // Currency multipliers
2652  uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
2653  uint32 rate = buf->ReadDWord();
2654 
2655  if (curidx < CURRENCY_END) {
2656  /* TTDPatch uses a multiple of 1000 for its conversion calculations,
2657  * which OTTD does not. For this reason, divide grf value by 1000,
2658  * to be compatible */
2659  _currency_specs[curidx].rate = rate / 1000;
2660  } else {
2661  grfmsg(1, "GlobalVarChangeInfo: Currency multipliers %d out of range, ignoring", curidx);
2662  }
2663  break;
2664  }
2665 
2666  case 0x0C: { // Currency options
2667  uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
2668  uint16 options = buf->ReadWord();
2669 
2670  if (curidx < CURRENCY_END) {
2671  _currency_specs[curidx].separator[0] = GB(options, 0, 8);
2672  _currency_specs[curidx].separator[1] = '\0';
2673  /* By specifying only one bit, we prevent errors,
2674  * since newgrf specs said that only 0 and 1 can be set for symbol_pos */
2675  _currency_specs[curidx].symbol_pos = GB(options, 8, 1);
2676  } else {
2677  grfmsg(1, "GlobalVarChangeInfo: Currency option %d out of range, ignoring", curidx);
2678  }
2679  break;
2680  }
2681 
2682  case 0x0D: { // Currency prefix symbol
2683  uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
2684  uint32 tempfix = buf->ReadDWord();
2685 
2686  if (curidx < CURRENCY_END) {
2687  memcpy(_currency_specs[curidx].prefix, &tempfix, 4);
2688  _currency_specs[curidx].prefix[4] = 0;
2689  } else {
2690  grfmsg(1, "GlobalVarChangeInfo: Currency symbol %d out of range, ignoring", curidx);
2691  }
2692  break;
2693  }
2694 
2695  case 0x0E: { // Currency suffix symbol
2696  uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
2697  uint32 tempfix = buf->ReadDWord();
2698 
2699  if (curidx < CURRENCY_END) {
2700  memcpy(&_currency_specs[curidx].suffix, &tempfix, 4);
2701  _currency_specs[curidx].suffix[4] = 0;
2702  } else {
2703  grfmsg(1, "GlobalVarChangeInfo: Currency symbol %d out of range, ignoring", curidx);
2704  }
2705  break;
2706  }
2707 
2708  case 0x0F: { // Euro introduction dates
2709  uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
2710  Year year_euro = buf->ReadWord();
2711 
2712  if (curidx < CURRENCY_END) {
2713  _currency_specs[curidx].to_euro = year_euro;
2714  } else {
2715  grfmsg(1, "GlobalVarChangeInfo: Euro intro date %d out of range, ignoring", curidx);
2716  }
2717  break;
2718  }
2719 
2720  case 0x10: // Snow line height table
2721  if (numinfo > 1 || IsSnowLineSet()) {
2722  grfmsg(1, "GlobalVarChangeInfo: The snowline can only be set once (%d)", numinfo);
2723  } else if (buf->Remaining() < SNOW_LINE_MONTHS * SNOW_LINE_DAYS) {
2724  grfmsg(1, "GlobalVarChangeInfo: Not enough entries set in the snowline table (" PRINTF_SIZE ")", buf->Remaining());
2725  } else {
2726  byte table[SNOW_LINE_MONTHS][SNOW_LINE_DAYS];
2727 
2728  for (uint i = 0; i < SNOW_LINE_MONTHS; i++) {
2729  for (uint j = 0; j < SNOW_LINE_DAYS; j++) {
2730  table[i][j] = buf->ReadByte();
2731  if (_cur.grffile->grf_version >= 8) {
2732  if (table[i][j] != 0xFF) table[i][j] = table[i][j] * (1 + _settings_game.construction.max_heightlevel) / 256;
2733  } else {
2734  if (table[i][j] >= 128) {
2735  /* no snow */
2736  table[i][j] = 0xFF;
2737  } else {
2738  table[i][j] = table[i][j] * (1 + _settings_game.construction.max_heightlevel) / 128;
2739  }
2740  }
2741  }
2742  }
2743  SetSnowLine(table);
2744  }
2745  break;
2746 
2747  case 0x11: // GRF match for engine allocation
2748  /* This is loaded during the reservation stage, so just skip it here. */
2749  /* Each entry is 8 bytes. */
2750  buf->Skip(8);
2751  break;
2752 
2753  case 0x13: // Gender translation table
2754  case 0x14: // Case translation table
2755  case 0x15: { // Plural form translation
2756  uint curidx = gvid + i; // The current index, i.e. language.
2757  const LanguageMetadata *lang = curidx < MAX_LANG ? GetLanguage(curidx) : NULL;
2758  if (lang == NULL) {
2759  grfmsg(1, "GlobalVarChangeInfo: Language %d is not known, ignoring", curidx);
2760  /* Skip over the data. */
2761  if (prop == 0x15) {
2762  buf->ReadByte();
2763  } else {
2764  while (buf->ReadByte() != 0) {
2765  buf->ReadString();
2766  }
2767  }
2768  break;
2769  }
2770 
2771  if (_cur.grffile->language_map == NULL) _cur.grffile->language_map = new LanguageMap[MAX_LANG];
2772 
2773  if (prop == 0x15) {
2774  uint plural_form = buf->ReadByte();
2775  if (plural_form >= LANGUAGE_MAX_PLURAL) {
2776  grfmsg(1, "GlobalVarChanceInfo: Plural form %d is out of range, ignoring", plural_form);
2777  } else {
2778  _cur.grffile->language_map[curidx].plural_form = plural_form;
2779  }
2780  break;
2781  }
2782 
2783  byte newgrf_id = buf->ReadByte(); // The NewGRF (custom) identifier.
2784  while (newgrf_id != 0) {
2785  const char *name = buf->ReadString(); // The name for the OpenTTD identifier.
2786 
2787  /* We'll just ignore the UTF8 identifier character. This is (fairly)
2788  * safe as OpenTTD's strings gender/cases are usually in ASCII which
2789  * is just a subset of UTF8, or they need the bigger UTF8 characters
2790  * such as Cyrillic. Thus we will simply assume they're all UTF8. */
2791  WChar c;
2792  size_t len = Utf8Decode(&c, name);
2793  if (c == NFO_UTF8_IDENTIFIER) name += len;
2794 
2796  map.newgrf_id = newgrf_id;
2797  if (prop == 0x13) {
2798  map.openttd_id = lang->GetGenderIndex(name);
2799  if (map.openttd_id >= MAX_NUM_GENDERS) {
2800  grfmsg(1, "GlobalVarChangeInfo: Gender name %s is not known, ignoring", name);
2801  } else {
2802  *_cur.grffile->language_map[curidx].gender_map.Append() = map;
2803  }
2804  } else {
2805  map.openttd_id = lang->GetCaseIndex(name);
2806  if (map.openttd_id >= MAX_NUM_CASES) {
2807  grfmsg(1, "GlobalVarChangeInfo: Case name %s is not known, ignoring", name);
2808  } else {
2809  *_cur.grffile->language_map[curidx].case_map.Append() = map;
2810  }
2811  }
2812  newgrf_id = buf->ReadByte();
2813  }
2814  break;
2815  }
2816 
2817  default:
2818  ret = CIR_UNKNOWN;
2819  break;
2820  }
2821  }
2822 
2823  return ret;
2824 }
2825 
2826 static ChangeInfoResult GlobalVarReserveInfo(uint gvid, int numinfo, int prop, ByteReader *buf)
2827 {
2828  /* Properties which are handled as a whole */
2829  switch (prop) {
2830  case 0x09: // Cargo Translation Table; loading during both reservation and activation stage (in case it is selected depending on defined cargos)
2831  return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->cargo_list, "Cargo");
2832 
2833  case 0x12: // Rail type translation table; loading during both reservation and activation stage (in case it is selected depending on defined railtypes)
2834  return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->railtype_list, "Rail type");
2835 
2836  default:
2837  break;
2838  }
2839 
2840  /* Properties which are handled per item */
2842  for (int i = 0; i < numinfo; i++) {
2843  switch (prop) {
2844  case 0x08: // Cost base factor
2845  case 0x15: // Plural form translation
2846  buf->ReadByte();
2847  break;
2848 
2849  case 0x0A: // Currency display names
2850  case 0x0C: // Currency options
2851  case 0x0F: // Euro introduction dates
2852  buf->ReadWord();
2853  break;
2854 
2855  case 0x0B: // Currency multipliers
2856  case 0x0D: // Currency prefix symbol
2857  case 0x0E: // Currency suffix symbol
2858  buf->ReadDWord();
2859  break;
2860 
2861  case 0x10: // Snow line height table
2862  buf->Skip(SNOW_LINE_MONTHS * SNOW_LINE_DAYS);
2863  break;
2864 
2865  case 0x11: { // GRF match for engine allocation
2866  uint32 s = buf->ReadDWord();
2867  uint32 t = buf->ReadDWord();
2868  SetNewGRFOverride(s, t);
2869  break;
2870  }
2871 
2872  case 0x13: // Gender translation table
2873  case 0x14: // Case translation table
2874  while (buf->ReadByte() != 0) {
2875  buf->ReadString();
2876  }
2877  break;
2878 
2879  default:
2880  ret = CIR_UNKNOWN;
2881  break;
2882  }
2883  }
2884 
2885  return ret;
2886 }
2887 
2888 
2897 static ChangeInfoResult CargoChangeInfo(uint cid, int numinfo, int prop, ByteReader *buf)
2898 {
2900 
2901  if (cid + numinfo > NUM_CARGO) {
2902  grfmsg(2, "CargoChangeInfo: Cargo type %d out of range (max %d)", cid + numinfo, NUM_CARGO - 1);
2903  return CIR_INVALID_ID;
2904  }
2905 
2906  for (int i = 0; i < numinfo; i++) {
2907  CargoSpec *cs = CargoSpec::Get(cid + i);
2908 
2909  switch (prop) {
2910  case 0x08: // Bit number of cargo
2911  cs->bitnum = buf->ReadByte();
2912  if (cs->IsValid()) {
2913  cs->grffile = _cur.grffile;
2914  SetBit(_cargo_mask, cid + i);
2915  } else {
2916  ClrBit(_cargo_mask, cid + i);
2917  }
2918  break;
2919 
2920  case 0x09: // String ID for cargo type name
2921  AddStringForMapping(buf->ReadWord(), &cs->name);
2922  break;
2923 
2924  case 0x0A: // String for 1 unit of cargo
2925  AddStringForMapping(buf->ReadWord(), &cs->name_single);
2926  break;
2927 
2928  case 0x0B: // String for singular quantity of cargo (e.g. 1 tonne of coal)
2929  case 0x1B: // String for cargo units
2930  /* String for units of cargo. This is different in OpenTTD
2931  * (e.g. tonnes) to TTDPatch (e.g. {COMMA} tonne of coal).
2932  * Property 1B is used to set OpenTTD's behaviour. */
2933  AddStringForMapping(buf->ReadWord(), &cs->units_volume);
2934  break;
2935 
2936  case 0x0C: // String for plural quantity of cargo (e.g. 10 tonnes of coal)
2937  case 0x1C: // String for any amount of cargo
2938  /* Strings for an amount of cargo. This is different in OpenTTD
2939  * (e.g. {WEIGHT} of coal) to TTDPatch (e.g. {COMMA} tonnes of coal).
2940  * Property 1C is used to set OpenTTD's behaviour. */
2941  AddStringForMapping(buf->ReadWord(), &cs->quantifier);
2942  break;
2943 
2944  case 0x0D: // String for two letter cargo abbreviation
2945  AddStringForMapping(buf->ReadWord(), &cs->abbrev);
2946  break;
2947 
2948  case 0x0E: // Sprite ID for cargo icon
2949  cs->sprite = buf->ReadWord();
2950  break;
2951 
2952  case 0x0F: // Weight of one unit of cargo
2953  cs->weight = buf->ReadByte();
2954  break;
2955 
2956  case 0x10: // Used for payment calculation
2957  cs->transit_days[0] = buf->ReadByte();
2958  break;
2959 
2960  case 0x11: // Used for payment calculation
2961  cs->transit_days[1] = buf->ReadByte();
2962  break;
2963 
2964  case 0x12: // Base cargo price
2965  cs->initial_payment = buf->ReadDWord();
2966  break;
2967 
2968  case 0x13: // Colour for station rating bars
2969  cs->rating_colour = buf->ReadByte();
2970  break;
2971 
2972  case 0x14: // Colour for cargo graph
2973  cs->legend_colour = buf->ReadByte();
2974  break;
2975 
2976  case 0x15: // Freight status
2977  cs->is_freight = (buf->ReadByte() != 0);
2978  break;
2979 
2980  case 0x16: // Cargo classes
2981  cs->classes = buf->ReadWord();
2982  break;
2983 
2984  case 0x17: // Cargo label
2985  cs->label = buf->ReadDWord();
2986  cs->label = BSWAP32(cs->label);
2987  break;
2988 
2989  case 0x18: { // Town growth substitute type
2990  uint8 substitute_type = buf->ReadByte();
2991 
2992  switch (substitute_type) {
2993  case 0x00: cs->town_effect = TE_PASSENGERS; break;
2994  case 0x02: cs->town_effect = TE_MAIL; break;
2995  case 0x05: cs->town_effect = TE_GOODS; break;
2996  case 0x09: cs->town_effect = TE_WATER; break;
2997  case 0x0B: cs->town_effect = TE_FOOD; break;
2998  default:
2999  grfmsg(1, "CargoChangeInfo: Unknown town growth substitute value %d, setting to none.", substitute_type);
3000  FALLTHROUGH;
3001  case 0xFF: cs->town_effect = TE_NONE; break;
3002  }
3003  break;
3004  }
3005 
3006  case 0x19: // Town growth coefficient
3007  cs->multipliertowngrowth = buf->ReadWord();
3008  break;
3009 
3010  case 0x1A: // Bitmask of callbacks to use
3011  cs->callback_mask = buf->ReadByte();
3012  break;
3013 
3014  case 0x1D: // Vehicle capacity muliplier
3015  cs->multiplier = max<uint16>(1u, buf->ReadWord());
3016  break;
3017 
3018  default:
3019  ret = CIR_UNKNOWN;
3020  break;
3021  }
3022  }
3023 
3024  return ret;
3025 }
3026 
3027 
3036 static ChangeInfoResult SoundEffectChangeInfo(uint sid, int numinfo, int prop, ByteReader *buf)
3037 {
3039 
3040  if (_cur.grffile->sound_offset == 0) {
3041  grfmsg(1, "SoundEffectChangeInfo: No effects defined, skipping");
3042  return CIR_INVALID_ID;
3043  }
3044 
3045  if (sid + numinfo - ORIGINAL_SAMPLE_COUNT > _cur.grffile->num_sounds) {
3046  grfmsg(1, "SoundEffectChangeInfo: Attempting to change undefined sound effect (%u), max (%u). Ignoring.", sid + numinfo, ORIGINAL_SAMPLE_COUNT + _cur.grffile->num_sounds);
3047  return CIR_INVALID_ID;
3048  }
3049 
3050  for (int i = 0; i < numinfo; i++) {
3051  SoundEntry *sound = GetSound(sid + i + _cur.grffile->sound_offset - ORIGINAL_SAMPLE_COUNT);
3052 
3053  switch (prop) {
3054  case 0x08: // Relative volume
3055  sound->volume = buf->ReadByte();
3056  break;
3057 
3058  case 0x09: // Priority
3059  sound->priority = buf->ReadByte();
3060  break;
3061 
3062  case 0x0A: { // Override old sound
3063  SoundID orig_sound = buf->ReadByte();
3064 
3065  if (orig_sound >= ORIGINAL_SAMPLE_COUNT) {
3066  grfmsg(1, "SoundEffectChangeInfo: Original sound %d not defined (max %d)", orig_sound, ORIGINAL_SAMPLE_COUNT);
3067  } else {
3068  SoundEntry *old_sound = GetSound(orig_sound);
3069 
3070  /* Literally copy the data of the new sound over the original */
3071  *old_sound = *sound;
3072  }
3073  break;
3074  }
3075 
3076  default:
3077  ret = CIR_UNKNOWN;
3078  break;
3079  }
3080  }
3081 
3082  return ret;
3083 }
3084 
3092 {
3094 
3095  switch (prop) {
3096  case 0x09:
3097  case 0x0D:
3098  case 0x0E:
3099  case 0x10:
3100  case 0x11:
3101  case 0x12:
3102  buf->ReadByte();
3103  break;
3104 
3105  case 0x0A:
3106  case 0x0B:
3107  case 0x0C:
3108  case 0x0F:
3109  buf->ReadWord();
3110  break;
3111 
3112  case 0x13:
3113  buf->Skip(buf->ReadByte() * 2);
3114  break;
3115 
3116  default:
3117  ret = CIR_UNKNOWN;
3118  break;
3119  }
3120  return ret;
3121 }
3122 
3131 static ChangeInfoResult IndustrytilesChangeInfo(uint indtid, int numinfo, int prop, ByteReader *buf)
3132 {
3134 
3135  if (indtid + numinfo > NUM_INDUSTRYTILES_PER_GRF) {
3136  grfmsg(1, "IndustryTilesChangeInfo: Too many industry tiles loaded (%u), max (%u). Ignoring.", indtid + numinfo, NUM_INDUSTRYTILES_PER_GRF);
3137  return CIR_INVALID_ID;
3138  }
3139 
3140  /* Allocate industry tile specs if they haven't been allocated already. */
3141  if (_cur.grffile->indtspec == NULL) {
3142  _cur.grffile->indtspec = CallocT<IndustryTileSpec*>(NUM_INDUSTRYTILES_PER_GRF);
3143  }
3144 
3145  for (int i = 0; i < numinfo; i++) {
3146  IndustryTileSpec *tsp = _cur.grffile->indtspec[indtid + i];
3147 
3148  if (prop != 0x08 && tsp == NULL) {
3150  if (cir > ret) ret = cir;
3151  continue;
3152  }
3153 
3154  switch (prop) {
3155  case 0x08: { // Substitute industry tile type
3156  IndustryTileSpec **tilespec = &_cur.grffile->indtspec[indtid + i];
3157  byte subs_id = buf->ReadByte();
3158 
3159  if (subs_id >= NEW_INDUSTRYTILEOFFSET) {
3160  /* The substitute id must be one of the original industry tile. */
3161  grfmsg(2, "IndustryTilesChangeInfo: Attempt to use new industry tile %u as substitute industry tile for %u. Ignoring.", subs_id, indtid + i);
3162  continue;
3163  }
3164 
3165  /* Allocate space for this industry. */
3166  if (*tilespec == NULL) {
3167  *tilespec = CallocT<IndustryTileSpec>(1);
3168  tsp = *tilespec;
3169 
3170  memcpy(tsp, &_industry_tile_specs[subs_id], sizeof(_industry_tile_specs[subs_id]));
3171  tsp->enabled = true;
3172 
3173  /* A copied tile should not have the animation infos copied too.
3174  * The anim_state should be left untouched, though
3175  * It is up to the author to animate them himself */
3176  tsp->anim_production = INDUSTRYTILE_NOANIM;
3177  tsp->anim_next = INDUSTRYTILE_NOANIM;
3178 
3179  tsp->grf_prop.local_id = indtid + i;
3180  tsp->grf_prop.subst_id = subs_id;
3181  tsp->grf_prop.grffile = _cur.grffile;
3182  _industile_mngr.AddEntityID(indtid + i, _cur.grffile->grfid, subs_id); // pre-reserve the tile slot
3183  }
3184  break;
3185  }
3186 
3187  case 0x09: { // Industry tile override
3188  byte ovrid = buf->ReadByte();
3189 
3190  /* The industry being overridden must be an original industry. */
3191  if (ovrid >= NEW_INDUSTRYTILEOFFSET) {
3192  grfmsg(2, "IndustryTilesChangeInfo: Attempt to override new industry tile %u with industry tile id %u. Ignoring.", ovrid, indtid + i);
3193  continue;
3194  }
3195 
3196  _industile_mngr.Add(indtid + i, _cur.grffile->grfid, ovrid);
3197  break;
3198  }
3199 
3200  case 0x0A: // Tile acceptance
3201  case 0x0B:
3202  case 0x0C: {
3203  uint16 acctp = buf->ReadWord();
3204  tsp->accepts_cargo[prop - 0x0A] = GetCargoTranslation(GB(acctp, 0, 8), _cur.grffile);
3205  tsp->acceptance[prop - 0x0A] = Clamp(GB(acctp, 8, 8), 0, 16);
3206  break;
3207  }
3208 
3209  case 0x0D: // Land shape flags
3210  tsp->slopes_refused = (Slope)buf->ReadByte();
3211  break;
3212 
3213  case 0x0E: // Callback mask
3214  tsp->callback_mask = buf->ReadByte();
3215  break;
3216 
3217  case 0x0F: // Animation information
3218  tsp->animation.frames = buf->ReadByte();
3219  tsp->animation.status = buf->ReadByte();
3220  break;
3221 
3222  case 0x10: // Animation speed
3223  tsp->animation.speed = buf->ReadByte();
3224  break;
3225 
3226  case 0x11: // Triggers for callback 25
3227  tsp->animation.triggers = buf->ReadByte();
3228  break;
3229 
3230  case 0x12: // Special flags
3231  tsp->special_flags = (IndustryTileSpecialFlags)buf->ReadByte();
3232  break;
3233 
3234  case 0x13: { // variable length cargo acceptance
3235  byte num_cargoes = buf->ReadByte();
3236  if (num_cargoes > lengthof(tsp->acceptance)) {
3237  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
3238  error->param_value[1] = prop;
3239  return CIR_DISABLED;
3240  }
3241  for (uint i = 0; i < lengthof(tsp->acceptance); i++) {
3242  if (i < num_cargoes) {
3243  tsp->accepts_cargo[i] = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
3244  /* Tile acceptance can be negative to counteract the INDTILE_SPECIAL_ACCEPTS_ALL_CARGO flag */
3245  tsp->acceptance[i] = (int8)buf->ReadByte();
3246  } else {
3247  tsp->accepts_cargo[i] = CT_INVALID;
3248  tsp->acceptance[i] = 0;
3249  }
3250  }
3251  break;
3252  }
3253 
3254  default:
3255  ret = CIR_UNKNOWN;
3256  break;
3257  }
3258  }
3259 
3260  return ret;
3261 }
3262 
3270 {
3272 
3273  switch (prop) {
3274  case 0x09:
3275  case 0x0B:
3276  case 0x0F:
3277  case 0x12:
3278  case 0x13:
3279  case 0x14:
3280  case 0x17:
3281  case 0x18:
3282  case 0x19:
3283  case 0x21:
3284  case 0x22:
3285  buf->ReadByte();
3286  break;
3287 
3288  case 0x0C:
3289  case 0x0D:
3290  case 0x0E:
3291  case 0x10:
3292  case 0x1B:
3293  case 0x1F:
3294  case 0x24:
3295  buf->ReadWord();
3296  break;
3297 
3298  case 0x11:
3299  case 0x1A:
3300  case 0x1C:
3301  case 0x1D:
3302  case 0x1E:
3303  case 0x20:
3304  case 0x23:
3305  buf->ReadDWord();
3306  break;
3307 
3308  case 0x0A: {
3309  byte num_table = buf->ReadByte();
3310  for (byte j = 0; j < num_table; j++) {
3311  for (uint k = 0;; k++) {
3312  byte x = buf->ReadByte();
3313  if (x == 0xFE && k == 0) {
3314  buf->ReadByte();
3315  buf->ReadByte();
3316  break;
3317  }
3318 
3319  byte y = buf->ReadByte();
3320  if (x == 0 && y == 0x80) break;
3321 
3322  byte gfx = buf->ReadByte();
3323  if (gfx == 0xFE) buf->ReadWord();
3324  }
3325  }
3326  break;
3327  }
3328 
3329  case 0x16:
3330  for (byte j = 0; j < 3; j++) buf->ReadByte();
3331  break;
3332 
3333  case 0x15:
3334  case 0x25:
3335  case 0x26:
3336  case 0x27:
3337  buf->Skip(buf->ReadByte());
3338  break;
3339 
3340  case 0x28: {
3341  int num_inputs = buf->ReadByte();
3342  int num_outputs = buf->ReadByte();
3343  buf->Skip(num_inputs * num_outputs * 2);
3344  break;
3345  }
3346 
3347  default:
3348  ret = CIR_UNKNOWN;
3349  break;
3350  }
3351  return ret;
3352 }
3353 
3360 static bool ValidateIndustryLayout(const IndustryTileTable *layout, int size)
3361 {
3362  for (int i = 0; i < size - 1; i++) {
3363  for (int j = i + 1; j < size; j++) {
3364  if (layout[i].ti.x == layout[j].ti.x &&
3365  layout[i].ti.y == layout[j].ti.y) {
3366  return false;
3367  }
3368  }
3369  }
3370  return true;
3371 }
3372 
3375 {
3376  if (HasBit(ind->cleanup_flag, CLEAN_TILELAYOUT) && ind->table != NULL) {
3377  for (int j = 0; j < ind->num_table; j++) {
3378  /* remove the individual layouts */
3379  free(ind->table[j]);
3380  }
3381  /* remove the layouts pointers */
3382  free(ind->table);
3383  ind->table = NULL;
3384  }
3385 }
3386 
3395 static ChangeInfoResult IndustriesChangeInfo(uint indid, int numinfo, int prop, ByteReader *buf)
3396 {
3398 
3399  if (indid + numinfo > NUM_INDUSTRYTYPES_PER_GRF) {
3400  grfmsg(1, "IndustriesChangeInfo: Too many industries loaded (%u), max (%u). Ignoring.", indid + numinfo, NUM_INDUSTRYTYPES_PER_GRF);
3401  return CIR_INVALID_ID;
3402  }
3403 
3404  /* Allocate industry specs if they haven't been allocated already. */
3405  if (_cur.grffile->industryspec == NULL) {
3406  _cur.grffile->industryspec = CallocT<IndustrySpec*>(NUM_INDUSTRYTYPES_PER_GRF);
3407  }
3408 
3409  for (int i = 0; i < numinfo; i++) {
3410  IndustrySpec *indsp = _cur.grffile->industryspec[indid + i];
3411 
3412  if (prop != 0x08 && indsp == NULL) {
3413  ChangeInfoResult cir = IgnoreIndustryProperty(prop, buf);
3414  if (cir > ret) ret = cir;
3415  continue;
3416  }
3417 
3418  switch (prop) {
3419  case 0x08: { // Substitute industry type
3420  IndustrySpec **indspec = &_cur.grffile->industryspec[indid + i];
3421  byte subs_id = buf->ReadByte();
3422 
3423  if (subs_id == 0xFF) {
3424  /* Instead of defining a new industry, a substitute industry id
3425  * of 0xFF disables the old industry with the current id. */
3426  _industry_specs[indid + i].enabled = false;
3427  continue;
3428  } else if (subs_id >= NEW_INDUSTRYOFFSET) {
3429  /* The substitute id must be one of the original industry. */
3430  grfmsg(2, "_industry_specs: Attempt to use new industry %u as substitute industry for %u. Ignoring.", subs_id, indid + i);
3431  continue;
3432  }
3433 
3434  /* Allocate space for this industry.
3435  * Only need to do it once. If ever it is called again, it should not
3436  * do anything */
3437  if (*indspec == NULL) {
3438  *indspec = CallocT<IndustrySpec>(1);
3439  indsp = *indspec;
3440 
3441  memcpy(indsp, &_origin_industry_specs[subs_id], sizeof(_industry_specs[subs_id]));
3442  indsp->enabled = true;
3443  indsp->grf_prop.local_id = indid + i;
3444  indsp->grf_prop.subst_id = subs_id;
3445  indsp->grf_prop.grffile = _cur.grffile;
3446  /* If the grf industry needs to check its surounding upon creation, it should
3447  * rely on callbacks, not on the original placement functions */
3448  indsp->check_proc = CHECK_NOTHING;
3449  }
3450  break;
3451  }
3452 
3453  case 0x09: { // Industry type override
3454  byte ovrid = buf->ReadByte();
3455 
3456  /* The industry being overridden must be an original industry. */
3457  if (ovrid >= NEW_INDUSTRYOFFSET) {
3458  grfmsg(2, "IndustriesChangeInfo: Attempt to override new industry %u with industry id %u. Ignoring.", ovrid, indid + i);
3459  continue;
3460  }
3461  indsp->grf_prop.override = ovrid;
3462  _industry_mngr.Add(indid + i, _cur.grffile->grfid, ovrid);
3463  break;
3464  }
3465 
3466  case 0x0A: { // Set industry layout(s)
3467  byte new_num_layouts = buf->ReadByte(); // Number of layaouts
3468  /* We read the total size in bytes, but we can't rely on the
3469  * newgrf to provide a sane value. First assume the value is
3470  * sane but later on we make sure we enlarge the array if the
3471  * newgrf contains more data. Each tile uses either 3 or 5
3472  * bytes, so to play it safe we assume 3. */
3473  uint32 def_num_tiles = buf->ReadDWord() / 3 + 1;
3474  IndustryTileTable **tile_table = CallocT<IndustryTileTable*>(new_num_layouts); // Table with tiles to compose an industry
3475  IndustryTileTable *itt = CallocT<IndustryTileTable>(def_num_tiles); // Temporary array to read the tile layouts from the GRF
3476  uint size;
3477  const IndustryTileTable *copy_from;
3478 
3479  try {
3480  for (byte j = 0; j < new_num_layouts; j++) {
3481  for (uint k = 0;; k++) {
3482  if (k >= def_num_tiles) {
3483  grfmsg(3, "IndustriesChangeInfo: Incorrect size for industry tile layout definition for industry %u.", indid);
3484  /* Size reported by newgrf was not big enough so enlarge the array. */
3485  def_num_tiles *= 2;
3486  itt = ReallocT<IndustryTileTable>(itt, def_num_tiles);
3487  }
3488 
3489  itt[k].ti.x = buf->ReadByte(); // Offsets from northermost tile
3490 
3491  if (itt[k].ti.x == 0xFE && k == 0) {
3492  /* This means we have to borrow the layout from an old industry */
3493  IndustryType type = buf->ReadByte(); // industry holding required layout
3494  byte laynbr = buf->ReadByte(); // layout number to borrow
3495 
3496  copy_from = _origin_industry_specs[type].table[laynbr];
3497  for (size = 1;; size++) {
3498  if (copy_from[size - 1].ti.x == -0x80 && copy_from[size - 1].ti.y == 0) break;
3499  }
3500  break;
3501  }
3502 
3503  itt[k].ti.y = buf->ReadByte(); // Or table definition finalisation
3504 
3505  if (itt[k].ti.x == 0 && itt[k].ti.y == 0x80) {
3506  /* Not the same terminator. The one we are using is rather
3507  x = -80, y = x . So, adjust it. */
3508  itt[k].ti.x = -0x80;
3509  itt[k].ti.y = 0;
3510  itt[k].gfx = 0;
3511 
3512  size = k + 1;
3513  copy_from = itt;
3514  break;
3515  }
3516 
3517  itt[k].gfx = buf->ReadByte();
3518 
3519  if (itt[k].gfx == 0xFE) {
3520  /* Use a new tile from this GRF */
3521  int local_tile_id = buf->ReadWord();
3522 
3523  /* Read the ID from the _industile_mngr. */
3524  int tempid = _industile_mngr.GetID(local_tile_id, _cur.grffile->grfid);
3525 
3526  if (tempid == INVALID_INDUSTRYTILE) {
3527  grfmsg(2, "IndustriesChangeInfo: Attempt to use industry tile %u with industry id %u, not yet defined. Ignoring.", local_tile_id, indid);
3528  } else {
3529  /* Declared as been valid, can be used */
3530  itt[k].gfx = tempid;
3531  }
3532  } else if (itt[k].gfx == 0xFF) {
3533  itt[k].ti.x = (int8)GB(itt[k].ti.x, 0, 8);
3534  itt[k].ti.y = (int8)GB(itt[k].ti.y, 0, 8);
3535 
3536  /* When there were only 256x256 maps, TileIndex was a uint16 and
3537  * itt[k].ti was just a TileIndexDiff that was added to it.
3538  * As such negative "x" values were shifted into the "y" position.
3539  * x = -1, y = 1 -> x = 255, y = 0
3540  * Since GRF version 8 the position is interpreted as pair of independent int8.
3541  * For GRF version < 8 we need to emulate the old shifting behaviour.
3542  */
3543  if (_cur.grffile->grf_version < 8 && itt[k].ti.x < 0) itt[k].ti.y += 1;
3544  }
3545  }
3546 
3547  if (!ValidateIndustryLayout(copy_from, size)) {
3548  /* The industry layout was not valid, so skip this one. */
3549  grfmsg(1, "IndustriesChangeInfo: Invalid industry layout for industry id %u. Ignoring", indid);
3550  new_num_layouts--;
3551  j--;
3552  } else {
3553  tile_table[j] = CallocT<IndustryTileTable>(size);
3554  memcpy(tile_table[j], copy_from, sizeof(*copy_from) * size);
3555  }
3556  }
3557  } catch (...) {
3558  for (int i = 0; i < new_num_layouts; i++) {
3559  free(tile_table[i]);
3560  }
3561  free(tile_table);
3562  free(itt);
3563  throw;
3564  }
3565 
3566  /* Clean the tile table if it was already set by a previous prop A. */
3567  CleanIndustryTileTable(indsp);
3568  /* Install final layout construction in the industry spec */
3569  indsp->num_table = new_num_layouts;
3570  indsp->table = tile_table;
3572  free(itt);
3573  break;
3574  }
3575 
3576  case 0x0B: // Industry production flags
3577  indsp->life_type = (IndustryLifeType)buf->ReadByte();
3578  break;
3579 
3580  case 0x0C: // Industry closure message
3581  AddStringForMapping(buf->ReadWord(), &indsp->closure_text);
3582  break;
3583 
3584  case 0x0D: // Production increase message
3585  AddStringForMapping(buf->ReadWord(), &indsp->production_up_text);
3586  break;
3587 
3588  case 0x0E: // Production decrease message
3589  AddStringForMapping(buf->ReadWord(), &indsp->production_down_text);
3590  break;
3591 
3592  case 0x0F: // Fund cost multiplier
3593  indsp->cost_multiplier = buf->ReadByte();
3594  break;
3595 
3596  case 0x10: // Production cargo types
3597  for (byte j = 0; j < 2; j++) {
3598  indsp->produced_cargo[j] = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
3599  }
3600  break;
3601 
3602  case 0x11: // Acceptance cargo types
3603  for (byte j = 0; j < 3; j++) {
3604  indsp->accepts_cargo[j] = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
3605  }
3606  buf->ReadByte(); // Unnused, eat it up
3607  break;
3608 
3609  case 0x12: // Production multipliers
3610  case 0x13:
3611  indsp->production_rate[prop - 0x12] = buf->ReadByte();
3612  break;
3613 
3614  case 0x14: // Minimal amount of cargo distributed
3615  indsp->minimal_cargo = buf->ReadByte();
3616  break;
3617 
3618  case 0x15: { // Random sound effects
3619  indsp->number_of_sounds = buf->ReadByte();
3620  uint8 *sounds = MallocT<uint8>(indsp->number_of_sounds);
3621 
3622  try {
3623  for (uint8 j = 0; j < indsp->number_of_sounds; j++) {
3624  sounds[j] = buf->ReadByte();
3625  }
3626  } catch (...) {
3627  free(sounds);
3628  throw;
3629  }
3630 
3631  if (HasBit(indsp->cleanup_flag, CLEAN_RANDOMSOUNDS)) {
3632  free(indsp->random_sounds);
3633  }
3634  indsp->random_sounds = sounds;
3636  break;
3637  }
3638 
3639  case 0x16: // Conflicting industry types
3640  for (byte j = 0; j < 3; j++) indsp->conflicting[j] = buf->ReadByte();
3641  break;
3642 
3643  case 0x17: // Probability in random game
3644  indsp->appear_creation[_settings_game.game_creation.landscape] = buf->ReadByte();
3645  break;
3646 
3647  case 0x18: // Probability during gameplay
3648  indsp->appear_ingame[_settings_game.game_creation.landscape] = buf->ReadByte();
3649  break;
3650 
3651  case 0x19: // Map colour
3652  indsp->map_colour = buf->ReadByte();
3653  break;
3654 
3655  case 0x1A: // Special industry flags to define special behavior
3656  indsp->behaviour = (IndustryBehaviour)buf->ReadDWord();
3657  break;
3658 
3659  case 0x1B: // New industry text ID
3660  AddStringForMapping(buf->ReadWord(), &indsp->new_industry_text);
3661  break;
3662 
3663  case 0x1C: // Input cargo multipliers for the three input cargo types
3664  case 0x1D:
3665  case 0x1E: {
3666  uint32 multiples = buf->ReadDWord();
3667  indsp->input_cargo_multiplier[prop - 0x1C][0] = GB(multiples, 0, 16);
3668  indsp->input_cargo_multiplier[prop - 0x1C][1] = GB(multiples, 16, 16);
3669  break;
3670  }
3671 
3672  case 0x1F: // Industry name
3673  AddStringForMapping(buf->ReadWord(), &indsp->name);
3674  break;
3675 
3676  case 0x20: // Prospecting success chance
3677  indsp->prospecting_chance = buf->ReadDWord();
3678  break;
3679 
3680  case 0x21: // Callback mask
3681  case 0x22: { // Callback additional mask
3682  byte aflag = buf->ReadByte();
3683  SB(indsp->callback_mask, (prop - 0x21) * 8, 8, aflag);
3684  break;
3685  }
3686 
3687  case 0x23: // removal cost multiplier
3688  indsp->removal_cost_multiplier = buf->ReadDWord();
3689  break;
3690 
3691  case 0x24: { // name for nearby station
3692  uint16 str = buf->ReadWord();
3693  if (str == 0) {
3694  indsp->station_name = STR_NULL;
3695  } else {
3696  AddStringForMapping(str, &indsp->station_name);
3697  }
3698  break;
3699  }
3700 
3701  case 0x25: { // variable length produced cargoes
3702  byte num_cargoes = buf->ReadByte();
3703  if (num_cargoes > lengthof(indsp->produced_cargo)) {
3704  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
3705  error->param_value[1] = prop;
3706  return CIR_DISABLED;
3707  }
3708  for (uint i = 0; i < lengthof(indsp->produced_cargo); i++) {
3709  if (i < num_cargoes) {
3710  CargoID cargo = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
3711  indsp->produced_cargo[i] = cargo;
3712  } else {
3713  indsp->produced_cargo[i] = CT_INVALID;
3714  }
3715  }
3716  break;
3717  }
3718 
3719  case 0x26: { // variable length accepted cargoes
3720  byte num_cargoes = buf->ReadByte();
3721  if (num_cargoes > lengthof(indsp->accepts_cargo)) {
3722  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
3723  error->param_value[1] = prop;
3724  return CIR_DISABLED;
3725  }
3726  for (uint i = 0; i < lengthof(indsp->accepts_cargo); i++) {
3727  if (i < num_cargoes) {
3728  CargoID cargo = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
3729  indsp->accepts_cargo[i] = cargo;
3730  } else {
3731  indsp->accepts_cargo[i] = CT_INVALID;
3732  }
3733  }
3734  break;
3735  }
3736 
3737  case 0x27: { // variable length production rates
3738  byte num_cargoes = buf->ReadByte();
3739  if (num_cargoes > lengthof(indsp->production_rate)) {
3740  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
3741  error->param_value[1] = prop;
3742  return CIR_DISABLED;
3743  }
3744  for (uint i = 0; i < lengthof(indsp->production_rate); i++) {
3745  if (i < num_cargoes) {
3746  indsp->production_rate[i] = buf->ReadByte();
3747  } else {
3748  indsp->production_rate[i] = 0;
3749  }
3750  }
3751  break;
3752  }
3753 
3754  case 0x28: { // variable size input/output production multiplier table
3755  byte num_inputs = buf->ReadByte();
3756  byte num_outputs = buf->ReadByte();
3757  if (num_inputs > lengthof(indsp->accepts_cargo) || num_outputs > lengthof(indsp->produced_cargo)) {
3758  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
3759  error->param_value[1] = prop;
3760  return CIR_DISABLED;
3761  }
3762  for (uint i = 0; i < lengthof(indsp->accepts_cargo); i++) {
3763  for (uint j = 0; j < lengthof(indsp->produced_cargo); j++) {
3764  uint16 mult = 0;
3765  if (i < num_inputs && j < num_outputs) mult = buf->ReadWord();
3766  indsp->input_cargo_multiplier[i][j] = mult;
3767  }
3768  }
3769  break;
3770  }
3771 
3772  default:
3773  ret = CIR_UNKNOWN;
3774  break;
3775  }
3776  }
3777 
3778  return ret;
3779 }
3780 
3787 {
3788  AirportTileTable **table_list = MallocT<AirportTileTable*>(as->num_table);
3789  for (int i = 0; i < as->num_table; i++) {
3790  uint num_tiles = 1;
3791  const AirportTileTable *it = as->table[0];
3792  do {
3793  num_tiles++;
3794  } while ((++it)->ti.x != -0x80);
3795  table_list[i] = MallocT<AirportTileTable>(num_tiles);
3796  MemCpyT(table_list[i], as->table[i], num_tiles);
3797  }
3798  as->table = table_list;
3799  HangarTileTable *depot_table = MallocT<HangarTileTable>(as->nof_depots);
3800  MemCpyT(depot_table, as->depot_table, as->nof_depots);
3801  as->depot_table = depot_table;
3802  Direction *rotation = MallocT<Direction>(as->num_table);
3803  MemCpyT(rotation, as->rotation, as->num_table);
3804  as->rotation = rotation;
3805 }
3806 
3815 static ChangeInfoResult AirportChangeInfo(uint airport, int numinfo, int prop, ByteReader *buf)
3816 {
3818 
3819  if (airport + numinfo > NUM_AIRPORTS_PER_GRF) {
3820  grfmsg(1, "AirportChangeInfo: Too many airports, trying id (%u), max (%u). Ignoring.", airport + numinfo, NUM_AIRPORTS_PER_GRF);
3821  return CIR_INVALID_ID;
3822  }
3823 
3824  /* Allocate industry specs if they haven't been allocated already. */
3825  if (_cur.grffile->airportspec == NULL) {
3826  _cur.grffile->airportspec = CallocT<AirportSpec*>(NUM_AIRPORTS_PER_GRF);
3827  }
3828 
3829  for (int i = 0; i < numinfo; i++) {
3830  AirportSpec *as = _cur.grffile->airportspec[airport + i];
3831 
3832  if (as == NULL && prop != 0x08 && prop != 0x09) {
3833  grfmsg(2, "AirportChangeInfo: Attempt to modify undefined airport %u, ignoring", airport + i);
3834  return CIR_INVALID_ID;
3835  }
3836 
3837  switch (prop) {
3838  case 0x08: { // Modify original airport
3839  byte subs_id = buf->ReadByte();
3840 
3841  if (subs_id == 0xFF) {
3842  /* Instead of defining a new airport, an airport id
3843  * of 0xFF disables the old airport with the current id. */
3844  AirportSpec::GetWithoutOverride(airport + i)->enabled = false;
3845  continue;
3846  } else if (subs_id >= NEW_AIRPORT_OFFSET) {
3847  /* The substitute id must be one of the original airports. */
3848  grfmsg(2, "AirportChangeInfo: Attempt to use new airport %u as substitute airport for %u. Ignoring.", subs_id, airport + i);
3849  continue;
3850  }
3851 
3852  AirportSpec **spec = &_cur.grffile->airportspec[airport + i];
3853  /* Allocate space for this airport.
3854  * Only need to do it once. If ever it is called again, it should not
3855  * do anything */
3856  if (*spec == NULL) {
3857  *spec = MallocT<AirportSpec>(1);
3858  as = *spec;
3859 
3860  memcpy(as, AirportSpec::GetWithoutOverride(subs_id), sizeof(*as));
3861  as->enabled = true;
3862  as->grf_prop.local_id = airport + i;
3863  as->grf_prop.subst_id = subs_id;
3864  as->grf_prop.grffile = _cur.grffile;
3865  /* override the default airport */
3866  _airport_mngr.Add(airport + i, _cur.grffile->grfid, subs_id);
3867  /* Create a copy of the original tiletable so it can be freed later. */
3868  DuplicateTileTable(as);
3869  }
3870  break;
3871  }
3872 
3873  case 0x0A: { // Set airport layout
3874  free(as->rotation);
3875  as->num_table = buf->ReadByte(); // Number of layaouts
3876  as->rotation = MallocT<Direction>(as->num_table);
3877  uint32 defsize = buf->ReadDWord(); // Total size of the definition
3878  AirportTileTable **tile_table = CallocT<AirportTileTable*>(as->num_table); // Table with tiles to compose the airport
3879  AirportTileTable *att = CallocT<AirportTileTable>(defsize); // Temporary array to read the tile layouts from the GRF
3880  int size;
3881  const AirportTileTable *copy_from;
3882  try {
3883  for (byte j = 0; j < as->num_table; j++) {
3884  const_cast<Direction&>(as->rotation[j]) = (Direction)buf->ReadByte();
3885  for (int k = 0;; k++) {
3886  att[k].ti.x = buf->ReadByte(); // Offsets from northermost tile
3887  att[k].ti.y = buf->ReadByte();
3888 
3889  if (att[k].ti.x == 0 && att[k].ti.y == 0x80) {
3890  /* Not the same terminator. The one we are using is rather
3891  * x = -80, y = 0 . So, adjust it. */
3892  att[k].ti.x = -0x80;
3893  att[k].ti.y = 0;
3894  att[k].gfx = 0;
3895 
3896  size = k + 1;
3897  copy_from = att;
3898  break;
3899  }
3900 
3901  att[k].gfx = buf->ReadByte();
3902 
3903  if (att[k].gfx == 0xFE) {
3904  /* Use a new tile from this GRF */
3905  int local_tile_id = buf->ReadWord();
3906 
3907  /* Read the ID from the _airporttile_mngr. */
3908  uint16 tempid = _airporttile_mngr.GetID(local_tile_id, _cur.grffile->grfid);
3909 
3910  if (tempid == INVALID_AIRPORTTILE) {
3911  grfmsg(2, "AirportChangeInfo: Attempt to use airport tile %u with airport id %u, not yet defined. Ignoring.", local_tile_id, airport + i);
3912  } else {
3913  /* Declared as been valid, can be used */
3914  att[k].gfx = tempid;
3915  }
3916  } else if (att[k].gfx == 0xFF) {
3917  att[k].ti.x = (int8)GB(att[k].ti.x, 0, 8);
3918  att[k].ti.y = (int8)GB(att[k].ti.y, 0, 8);
3919  }
3920 
3921  if (as->rotation[j] == DIR_E || as->rotation[j] == DIR_W) {
3922  as->size_x = max<byte>(as->size_x, att[k].ti.y + 1);
3923  as->size_y = max<byte>(as->size_y, att[k].ti.x + 1);
3924  } else {
3925  as->size_x = max<byte>(as->size_x, att[k].ti.x + 1);
3926  as->size_y = max<byte>(as->size_y, att[k].ti.y + 1);
3927  }
3928  }
3929  tile_table[j] = CallocT<AirportTileTable>(size);
3930  memcpy(tile_table[j], copy_from, sizeof(*copy_from) * size);
3931  }
3932  /* Install final layout construction in the airport spec */
3933  as->table = tile_table;
3934  free(att);
3935  } catch (...) {
3936  for (int i = 0; i < as->num_table; i++) {
3937  free(tile_table[i]);
3938  }
3939  free(tile_table);
3940  free(att);
3941  throw;
3942  }
3943  break;
3944  }
3945 
3946  case 0x0C:
3947  as->min_year = buf->ReadWord();
3948  as->max_year = buf->ReadWord();
3949  if (as->max_year == 0xFFFF) as->max_year = MAX_YEAR;
3950  break;
3951 
3952  case 0x0D:
3953  as->ttd_airport_type = (TTDPAirportType)buf->ReadByte();
3954  break;
3955 
3956  case 0x0E:
3957  as->catchment = Clamp(buf->ReadByte(), 1, MAX_CATCHMENT);
3958  break;
3959 
3960  case 0x0F:
3961  as->noise_level = buf->ReadByte();
3962  break;
3963 
3964  case 0x10:
3965  AddStringForMapping(buf->ReadWord(), &as->name);
3966  break;
3967 
3968  case 0x11: // Maintenance cost factor
3969  as->maintenance_cost = buf->ReadWord();
3970  break;
3971 
3972  default:
3973  ret = CIR_UNKNOWN;
3974  break;
3975  }
3976  }
3977 
3978  return ret;
3979 }
3980 
3988 {
3990 
3991  switch (prop) {
3992  case 0x0B:
3993  case 0x0C:
3994  case 0x0D:
3995  case 0x12:
3996  case 0x14:
3997  case 0x16:
3998  case 0x17:
3999  buf->ReadByte();
4000  break;
4001 
4002  case 0x09:
4003  case 0x0A:
4004  case 0x10:
4005  case 0x11:
4006  case 0x13:
4007  case 0x15:
4008  buf->ReadWord();
4009  break;
4010 
4011  case 0x08:
4012  case 0x0E:
4013  case 0x0F:
4014  buf->ReadDWord();
4015  break;
4016 
4017  default:
4018  ret = CIR_UNKNOWN;
4019  break;
4020  }
4021 
4022  return ret;
4023 }
4024 
4033 static ChangeInfoResult ObjectChangeInfo(uint id, int numinfo, int prop, ByteReader *buf)
4034 {
4036 
4037  if (id + numinfo > NUM_OBJECTS_PER_GRF) {
4038  grfmsg(1, "ObjectChangeInfo: Too many objects loaded (%u), max (%u). Ignoring.", id + numinfo, NUM_OBJECTS_PER_GRF);
4039  return CIR_INVALID_ID;
4040  }
4041 
4042  /* Allocate object specs if they haven't been allocated already. */
4043  if (_cur.grffile->objectspec == NULL) {
4044  _cur.grffile->objectspec = CallocT<ObjectSpec*>(NUM_OBJECTS_PER_GRF);
4045  }
4046 
4047  for (int i = 0; i < numinfo; i++) {
4048  ObjectSpec *spec = _cur.grffile->objectspec[id + i];
4049 
4050  if (prop != 0x08 && spec == NULL) {
4051  /* If the object property 08 is not yet set, ignore this property */
4052  ChangeInfoResult cir = IgnoreObjectProperty(prop, buf);
4053  if (cir > ret) ret = cir;
4054  continue;
4055  }
4056 
4057  switch (prop) {
4058  case 0x08: { // Class ID
4059  ObjectSpec **ospec = &_cur.grffile->objectspec[id + i];
4060 
4061  /* Allocate space for this object. */
4062  if (*ospec == NULL) {
4063  *ospec = CallocT<ObjectSpec>(1);
4064  (*ospec)->views = 1; // Default for NewGRFs that don't set it.
4065  }
4066 
4067  /* Swap classid because we read it in BE. */
4068  uint32 classid = buf->ReadDWord();
4069  (*ospec)->cls_id = ObjectClass::Allocate(BSWAP32(classid));
4070  (*ospec)->enabled = true;
4071  break;
4072  }
4073 
4074  case 0x09: { // Class name
4075  ObjectClass *objclass = ObjectClass::Get(spec->cls_id);
4076  AddStringForMapping(buf->ReadWord(), &objclass->name);
4077  break;
4078  }
4079 
4080  case 0x0A: // Object name
4081  AddStringForMapping(buf->ReadWord(), &spec->name);
4082  break;
4083 
4084  case 0x0B: // Climate mask
4085  spec->climate = buf->ReadByte();
4086  break;
4087 
4088  case 0x0C: // Size
4089  spec->size = buf->ReadByte();
4090  break;
4091 
4092  case 0x0D: // Build cost multipler
4093  spec->build_cost_multiplier = buf->ReadByte();
4095  break;
4096 
4097  case 0x0E: // Introduction date
4098  spec->introduction_date = buf->ReadDWord();
4099  break;
4100 
4101  case 0x0F: // End of life
4102  spec->end_of_life_date = buf->ReadDWord();
4103  break;
4104 
4105  case 0x10: // Flags
4106  spec->flags = (ObjectFlags)buf->ReadWord();
4107  _loaded_newgrf_features.has_2CC |= (spec->flags & OBJECT_FLAG_2CC_COLOUR) != 0;
4108  break;
4109 
4110  case 0x11: // Animation info
4111  spec->animation.frames = buf->ReadByte();
4112  spec->animation.status = buf->ReadByte();
4113  break;
4114 
4115  case 0x12: // Animation speed
4116  spec->animation.speed = buf->ReadByte();
4117  break;
4118 
4119  case 0x13: // Animation triggers
4120  spec->animation.triggers = buf->ReadWord();
4121  break;
4122 
4123  case 0x14: // Removal cost multiplier
4124  spec->clear_cost_multiplier = buf->ReadByte();
4125  break;
4126 
4127  case 0x15: // Callback mask
4128  spec->callback_mask = buf->ReadWord();
4129  break;
4130 
4131  case 0x16: // Building height
4132  spec->height = buf->ReadByte();
4133  break;
4134 
4135  case 0x17: // Views
4136  spec->views = buf->ReadByte();
4137  if (spec->views != 1 && spec->views != 2 && spec->views != 4) {
4138  grfmsg(2, "ObjectChangeInfo: Invalid number of views (%u) for object id %u. Ignoring.", spec->views, id + i);
4139  spec->views = 1;
4140  }
4141  break;
4142 
4143  case 0x18: // Amount placed on 256^2 map on map creation
4144  spec->generate_amount = buf->ReadByte();
4145  break;
4146 
4147  default:
4148  ret = CIR_UNKNOWN;
4149  break;
4150  }
4151  }
4152 
4153  return ret;
4154 }
4155 
4164 static ChangeInfoResult RailTypeChangeInfo(uint id, int numinfo, int prop, ByteReader *buf)
4165 {
4167 
4168  extern RailtypeInfo _railtypes[RAILTYPE_END];
4169 
4170  if (id + numinfo > RAILTYPE_END) {
4171  grfmsg(1, "RailTypeChangeInfo: Rail type %u is invalid, max %u, ignoring", id + numinfo, RAILTYPE_END);
4172  return CIR_INVALID_ID;
4173  }
4174 
4175  for (int i = 0; i < numinfo; i++) {
4176  RailType rt = _cur.grffile->railtype_map[id + i];
4177  if (rt == INVALID_RAILTYPE) return CIR_INVALID_ID;
4178 
4179  RailtypeInfo *rti = &_railtypes[rt];
4180 
4181  switch (prop) {
4182  case 0x08: // Label of rail type
4183  /* Skipped here as this is loaded during reservation stage. */
4184  buf->ReadDWord();
4185  break;
4186 
4187  case 0x09: { // Toolbar caption of railtype (sets name as well for backwards compatibility for grf ver < 8)
4188  uint16 str = buf->ReadWord();
4190  if (_cur.grffile->grf_version < 8) {
4191  AddStringForMapping(str, &rti->strings.name);
4192  }
4193  break;
4194  }
4195 
4196  case 0x0A: // Menu text of railtype
4197  AddStringForMapping(buf->ReadWord(), &rti->strings.menu_text);
4198  break;
4199 
4200  case 0x0B: // Build window caption
4201  AddStringForMapping(buf->ReadWord(), &rti->strings.build_caption);
4202  break;
4203 
4204  case 0x0C: // Autoreplace text
4205  AddStringForMapping(buf->ReadWord(), &rti->strings.replace_text);
4206  break;
4207 
4208  case 0x0D: // New locomotive text
4209  AddStringForMapping(buf->ReadWord(), &rti->strings.new_loco);
4210  break;
4211 
4212  case 0x0E: // Compatible railtype list
4213  case 0x0F: // Powered railtype list
4214  case 0x18: // Railtype list required for date introduction
4215  case 0x19: // Introduced railtype list
4216  {
4217  /* Rail type compatibility bits are added to the existing bits
4218  * to allow multiple GRFs to modify compatibility with the
4219  * default rail types. */
4220  int n = buf->ReadByte();
4221  for (int j = 0; j != n; j++) {
4222  RailTypeLabel label = buf->ReadDWord();
4223  RailType rt = GetRailTypeByLabel(BSWAP32(label), false);
4224  if (rt != INVALID_RAILTYPE) {
4225  switch (prop) {
4226  case 0x0F: SetBit(rti->powered_railtypes, rt); FALLTHROUGH; // Powered implies compatible.
4227  case 0x0E: SetBit(rti->compatible_railtypes, rt); break;
4228  case 0x18: SetBit(rti->introduction_required_railtypes, rt); break;
4229  case 0x19: SetBit(rti->introduces_railtypes, rt); break;
4230  }
4231  }
4232  }
4233  break;
4234  }
4235 
4236  case 0x10: // Rail Type flags
4237  rti->flags = (RailTypeFlags)buf->ReadByte();
4238  break;
4239 
4240  case 0x11: // Curve speed advantage
4241  rti->curve_speed = buf->ReadByte();
4242  break;
4243 
4244  case 0x12: // Station graphic
4245  rti->fallback_railtype = Clamp(buf->ReadByte(), 0, 2);
4246  break;
4247 
4248  case 0x13: // Construction cost factor
4249  rti->cost_multiplier = buf->ReadWord();
4250  break;
4251 
4252  case 0x14: // Speed limit
4253  rti->max_speed = buf->ReadWord();
4254  break;
4255 
4256  case 0x15: // Acceleration model
4257  rti->acceleration_type = Clamp(buf->ReadByte(), 0, 2);
4258  break;
4259 
4260  case 0x16: // Map colour
4261  rti->map_colour = buf->ReadByte();
4262  break;
4263 
4264  case 0x17: // Introduction date
4265  rti->introduction_date = buf->ReadDWord();
4266  break;
4267 
4268  case 0x1A: // Sort order
4269  rti->sorting_order = buf->ReadByte();
4270  break;
4271 
4272  case 0x1B: // Name of railtype (overridden by prop 09 for grf ver < 8)
4273  AddStringForMapping(buf->ReadWord(), &rti->strings.name);
4274  break;
4275 
4276  case 0x1C: // Maintenance cost factor
4277  rti->maintenance_multiplier = buf->ReadWord();
4278  break;
4279 
4280  case 0x1D: // Alternate rail type label list
4281  /* Skipped here as this is loaded during reservation stage. */
4282  for (int j = buf->ReadByte(); j != 0; j--) buf->ReadDWord();
4283  break;
4284 
4285  default:
4286  ret = CIR_UNKNOWN;
4287  break;
4288  }
4289  }
4290 
4291  return ret;
4292 }
4293 
4294 static ChangeInfoResult RailTypeReserveInfo(uint id, int numinfo, int prop, ByteReader *buf)
4295 {
4297 
4298  extern RailtypeInfo _railtypes[RAILTYPE_END];
4299 
4300  if (id + numinfo > RAILTYPE_END) {
4301  grfmsg(1, "RailTypeReserveInfo: Rail type %u is invalid, max %u, ignoring", id + numinfo, RAILTYPE_END);
4302  return CIR_INVALID_ID;
4303  }
4304 
4305  for (int i = 0; i < numinfo; i++) {
4306  switch (prop) {
4307  case 0x08: // Label of rail type
4308  {
4309  RailTypeLabel rtl = buf->ReadDWord();
4310  rtl = BSWAP32(rtl);
4311 
4312  RailType rt = GetRailTypeByLabel(rtl, false);
4313  if (rt == INVALID_RAILTYPE) {
4314  /* Set up new rail type */
4315  rt = AllocateRailType(rtl);
4316  }
4317 
4318  _cur.grffile->railtype_map[id + i] = rt;
4319  break;
4320  }
4321 
4322  case 0x09: // Toolbar caption of railtype
4323  case 0x0A: // Menu text
4324  case 0x0B: // Build window caption
4325  case 0x0C: // Autoreplace text
4326  case 0x0D: // New loco
4327  case 0x13: // Construction cost
4328  case 0x14: // Speed limit
4329  case 0x1B: // Name of railtype
4330  case 0x1C: // Maintenance cost factor
4331  buf->ReadWord();
4332  break;
4333 
4334  case 0x1D: // Alternate rail type label list
4335  if (_cur.grffile->railtype_map[id + i] != INVALID_RAILTYPE) {
4336  int n = buf->ReadByte();
4337  for (int j = 0; j != n; j++) {
4338  *_railtypes[_cur.grffile->railtype_map[id + i]].alternate_labels.Append() = BSWAP32(buf->ReadDWord());
4339  }
4340  break;
4341  }
4342  grfmsg(1, "RailTypeReserveInfo: Ignoring property 1D for rail type %u because no label was set", id + i);
4343  FALLTHROUGH;
4344 
4345  case 0x0E: // Compatible railtype list
4346  case 0x0F: // Powered railtype list
4347  case 0x18: // Railtype list required for date introduction
4348  case 0x19: // Introduced railtype list
4349  for (int j = buf->ReadByte(); j != 0; j--) buf->ReadDWord();
4350  break;
4351 
4352  case 0x10: // Rail Type flags
4353  case 0x11: // Curve speed advantage
4354  case 0x12: // Station graphic
4355  case 0x15: // Acceleration model
4356  case 0x16: // Map colour
4357  case 0x1A: // Sort order
4358  buf->ReadByte();
4359  break;
4360 
4361  case 0x17: // Introduction date
4362  buf->ReadDWord();
4363  break;
4364 
4365  default:
4366  ret = CIR_UNKNOWN;
4367  break;
4368  }
4369  }
4370 
4371  return ret;
4372 }
4373 
4374 static ChangeInfoResult AirportTilesChangeInfo(uint airtid, int numinfo, int prop, ByteReader *buf)
4375 {
4377 
4378  if (airtid + numinfo > NUM_AIRPORTTILES_PER_GRF) {
4379  grfmsg(1, "AirportTileChangeInfo: Too many airport tiles loaded (%u), max (%u). Ignoring.", airtid + numinfo, NUM_AIRPORTTILES_PER_GRF);
4380  return CIR_INVALID_ID;
4381  }
4382 
4383  /* Allocate airport tile specs if they haven't been allocated already. */
4384  if (_cur.grffile->airtspec == NULL) {
4385  _cur.grffile->airtspec = CallocT<AirportTileSpec*>(NUM_AIRPORTTILES_PER_GRF);
4386  }
4387 
4388  for (int i = 0; i < numinfo; i++) {
4389  AirportTileSpec *tsp = _cur.grffile->airtspec[airtid + i];
4390 
4391  if (prop != 0x08 && tsp == NULL) {
4392  grfmsg(2, "AirportTileChangeInfo: Attempt to modify undefined airport tile %u. Ignoring.", airtid + i);
4393  return CIR_INVALID_ID;
4394  }
4395 
4396  switch (prop) {
4397  case 0x08: { // Substitute airport tile type
4398  AirportTileSpec **tilespec = &_cur.grffile->airtspec[airtid + i];
4399  byte subs_id = buf->ReadByte();
4400 
4401  if (subs_id >= NEW_AIRPORTTILE_OFFSET) {
4402  /* The substitute id must be one of the original airport tiles. */
4403  grfmsg(2, "AirportTileChangeInfo: Attempt to use new airport tile %u as substitute airport tile for %u. Ignoring.", subs_id, airtid + i);
4404  continue;
4405  }
4406 
4407  /* Allocate space for this airport tile. */
4408  if (*tilespec == NULL) {
4409  *tilespec = CallocT<AirportTileSpec>(1);
4410  tsp = *tilespec;
4411 
4412  memcpy(tsp, AirportTileSpec::Get(subs_id), sizeof(AirportTileSpec));
4413  tsp->enabled = true;
4414 
4415  tsp->animation.status = ANIM_STATUS_NO_ANIMATION;
4416 
4417  tsp->grf_prop.local_id = airtid + i;
4418  tsp->grf_prop.subst_id = subs_id;
4419  tsp->grf_prop.grffile = _cur.grffile;
4420  _airporttile_mngr.AddEntityID(airtid + i, _cur.grffile->grfid, subs_id); // pre-reserve the tile slot
4421  }
4422  break;
4423  }
4424 
4425  case 0x09: { // Airport tile override
4426  byte override = buf->ReadByte();
4427 
4428  /* The airport tile being overridden must be an original airport tile. */
4429  if (override >= NEW_AIRPORTTILE_OFFSET) {
4430  grfmsg(2, "AirportTileChangeInfo: Attempt to override new airport tile %u with airport tile id %u. Ignoring.", override, airtid + i);
4431  continue;
4432  }
4433 
4434  _airporttile_mngr.Add(airtid + i, _cur.grffile->grfid, override);
4435  break;
4436  }
4437 
4438  case 0x0E: // Callback mask
4439  tsp->callback_mask = buf->ReadByte();
4440  break;
4441 
4442  case 0x0F: // Animation information
4443  tsp->animation.frames = buf->ReadByte();
4444  tsp->animation.status = buf->ReadByte();
4445  break;
4446 
4447  case 0x10: // Animation speed
4448  tsp->animation.speed = buf->ReadByte();
4449  break;
4450 
4451  case 0x11: // Animation triggers
4452  tsp->animation.triggers = buf->ReadByte();
4453  break;
4454 
4455  default:
4456  ret = CIR_UNKNOWN;
4457  break;
4458  }
4459  }
4460 
4461  return ret;
4462 }
4463 
4464 static bool HandleChangeInfoResult(const char *caller, ChangeInfoResult cir, uint8 feature, uint8 property)
4465 {
4466  switch (cir) {
4467  default: NOT_REACHED();
4468 
4469  case CIR_DISABLED:
4470  /* Error has already been printed; just stop parsing */
4471  return true;
4472 
4473  case CIR_SUCCESS:
4474  return false;
4475 
4476  case CIR_UNHANDLED:
4477  grfmsg(1, "%s: Ignoring property 0x%02X of feature 0x%02X (not implemented)", caller, property, feature);
4478  return false;
4479 
4480  case CIR_UNKNOWN:
4481  grfmsg(0, "%s: Unknown property 0x%02X of feature 0x%02X, disabling", caller, property, feature);
4482  FALLTHROUGH;
4483 
4484  case CIR_INVALID_ID: {
4485  /* No debug message for an invalid ID, as it has already been output */
4486  GRFError *error = DisableGrf(cir == CIR_INVALID_ID ? STR_NEWGRF_ERROR_INVALID_ID : STR_NEWGRF_ERROR_UNKNOWN_PROPERTY);
4487  if (cir != CIR_INVALID_ID) error->param_value[1] = property;
4488  return true;
4489  }
4490  }
4491 }
4492 
4493 /* Action 0x00 */
4494 static void FeatureChangeInfo(ByteReader *buf)
4495 {
4496  /* <00> <feature> <num-props> <num-info> <id> (<property <new-info>)...
4497  *
4498  * B feature
4499  * B num-props how many properties to change per vehicle/station
4500  * B num-info how many vehicles/stations to change
4501  * E id ID of first vehicle/station to change, if num-info is
4502  * greater than one, this one and the following
4503  * vehicles/stations will be changed
4504  * B property what property to change, depends on the feature
4505  * V new-info new bytes of info (variable size; depends on properties) */
4506 
4507  static const VCI_Handler handler[] = {
4508  /* GSF_TRAINS */ RailVehicleChangeInfo,
4509  /* GSF_ROADVEHICLES */ RoadVehicleChangeInfo,
4510  /* GSF_SHIPS */ ShipVehicleChangeInfo,
4511  /* GSF_AIRCRAFT */ AircraftVehicleChangeInfo,
4512  /* GSF_STATIONS */ StationChangeInfo,
4513  /* GSF_CANALS */ CanalChangeInfo,
4514  /* GSF_BRIDGES */ BridgeChangeInfo,
4515  /* GSF_HOUSES */ TownHouseChangeInfo,
4516  /* GSF_GLOBALVAR */ GlobalVarChangeInfo,
4517  /* GSF_INDUSTRYTILES */ IndustrytilesChangeInfo,
4518  /* GSF_INDUSTRIES */ IndustriesChangeInfo,
4519  /* GSF_CARGOES */ NULL, // Cargo is handled during reservation
4520  /* GSF_SOUNDFX */ SoundEffectChangeInfo,
4521  /* GSF_AIRPORTS */ AirportChangeInfo,
4522  /* GSF_SIGNALS */ NULL,
4523  /* GSF_OBJECTS */ ObjectChangeInfo,
4524  /* GSF_RAILTYPES */ RailTypeChangeInfo,
4525  /* GSF_AIRPORTTILES */ AirportTilesChangeInfo,
4526  };
4527 
4528  uint8 feature = buf->ReadByte();
4529  uint8 numprops = buf->ReadByte();
4530  uint numinfo = buf->ReadByte();
4531  uint engine = buf->ReadExtendedByte();
4532 
4533  grfmsg(6, "FeatureChangeInfo: feature %d, %d properties, to apply to %d+%d",
4534  feature, numprops, engine, numinfo);
4535 
4536  if (feature >= lengthof(handler) || handler[feature] == NULL) {
4537  if (feature != GSF_CARGOES) grfmsg(1, "FeatureChangeInfo: Unsupported feature %d, skipping", feature);
4538  return;
4539  }
4540 
4541  /* Mark the feature as used by the grf */
4542  SetBit(_cur.grffile->grf_features, feature);
4543 
4544  while (numprops-- && buf->HasData()) {
4545  uint8 prop = buf->ReadByte();
4546 
4547  ChangeInfoResult cir = handler[feature](engine, numinfo, prop, buf);
4548  if (HandleChangeInfoResult("FeatureChangeInfo", cir, feature, prop)) return;
4549  }
4550 }
4551 
4552 /* Action 0x00 (GLS_SAFETYSCAN) */
4553 static void SafeChangeInfo(ByteReader *buf)
4554 {
4555  uint8 feature = buf->ReadByte();
4556  uint8 numprops = buf->ReadByte();
4557  uint numinfo = buf->ReadByte();
4558  buf->ReadExtendedByte(); // id
4559 
4560  if (feature == GSF_BRIDGES && numprops == 1) {
4561  uint8 prop = buf->ReadByte();
4562  /* Bridge property 0x0D is redefinition of sprite layout tables, which
4563  * is considered safe. */
4564  if (prop == 0x0D) return;
4565  } else if (feature == GSF_GLOBALVAR && numprops == 1) {
4566  uint8 prop = buf->ReadByte();
4567  /* Engine ID Mappings are safe, if the source is static */
4568  if (prop == 0x11) {
4569  bool is_safe = true;
4570  for (uint i = 0; i < numinfo; i++) {
4571  uint32 s = buf->ReadDWord();
4572  buf->ReadDWord(); // dest
4573  const GRFConfig *grfconfig = GetGRFConfig(s);
4574  if (grfconfig != NULL && !HasBit(grfconfig->flags, GCF_STATIC)) {
4575  is_safe = false;
4576  break;
4577  }
4578  }
4579  if (is_safe) return;
4580  }
4581  }
4582 
4583  SetBit(_cur.grfconfig->flags, GCF_UNSAFE);
4584 
4585  /* Skip remainder of GRF */
4586  _cur.skip_sprites = -1;
4587 }
4588 
4589 /* Action 0x00 (GLS_RESERVE) */
4590 static void ReserveChangeInfo(ByteReader *buf)
4591 {
4592  uint8 feature = buf->ReadByte();
4593 
4594  if (feature != GSF_CARGOES && feature != GSF_GLOBALVAR && feature != GSF_RAILTYPES) return;
4595 
4596  uint8 numprops = buf->ReadByte();
4597  uint8 numinfo = buf->ReadByte();
4598  uint8 index = buf->ReadExtendedByte();
4599 
4600  while (numprops-- && buf->HasData()) {
4601  uint8 prop = buf->ReadByte();
4603 
4604  switch (feature) {
4605  default: NOT_REACHED();
4606  case GSF_CARGOES:
4607  cir = CargoChangeInfo(index, numinfo, prop, buf);
4608  break;
4609 
4610  case GSF_GLOBALVAR:
4611  cir = GlobalVarReserveInfo(index, numinfo, prop, buf);
4612  break;
4613 
4614  case GSF_RAILTYPES:
4615  cir = RailTypeReserveInfo(index, numinfo, prop, buf);
4616  break;
4617  }
4618 
4619  if (HandleChangeInfoResult("ReserveChangeInfo", cir, feature, prop)) return;
4620  }
4621 }
4622 
4623 /* Action 0x01 */
4624 static void NewSpriteSet(ByteReader *buf)
4625 {
4626  /* Basic format: <01> <feature> <num-sets> <num-ent>
4627  * Extended format: <01> <feature> 00 <first-set> <num-sets> <num-ent>
4628  *
4629  * B feature feature to define sprites for
4630  * 0, 1, 2, 3: veh-type, 4: train stations
4631  * E first-set first sprite set to define
4632  * B num-sets number of sprite sets (extended byte in extended format)
4633  * E num-ent how many entries per sprite set
4634  * For vehicles, this is the number of different
4635  * vehicle directions in each sprite set
4636  * Set num-dirs=8, unless your sprites are symmetric.
4637  * In that case, use num-dirs=4.
4638  */
4639 
4640  uint8 feature = buf->ReadByte();
4641  uint16 num_sets = buf->ReadByte();
4642  uint16 first_set = 0;
4643 
4644  if (num_sets == 0 && buf->HasData(3)) {
4645  /* Extended Action1 format.
4646  * Some GRFs define zero sets of zero sprites, though there is actually no use in that. Ignore them. */
4647  first_set = buf->ReadExtendedByte();
4648  num_sets = buf->ReadExtendedByte();
4649  }
4650  uint16 num_ents = buf->ReadExtendedByte();
4651 
4652  _cur.AddSpriteSets(feature, _cur.spriteid, first_set, num_sets, num_ents);
4653 
4654  grfmsg(7, "New sprite set at %d of type %d, consisting of %d sets with %d views each (total %d)",
4655  _cur.spriteid, feature, num_sets, num_ents, num_sets * num_ents
4656  );
4657 
4658  for (int i = 0; i < num_sets * num_ents; i++) {
4659  _cur.nfo_line++;
4660  LoadNextSprite(_cur.spriteid++, _cur.file_index, _cur.nfo_line, _cur.grf_container_ver);
4661  }
4662 }
4663 
4664 /* Action 0x01 (SKIP) */
4665 static void SkipAct1(ByteReader *buf)
4666 {
4667  buf->ReadByte();
4668  uint16 num_sets = buf->ReadByte();
4669 
4670  if (num_sets == 0 && buf->HasData(3)) {
4671  /* Extended Action1 format.
4672  * Some GRFs define zero sets of zero sprites, though there is actually no use in that. Ignore them. */
4673  buf->ReadExtendedByte(); // first_set
4674  num_sets = buf->ReadExtendedByte();
4675  }
4676  uint16 num_ents = buf->ReadExtendedByte();
4677 
4678  _cur.skip_sprites = num_sets * num_ents;
4679 
4680  grfmsg(3, "SkipAct1: Skipping %d sprites", _cur.skip_sprites);
4681 }
4682 
4683 /* Helper function to either create a callback or link to a previously
4684  * defined spritegroup. */
4685 static const SpriteGroup *GetGroupFromGroupID(byte setid, byte type, uint16 groupid)
4686 {
4687  if (HasBit(groupid, 15)) {
4689  return new CallbackResultSpriteGroup(groupid, _cur.grffile->grf_version >= 8);
4690  }
4691 
4692  if (groupid > MAX_SPRITEGROUP || _cur.spritegroups[groupid] == NULL) {
4693  grfmsg(1, "GetGroupFromGroupID(0x%02X:0x%02X): Groupid 0x%04X does not exist, leaving empty", setid, type, groupid);
4694  return NULL;
4695  }
4696 
4697  return _cur.spritegroups[groupid];
4698 }
4699 
4708 static const SpriteGroup *CreateGroupFromGroupID(byte feature, byte setid, byte type, uint16 spriteid)
4709 {
4710  if (HasBit(spriteid, 15)) {
4712  return new CallbackResultSpriteGroup(spriteid, _cur.grffile->grf_version >= 8);
4713  }
4714 
4715  if (!_cur.IsValidSpriteSet(feature, spriteid)) {
4716  grfmsg(1, "CreateGroupFromGroupID(0x%02X:0x%02X): Sprite set %u invalid", setid, type, spriteid);
4717  return NULL;
4718  }
4719 
4720  SpriteID spriteset_start = _cur.GetSprite(feature, spriteid);
4721  uint num_sprites = _cur.GetNumEnts(feature, spriteid);
4722 
4723  /* Ensure that the sprites are loeded */
4724  assert(spriteset_start + num_sprites <= _cur.spriteid);
4725 
4727  return new ResultSpriteGroup(spriteset_start, num_sprites);
4728 }
4729 
4730 /* Action 0x02 */
4731 static void NewSpriteGroup(ByteReader *buf)
4732 {
4733  /* <02> <feature> <set-id> <type/num-entries> <feature-specific-data...>
4734  *
4735  * B feature see action 1
4736  * B set-id ID of this particular definition
4737  * B type/num-entries
4738  * if 80 or greater, this is a randomized or variational
4739  * list definition, see below
4740  * otherwise it specifies a number of entries, the exact
4741  * meaning depends on the feature
4742  * V feature-specific-data (huge mess, don't even look it up --pasky) */
4743  SpriteGroup *act_group = NULL;
4744 
4745  uint8 feature = buf->ReadByte();
4746  uint8 setid = buf->ReadByte();
4747  uint8 type = buf->ReadByte();
4748 
4749  /* Sprite Groups are created here but they are allocated from a pool, so
4750  * we do not need to delete anything if there is an exception from the
4751  * ByteReader. */
4752 
4753  switch (type) {
4754  /* Deterministic Sprite Group */
4755  case 0x81: // Self scope, byte
4756  case 0x82: // Parent scope, byte
4757  case 0x85: // Self scope, word
4758  case 0x86: // Parent scope, word
4759  case 0x89: // Self scope, dword
4760  case 0x8A: // Parent scope, dword
4761  {
4762  byte varadjust;
4763  byte varsize;
4764 
4767  act_group = group;
4768  group->var_scope = HasBit(type, 1) ? VSG_SCOPE_PARENT : VSG_SCOPE_SELF;
4769 
4770  switch (GB(type, 2, 2)) {
4771  default: NOT_REACHED();
4772  case 0: group->size = DSG_SIZE_BYTE; varsize = 1; break;
4773  case 1: group->size = DSG_SIZE_WORD; varsize = 2; break;
4774  case 2: group->size = DSG_SIZE_DWORD; varsize = 4; break;
4775  }
4776 
4778  adjusts.Clear();
4779 
4780  /* Loop through the var adjusts. Unfortunately we don't know how many we have
4781  * from the outset, so we shall have to keep reallocing. */
4782  do {
4783  DeterministicSpriteGroupAdjust *adjust = adjusts.Append();
4784 
4785  /* The first var adjust doesn't have an operation specified, so we set it to add. */
4786  adjust->operation = adjusts.Length() == 1 ? DSGA_OP_ADD : (DeterministicSpriteGroupAdjustOperation)buf->ReadByte();
4787  adjust->variable = buf->ReadByte();
4788  if (adjust->variable == 0x7E) {
4789  /* Link subroutine group */
4790  adjust->subroutine = GetGroupFromGroupID(setid, type, buf->ReadByte());
4791  } else {
4792  adjust->parameter = IsInsideMM(adjust->variable, 0x60, 0x80) ? buf->ReadByte() : 0;
4793  }
4794 
4795  varadjust = buf->ReadByte();
4796  adjust->shift_num = GB(varadjust, 0, 5);
4797  adjust->type = (DeterministicSpriteGroupAdjustType)GB(varadjust, 6, 2);
4798  adjust->and_mask = buf->ReadVarSize(varsize);
4799 
4800  if (adjust->type != DSGA_TYPE_NONE) {
4801  adjust->add_val = buf->ReadVarSize(varsize);
4802  adjust->divmod_val = buf->ReadVarSize(varsize);
4803  } else {
4804  adjust->add_val = 0;
4805  adjust->divmod_val = 0;
4806  }
4807 
4808  /* Continue reading var adjusts while bit 5 is set. */
4809  } while (HasBit(varadjust, 5));
4810 
4811  group->num_adjusts = adjusts.Length();
4812  group->adjusts = MallocT<DeterministicSpriteGroupAdjust>(group->num_adjusts);
4813  MemCpyT(group->adjusts, adjusts.Begin(), group->num_adjusts);
4814 
4815  std::vector<DeterministicSpriteGroupRange> ranges;
4816  ranges.resize(buf->ReadByte());
4817  for (uint i = 0; i < ranges.size(); i++) {
4818  ranges[i].group = GetGroupFromGroupID(setid, type, buf->ReadWord());
4819  ranges[i].low = buf->ReadVarSize(varsize);
4820  ranges[i].high = buf->ReadVarSize(varsize);
4821  }
4822 
4823  group->default_group = GetGroupFromGroupID(setid, type, buf->ReadWord());
4824  group->error_group = ranges.size() > 0 ? ranges[0].group : group->default_group;
4825  /* nvar == 0 is a special case -- we turn our value into a callback result */
4826  group->calculated_result = ranges.size() == 0;
4827 
4828  /* Sort ranges ascending. When ranges overlap, this may required clamping or splitting them */
4829  std::vector<uint32> bounds;
4830  for (uint i = 0; i < ranges.size(); i++) {
4831  bounds.push_back(ranges[i].low);
4832  if (ranges[i].high != UINT32_MAX) bounds.push_back(ranges[i].high + 1);
4833  }
4834  std::sort(bounds.begin(), bounds.end());
4835  bounds.erase(std::unique(bounds.begin(), bounds.end()), bounds.end());
4836 
4837  std::vector<const SpriteGroup *> target;
4838  for (uint j = 0; j < bounds.size(); ++j) {
4839  uint32 v = bounds[j];
4840  const SpriteGroup *t = group->default_group;
4841  for (uint i = 0; i < ranges.size(); i++) {
4842  if (ranges[i].low <= v && v <= ranges[i].high) {
4843  t = ranges[i].group;
4844  break;
4845  }
4846  }
4847  target.push_back(t);
4848  }
4849  assert(target.size() == bounds.size());
4850 
4851  std::vector<DeterministicSpriteGroupRange> optimised;
4852  for (uint j = 0; j < bounds.size(); ) {
4853  if (target[j] != group->default_group) {
4855  r.group = target[j];
4856  r.low = bounds[j];
4857  while (j < bounds.size() && target[j] == r.group) {
4858  j++;
4859  }
4860  r.high = j < bounds.size() ? bounds[j] - 1 : UINT32_MAX;
4861  optimised.push_back(r);
4862  } else {
4863  j++;
4864  }
4865  }
4866 
4867  group->num_ranges = (uint)optimised.size(); // cast is safe, there should never be 2**31 elements here
4868  if (group->num_ranges > 0) {
4869  group->ranges = MallocT<DeterministicSpriteGroupRange>(group->num_ranges);
4870  MemCpyT(group->ranges, &optimised.front(), group->num_ranges);
4871  }
4872  break;
4873  }
4874 
4875  /* Randomized Sprite Group */
4876  case 0x80: // Self scope
4877  case 0x83: // Parent scope
4878  case 0x84: // Relative scope
4879  {
4882  act_group = group;
4883  group->var_scope = HasBit(type, 1) ? VSG_SCOPE_PARENT : VSG_SCOPE_SELF;
4884 
4885  if (HasBit(type, 2)) {
4886  if (feature <= GSF_AIRCRAFT) group->var_scope = VSG_SCOPE_RELATIVE;
4887  group->count = buf->ReadByte();
4888  }
4889 
4890  uint8 triggers = buf->ReadByte();
4891  group->triggers = GB(triggers, 0, 7);
4892  group->cmp_mode = HasBit(triggers, 7) ? RSG_CMP_ALL : RSG_CMP_ANY;
4893  group->lowest_randbit = buf->ReadByte();
4894  group->num_groups = buf->ReadByte();
4895  group->groups = CallocT<const SpriteGroup*>(group->num_groups);
4896 
4897  for (uint i = 0; i < group->num_groups; i++) {
4898  group->groups[i] = GetGroupFromGroupID(setid, type, buf->ReadWord());
4899  }
4900 
4901  break;
4902  }
4903 
4904  /* Neither a variable or randomized sprite group... must be a real group */
4905  default:
4906  {
4907  switch (feature) {
4908  case GSF_TRAINS:
4909  case GSF_ROADVEHICLES:
4910  case GSF_SHIPS:
4911  case GSF_AIRCRAFT:
4912  case GSF_STATIONS:
4913  case GSF_CANALS:
4914  case GSF_CARGOES:
4915  case GSF_AIRPORTS:
4916  case GSF_RAILTYPES:
4917  {
4918  byte num_loaded = type;
4919  byte num_loading = buf->ReadByte();
4920 
4921  if (!_cur.HasValidSpriteSets(feature)) {
4922  grfmsg(0, "NewSpriteGroup: No sprite set to work on! Skipping");
4923  return;
4924  }
4925 
4927  RealSpriteGroup *group = new RealSpriteGroup();
4928  act_group = group;
4929 
4930  group->num_loaded = num_loaded;
4931  group->num_loading = num_loading;
4932  if (num_loaded > 0) group->loaded = CallocT<const SpriteGroup*>(num_loaded);
4933  if (num_loading > 0) group->loading = CallocT<const SpriteGroup*>(num_loading);
4934 
4935  grfmsg(6, "NewSpriteGroup: New SpriteGroup 0x%02X, %u loaded, %u loading",
4936  setid, num_loaded, num_loading);
4937 
4938  for (uint i = 0; i < num_loaded; i++) {
4939  uint16 spriteid = buf->ReadWord();
4940  group->loaded[i] = CreateGroupFromGroupID(feature, setid, type, spriteid);
4941  grfmsg(8, "NewSpriteGroup: + rg->loaded[%i] = subset %u", i, spriteid);
4942  }
4943 
4944  for (uint i = 0; i < num_loading; i++) {
4945  uint16 spriteid = buf->ReadWord();
4946  group->loading[i] = CreateGroupFromGroupID(feature, setid, type, spriteid);
4947  grfmsg(8, "NewSpriteGroup: + rg->loading[%i] = subset %u", i, spriteid);
4948  }
4949 
4950  break;
4951  }
4952 
4953  case GSF_HOUSES:
4954  case GSF_AIRPORTTILES:
4955  case GSF_OBJECTS:
4956  case GSF_INDUSTRYTILES: {
4957  byte num_building_sprites = max((uint8)1, type);
4958 
4961  act_group = group;
4962 
4963  /* On error, bail out immediately. Temporary GRF data was already freed */
4964  if (ReadSpriteLayout(buf, num_building_sprites, true, feature, false, type == 0, &group->dts)) return;
4965  break;
4966  }
4967 
4968  case GSF_INDUSTRIES: {
4969  if (type > 2) {
4970  grfmsg(1, "NewSpriteGroup: Unsupported industry production version %d, skipping", type);
4971  break;
4972  }
4973 
4976  act_group = group;
4977  group->version = type;
4978  if (type == 0) {
4979  group->num_input = 3;
4980  for (uint i = 0; i < 3; i++) {
4981  group->subtract_input[i] = (int16)buf->ReadWord(); // signed
4982  }
4983  group->num_output = 2;
4984  for (uint i = 0; i < 2; i++) {
4985  group->add_output[i] = buf->ReadWord(); // unsigned
4986  }
4987  group->again = buf->ReadByte();
4988  } else if (type == 1) {
4989  group->num_input = 3;
4990  for (uint i = 0; i < 3; i++) {
4991  group->subtract_input[i] = buf->ReadByte();
4992  }
4993  group->num_output = 2;
4994  for (uint i = 0; i < 2; i++) {
4995  group->add_output[i] = buf->ReadByte();
4996  }
4997  group->again = buf->ReadByte();
4998  } else if (type == 2) {
4999  group->num_input = buf->ReadByte();
5000  if (group->num_input > lengthof(group->subtract_input)) {
5001  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK);
5002  error->data = stredup("too many inputs (max 16)");
5003  return;
5004  }
5005  for (uint i = 0; i < group->num_input; i++) {
5006  byte rawcargo = buf->ReadByte();
5007  CargoID cargo = GetCargoTranslation(rawcargo, _cur.grffile);
5008  if (std::find(group->cargo_input, group->cargo_input + i, cargo) != group->cargo_input + i) {
5009  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK);
5010  error->data = stredup("duplicate input cargo");
5011  return;
5012  }
5013  group->cargo_input[i] = cargo;
5014  group->subtract_input[i] = buf->ReadByte();
5015  }
5016  group->num_output = buf->ReadByte();
5017  if (group->num_output > lengthof(group->add_output)) {
5018  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK);
5019  error->data = stredup("too many outputs (max 16)");
5020  return;
5021  }
5022  for (uint i = 0; i < group->num_output; i++) {
5023  byte rawcargo = buf->ReadByte();
5024  CargoID cargo = GetCargoTranslation(rawcargo, _cur.grffile);
5025  if (std::find(group->cargo_output, group->cargo_output + i, cargo) != group->cargo_output + i) {
5026  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK);
5027  error->data = stredup("duplicate output cargo");
5028  return;
5029  }
5030  group->cargo_output[i] = cargo;
5031  group->add_output[i] = buf->ReadByte();
5032  }
5033  group->again = buf->ReadByte();
5034  } else {
5035  NOT_REACHED();
5036  }
5037  break;
5038  }
5039 
5040  /* Loading of Tile Layout and Production Callback groups would happen here */
5041  default: grfmsg(1, "NewSpriteGroup: Unsupported feature %d, skipping", feature);
5042  }
5043  }
5044  }
5045 
5046  _cur.spritegroups[setid] = act_group;
5047 }
5048 
5049 static CargoID TranslateCargo(uint8 feature, uint8 ctype)
5050 {
5051  if (feature == GSF_OBJECTS) {
5052  switch (ctype) {
5053  case 0: return 0;
5054  case 0xFF: return CT_PURCHASE_OBJECT;
5055  default:
5056  grfmsg(1, "TranslateCargo: Invalid cargo bitnum %d for objects, skipping.", ctype);
5057  return CT_INVALID;
5058  }
5059  }
5060  /* Special cargo types for purchase list and stations */
5061  if (feature == GSF_STATIONS && ctype == 0xFE) return CT_DEFAULT_NA;
5062  if (ctype == 0xFF) return CT_PURCHASE;
5063 
5064  if (_cur.grffile->cargo_list.Length() == 0) {
5065  /* No cargo table, so use bitnum values */
5066  if (ctype >= 32) {
5067  grfmsg(1, "TranslateCargo: Cargo bitnum %d out of range (max 31), skipping.", ctype);
5068  return CT_INVALID;
5069  }
5070 
5071  const CargoSpec *cs;
5072  FOR_ALL_CARGOSPECS(cs) {
5073  if (cs->bitnum == ctype) {
5074  grfmsg(6, "TranslateCargo: Cargo bitnum %d mapped to cargo type %d.", ctype, cs->Index());
5075  return cs->Index();
5076  }
5077  }
5078 
5079  grfmsg(5, "TranslateCargo: Cargo bitnum %d not available in this climate, skipping.", ctype);
5080  return CT_INVALID;
5081  }
5082 
5083  /* Check if the cargo type is out of bounds of the cargo translation table */
5084  if (ctype >= _cur.grffile->cargo_list.Length()) {
5085  grfmsg(1, "TranslateCargo: Cargo type %d out of range (max %d), skipping.", ctype, _cur.grffile->cargo_list.Length() - 1);
5086  return CT_INVALID;
5087  }
5088 
5089  /* Look up the cargo label from the translation table */
5090  CargoLabel cl = _cur.grffile->cargo_list[ctype];
5091  if (cl == 0) {
5092  grfmsg(5, "TranslateCargo: Cargo type %d not available in this climate, skipping.", ctype);
5093  return CT_INVALID;
5094  }
5095 
5096  ctype = GetCargoIDByLabel(cl);
5097  if (ctype == CT_INVALID) {
5098  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));
5099  return CT_INVALID;
5100  }
5101 
5102  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);
5103  return ctype;
5104 }
5105 
5106 
5107 static bool IsValidGroupID(uint16 groupid, const char *function)
5108 {
5109  if (groupid > MAX_SPRITEGROUP || _cur.spritegroups[groupid] == NULL) {
5110  grfmsg(1, "%s: Spritegroup 0x%04X out of range or empty, skipping.", function, groupid);
5111  return false;
5112  }
5113 
5114  return true;
5115 }
5116 
5117 static void VehicleMapSpriteGroup(ByteReader *buf, byte feature, uint8 idcount)
5118 {
5119  static EngineID *last_engines;
5120  static uint last_engines_count;
5121  bool wagover = false;
5122 
5123  /* Test for 'wagon override' flag */
5124  if (HasBit(idcount, 7)) {
5125  wagover = true;
5126  /* Strip off the flag */
5127  idcount = GB(idcount, 0, 7);
5128 
5129  if (last_engines_count == 0) {
5130  grfmsg(0, "VehicleMapSpriteGroup: WagonOverride: No engine to do override with");
5131  return;
5132  }
5133 
5134  grfmsg(6, "VehicleMapSpriteGroup: WagonOverride: %u engines, %u wagons",
5135  last_engines_count, idcount);
5136  } else {
5137  if (last_engines_count != idcount) {
5138  last_engines = ReallocT(last_engines, idcount);
5139  last_engines_count = idcount;
5140  }
5141  }
5142 
5143  EngineID *engines = AllocaM(EngineID, idcount);
5144  for (uint i = 0; i < idcount; i++) {
5145  Engine *e = GetNewEngine(_cur.grffile, (VehicleType)feature, buf->ReadExtendedByte());
5146  if (e == NULL) {
5147  /* No engine could be allocated?!? Deal with it. Okay,
5148  * this might look bad. Also make sure this NewGRF
5149  * gets disabled, as a half loaded one is bad. */
5150  HandleChangeInfoResult("VehicleMapSpriteGroup", CIR_INVALID_ID, 0, 0);
5151  return;
5152  }
5153 
5154  engines[i] = e->index;
5155  if (!wagover) last_engines[i] = engines[i];
5156  }
5157 
5158  uint8 cidcount = buf->ReadByte();
5159  for (uint c = 0; c < cidcount; c++) {
5160  uint8 ctype = buf->ReadByte();
5161  uint16 groupid = buf->ReadWord();
5162  if (!IsValidGroupID(groupid, "VehicleMapSpriteGroup")) continue;
5163 
5164  grfmsg(8, "VehicleMapSpriteGroup: * [%d] Cargo type 0x%X, group id 0x%02X", c, ctype, groupid);
5165 
5166  ctype = TranslateCargo(feature, ctype);
5167  if (ctype == CT_INVALID) continue;
5168 
5169  for (uint i = 0; i < idcount; i++) {
5170  EngineID engine = engines[i];
5171 
5172  grfmsg(7, "VehicleMapSpriteGroup: [%d] Engine %d...", i, engine);
5173 
5174  if (wagover) {
5175  SetWagonOverrideSprites(engine, ctype, _cur.spritegroups[groupid], last_engines, last_engines_count);
5176  } else {
5177  SetCustomEngineSprites(engine, ctype, _cur.spritegroups[groupid]);
5178  }
5179  }
5180  }
5181 
5182  uint16 groupid = buf->ReadWord();
5183  if (!IsValidGroupID(groupid, "VehicleMapSpriteGroup")) return;
5184 
5185  grfmsg(8, "-- Default group id 0x%04X", groupid);
5186 
5187  for (uint i = 0; i < idcount; i++) {
5188  EngineID engine = engines[i];
5189 
5190  if (wagover) {
5191  SetWagonOverrideSprites(engine, CT_DEFAULT, _cur.spritegroups[groupid], last_engines, last_engines_count);
5192  } else {
5193  SetCustomEngineSprites(engine, CT_DEFAULT, _cur.spritegroups[groupid]);
5194  SetEngineGRF(engine, _cur.grffile);
5195  }
5196  }
5197 }
5198 
5199 
5200 static void CanalMapSpriteGroup(ByteReader *buf, uint8 idcount)
5201 {
5202  CanalFeature *cfs = AllocaM(CanalFeature, idcount);
5203  for (uint i = 0; i < idcount; i++) {
5204  cfs[i] = (CanalFeature)buf->ReadByte();
5205  }
5206 
5207  uint8 cidcount = buf->ReadByte();
5208  buf->Skip(cidcount * 3);
5209 
5210  uint16 groupid = buf->ReadWord();
5211  if (!IsValidGroupID(groupid, "CanalMapSpriteGroup")) return;
5212 
5213  for (uint i = 0; i < idcount; i++) {
5214  CanalFeature cf = cfs[i];
5215 
5216  if (cf >= CF_END) {
5217  grfmsg(1, "CanalMapSpriteGroup: Canal subset %d out of range, skipping", cf);
5218  continue;
5219  }
5220 
5221  _water_feature[cf].grffile = _cur.grffile;
5222  _water_feature[cf].group = _cur.spritegroups[groupid];
5223  }
5224 }
5225 
5226 
5227 static void StationMapSpriteGroup(ByteReader *buf, uint8 idcount)
5228 {
5229  uint8 *stations = AllocaM(uint8, idcount);
5230  for (uint i = 0; i < idcount; i++) {
5231  stations[i] = buf->ReadByte();
5232  }
5233 
5234  uint8 cidcount = buf->ReadByte();
5235  for (uint c = 0; c < cidcount; c++) {
5236  uint8 ctype = buf->ReadByte();
5237  uint16 groupid = buf->ReadWord();
5238  if (!IsValidGroupID(groupid, "StationMapSpriteGroup")) continue;
5239 
5240  ctype = TranslateCargo(GSF_STATIONS, ctype);
5241  if (ctype == CT_INVALID) continue;
5242 
5243  for (uint i = 0; i < idcount; i++) {
5244  StationSpec *statspec = _cur.grffile->stations == NULL ? NULL : _cur.grffile->stations[stations[i]];
5245 
5246  if (statspec == NULL) {
5247  grfmsg(1, "StationMapSpriteGroup: Station with ID 0x%02X does not exist, skipping", stations[i]);
5248  continue;
5249  }
5250 
5251  statspec->grf_prop.spritegroup[ctype] = _cur.spritegroups[groupid];
5252  }
5253  }
5254 
5255  uint16 groupid = buf->ReadWord();
5256  if (!IsValidGroupID(groupid, "StationMapSpriteGroup")) return;
5257 
5258  for (uint i = 0; i < idcount; i++) {
5259  StationSpec *statspec = _cur.grffile->stations == NULL ? NULL : _cur.grffile->stations[stations[i]];
5260 
5261  if (statspec == NULL) {
5262  grfmsg(1, "StationMapSpriteGroup: Station with ID 0x%02X does not exist, skipping", stations[i]);
5263  continue;
5264  }
5265 
5266  if (statspec->grf_prop.grffile != NULL) {
5267  grfmsg(1, "StationMapSpriteGroup: Station with ID 0x%02X mapped multiple times, skipping", stations[i]);
5268  continue;
5269  }
5270 
5271  statspec->grf_prop.spritegroup[CT_DEFAULT] = _cur.spritegroups[groupid];
5272  statspec->grf_prop.grffile = _cur.grffile;
5273  statspec->grf_prop.local_id = stations[i];
5274  StationClass::Assign(statspec);
5275  }
5276 }
5277 
5278 
5279 static void TownHouseMapSpriteGroup(ByteReader *buf, uint8 idcount)
5280 {
5281  uint8 *houses = AllocaM(uint8, idcount);
5282  for (uint i = 0; i < idcount; i++) {
5283  houses[i] = buf->ReadByte();
5284  }
5285 
5286  /* Skip the cargo type section, we only care about the default group */
5287  uint8 cidcount = buf->ReadByte();
5288  buf->Skip(cidcount * 3);
5289 
5290  uint16 groupid = buf->ReadWord();
5291  if (!IsValidGroupID(groupid, "TownHouseMapSpriteGroup")) return;
5292 
5293  if (_cur.grffile->housespec == NULL) {
5294  grfmsg(1, "TownHouseMapSpriteGroup: No houses defined, skipping");
5295  return;
5296  }
5297 
5298  for (uint i = 0; i < idcount; i++) {
5299  HouseSpec *hs = _cur.grffile->housespec[houses[i]];
5300 
5301  if (hs == NULL) {
5302  grfmsg(1, "TownHouseMapSpriteGroup: House %d undefined, skipping.", houses[i]);
5303  continue;
5304  }
5305 
5306  hs->grf_prop.spritegroup[0] = _cur.spritegroups[groupid];
5307  }
5308 }
5309 
5310 static void IndustryMapSpriteGroup(ByteReader *buf, uint8 idcount)
5311 {
5312  uint8 *industries = AllocaM(uint8, idcount);
5313  for (uint i = 0; i < idcount; i++) {
5314  industries[i] = buf->ReadByte();
5315  }
5316 
5317  /* Skip the cargo type section, we only care about the default group */
5318  uint8 cidcount = buf->ReadByte();
5319  buf->Skip(cidcount * 3);
5320 
5321  uint16 groupid = buf->ReadWord();
5322  if (!IsValidGroupID(groupid, "IndustryMapSpriteGroup")) return;
5323 
5324  if (_cur.grffile->industryspec == NULL) {
5325  grfmsg(1, "IndustryMapSpriteGroup: No industries defined, skipping");
5326  return;
5327  }
5328 
5329  for (uint i = 0; i < idcount; i++) {
5330  IndustrySpec *indsp = _cur.grffile->industryspec[industries[i]];
5331 
5332  if (indsp == NULL) {
5333  grfmsg(1, "IndustryMapSpriteGroup: Industry %d undefined, skipping", industries[i]);
5334  continue;
5335  }
5336 
5337  indsp->grf_prop.spritegroup[0] = _cur.spritegroups[groupid];
5338  }
5339 }
5340 
5341 static void IndustrytileMapSpriteGroup(ByteReader *buf, uint8 idcount)
5342 {
5343  uint8 *indtiles = AllocaM(uint8, idcount);
5344  for (uint i = 0; i < idcount; i++) {
5345  indtiles[i] = buf->ReadByte();
5346  }
5347 
5348  /* Skip the cargo type section, we only care about the default group */
5349  uint8 cidcount = buf->ReadByte();
5350  buf->Skip(cidcount * 3);
5351 
5352  uint16 groupid = buf->ReadWord();
5353  if (!IsValidGroupID(groupid, "IndustrytileMapSpriteGroup")) return;
5354 
5355  if (_cur.grffile->indtspec == NULL) {
5356  grfmsg(1, "IndustrytileMapSpriteGroup: No industry tiles defined, skipping");
5357  return;
5358  }
5359 
5360  for (uint i = 0; i < idcount; i++) {
5361  IndustryTileSpec *indtsp = _cur.grffile->indtspec[indtiles[i]];
5362 
5363  if (indtsp == NULL) {
5364  grfmsg(1, "IndustrytileMapSpriteGroup: Industry tile %d undefined, skipping", indtiles[i]);
5365  continue;
5366  }
5367 
5368  indtsp->grf_prop.spritegroup[0] = _cur.spritegroups[groupid];
5369  }
5370 }
5371 
5372 static void CargoMapSpriteGroup(ByteReader *buf, uint8 idcount)
5373 {
5374  CargoID *cargoes = AllocaM(CargoID, idcount);
5375  for (uint i = 0; i < idcount; i++) {
5376  cargoes[i] = buf->ReadByte();
5377  }
5378 
5379  /* Skip the cargo type section, we only care about the default group */
5380  uint8 cidcount = buf->ReadByte();
5381  buf->Skip(cidcount * 3);
5382 
5383  uint16 groupid = buf->ReadWord();
5384  if (!IsValidGroupID(groupid, "CargoMapSpriteGroup")) return;
5385 
5386  for (uint i = 0; i < idcount; i++) {
5387  CargoID cid = cargoes[i];
5388 
5389  if (cid >= NUM_CARGO) {
5390  grfmsg(1, "CargoMapSpriteGroup: Cargo ID %d out of range, skipping", cid);
5391  continue;
5392  }
5393 
5394  CargoSpec *cs = CargoSpec::Get(cid);
5395  cs->grffile = _cur.grffile;
5396  cs->group = _cur.spritegroups[groupid];
5397  }
5398 }
5399 
5400 static void ObjectMapSpriteGroup(ByteReader *buf, uint8 idcount)
5401 {
5402  if (_cur.grffile->objectspec == NULL) {
5403  grfmsg(1, "ObjectMapSpriteGroup: No object tiles defined, skipping");
5404  return;
5405  }
5406 
5407  uint8 *objects = AllocaM(uint8, idcount);
5408  for (uint i = 0; i < idcount; i++) {
5409  objects[i] = buf->ReadByte();
5410  }
5411 
5412  uint8 cidcount = buf->ReadByte();
5413  for (uint c = 0; c < cidcount; c++) {
5414  uint8 ctype = buf->ReadByte();
5415  uint16 groupid = buf->ReadWord();
5416  if (!IsValidGroupID(groupid, "ObjectMapSpriteGroup")) continue;
5417 
5418  ctype = TranslateCargo(GSF_OBJECTS, ctype);
5419  if (ctype == CT_INVALID) continue;
5420 
5421  for (uint i = 0; i < idcount; i++) {
5422  ObjectSpec *spec = _cur.grffile->objectspec[objects[i]];
5423 
5424  if (spec == NULL) {
5425  grfmsg(1, "ObjectMapSpriteGroup: Object with ID 0x%02X undefined, skipping", objects[i]);
5426  continue;
5427  }
5428 
5429  spec->grf_prop.spritegroup[ctype] = _cur.spritegroups[groupid];
5430  }
5431  }
5432 
5433  uint16 groupid = buf->ReadWord();
5434  if (!IsValidGroupID(groupid, "ObjectMapSpriteGroup")) return;
5435 
5436  for (uint i = 0; i < idcount; i++) {
5437  ObjectSpec *spec = _cur.grffile->objectspec[objects[i]];
5438 
5439  if (spec == NULL) {
5440  grfmsg(1, "ObjectMapSpriteGroup: Object with ID 0x%02X undefined, skipping", objects[i]);
5441  continue;
5442  }
5443 
5444  if (spec->grf_prop.grffile != NULL) {
5445  grfmsg(1, "ObjectMapSpriteGroup: Object with ID 0x%02X mapped multiple times, skipping", objects[i]);
5446  continue;
5447  }
5448 
5449  spec->grf_prop.spritegroup[0] = _cur.spritegroups[groupid];
5450  spec->grf_prop.grffile = _cur.grffile;
5451  spec->grf_prop.local_id = objects[i];
5452  }
5453 }
5454 
5455 static void RailTypeMapSpriteGroup(ByteReader *buf, uint8 idcount)
5456 {
5457  uint8 *railtypes = AllocaM(uint8, idcount);
5458  for (uint i = 0; i < idcount; i++) {
5459  railtypes[i] = _cur.grffile->railtype_map[buf->ReadByte()];
5460  }
5461 
5462  uint8 cidcount = buf->ReadByte();
5463  for (uint c = 0; c < cidcount; c++) {
5464  uint8 ctype = buf->ReadByte();
5465  uint16 groupid = buf->ReadWord();
5466  if (!IsValidGroupID(groupid, "RailTypeMapSpriteGroup")) continue;
5467 
5468  if (ctype >= RTSG_END) continue;
5469 
5470  extern RailtypeInfo _railtypes[RAILTYPE_END];
5471  for (uint i = 0; i < idcount; i++) {
5472  if (railtypes[i] != INVALID_RAILTYPE) {
5473  RailtypeInfo *rti = &_railtypes[railtypes[i]];
5474 
5475  rti->grffile[ctype] = _cur.grffile;
5476  rti->group[ctype] = _cur.spritegroups[groupid];
5477  }
5478  }
5479  }
5480 
5481  /* Railtypes do not use the default group. */
5482  buf->ReadWord();
5483 }
5484 
5485 static void AirportMapSpriteGroup(ByteReader *buf, uint8 idcount)
5486 {
5487  uint8 *airports = AllocaM(uint8, idcount);
5488  for (uint i = 0; i < idcount; i++) {
5489  airports[i] = buf->ReadByte();
5490  }
5491 
5492  /* Skip the cargo type section, we only care about the default group */
5493  uint8 cidcount = buf->ReadByte();
5494  buf->Skip(cidcount * 3);
5495 
5496  uint16 groupid = buf->ReadWord();
5497  if (!IsValidGroupID(groupid, "AirportMapSpriteGroup")) return;
5498 
5499  if (_cur.grffile->airportspec == NULL) {
5500  grfmsg(1, "AirportMapSpriteGroup: No airports defined, skipping");
5501  return;
5502  }
5503 
5504  for (uint i = 0; i < idcount; i++) {
5505  AirportSpec *as = _cur.grffile->airportspec[airports[i]];
5506 
5507  if (as == NULL) {
5508  grfmsg(1, "AirportMapSpriteGroup: Airport %d undefined, skipping", airports[i]);
5509  continue;
5510  }
5511 
5512  as->grf_prop.spritegroup[0] = _cur.spritegroups[groupid];
5513  }
5514 }
5515 
5516 static void AirportTileMapSpriteGroup(ByteReader *buf, uint8 idcount)
5517 {
5518  uint8 *airptiles = AllocaM(uint8, idcount);
5519  for (uint i = 0; i < idcount; i++) {
5520  airptiles[i] = buf->ReadByte();
5521  }
5522 
5523  /* Skip the cargo type section, we only care about the default group */
5524  uint8 cidcount = buf->ReadByte();
5525  buf->Skip(cidcount * 3);
5526 
5527  uint16 groupid = buf->ReadWord();
5528  if (!IsValidGroupID(groupid, "AirportTileMapSpriteGroup")) return;
5529 
5530  if (_cur.grffile->airtspec == NULL) {
5531  grfmsg(1, "AirportTileMapSpriteGroup: No airport tiles defined, skipping");
5532  return;
5533  }
5534 
5535  for (uint i = 0; i < idcount; i++) {
5536  AirportTileSpec *airtsp = _cur.grffile->airtspec[airptiles[i]];
5537 
5538  if (airtsp == NULL) {
5539  grfmsg(1, "AirportTileMapSpriteGroup: Airport tile %d undefined, skipping", airptiles[i]);
5540  continue;
5541  }
5542 
5543  airtsp->grf_prop.spritegroup[0] = _cur.spritegroups[groupid];
5544  }
5545 }
5546 
5547 
5548 /* Action 0x03 */
5549 static void FeatureMapSpriteGroup(ByteReader *buf)
5550 {
5551  /* <03> <feature> <n-id> <ids>... <num-cid> [<cargo-type> <cid>]... <def-cid>
5552  * id-list := [<id>] [id-list]
5553  * cargo-list := <cargo-type> <cid> [cargo-list]
5554  *
5555  * B feature see action 0
5556  * B n-id bits 0-6: how many IDs this definition applies to
5557  * bit 7: if set, this is a wagon override definition (see below)
5558  * B ids the IDs for which this definition applies
5559  * B num-cid number of cargo IDs (sprite group IDs) in this definition
5560  * can be zero, in that case the def-cid is used always
5561  * B cargo-type type of this cargo type (e.g. mail=2, wood=7, see below)
5562  * W cid cargo ID (sprite group ID) for this type of cargo
5563  * W def-cid default cargo ID (sprite group ID) */
5564 
5565  uint8 feature = buf->ReadByte();
5566  uint8 idcount = buf->ReadByte();
5567 
5568  /* If idcount is zero, this is a feature callback */
5569  if (idcount == 0) {
5570  /* Skip number of cargo ids? */
5571  buf->ReadByte();
5572  uint16 groupid = buf->ReadWord();
5573  if (!IsValidGroupID(groupid, "FeatureMapSpriteGroup")) return;
5574 
5575  grfmsg(6, "FeatureMapSpriteGroup: Adding generic feature callback for feature %d", feature);
5576 
5577  AddGenericCallback(feature, _cur.grffile, _cur.spritegroups[groupid]);
5578  return;
5579  }
5580 
5581  /* Mark the feature as used by the grf (generic callbacks do not count) */
5582  SetBit(_cur.grffile->grf_features, feature);
5583 
5584  grfmsg(6, "FeatureMapSpriteGroup: Feature %d, %d ids", feature, idcount);
5585 
5586  switch (feature) {
5587  case GSF_TRAINS:
5588  case GSF_ROADVEHICLES:
5589  case GSF_SHIPS:
5590  case GSF_AIRCRAFT:
5591  VehicleMapSpriteGroup(buf, feature, idcount);
5592  return;
5593 
5594  case GSF_CANALS:
5595  CanalMapSpriteGroup(buf, idcount);
5596  return;
5597 
5598  case GSF_STATIONS:
5599  StationMapSpriteGroup(buf, idcount);
5600  return;
5601 
5602  case GSF_HOUSES:
5603  TownHouseMapSpriteGroup(buf, idcount);
5604  return;
5605 
5606  case GSF_INDUSTRIES:
5607  IndustryMapSpriteGroup(buf, idcount);
5608  return;
5609 
5610  case GSF_INDUSTRYTILES:
5611  IndustrytileMapSpriteGroup(buf, idcount);
5612  return;
5613 
5614  case GSF_CARGOES:
5615  CargoMapSpriteGroup(buf, idcount);
5616  return;
5617 
5618  case GSF_AIRPORTS:
5619  AirportMapSpriteGroup(buf, idcount);
5620  return;
5621 
5622  case GSF_OBJECTS:
5623  ObjectMapSpriteGroup(buf, idcount);
5624  break;
5625 
5626  case GSF_RAILTYPES:
5627  RailTypeMapSpriteGroup(buf, idcount);
5628  break;
5629 
5630  case GSF_AIRPORTTILES:
5631  AirportTileMapSpriteGroup(buf, idcount);
5632  return;
5633 
5634  default:
5635  grfmsg(1, "FeatureMapSpriteGroup: Unsupported feature %d, skipping", feature);
5636  return;
5637  }
5638 }
5639 
5640 /* Action 0x04 */
5641 static void FeatureNewName(ByteReader *buf)
5642 {
5643  /* <04> <veh-type> <language-id> <num-veh> <offset> <data...>
5644  *
5645  * B veh-type see action 0 (as 00..07, + 0A
5646  * But IF veh-type = 48, then generic text
5647  * B language-id If bit 6 is set, This is the extended language scheme,
5648  * with up to 64 language.
5649  * Otherwise, it is a mapping where set bits have meaning
5650  * 0 = american, 1 = english, 2 = german, 3 = french, 4 = spanish
5651  * Bit 7 set means this is a generic text, not a vehicle one (or else)
5652  * B num-veh number of vehicles which are getting a new name
5653  * B/W offset number of the first vehicle that gets a new name
5654  * Byte : ID of vehicle to change
5655  * Word : ID of string to change/add
5656  * S data new texts, each of them zero-terminated, after
5657  * which the next name begins. */
5658 
5659  bool new_scheme = _cur.grffile->grf_version >= 7;
5660 
5661  uint8 feature = buf->ReadByte();
5662  uint8 lang = buf->ReadByte();
5663  uint8 num = buf->ReadByte();
5664  bool generic = HasBit(lang, 7);
5665  uint16 id;
5666  if (generic) {
5667  id = buf->ReadWord();
5668  } else if (feature <= GSF_AIRCRAFT) {
5669  id = buf->ReadExtendedByte();
5670  } else {
5671  id = buf->ReadByte();
5672  }
5673 
5674  ClrBit(lang, 7);
5675 
5676  uint16 endid = id + num;
5677 
5678  grfmsg(6, "FeatureNewName: About to rename engines %d..%d (feature %d) in language 0x%02X",
5679  id, endid, feature, lang);
5680 
5681  for (; id < endid && buf->HasData(); id++) {
5682  const char *name = buf->ReadString();
5683  grfmsg(8, "FeatureNewName: 0x%04X <- %s", id, name);
5684 
5685  switch (feature) {
5686  case GSF_TRAINS:
5687  case GSF_ROADVEHICLES:
5688  case GSF_SHIPS:
5689  case GSF_AIRCRAFT:
5690  if (!generic) {
5691  Engine *e = GetNewEngine(_cur.grffile, (VehicleType)feature, id, HasBit(_cur.grfconfig->flags, GCF_STATIC));
5692  if (e == NULL) break;
5693  StringID string = AddGRFString(_cur.grffile->grfid, e->index, lang, new_scheme, false, name, e->info.string_id);
5694  e->info.string_id = string;
5695  } else {
5696  AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, true, name, STR_UNDEFINED);
5697  }
5698  break;
5699 
5700  default:
5701  if (IsInsideMM(id, 0xD000, 0xD400) || IsInsideMM(id, 0xD800, 0xE000)) {
5702  AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, true, name, STR_UNDEFINED);
5703  break;
5704  }
5705 
5706  switch (GB(id, 8, 8)) {
5707  case 0xC4: // Station class name
5708  if (_cur.grffile->stations == NULL || _cur.grffile->stations[GB(id, 0, 8)] == NULL) {
5709  grfmsg(1, "FeatureNewName: Attempt to name undefined station 0x%X, ignoring", GB(id, 0, 8));
5710  } else {
5711  StationClassID cls_id = _cur.grffile->stations[GB(id, 0, 8)]->cls_id;
5712  StationClass::Get(cls_id)->name = AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
5713  }
5714  break;
5715 
5716  case 0xC5: // Station name
5717  if (_cur.grffile->stations == NULL || _cur.grffile->stations[GB(id, 0, 8)] == NULL) {
5718  grfmsg(1, "FeatureNewName: Attempt to name undefined station 0x%X, ignoring", GB(id, 0, 8));
5719  } else {
5720  _cur.grffile->stations[GB(id, 0, 8)]->name = AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
5721  }
5722  break;
5723 
5724  case 0xC7: // Airporttile name
5725  if (_cur.grffile->airtspec == NULL || _cur.grffile->airtspec[GB(id, 0, 8)] == NULL) {
5726  grfmsg(1, "FeatureNewName: Attempt to name undefined airport tile 0x%X, ignoring", GB(id, 0, 8));
5727  } else {
5728  _cur.grffile->airtspec[GB(id, 0, 8)]->name = AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
5729  }
5730  break;
5731 
5732  case 0xC9: // House name
5733  if (_cur.grffile->housespec == NULL || _cur.grffile->housespec[GB(id, 0, 8)] == NULL) {
5734  grfmsg(1, "FeatureNewName: Attempt to name undefined house 0x%X, ignoring.", GB(id, 0, 8));
5735  } else {
5736  _cur.grffile->housespec[GB(id, 0, 8)]->building_name = AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
5737  }
5738  break;
5739 
5740  default:
5741  grfmsg(7, "FeatureNewName: Unsupported ID (0x%04X)", id);
5742  break;
5743  }
5744  break;
5745  }
5746  }
5747 }
5748 
5757 static uint16 SanitizeSpriteOffset(uint16& num, uint16 offset, int max_sprites, const char *name)
5758 {
5759 
5760  if (offset >= max_sprites) {
5761  grfmsg(1, "GraphicsNew: %s sprite offset must be less than %i, skipping", name, max_sprites);
5762  uint orig_num = num;
5763  num = 0;
5764  return orig_num;
5765  }
5766 
5767  if (offset + num > max_sprites) {
5768  grfmsg(4, "GraphicsNew: %s sprite overflow, truncating...", name);
5769  uint orig_num = num;
5770  num = max(max_sprites - offset, 0);
5771  return orig_num - num;
5772  }
5773 
5774  return 0;
5775 }
5776 
5777 
5783 };
5785 struct Action5Type {
5788  uint16 min_sprites;
5789  uint16 max_sprites;
5790  const char *name;
5791 };
5792 
5794 static const Action5Type _action5_types[] = {
5795  /* Note: min_sprites should not be changed. Therefore these constants are directly here and not in sprites.h */
5796  /* 0x00 */ { A5BLOCK_INVALID, 0, 0, 0, "Type 0x00" },
5797  /* 0x01 */ { A5BLOCK_INVALID, 0, 0, 0, "Type 0x01" },
5798  /* 0x02 */ { A5BLOCK_INVALID, 0, 0, 0, "Type 0x02" },
5799  /* 0x03 */ { A5BLOCK_INVALID, 0, 0, 0, "Type 0x03" },
5800  /* 0x04 */ { A5BLOCK_ALLOW_OFFSET, SPR_SIGNALS_BASE, 1, PRESIGNAL_SEMAPHORE_AND_PBS_SPRITE_COUNT, "Signal graphics" },
5801  /* 0x05 */ { A5BLOCK_ALLOW_OFFSET, SPR_ELRAIL_BASE, 1, ELRAIL_SPRITE_COUNT, "Rail catenary graphics" },
5802  /* 0x06 */ { A5BLOCK_ALLOW_OFFSET, SPR_SLOPES_BASE, 1, NORMAL_AND_HALFTILE_FOUNDATION_SPRITE_COUNT, "Foundation graphics" },
5803  /* 0x07 */ { A5BLOCK_INVALID, 0, 75, 0, "TTDP GUI graphics" }, // Not used by OTTD.
5804  /* 0x08 */ { A5BLOCK_ALLOW_OFFSET, SPR_CANALS_BASE, 1, CANALS_SPRITE_COUNT, "Canal graphics" },
5805  /* 0x09 */ { A5BLOCK_ALLOW_OFFSET, SPR_ONEWAY_BASE, 1, ONEWAY_SPRITE_COUNT, "One way road graphics" },
5806  /* 0x0A */ { A5BLOCK_ALLOW_OFFSET, SPR_2CCMAP_BASE, 1, TWOCCMAP_SPRITE_COUNT, "2CC colour maps" },
5807  /* 0x0B */ { A5BLOCK_ALLOW_OFFSET, SPR_TRAMWAY_BASE, 1, TRAMWAY_SPRITE_COUNT, "Tramway graphics" },
5808  /* 0x0C */ { A5BLOCK_INVALID, 0, 133, 0, "Snowy temperate tree" }, // Not yet used by OTTD.
5809  /* 0x0D */ { A5BLOCK_FIXED, SPR_SHORE_BASE, 16, SPR_SHORE_SPRITE_COUNT, "Shore graphics" },
5810  /* 0x0E */ { A5BLOCK_INVALID, 0, 0, 0, "New Signals graphics" }, // Not yet used by OTTD.
5811  /* 0x0F */ { A5BLOCK_ALLOW_OFFSET, SPR_TRACKS_FOR_SLOPES_BASE, 1, TRACKS_FOR_SLOPES_SPRITE_COUNT, "Sloped rail track" },
5812  /* 0x10 */ { A5BLOCK_ALLOW_OFFSET, SPR_AIRPORTX_BASE, 1, AIRPORTX_SPRITE_COUNT, "Airport graphics" },
5813  /* 0x11 */ { A5BLOCK_ALLOW_OFFSET, SPR_ROADSTOP_BASE, 1, ROADSTOP_SPRITE_COUNT, "Road stop graphics" },
5814  /* 0x12 */ { A5BLOCK_ALLOW_OFFSET, SPR_AQUEDUCT_BASE, 1, AQUEDUCT_SPRITE_COUNT, "Aqueduct graphics" },
5815  /* 0x13 */ { A5BLOCK_ALLOW_OFFSET, SPR_AUTORAIL_BASE, 1, AUTORAIL_SPRITE_COUNT, "Autorail graphics" },
5816  /* 0x14 */ { A5BLOCK_ALLOW_OFFSET, SPR_FLAGS_BASE, 1, FLAGS_SPRITE_COUNT, "Flag graphics" },
5817  /* 0x15 */ { A5BLOCK_ALLOW_OFFSET, SPR_OPENTTD_BASE, 1, OPENTTD_SPRITE_COUNT, "OpenTTD GUI graphics" },
5818  /* 0x16 */ { A5BLOCK_ALLOW_OFFSET, SPR_AIRPORT_PREVIEW_BASE, 1, SPR_AIRPORT_PREVIEW_COUNT, "Airport preview graphics" },
5819  /* 0x17 */ { A5BLOCK_ALLOW_OFFSET, SPR_RAILTYPE_TUNNEL_BASE, 1, RAILTYPE_TUNNEL_BASE_COUNT, "Railtype tunnel base" },
5820  /* 0x18 */ { A5BLOCK_ALLOW_OFFSET, SPR_PALETTE_BASE, 1, PALETTE_SPRITE_COUNT, "Palette" },
5821 };
5822 
5823 /* Action 0x05 */
5824 static void GraphicsNew(ByteReader *buf)
5825 {
5826  /* <05> <graphics-type> <num-sprites> <other data...>
5827  *
5828  * B graphics-type What set of graphics the sprites define.
5829  * E num-sprites How many sprites are in this set?
5830  * V other data Graphics type specific data. Currently unused. */
5831  /* TODO */
5832 
5833  uint8 type = buf->ReadByte();
5834  uint16 num = buf->ReadExtendedByte();
5835  uint16 offset = HasBit(type, 7) ? buf->ReadExtendedByte() : 0;
5836  ClrBit(type, 7); // Clear the high bit as that only indicates whether there is an offset.
5837 
5838  if ((type == 0x0D) && (num == 10) && HasBit(_cur.grfconfig->flags, GCF_SYSTEM)) {
5839  /* Special not-TTDP-compatible case used in openttd.grf
5840  * Missing shore sprites and initialisation of SPR_SHORE_BASE */
5841  grfmsg(2, "GraphicsNew: Loading 10 missing shore sprites from extra grf.");
5842  LoadNextSprite(SPR_SHORE_BASE + 0, _cur.file_index, _cur.nfo_line++, _cur.grf_container_ver); // SLOPE_STEEP_S
5843  LoadNextSprite(SPR_SHORE_BASE + 5, _cur.file_index, _cur.nfo_line++, _cur.grf_container_ver); // SLOPE_STEEP_W
5844  LoadNextSprite(SPR_SHORE_BASE + 7, _cur.file_index, _cur.nfo_line++, _cur.grf_container_ver); // SLOPE_WSE
5845  LoadNextSprite(SPR_SHORE_BASE + 10, _cur.file_index, _cur.nfo_line++, _cur.grf_container_ver); // SLOPE_STEEP_N
5846  LoadNextSprite(SPR_SHORE_BASE + 11, _cur.file_index, _cur.nfo_line++, _cur.grf_container_ver); // SLOPE_NWS
5847  LoadNextSprite(SPR_SHORE_BASE + 13, _cur.file_index, _cur.nfo_line++, _cur.grf_container_ver); // SLOPE_ENW
5848  LoadNextSprite(SPR_SHORE_BASE + 14, _cur.file_index, _cur.nfo_line++, _cur.grf_container_ver); // SLOPE_SEN
5849  LoadNextSprite(SPR_SHORE_BASE + 15, _cur.file_index, _cur.nfo_line++, _cur.grf_container_ver); // SLOPE_STEEP_E
5850  LoadNextSprite(SPR_SHORE_BASE + 16, _cur.file_index, _cur.nfo_line++, _cur.grf_container_ver); // SLOPE_EW
5851  LoadNextSprite(SPR_SHORE_BASE + 17, _cur.file_index, _cur.nfo_line++, _cur.grf_container_ver); // SLOPE_NS
5852  if (_loaded_newgrf_features.shore == SHORE_REPLACE_NONE) _loaded_newgrf_features.shore = SHORE_REPLACE_ONLY_NEW;
5853  return;
5854  }
5855 
5856  /* Supported type? */
5857  if ((type >= lengthof(_action5_types)) || (_action5_types[type].block_type == A5BLOCK_INVALID)) {
5858  grfmsg(2, "GraphicsNew: Custom graphics (type 0x%02X) sprite block of length %u (unimplemented, ignoring)", type, num);
5859  _cur.skip_sprites = num;
5860  return;
5861  }
5862 
5863  const Action5Type *action5_type = &_action5_types[type];
5864 
5865  /* Contrary to TTDP we allow always to specify too few sprites as we allow always an offset,
5866  * except for the long version of the shore type:
5867  * Ignore offset if not allowed */
5868  if ((action5_type->block_type != A5BLOCK_ALLOW_OFFSET) && (offset != 0)) {
5869  grfmsg(1, "GraphicsNew: %s (type 0x%02X) do not allow an <offset> field. Ignoring offset.", action5_type->name, type);
5870  offset = 0;
5871  }
5872 
5873  /* Ignore action5 if too few sprites are specified. (for TTDP compatibility)
5874  * This does not make sense, if <offset> is allowed */
5875  if ((action5_type->block_type == A5BLOCK_FIXED) && (num < action5_type->min_sprites)) {
5876  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);
5877  _cur.skip_sprites = num;
5878  return;
5879  }
5880 
5881  /* Load at most max_sprites sprites. Skip remaining sprites. (for compatibility with TTDP and future extentions) */
5882  uint16 skip_num = SanitizeSpriteOffset(num, offset, action5_type->max_sprites, action5_type->name);
5883  SpriteID replace = action5_type->sprite_base + offset;
5884 
5885  /* Load <num> sprites starting from <replace>, then skip <skip_num> sprites. */
5886  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);
5887 
5888  for (; num > 0; num--) {
5889  _cur.nfo_line++;
5890  LoadNextSprite(replace == 0 ? _cur.spriteid++ : replace++, _cur.file_index, _cur.nfo_line, _cur.grf_container_ver);
5891  }
5892 
5893  if (type == 0x0D) _loaded_newgrf_features.shore = SHORE_REPLACE_ACTION_5;
5894 
5895  _cur.skip_sprites = skip_num;
5896 }
5897 
5898 /* Action 0x05 (SKIP) */
5899 static void SkipAct5(ByteReader *buf)
5900 {
5901  /* Ignore type byte */
5902  buf->ReadByte();
5903 
5904  /* Skip the sprites of this action */
5905  _cur.skip_sprites = buf->ReadExtendedByte();
5906 
5907  grfmsg(3, "SkipAct5: Skipping %d sprites", _cur.skip_sprites);
5908 }
5909 
5921 bool GetGlobalVariable(byte param, uint32 *value, const GRFFile *grffile)
5922 {
5923  switch (param) {
5924  case 0x00: // current date
5925  *value = max(_date - DAYS_TILL_ORIGINAL_BASE_YEAR, 0);
5926  return true;
5927 
5928  case 0x01: // current year
5930  return true;
5931 
5932  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)
5933  YearMonthDay ymd;
5934  ConvertDateToYMD(_date, &ymd);
5935  Date start_of_year = ConvertYMDToDate(ymd.year, 0, 1);
5936  *value = ymd.month | (ymd.day - 1) << 8 | (IsLeapYear(ymd.year) ? 1 << 15 : 0) | (_date - start_of_year) << 16;
5937  return true;
5938  }
5939 
5940  case 0x03: // current climate, 0=temp, 1=arctic, 2=trop, 3=toyland
5942  return true;
5943 
5944  case 0x06: // road traffic side, bit 4 clear=left, set=right
5945  *value = _settings_game.vehicle.road_side << 4;
5946  return true;
5947 
5948  case 0x09: // date fraction
5949  *value = _date_fract * 885;
5950  return true;
5951 
5952  case 0x0A: // animation counter
5953  *value = _tick_counter;
5954  return true;
5955 
5956  case 0x0B: { // TTDPatch version
5957  uint major = 2;
5958  uint minor = 6;
5959  uint revision = 1; // special case: 2.0.1 is 2.0.10
5960  uint build = 1382;
5961  *value = (major << 24) | (minor << 20) | (revision << 16) | build;
5962  return true;
5963  }
5964 
5965  case 0x0D: // TTD Version, 00=DOS, 01=Windows
5966  *value = _cur.grfconfig->palette & GRFP_USE_MASK;
5967  return true;
5968 
5969  case 0x0E: // Y-offset for train sprites
5970  *value = _cur.grffile->traininfo_vehicle_pitch;
5971  return true;
5972 
5973  case 0x0F: // Rail track type cost factors
5974  *value = 0;
5975  SB(*value, 0, 8, GetRailTypeInfo(RAILTYPE_RAIL)->cost_multiplier); // normal rail
5977  /* skip elrail multiplier - disabled */
5978  SB(*value, 8, 8, GetRailTypeInfo(RAILTYPE_MONO)->cost_multiplier); // monorail
5979  } else {
5980  SB(*value, 8, 8, GetRailTypeInfo(RAILTYPE_ELECTRIC)->cost_multiplier); // electified railway
5981  /* Skip monorail multiplier - no space in result */
5982  }
5983  SB(*value, 16, 8, GetRailTypeInfo(RAILTYPE_MAGLEV)->cost_multiplier); // maglev
5984  return true;
5985 
5986  case 0x11: // current rail tool type
5987  *value = 0; // constant fake value to avoid desync
5988  return true;
5989 
5990  case 0x12: // Game mode
5991  *value = _game_mode;
5992  return true;
5993 
5994  /* case 0x13: // Tile refresh offset to left not implemented */
5995  /* case 0x14: // Tile refresh offset to right not implemented */
5996  /* case 0x15: // Tile refresh offset upwards not implemented */
5997  /* case 0x16: // Tile refresh offset downwards not implemented */
5998  /* case 0x17: // temperate snow line not implemented */
5999 
6000  case 0x1A: // Always -1
6001  *value = UINT_MAX;
6002  return true;
6003 
6004  case 0x1B: // Display options
6005  *value = 0x3F; // constant fake value to avoid desync
6006  return true;
6007 
6008  case 0x1D: // TTD Platform, 00=TTDPatch, 01=OpenTTD
6009  *value = 1;
6010  return true;
6011 
6012  case 0x1E: // Miscellaneous GRF features
6013  *value = _misc_grf_features;
6014 
6015  /* Add the local flags */
6016  assert(!HasBit(*value, GMB_TRAIN_WIDTH_32_PIXELS));
6017  if (_cur.grffile->traininfo_vehicle_width == VEHICLEINFO_FULL_VEHICLE_WIDTH) SetBit(*value, GMB_TRAIN_WIDTH_32_PIXELS);
6018  return true;
6019 
6020  /* case 0x1F: // locale dependent settings not implemented to avoid desync */
6021 
6022  case 0x20: { // snow line height
6023  byte snowline = GetSnowLine();
6025  *value = Clamp(snowline * (grffile->grf_version >= 8 ? 1 : TILE_HEIGHT), 0, 0xFE);
6026  } else {
6027  /* No snow */
6028  *value = 0xFF;
6029  }
6030  return true;
6031  }
6032 
6033  case 0x21: // OpenTTD version
6034  *value = _openttd_newgrf_version;
6035  return true;
6036 
6037  case 0x22: // difficulty level
6038  *value = SP_CUSTOM;
6039  return true;
6040 
6041  case 0x23: // long format date
6042  *value = _date;
6043  return true;
6044 
6045  case 0x24: // long format year
6046  *value = _cur_year;
6047  return true;
6048 
6049  default: return false;
6050  }
6051 }
6052 
6053 static uint32 GetParamVal(byte param, uint32 *cond_val)
6054 {
6055  /* First handle variable common with VarAction2 */
6056  uint32 value;
6057  if (GetGlobalVariable(param - 0x80, &value, _cur.grffile)) return value;
6058 
6059  /* Non-common variable */
6060  switch (param) {
6061  case 0x84: { // GRF loading stage
6062  uint32 res = 0;
6063 
6064  if (_cur.stage > GLS_INIT) SetBit(res, 0);
6065  if (_cur.stage == GLS_RESERVE) SetBit(res, 8);
6066  if (_cur.stage == GLS_ACTIVATION) SetBit(res, 9);
6067  return res;
6068  }
6069 
6070  case 0x85: // TTDPatch flags, only for bit tests
6071  if (cond_val == NULL) {
6072  /* Supported in Action 0x07 and 0x09, not 0x0D */
6073  return 0;
6074  } else {
6075  uint32 index = *cond_val / 0x20;
6076  uint32 param_val = index < lengthof(_ttdpatch_flags) ? _ttdpatch_flags[index] : 0;
6077  *cond_val %= 0x20;
6078  return param_val;
6079  }
6080 
6081  case 0x88: // GRF ID check
6082  return 0;
6083 
6084  /* case 0x99: Global ID offset not implemented */
6085 
6086  default:
6087  /* GRF Parameter */
6088  if (param < 0x80) return _cur.grffile->GetParam(param);
6089 
6090  /* In-game variable. */
6091  grfmsg(1, "Unsupported in-game variable 0x%02X", param);
6092  return UINT_MAX;
6093  }
6094 }
6095 
6096 /* Action 0x06 */
6097 static void CfgApply(ByteReader *buf)
6098 {
6099  /* <06> <param-num> <param-size> <offset> ... <FF>
6100  *
6101  * B param-num Number of parameter to substitute (First = "zero")
6102  * Ignored if that parameter was not specified in newgrf.cfg
6103  * B param-size How many bytes to replace. If larger than 4, the
6104  * bytes of the following parameter are used. In that
6105  * case, nothing is applied unless *all* parameters
6106  * were specified.
6107  * B offset Offset into data from beginning of next sprite
6108  * to place where parameter is to be stored. */
6109 
6110  /* Preload the next sprite */
6111  size_t pos = FioGetPos();
6112  uint32 num = _cur.grf_container_ver >= 2 ? FioReadDword() : FioReadWord();
6113  uint8 type = FioReadByte();
6114  byte *preload_sprite = NULL;
6115 
6116  /* Check if the sprite is a pseudo sprite. We can't operate on real sprites. */
6117  if (type == 0xFF) {
6118  preload_sprite = MallocT<byte>(num);
6119  FioReadBlock(preload_sprite, num);
6120  }
6121 
6122  /* Reset the file position to the start of the next sprite */
6123  FioSeekTo(pos, SEEK_SET);
6124 
6125  if (type != 0xFF) {
6126  grfmsg(2, "CfgApply: Ignoring (next sprite is real, unsupported)");
6127  free(preload_sprite);
6128  return;
6129  }
6130 
6131  GRFLocation location(_cur.grfconfig->ident.grfid, _cur.nfo_line + 1);
6132  GRFLineToSpriteOverride::iterator it = _grf_line_to_action6_sprite_override.find(location);
6133  if (it != _grf_line_to_action6_sprite_override.end()) {
6134  free(preload_sprite);
6135  preload_sprite = _grf_line_to_action6_sprite_override[location];
6136  } else {
6137  _grf_line_to_action6_sprite_override[location] = preload_sprite;
6138  }
6139 
6140  /* Now perform the Action 0x06 on our data. */
6141 
6142  for (;;) {
6143  uint i;
6144  uint param_num;
6145  uint param_size;
6146  uint offset;
6147  bool add_value;
6148 
6149  /* Read the parameter to apply. 0xFF indicates no more data to change. */
6150  param_num = buf->ReadByte();
6151  if (param_num == 0xFF) break;
6152 
6153  /* Get the size of the parameter to use. If the size covers multiple
6154  * double words, sequential parameter values are used. */
6155  param_size = buf->ReadByte();
6156 
6157  /* Bit 7 of param_size indicates we should add to the original value
6158  * instead of replacing it. */
6159  add_value = HasBit(param_size, 7);
6160  param_size = GB(param_size, 0, 7);
6161 
6162  /* Where to apply the data to within the pseudo sprite data. */
6163  offset = buf->ReadExtendedByte();
6164 
6165  /* If the parameter is a GRF parameter (not an internal variable) check
6166  * if it (and all further sequential parameters) has been defined. */
6167  if (param_num < 0x80 && (param_num + (param_size - 1) / 4) >= _cur.grffile->param_end) {
6168  grfmsg(2, "CfgApply: Ignoring (param %d not set)", (param_num + (param_size - 1) / 4));
6169  break;
6170  }
6171 
6172  grfmsg(8, "CfgApply: Applying %u bytes from parameter 0x%02X at offset 0x%04X", param_size, param_num, offset);
6173 
6174  bool carry = false;
6175  for (i = 0; i < param_size && offset + i < num; i++) {
6176  uint32 value = GetParamVal(param_num + i / 4, NULL);
6177  /* Reset carry flag for each iteration of the variable (only really
6178  * matters if param_size is greater than 4) */
6179  if (i % 4 == 0) carry = false;
6180 
6181  if (add_value) {
6182  uint new_value = preload_sprite[offset + i] + GB(value, (i % 4) * 8, 8) + (carry ? 1 : 0);
6183  preload_sprite[offset + i] = GB(new_value, 0, 8);
6184  /* Check if the addition overflowed */
6185  carry = new_value >= 256;
6186  } else {
6187  preload_sprite[offset + i] = GB(value, (i % 4) * 8, 8);
6188  }
6189  }
6190  }
6191 }
6192 
6203 {
6204  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_STATIC_GRF_CAUSES_DESYNC, c);
6205  error->data = stredup(_cur.grfconfig->GetName());
6206 }
6207 
6208 /* Action 0x07
6209  * Action 0x09 */
6210 static void SkipIf(ByteReader *buf)
6211 {
6212  /* <07/09> <param-num> <param-size> <condition-type> <value> <num-sprites>
6213  *
6214  * B param-num
6215  * B param-size
6216  * B condition-type
6217  * V value
6218  * B num-sprites */
6219  /* TODO: More params. More condition types. */
6220  uint32 cond_val = 0;
6221  uint32 mask = 0;
6222  bool result;
6223 
6224  uint8 param = buf->ReadByte();
6225  uint8 paramsize = buf->ReadByte();
6226  uint8 condtype = buf->ReadByte();
6227 
6228  if (condtype < 2) {
6229  /* Always 1 for bit tests, the given value should be ignored. */
6230  paramsize = 1;
6231  }
6232 
6233  switch (paramsize) {
6234  case 8: cond_val = buf->ReadDWord(); mask = buf->ReadDWord(); break;
6235  case 4: cond_val = buf->ReadDWord(); mask = 0xFFFFFFFF; break;
6236  case 2: cond_val = buf->ReadWord(); mask = 0x0000FFFF; break;
6237  case 1: cond_val = buf->ReadByte(); mask = 0x000000FF; break;
6238  default: break;
6239  }
6240 
6241  if (param < 0x80 && _cur.grffile->param_end <= param) {
6242  grfmsg(7, "SkipIf: Param %d undefined, skipping test", param);
6243  return;
6244  }
6245 
6246  uint32 param_val = GetParamVal(param, &cond_val);
6247 
6248  grfmsg(7, "SkipIf: Test condtype %d, param 0x%08X, condval 0x%08X", condtype, param_val, cond_val);
6249 
6250  /*
6251  * Parameter (variable in specs) 0x88 can only have GRF ID checking
6252  * conditions, except conditions 0x0B, 0x0C (cargo availability) and
6253  * 0x0D, 0x0E (Rail type availability) as those ignore the parameter.
6254  * So, when the condition type is one of those, the specific variable
6255  * 0x88 code is skipped, so the "general" code for the cargo
6256  * availability conditions kicks in.
6257  */
6258  if (param == 0x88 && (condtype < 0x0B || condtype > 0x0E)) {
6259  /* GRF ID checks */
6260 
6261  GRFConfig *c = GetGRFConfig(cond_val, mask);
6262 
6263  if (c != NULL && HasBit(c->flags, GCF_STATIC) && !HasBit(_cur.grfconfig->flags, GCF_STATIC) && _networking) {
6265  c = NULL;
6266  }
6267 
6268  if (condtype != 10 && c == NULL) {
6269  grfmsg(7, "SkipIf: GRFID 0x%08X unknown, skipping test", BSWAP32(cond_val));
6270  return;
6271  }
6272 
6273  switch (condtype) {
6274  /* Tests 0x06 to 0x0A are only for param 0x88, GRFID checks */
6275  case 0x06: // Is GRFID active?
6276  result = c->status == GCS_ACTIVATED;
6277  break;
6278 
6279  case 0x07: // Is GRFID non-active?
6280  result = c->status != GCS_ACTIVATED;
6281  break;
6282 
6283  case 0x08: // GRFID is not but will be active?
6284  result = c->status == GCS_INITIALISED;
6285  break;
6286 
6287  case 0x09: // GRFID is or will be active?
6288  result = c->status == GCS_ACTIVATED || c->status == GCS_INITIALISED;
6289  break;
6290 
6291  case 0x0A: // GRFID is not nor will be active
6292  /* This is the only condtype that doesn't get ignored if the GRFID is not found */
6293  result = c == NULL || c->status == GCS_DISABLED || c->status == GCS_NOT_FOUND;
6294  break;
6295 
6296  default: grfmsg(1, "SkipIf: Unsupported GRF condition type %02X. Ignoring", condtype); return;
6297  }
6298  } else {
6299  /* Parameter or variable tests */
6300  switch (condtype) {
6301  case 0x00: result = !!(param_val & (1 << cond_val));
6302  break;
6303  case 0x01: result = !(param_val & (1 << cond_val));
6304  break;
6305  case 0x02: result = (param_val & mask) == cond_val;
6306  break;
6307  case 0x03: result = (param_val & mask) != cond_val;
6308  break;
6309  case 0x04: result = (param_val & mask) < cond_val;
6310  break;
6311  case 0x05: result = (param_val & mask) > cond_val;
6312  break;
6313  case 0x0B: result = GetCargoIDByLabel(BSWAP32(cond_val)) == CT_INVALID;
6314  break;
6315  case 0x0C: result = GetCargoIDByLabel(BSWAP32(cond_val)) != CT_INVALID;
6316  break;
6317  case 0x0D: result = GetRailTypeByLabel(BSWAP32(cond_val)) == INVALID_RAILTYPE;
6318  break;
6319  case 0x0E: result = GetRailTypeByLabel(BSWAP32(cond_val)) != INVALID_RAILTYPE;
6320  break;
6321 
6322  default: grfmsg(1, "SkipIf: Unsupported condition type %02X. Ignoring", condtype); return;
6323  }
6324  }
6325 
6326  if (!result) {
6327  grfmsg(2, "SkipIf: Not skipping sprites, test was false");
6328  return;
6329  }
6330 
6331  uint8 numsprites = buf->ReadByte();
6332 
6333  /* numsprites can be a GOTO label if it has been defined in the GRF
6334  * file. The jump will always be the first matching label that follows
6335  * the current nfo_line. If no matching label is found, the first matching
6336  * label in the file is used. */
6337  GRFLabel *choice = NULL;
6338  for (GRFLabel *label = _cur.grffile->label; label != NULL; label = label->next) {
6339  if (label->label != numsprites) continue;
6340 
6341  /* Remember a goto before the current line */
6342  if (choice == NULL) choice = label;
6343  /* If we find a label here, this is definitely good */
6344  if (label->nfo_line > _cur.nfo_line) {
6345  choice = label;
6346  break;
6347  }
6348  }
6349 
6350  if (choice != NULL) {
6351  grfmsg(2, "SkipIf: Jumping to label 0x%0X at line %d, test was true", choice->label, choice->nfo_line);
6352  FioSeekTo(choice->pos, SEEK_SET);
6353  _cur.nfo_line = choice->nfo_line;
6354  return;
6355  }
6356 
6357  grfmsg(2, "SkipIf: Skipping %d sprites, test was true", numsprites);
6358  _cur.skip_sprites = numsprites;
6359  if (_cur.skip_sprites == 0) {
6360  /* Zero means there are no sprites to skip, so
6361  * we use -1 to indicate that all further
6362  * sprites should be skipped. */
6363  _cur.skip_sprites = -1;
6364 
6365  /* If an action 8 hasn't been encountered yet, disable the grf. */
6366  if (_cur.grfconfig->status != (_cur.stage < GLS_RESERVE ? GCS_INITIALISED : GCS_ACTIVATED)) {
6367  DisableGrf();
6368  }
6369  }
6370 }
6371 
6372 
6373 /* Action 0x08 (GLS_FILESCAN) */
6374 static void ScanInfo(ByteReader *buf)
6375 {
6376  uint8 grf_version = buf->ReadByte();
6377  uint32 grfid = buf->ReadDWord();
6378  const char *name = buf->ReadString();
6379 
6380  _cur.grfconfig->ident.grfid = grfid;
6381 
6382  if (grf_version < 2 || grf_version > 8) {
6384  DEBUG(grf, 0, "%s: NewGRF \"%s\" (GRFID %08X) uses GRF version %d, which is incompatible with this version of OpenTTD.", _cur.grfconfig->filename, name, BSWAP32(grfid), grf_version);
6385  }
6386 
6387  /* GRF IDs starting with 0xFF are reserved for internal TTDPatch use */
6388  if (GB(grfid, 0, 8) == 0xFF) SetBit(_cur.grfconfig->flags, GCF_SYSTEM);
6389 
6390  AddGRFTextToList(&_cur.grfconfig->name->text, 0x7F, grfid, false, name);
6391 
6392  if (buf->HasData()) {
6393  const char *info = buf->ReadString();
6394  AddGRFTextToList(&_cur.grfconfig->info->text, 0x7F, grfid, true, info);
6395  }
6396 
6397  /* GLS_INFOSCAN only looks for the action 8, so we can skip the rest of the file */
6398  _cur.skip_sprites = -1;
6399 }
6400 
6401 /* Action 0x08 */
6402 static void GRFInfo(ByteReader *buf)
6403 {
6404  /* <08> <version> <grf-id> <name> <info>
6405  *
6406  * B version newgrf version, currently 06
6407  * 4*B grf-id globally unique ID of this .grf file
6408  * S name name of this .grf set
6409  * S info string describing the set, and e.g. author and copyright */
6410 
6411  uint8 version = buf->ReadByte();
6412  uint32 grfid = buf->ReadDWord();
6413  const char *name = buf->ReadString();
6414 
6415  if (_cur.stage < GLS_RESERVE && _cur.grfconfig->status != GCS_UNKNOWN) {
6416  DisableGrf(STR_NEWGRF_ERROR_MULTIPLE_ACTION_8);
6417  return;
6418  }
6419 
6420  if (_cur.grffile->grfid != grfid) {
6421  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));
6422  _cur.grffile->grfid = grfid;
6423  }
6424 
6425  _cur.grffile->grf_version = version;
6426  _cur.grfconfig->status = _cur.stage < GLS_RESERVE ? GCS_INITIALISED : GCS_ACTIVATED;
6427 
6428  /* Do swap the GRFID for displaying purposes since people expect that */
6429  DEBUG(grf, 1, "GRFInfo: Loaded GRFv%d set %08X - %s (palette: %s, version: %i)", version, BSWAP32(grfid), name, (_cur.grfconfig->palette & GRFP_USE_MASK) ? "Windows" : "DOS", _cur.grfconfig->version);
6430 }
6431 
6432 /* Action 0x0A */
6433 static void SpriteReplace(ByteReader *buf)
6434 {
6435  /* <0A> <num-sets> <set1> [<set2> ...]
6436  * <set>: <num-sprites> <first-sprite>
6437  *
6438  * B num-sets How many sets of sprites to replace.
6439  * Each set:
6440  * B num-sprites How many sprites are in this set
6441  * W first-sprite First sprite number to replace */
6442 
6443  uint8 num_sets = buf->ReadByte();
6444 
6445  for (uint i = 0; i < num_sets; i++) {
6446  uint8 num_sprites = buf->ReadByte();
6447  uint16 first_sprite = buf->ReadWord();
6448 
6449  grfmsg(2, "SpriteReplace: [Set %d] Changing %d sprites, beginning with %d",
6450  i, num_sprites, first_sprite
6451  );
6452 
6453  for (uint j = 0; j < num_sprites; j++) {
6454  int load_index = first_sprite + j;
6455  _cur.nfo_line++;
6456  LoadNextSprite(load_index, _cur.file_index, _cur.nfo_line, _cur.grf_container_ver); // XXX
6457 
6458  /* Shore sprites now located at different addresses.
6459  * So detect when the old ones get replaced. */
6460  if (IsInsideMM(load_index, SPR_ORIGINALSHORE_START, SPR_ORIGINALSHORE_END + 1)) {
6461  if (_loaded_newgrf_features.shore != SHORE_REPLACE_ACTION_5) _loaded_newgrf_features.shore = SHORE_REPLACE_ACTION_A;
6462  }
6463  }
6464  }
6465 }
6466 
6467 /* Action 0x0A (SKIP) */
6468 static void SkipActA(ByteReader *buf)
6469 {
6470  uint8 num_sets = buf->ReadByte();
6471 
6472  for (uint i = 0; i < num_sets; i++) {
6473  /* Skip the sprites this replaces */
6474  _cur.skip_sprites += buf->ReadByte();
6475  /* But ignore where they go */
6476  buf->ReadWord();
6477  }
6478 
6479  grfmsg(3, "SkipActA: Skipping %d sprites", _cur.skip_sprites);
6480 }
6481 
6482 /* Action 0x0B */
6483 static void GRFLoadError(ByteReader *buf)
6484 {
6485  /* <0B> <severity> <language-id> <message-id> [<message...> 00] [<data...>] 00 [<parnum>]
6486  *
6487  * B severity 00: notice, contine loading grf file
6488  * 01: warning, continue loading grf file
6489  * 02: error, but continue loading grf file, and attempt
6490  * loading grf again when loading or starting next game
6491  * 03: error, abort loading and prevent loading again in
6492  * the future (only when restarting the patch)
6493  * B language-id see action 4, use 1F for built-in error messages
6494  * B message-id message to show, see below
6495  * S message for custom messages (message-id FF), text of the message
6496  * not present for built-in messages.
6497  * V data additional data for built-in (or custom) messages
6498  * B parnum parameter numbers to be shown in the message (maximum of 2) */
6499 
6500  static const StringID msgstr[] = {
6501  STR_NEWGRF_ERROR_VERSION_NUMBER,
6502  STR_NEWGRF_ERROR_DOS_OR_WINDOWS,
6503  STR_NEWGRF_ERROR_UNSET_SWITCH,
6504  STR_NEWGRF_ERROR_INVALID_PARAMETER,
6505  STR_NEWGRF_ERROR_LOAD_BEFORE,
6506  STR_NEWGRF_ERROR_LOAD_AFTER,
6507  STR_NEWGRF_ERROR_OTTD_VERSION_NUMBER,
6508  };
6509 
6510  static const StringID sevstr[] = {
6511  STR_NEWGRF_ERROR_MSG_INFO,
6512  STR_NEWGRF_ERROR_MSG_WARNING,
6513  STR_NEWGRF_ERROR_MSG_ERROR,
6514  STR_NEWGRF_ERROR_MSG_FATAL
6515  };
6516 
6517  byte severity = buf->ReadByte();
6518  byte lang = buf->ReadByte();
6519  byte message_id = buf->ReadByte();
6520 
6521  /* Skip the error if it isn't valid for the current language. */
6522  if (!CheckGrfLangID(lang, _cur.grffile->grf_version)) return;
6523 
6524  /* Skip the error until the activation stage unless bit 7 of the severity
6525  * is set. */
6526  if (!HasBit(severity, 7) && _cur.stage == GLS_INIT) {
6527  grfmsg(7, "GRFLoadError: Skipping non-fatal GRFLoadError in stage %d", _cur.stage);
6528  return;
6529  }
6530  ClrBit(severity, 7);
6531 
6532  if (severity >= lengthof(sevstr)) {
6533  grfmsg(7, "GRFLoadError: Invalid severity id %d. Setting to 2 (non-fatal error).", severity);
6534  severity = 2;
6535  } else if (severity == 3) {
6536  /* This is a fatal error, so make sure the GRF is deactivated and no
6537  * more of it gets loaded. */
6538  DisableGrf();
6539 
6540  /* Make sure we show fatal errors, instead of silly infos from before */
6541  delete _cur.grfconfig->error;
6542  _cur.grfconfig->error = NULL;
6543  }
6544 
6545  if (message_id >= lengthof(msgstr) && message_id != 0xFF) {
6546  grfmsg(7, "GRFLoadError: Invalid message id.");
6547  return;
6548  }
6549 
6550  if (buf->Remaining() <= 1) {
6551  grfmsg(7, "GRFLoadError: No message data supplied.");
6552  return;
6553  }
6554 
6555  /* For now we can only show one message per newgrf file. */
6556  if (_cur.grfconfig->error != NULL) return;
6557 
6558  GRFError *error = new GRFError(sevstr[severity]);
6559 
6560  if (message_id == 0xFF) {
6561  /* This is a custom error message. */
6562  if (buf->HasData()) {
6563  const char *message = buf->ReadString();
6564 
6565  error->custom_message = TranslateTTDPatchCodes(_cur.grffile->grfid, lang, true, message, NULL, SCC_RAW_STRING_POINTER);
6566  } else {
6567  grfmsg(7, "GRFLoadError: No custom message supplied.");
6568  error->custom_message = stredup("");
6569  }
6570  } else {
6571  error->message = msgstr[message_id];
6572  }
6573 
6574  if (buf->HasData()) {
6575  const char *data = buf->ReadString();
6576 
6577  error->data = TranslateTTDPatchCodes(_cur.grffile->grfid, lang, true, data);
6578  } else {
6579  grfmsg(7, "GRFLoadError: No message data supplied.");
6580  error->data = stredup("");
6581  }
6582 
6583  /* Only two parameter numbers can be used in the string. */
6584  for (uint i = 0; i < lengthof(error->param_value) && buf->HasData(); i++) {
6585  uint param_number = buf->ReadByte();
6586  error->param_value[i] = _cur.grffile->GetParam(param_number);
6587  }
6588 
6589  _cur.grfconfig->error = error;
6590 }
6591 
6592 /* Action 0x0C */
6593 static void GRFComment(ByteReader *buf)
6594 {
6595  /* <0C> [<ignored...>]
6596  *
6597  * V ignored Anything following the 0C is ignored */
6598 
6599  if (!buf->HasData()) return;
6600 
6601  const char *text = buf->ReadString();
6602  grfmsg(2, "GRFComment: %s", text);
6603 }
6604 
6605 /* Action 0x0D (GLS_SAFETYSCAN) */
6606 static void SafeParamSet(ByteReader *buf)
6607 {
6608  uint8 target = buf->ReadByte();
6609 
6610  /* Writing GRF parameters and some bits of 'misc GRF features' are safe. */
6611  if (target < 0x80 || target == 0x9E) return;
6612 
6613  /* GRM could be unsafe, but as here it can only happen after other GRFs
6614  * are loaded, it should be okay. If the GRF tried to use the slots it
6615  * reserved, it would be marked unsafe anyway. GRM for (e.g. bridge)
6616  * sprites is considered safe. */
6617 
6618  SetBit(_cur.grfconfig->flags, GCF_UNSAFE);
6619 
6620  /* Skip remainder of GRF */
6621  _cur.skip_sprites = -1;
6622 }
6623 
6624 
6625 static uint32 GetPatchVariable(uint8 param)
6626 {
6627  switch (param) {
6628  /* start year - 1920 */
6630 
6631  /* freight trains weight factor */
6632  case 0x0E: return _settings_game.vehicle.freight_trains;
6633 
6634  /* empty wagon speed increase */
6635  case 0x0F: return 0;
6636 
6637  /* plane speed factor; our patch option is reversed from TTDPatch's,
6638  * the following is good for 1x, 2x and 4x (most common?) and...
6639  * well not really for 3x. */
6640  case 0x10:
6642  default:
6643  case 4: return 1;
6644  case 3: return 2;
6645  case 2: return 2;
6646  case 1: return 4;
6647  }
6648 
6649 
6650  /* 2CC colourmap base sprite */
6651  case 0x11: return SPR_2CCMAP_BASE;
6652 
6653  /* map size: format = -MABXYSS
6654  * M : the type of map
6655  * bit 0 : set : squared map. Bit 1 is now not relevant
6656  * clear : rectangle map. Bit 1 will indicate the bigger edge of the map
6657  * bit 1 : set : Y is the bigger edge. Bit 0 is clear
6658  * clear : X is the bigger edge.
6659  * A : minimum edge(log2) of the map
6660  * B : maximum edge(log2) of the map
6661  * XY : edges(log2) of each side of the map.
6662  * SS : combination of both X and Y, thus giving the size(log2) of the map
6663  */
6664  case 0x13: {
6665  byte map_bits = 0;
6666  byte log_X = MapLogX() - 6; // substraction is required to make the minimal size (64) zero based
6667  byte log_Y = MapLogY() - 6;
6668  byte max_edge = max(log_X, log_Y);
6669 
6670  if (log_X == log_Y) { // we have a squared map, since both edges are identical
6671  SetBit(map_bits, 0);
6672  } else {
6673  if (max_edge == log_Y) SetBit(map_bits, 1); // edge Y been the biggest, mark it
6674  }
6675 
6676  return (map_bits << 24) | (min(log_X, log_Y) << 20) | (max_edge << 16) |
6677  (log_X << 12) | (log_Y << 8) | (log_X + log_Y);
6678  }
6679 
6680  /* The maximum height of the map. */
6681  case 0x14:
6683 
6684  /* Extra foundations base sprite */
6685  case 0x15:
6686  return SPR_SLOPES_BASE;
6687 
6688  /* Shore base sprite */
6689  case 0x16:
6690  return SPR_SHORE_BASE;
6691 
6692  default:
6693  grfmsg(2, "ParamSet: Unknown Patch variable 0x%02X.", param);
6694  return 0;
6695  }
6696 }
6697 
6698 
6699 static uint32 PerformGRM(uint32 *grm, uint16 num_ids, uint16 count, uint8 op, uint8 target, const char *type)
6700 {
6701  uint start = 0;
6702  uint size = 0;
6703 
6704  if (op == 6) {
6705  /* Return GRFID of set that reserved ID */
6706  return grm[_cur.grffile->GetParam(target)];
6707  }
6708 
6709  /* With an operation of 2 or 3, we want to reserve a specific block of IDs */
6710  if (op == 2 || op == 3) start = _cur.grffile->GetParam(target);
6711 
6712  for (uint i = start; i < num_ids; i++) {
6713  if (grm[i] == 0) {
6714  size++;
6715  } else {
6716  if (op == 2 || op == 3) break;
6717  start = i + 1;
6718  size = 0;
6719  }
6720 
6721  if (size == count) break;
6722  }
6723 
6724  if (size == count) {
6725  /* Got the slot... */
6726  if (op == 0 || op == 3) {
6727  grfmsg(2, "ParamSet: GRM: Reserving %d %s at %d", count, type, start);
6728  for (uint i = 0; i < count; i++) grm[start + i] = _cur.grffile->grfid;
6729  }
6730  return start;
6731  }
6732 
6733  /* Unable to allocate */
6734  if (op != 4 && op != 5) {
6735  /* Deactivate GRF */
6736  grfmsg(0, "ParamSet: GRM: Unable to allocate %d %s, deactivating", count, type);
6737  DisableGrf(STR_NEWGRF_ERROR_GRM_FAILED);
6738  return UINT_MAX;
6739  }
6740 
6741  grfmsg(1, "ParamSet: GRM: Unable to allocate %d %s", count, type);
6742  return UINT_MAX;
6743 }
6744 
6745 
6747 static void ParamSet(ByteReader *buf)
6748 {
6749  /* <0D> <target> <operation> <source1> <source2> [<data>]
6750  *
6751  * B target parameter number where result is stored
6752  * B operation operation to perform, see below
6753  * B source1 first source operand
6754  * B source2 second source operand
6755  * D data data to use in the calculation, not necessary
6756  * if both source1 and source2 refer to actual parameters
6757  *
6758  * Operations
6759  * 00 Set parameter equal to source1
6760  * 01 Addition, source1 + source2
6761  * 02 Subtraction, source1 - source2
6762  * 03 Unsigned multiplication, source1 * source2 (both unsigned)
6763  * 04 Signed multiplication, source1 * source2 (both signed)
6764  * 05 Unsigned bit shift, source1 by source2 (source2 taken to be a
6765  * signed quantity; left shift if positive and right shift if
6766  * negative, source1 is unsigned)
6767  * 06 Signed bit shift, source1 by source2
6768  * (source2 like in 05, and source1 as well)
6769  */
6770 
6771  uint8 target = buf->ReadByte();
6772  uint8 oper = buf->ReadByte();
6773  uint32 src1 = buf->ReadByte();
6774  uint32 src2 = buf->ReadByte();
6775 
6776  uint32 data = 0;
6777  if (buf->Remaining() >= 4) data = buf->ReadDWord();
6778 
6779  /* You can add 80 to the operation to make it apply only if the target
6780  * is not defined yet. In this respect, a parameter is taken to be
6781  * defined if any of the following applies:
6782  * - it has been set to any value in the newgrf(w).cfg parameter list
6783  * - it OR A PARAMETER WITH HIGHER NUMBER has been set to any value by
6784  * an earlier action D */
6785  if (HasBit(oper, 7)) {
6786  if (target < 0x80 && target < _cur.grffile->param_end) {
6787  grfmsg(7, "ParamSet: Param %u already defined, skipping", target);
6788  return;
6789  }
6790 
6791  oper = GB(oper, 0, 7);
6792  }
6793 
6794  if (src2 == 0xFE) {
6795  if (GB(data, 0, 8) == 0xFF) {
6796  if (data == 0x0000FFFF) {
6797  /* Patch variables */
6798  src1 = GetPatchVariable(src1);
6799  } else {
6800  /* GRF Resource Management */
6801  uint8 op = src1;
6802  uint8 feature = GB(data, 8, 8);
6803  uint16 count = GB(data, 16, 16);
6804 
6805  if (_cur.stage == GLS_RESERVE) {
6806  if (feature == 0x08) {
6807  /* General sprites */
6808  if (op == 0) {
6809  /* Check if the allocated sprites will fit below the original sprite limit */
6810  if (_cur.spriteid + count >= 16384) {
6811  grfmsg(0, "ParamSet: GRM: Unable to allocate %d sprites; try changing NewGRF order", count);
6812  DisableGrf(STR_NEWGRF_ERROR_GRM_FAILED);
6813  return;
6814  }
6815 
6816  /* Reserve space at the current sprite ID */
6817  grfmsg(4, "ParamSet: GRM: Allocated %d sprites at %d", count, _cur.spriteid);
6818  _grm_sprites[GRFLocation(_cur.grffile->grfid, _cur.nfo_line)] = _cur.spriteid;
6819  _cur.spriteid += count;
6820  }
6821  }
6822  /* Ignore GRM result during reservation */
6823  src1 = 0;
6824  } else if (_cur.stage == GLS_ACTIVATION) {
6825  switch (feature) {
6826  case 0x00: // Trains
6827  case 0x01: // Road Vehicles
6828  case 0x02: // Ships
6829  case 0x03: // Aircraft
6831  src1 = PerformGRM(&_grm_engines[_engine_offsets[feature]], _engine_counts[feature], count, op, target, "vehicles");
6832  if (_cur.skip_sprites == -1) return;
6833  } else {
6834  /* GRM does not apply for dynamic engine allocation. */
6835  switch (op) {
6836  case 2:
6837  case 3:
6838  src1 = _cur.grffile->GetParam(target);
6839  break;
6840 
6841  default:
6842  src1 = 0;
6843  break;
6844  }
6845  }
6846  break;
6847 
6848  case 0x08: // General sprites
6849  switch (op) {
6850  case 0:
6851  /* Return space reserved during reservation stage */
6852  src1 = _grm_sprites[GRFLocation(_cur.grffile->grfid, _cur.nfo_line)];
6853  grfmsg(4, "ParamSet: GRM: Using pre-allocated sprites at %d", src1);
6854  break;
6855 
6856  case 1:
6857  src1 = _cur.spriteid;
6858  break;
6859 
6860  default:
6861  grfmsg(1, "ParamSet: GRM: Unsupported operation %d for general sprites", op);
6862  return;
6863  }
6864  break;
6865 
6866  case 0x0B: // Cargo
6867  /* There are two ranges: one for cargo IDs and one for cargo bitmasks */
6868  src1 = PerformGRM(_grm_cargoes, NUM_CARGO * 2, count, op, target, "cargoes");
6869  if (_cur.skip_sprites == -1) return;
6870  break;
6871 
6872  default: grfmsg(1, "ParamSet: GRM: Unsupported feature 0x%X", feature); return;
6873  }
6874  } else {
6875  /* Ignore GRM during initialization */
6876  src1 = 0;
6877  }
6878  }
6879  } else {
6880  /* Read another GRF File's parameter */
6881  const GRFFile *file = GetFileByGRFID(data);
6882  GRFConfig *c = GetGRFConfig(data);
6883  if (c != NULL && HasBit(c->flags, GCF_STATIC) && !HasBit(_cur.grfconfig->flags, GCF_STATIC) && _networking) {
6884  /* Disable the read GRF if it is a static NewGRF. */
6886  src1 = 0;
6887  } else if (file == NULL || c == NULL || c->status == GCS_DISABLED) {
6888  src1 = 0;
6889  } else if (src1 == 0xFE) {
6890  src1 = c->version;
6891  } else {
6892  src1 = file->GetParam(src1);
6893  }
6894  }
6895  } else {
6896  /* The source1 and source2 operands refer to the grf parameter number
6897  * like in action 6 and 7. In addition, they can refer to the special
6898  * variables available in action 7, or they can be FF to use the value
6899  * of <data>. If referring to parameters that are undefined, a value
6900  * of 0 is used instead. */
6901  src1 = (src1 == 0xFF) ? data : GetParamVal(src1, NULL);
6902  src2 = (src2 == 0xFF) ? data : GetParamVal(src2, NULL);
6903  }
6904 
6905  /* TODO: You can access the parameters of another GRF file by using
6906  * source2=FE, source1=the other GRF's parameter number and data=GRF
6907  * ID. This is only valid with operation 00 (set). If the GRF ID
6908  * cannot be found, a value of 0 is used for the parameter value
6909  * instead. */
6910 
6911  uint32 res;
6912  switch (oper) {
6913  case 0x00:
6914  res = src1;
6915  break;
6916 
6917  case 0x01:
6918  res = src1 + src2;
6919  break;
6920 
6921  case 0x02:
6922  res = src1 - src2;
6923  break;
6924 
6925  case 0x03:
6926  res = src1 * src2;
6927  break;
6928 
6929  case 0x04:
6930  res = (int32)src1 * (int32)src2;
6931  break;
6932 
6933  case 0x05:
6934  if ((int32)src2 < 0) {
6935  res = src1 >> -(int32)src2;
6936  } else {
6937  res = src1 << (src2 & 0x1F); // Same behaviour as in EvalAdjustT, mask 'value' to 5 bits, which should behave the same on all architectures.
6938  }
6939  break;
6940 
6941  case 0x06:
6942  if ((int32)src2 < 0) {
6943  res = (int32)src1 >> -(int32)src2;
6944  } else {
6945  res = (int32)src1 << (src2 & 0x1F); // Same behaviour as in EvalAdjustT, mask 'value' to 5 bits, which should behave the same on all architectures.
6946  }
6947  break;
6948 
6949  case 0x07: // Bitwise AND
6950  res = src1 & src2;
6951  break;
6952 
6953  case 0x08: // Bitwise OR
6954  res = src1 | src2;
6955  break;
6956 
6957  case 0x09: // Unsigned division
6958  if (src2 == 0) {
6959  res = src1;
6960  } else {
6961  res = src1 / src2;
6962  }
6963  break;
6964 
6965  case 0x0A: // Signed divison
6966  if (src2 == 0) {
6967  res = src1;
6968  } else {
6969  res = (int32)src1 / (int32)src2;
6970  }
6971  break;
6972 
6973  case 0x0B: // Unsigned modulo
6974  if (src2 == 0) {
6975  res = src1;
6976  } else {
6977  res = src1 % src2;
6978  }
6979  break;
6980 
6981  case 0x0C: // Signed modulo
6982  if (src2 == 0) {
6983  res = src1;
6984  } else {
6985  res = (int32)src1 % (int32)src2;
6986  }
6987  break;
6988 
6989  default: grfmsg(0, "ParamSet: Unknown operation %d, skipping", oper); return;
6990  }
6991 
6992  switch (target) {
6993  case 0x8E: // Y-Offset for train sprites
6994  _cur.grffile->traininfo_vehicle_pitch = res;
6995  break;
6996 
6997  case 0x8F: { // Rail track type cost factors
6998  extern RailtypeInfo _railtypes[RAILTYPE_END];
6999  _railtypes[RAILTYPE_RAIL].cost_multiplier = GB(res, 0, 8);
7001  _railtypes[RAILTYPE_ELECTRIC].cost_multiplier = GB(res, 0, 8);
7002  _railtypes[RAILTYPE_MONO].cost_multiplier = GB(res, 8, 8);
7003  } else {
7004  _railtypes[RAILTYPE_ELECTRIC].cost_multiplier = GB(res, 8, 8);
7005  _railtypes[RAILTYPE_MONO].cost_multiplier = GB(res, 16, 8);
7006  }
7007  _railtypes[RAILTYPE_MAGLEV].cost_multiplier = GB(res, 16, 8);
7008  break;
7009  }
7010 
7011  /* @todo implement */
7012  case 0x93: // Tile refresh offset to left
7013  case 0x94: // Tile refresh offset to right
7014  case 0x95: // Tile refresh offset upwards
7015  case 0x96: // Tile refresh offset downwards
7016  case 0x97: // Snow line height
7017  case 0x99: // Global ID offset
7018  grfmsg(7, "ParamSet: Skipping unimplemented target 0x%02X", target);
7019  break;
7020 
7021  case 0x9E: // Miscellaneous GRF features
7022  /* Set train list engine width */
7023  _cur.grffile->traininfo_vehicle_width = HasBit(res, GMB_TRAIN_WIDTH_32_PIXELS) ? VEHICLEINFO_FULL_VEHICLE_WIDTH : TRAININFO_DEFAULT_VEHICLE_WIDTH;
7024  /* Remove the local flags from the global flags */
7026 
7027  /* Only copy safe bits for static grfs */
7028  if (HasBit(_cur.grfconfig->flags, GCF_STATIC)) {
7029  uint32 safe_bits = 0;
7030  SetBit(safe_bits, GMB_SECOND_ROCKY_TILE_SET);
7031 
7032  _misc_grf_features = (_misc_grf_features & ~safe_bits) | (res & safe_bits);
7033  } else {
7034  _misc_grf_features = res;
7035  }
7036  break;
7037 
7038  case 0x9F: // locale-dependent settings
7039  grfmsg(7, "ParamSet: Skipping unimplemented target 0x%02X", target);
7040  break;
7041 
7042  default:
7043  if (target < 0x80) {
7044  _cur.grffile->param[target] = res;
7045  /* param is zeroed by default */
7046  if (target + 1U > _cur.grffile->param_end) _cur.grffile->param_end = target + 1;
7047  } else {
7048  grfmsg(7, "ParamSet: Skipping unknown target 0x%02X", target);
7049  }
7050  break;
7051  }
7052 }
7053 
7054 /* Action 0x0E (GLS_SAFETYSCAN) */
7055 static void SafeGRFInhibit(ByteReader *buf)
7056 {
7057  /* <0E> <num> <grfids...>
7058  *
7059  * B num Number of GRFIDs that follow
7060  * D grfids GRFIDs of the files to deactivate */
7061 
7062  uint8 num = buf->ReadByte();
7063 
7064  for (uint i = 0; i < num; i++) {
7065  uint32 grfid = buf->ReadDWord();
7066 
7067  /* GRF is unsafe it if tries to deactivate other GRFs */
7068  if (grfid != _cur.grfconfig->ident.grfid) {
7069  SetBit(_cur.grfconfig->flags, GCF_UNSAFE);
7070 
7071  /* Skip remainder of GRF */
7072  _cur.skip_sprites = -1;
7073 
7074  return;
7075  }
7076  }
7077 }
7078 
7079 /* Action 0x0E */
7080 static void GRFInhibit(ByteReader *buf)
7081 {
7082  /* <0E> <num> <grfids...>
7083  *
7084  * B num Number of GRFIDs that follow
7085  * D grfids GRFIDs of the files to deactivate */
7086 
7087  uint8 num = buf->ReadByte();
7088 
7089  for (uint i = 0; i < num; i++) {
7090  uint32 grfid = buf->ReadDWord();
7091  GRFConfig *file = GetGRFConfig(grfid);
7092 
7093  /* Unset activation flag */
7094  if (file != NULL && file != _cur.grfconfig) {
7095  grfmsg(2, "GRFInhibit: Deactivating file '%s'", file->filename);
7096  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_FORCEFULLY_DISABLED, file);
7097  error->data = stredup(_cur.grfconfig->GetName());
7098  }
7099  }
7100 }
7101 
7103 static void FeatureTownName(ByteReader *buf)
7104 {
7105  /* <0F> <id> <style-name> <num-parts> <parts>
7106  *
7107  * B id ID of this definition in bottom 7 bits (final definition if bit 7 set)
7108  * V style-name Name of the style (only for final definition)
7109  * B num-parts Number of parts in this definition
7110  * V parts The parts */
7111 
7112  uint32 grfid = _cur.grffile->grfid;
7113 
7114  GRFTownName *townname = AddGRFTownName(grfid);
7115 
7116  byte id = buf->ReadByte();
7117  grfmsg(6, "FeatureTownName: definition 0x%02X", id & 0x7F);
7118 
7119  if (HasBit(id, 7)) {
7120  /* Final definition */
7121  ClrBit(id, 7);
7122  bool new_scheme = _cur.grffile->grf_version >= 7;
7123 
7124  byte lang = buf->ReadByte();
7125 
7126  byte nb_gen = townname->nb_gen;
7127  do {
7128  ClrBit(lang, 7);
7129 
7130  const char *name = buf->ReadString();
7131 
7132  char *lang_name = TranslateTTDPatchCodes(grfid, lang, false, name);
7133  grfmsg(6, "FeatureTownName: lang 0x%X -> '%s'", lang, lang_name);
7134  free(lang_name);
7135 
7136  townname->name[nb_gen] = AddGRFString(grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
7137 
7138  lang = buf->ReadByte();
7139  } while (lang != 0);
7140  townname->id[nb_gen] = id;
7141  townname->nb_gen++;
7142  }
7143 
7144  byte nb = buf->ReadByte();
7145  grfmsg(6, "FeatureTownName: %u parts", nb);
7146 
7147  townname->nbparts[id] = nb;
7148  townname->partlist[id] = CallocT<NamePartList>(nb);
7149 
7150  for (int i = 0; i < nb; i++) {
7151  byte nbtext = buf->ReadByte();
7152  townname->partlist[id][i].bitstart = buf->ReadByte();
7153  townname->partlist[id][i].bitcount = buf->ReadByte();
7154  townname->partlist[id][i].maxprob = 0;
7155  townname->partlist[id][i].partcount = nbtext;
7156  townname->partlist[id][i].parts = CallocT<NamePart>(nbtext);
7157  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);
7158 
7159  for (int j = 0; j < nbtext; j++) {
7160  byte prob = buf->ReadByte();
7161 
7162  if (HasBit(prob, 7)) {
7163  byte ref_id = buf->ReadByte();
7164 
7165  if (townname->nbparts[ref_id] == 0) {
7166  grfmsg(0, "FeatureTownName: definition 0x%02X doesn't exist, deactivating", ref_id);
7167  DelGRFTownName(grfid);
7168  DisableGrf(STR_NEWGRF_ERROR_INVALID_ID);
7169  return;
7170  }
7171 
7172  grfmsg(6, "FeatureTownName: part %d, text %d, uses intermediate definition 0x%02X (with probability %d)", i, j, ref_id, prob & 0x7F);
7173  townname->partlist[id][i].parts[j].data.id = ref_id;
7174  } else {
7175  const char *text = buf->ReadString();
7176  townname->partlist[id][i].parts[j].data.text = TranslateTTDPatchCodes(grfid, 0, false, text);
7177  grfmsg(6, "FeatureTownName: part %d, text %d, '%s' (with probability %d)", i, j, townname->partlist[id][i].parts[j].data.text, prob);
7178  }
7179  townname->partlist[id][i].parts[j].prob = prob;
7180  townname->partlist[id][i].maxprob += GB(prob, 0, 7);
7181  }
7182  grfmsg(6, "FeatureTownName: part %d, total probability %d", i, townname->partlist[id][i].maxprob);
7183  }
7184 }
7185 
7187 static void DefineGotoLabel(ByteReader *buf)
7188 {
7189  /* <10> <label> [<comment>]
7190  *
7191  * B label The label to define
7192  * V comment Optional comment - ignored */
7193 
7194  byte nfo_label = buf->ReadByte();
7195 
7196  GRFLabel *label = MallocT<GRFLabel>(1);
7197  label->label = nfo_label;
7198  label->nfo_line = _cur.nfo_line;
7199  label->pos = FioGetPos();
7200  label->next = NULL;
7201 
7202  /* Set up a linked list of goto targets which we will search in an Action 0x7/0x9 */
7203  if (_cur.grffile->label == NULL) {
7204  _cur.grffile->label = label;
7205  } else {
7206  /* Attach the label to the end of the list */
7207  GRFLabel *l;
7208  for (l = _cur.grffile->label; l->next != NULL; l = l->next) {}
7209  l->next = label;
7210  }
7211 
7212  grfmsg(2, "DefineGotoLabel: GOTO target with label 0x%02X", label->label);
7213 }
7214 
7219 static void ImportGRFSound(SoundEntry *sound)
7220 {
7221  const GRFFile *file;
7222  uint32 grfid = FioReadDword();
7223  SoundID sound_id = FioReadWord();
7224 
7225  file = GetFileByGRFID(grfid);
7226  if (file == NULL || file->sound_offset == 0) {
7227  grfmsg(1, "ImportGRFSound: Source file not available");
7228  return;
7229  }
7230 
7231  if (sound_id >= file->num_sounds) {
7232  grfmsg(1, "ImportGRFSound: Sound effect %d is invalid", sound_id);
7233  return;
7234  }
7235 
7236  grfmsg(2, "ImportGRFSound: Copying sound %d (%d) from file %X", sound_id, file->sound_offset + sound_id, grfid);
7237 
7238  *sound = *GetSound(file->sound_offset + sound_id);
7239 
7240  /* Reset volume and priority, which TTDPatch doesn't copy */
7241  sound->volume = 128;
7242  sound->priority = 0;
7243 }
7244 
7250 static void LoadGRFSound(size_t offs, SoundEntry *sound)
7251 {
7252  /* Set default volume and priority */
7253  sound->volume = 0x80;
7254  sound->priority = 0;
7255 
7256  if (offs != SIZE_MAX) {
7257  /* Sound is present in the NewGRF. */
7258  sound->file_slot = _cur.file_index;
7259  sound->file_offset = offs;
7260  sound->grf_container_ver = _cur.grf_container_ver;
7261  }
7262 }
7263 
7264 /* Action 0x11 */
7265 static void GRFSound(ByteReader *buf)
7266 {
7267  /* <11> <num>
7268  *
7269  * W num Number of sound files that follow */
7270 
7271  uint16 num = buf->ReadWord();
7272  if (num == 0) return;
7273 
7274  SoundEntry *sound;
7275  if (_cur.grffile->sound_offset == 0) {
7276  _cur.grffile->sound_offset = GetNumSounds();
7277  _cur.grffile->num_sounds = num;
7278  sound = AllocateSound(num);
7279  } else {
7280  sound = GetSound(_cur.grffile->sound_offset);
7281  }
7282 
7283  for (int i = 0; i < num; i++) {
7284  _cur.nfo_line++;
7285 
7286  /* Check whether the index is in range. This might happen if multiple action 11 are present.
7287  * While this is invalid, we do not check for this. But we should prevent it from causing bigger trouble */
7288  bool invalid = i >= _cur.grffile->num_sounds;
7289 
7290  size_t offs = FioGetPos();
7291 
7292  uint32 len = _cur.grf_container_ver >= 2 ? FioReadDword() : FioReadWord();
7293  byte type = FioReadByte();
7294 
7295  if (_cur.grf_container_ver >= 2 && type == 0xFD) {
7296  /* Reference to sprite section. */
7297  if (invalid) {
7298  grfmsg(1, "GRFSound: Sound index out of range (multiple Action 11?)");
7299  FioSkipBytes(len);
7300  } else if (len != 4) {
7301  grfmsg(1, "GRFSound: Invalid sprite section import");
7302  FioSkipBytes(len);
7303  } else {
7304  uint32 id = FioReadDword();
7305  if (_cur.stage == GLS_INIT) LoadGRFSound(GetGRFSpriteOffset(id), sound + i);
7306  }
7307  continue;
7308  }
7309 
7310  if (type != 0xFF) {
7311  grfmsg(1, "GRFSound: Unexpected RealSprite found, skipping");
7312  FioSkipBytes(7);
7313  SkipSpriteData(type, len - 8);
7314  continue;
7315  }
7316 
7317  if (invalid) {
7318  grfmsg(1, "GRFSound: Sound index out of range (multiple Action 11?)");
7319  FioSkipBytes(len);
7320  }
7321 
7322  byte action = FioReadByte();
7323  switch (action) {
7324  case 0xFF:
7325  /* Allocate sound only in init stage. */
7326  if (_cur.stage == GLS_INIT) {
7327  if (_cur.grf_container_ver >= 2) {
7328  grfmsg(1, "GRFSound: Inline sounds are not supported for container version >= 2");
7329  } else {
7330  LoadGRFSound(offs, sound + i);
7331  }
7332  }
7333  FioSkipBytes(len - 1); // already read <action>
7334  break;
7335 
7336  case 0xFE:
7337  if (_cur.stage == GLS_ACTIVATION) {
7338  /* XXX 'Action 0xFE' isn't really specified. It is only mentioned for
7339  * importing sounds, so this is probably all wrong... */
7340  if (FioReadByte() != 0) grfmsg(1, "GRFSound: Import type mismatch");
7341  ImportGRFSound(sound + i);
7342  } else {
7343  FioSkipBytes(len - 1); // already read <action>
7344  }
7345  break;
7346 
7347  default:
7348  grfmsg(1, "GRFSound: Unexpected Action %x found, skipping", action);
7349  FioSkipBytes(len - 1); // already read <action>
7350  break;
7351  }
7352  }
7353 }
7354 
7355 /* Action 0x11 (SKIP) */
7356 static void SkipAct11(ByteReader *buf)
7357 {
7358  /* <11> <num>
7359  *
7360  * W num Number of sound files that follow */
7361 
7362  _cur.skip_sprites = buf->ReadWord();
7363 
7364  grfmsg(3, "SkipAct11: Skipping %d sprites", _cur.skip_sprites);
7365 }
7366 
7368 static void LoadFontGlyph(ByteReader *buf)
7369 {
7370  /* <12> <num_def> <font_size> <num_char> <base_char>
7371  *
7372  * B num_def Number of definitions
7373  * B font_size Size of font (0 = normal, 1 = small, 2 = large, 3 = mono)
7374  * B num_char Number of consecutive glyphs
7375  * W base_char First character index */
7376 
7377  uint8 num_def = buf->ReadByte();
7378 
7379  for (uint i = 0; i < num_def; i++) {
7380  FontSize size = (FontSize)buf->ReadByte();
7381  uint8 num_char = buf->ReadByte();
7382  uint16 base_char = buf->ReadWord();
7383 
7384  if (size >= FS_END) {
7385  grfmsg(1, "LoadFontGlyph: Size %u is not supported, ignoring", size);
7386  }
7387 
7388  grfmsg(7, "LoadFontGlyph: Loading %u glyph(s) at 0x%04X for size %u", num_char, base_char, size);
7389 
7390  for (uint c = 0; c < num_char; c++) {
7391  if (size < FS_END) SetUnicodeGlyph(size, base_char + c, _cur.spriteid);
7392  _cur.nfo_line++;
7393  LoadNextSprite(_cur.spriteid++, _cur.file_index, _cur.nfo_line, _cur.grf_container_ver);
7394  }
7395  }
7396 }
7397 
7399 static void SkipAct12(ByteReader *buf)
7400 {
7401  /* <12> <num_def> <font_size> <num_char> <base_char>
7402  *
7403  * B num_def Number of definitions
7404  * B font_size Size of font (0 = normal, 1 = small, 2 = large)
7405  * B num_char Number of consecutive glyphs
7406  * W base_char First character index */
7407 
7408  uint8 num_def = buf->ReadByte();
7409 
7410  for (uint i = 0; i < num_def; i++) {
7411  /* Ignore 'size' byte */
7412  buf->ReadByte();
7413 
7414  /* Sum up number of characters */
7415  _cur.skip_sprites += buf->ReadByte();
7416 
7417  /* Ignore 'base_char' word */
7418  buf->ReadWord();
7419  }
7420 
7421  grfmsg(3, "SkipAct12: Skipping %d sprites", _cur.skip_sprites);
7422 }
7423 
7426 {
7427  /* <13> <grfid> <num-ent> <offset> <text...>
7428  *
7429  * 4*B grfid The GRFID of the file whose texts are to be translated
7430  * B num-ent Number of strings
7431  * W offset First text ID
7432  * S text... Zero-terminated strings */
7433 
7434  uint32 grfid = buf->ReadDWord();
7435  const GRFConfig *c = GetGRFConfig(grfid);
7436  if (c == NULL || (c->status != GCS_INITIALISED && c->status != GCS_ACTIVATED)) {
7437  grfmsg(7, "TranslateGRFStrings: GRFID 0x%08x unknown, skipping action 13", BSWAP32(grfid));
7438  return;
7439  }
7440 
7441  if (c->status == GCS_INITIALISED) {
7442  /* If the file is not active but will be activated later, give an error
7443  * and disable this file. */
7444  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LOAD_AFTER);
7445 
7446  char tmp[256];
7447  GetString(tmp, STR_NEWGRF_ERROR_AFTER_TRANSLATED_FILE, lastof(tmp));
7448  error->data = stredup(tmp);
7449 
7450  return;
7451  }
7452 
7453  /* Since no language id is supplied for with version 7 and lower NewGRFs, this string has
7454  * to be added as a generic string, thus the language id of 0x7F. For this to work
7455  * new_scheme has to be true as well, which will also be implicitly the case for version 8
7456  * and higher. A language id of 0x7F will be overridden by a non-generic id, so this will
7457  * not change anything if a string has been provided specifically for this language. */
7458  byte language = _cur.grffile->grf_version >= 8 ? buf->ReadByte() : 0x7F;
7459  byte num_strings = buf->ReadByte();
7460  uint16 first_id = buf->ReadWord();
7461 
7462  if (!((first_id >= 0xD000 && first_id + num_strings <= 0xD400) || (first_id >= 0xD800 && first_id + num_strings <= 0xE000))) {
7463  grfmsg(7, "TranslateGRFStrings: Attempting to set out-of-range string IDs in action 13 (first: 0x%4X, number: 0x%2X)", first_id, num_strings);
7464  return;
7465  }
7466 
7467  for (uint i = 0; i < num_strings && buf->HasData(); i++) {
7468  const char *string = buf->ReadString();
7469 
7470  if (StrEmpty(string)) {
7471  grfmsg(7, "TranslateGRFString: Ignoring empty string.");
7472  continue;
7473  }
7474 
7475  AddGRFString(grfid, first_id + i, language, true, true, string, STR_UNDEFINED);
7476  }
7477 }
7478 
7480 static bool ChangeGRFName(byte langid, const char *str)
7481 {
7482  AddGRFTextToList(&_cur.grfconfig->name->text, langid, _cur.grfconfig->ident.grfid, false, str);
7483  return true;
7484 }
7485 
7487 static bool ChangeGRFDescription(byte langid, const char *str)
7488 {
7489  AddGRFTextToList(&_cur.grfconfig->info->text, langid, _cur.grfconfig->ident.grfid, true, str);
7490  return true;
7491 }
7492 
7494 static bool ChangeGRFURL(byte langid, const char *str)
7495 {
7496  AddGRFTextToList(&_cur.grfconfig->url->text, langid, _cur.grfconfig->ident.grfid, false, str);
7497  return true;
7498 }
7499 
7501 static bool ChangeGRFNumUsedParams(size_t len, ByteReader *buf)
7502 {
7503  if (len != 1) {
7504  grfmsg(2, "StaticGRFInfo: expected only 1 byte for 'INFO'->'NPAR' but got " PRINTF_SIZE ", ignoring this field", len);
7505  buf->Skip(len);
7506  } else {
7507  _cur.grfconfig->num_valid_params = min(buf->ReadByte(), lengthof(_cur.grfconfig->param));
7508  }
7509  return true;
7510 }
7511 
7513 static bool ChangeGRFPalette(size_t len, ByteReader *buf)
7514 {
7515  if (len != 1) {
7516  grfmsg(2, "StaticGRFInfo: expected only 1 byte for 'INFO'->'PALS' but got " PRINTF_SIZE ", ignoring this field", len);
7517  buf->Skip(len);
7518  } else {
7519  char data = buf->ReadByte();
7520  GRFPalette pal = GRFP_GRF_UNSET;
7521  switch (data) {
7522  case '*':
7523  case 'A': pal = GRFP_GRF_ANY; break;
7524  case 'W': pal = GRFP_GRF_WINDOWS; break;
7525  case 'D': pal = GRFP_GRF_DOS; break;
7526  default:
7527  grfmsg(2, "StaticGRFInfo: unexpected value '%02x' for 'INFO'->'PALS', ignoring this field", data);
7528  break;
7529  }
7530  if (pal != GRFP_GRF_UNSET) {
7531  _cur.grfconfig->palette &= ~GRFP_GRF_MASK;
7532  _cur.grfconfig->palette |= pal;
7533  }
7534  }
7535  return true;
7536 }
7537 
7539 static bool ChangeGRFBlitter(size_t len, ByteReader *buf)
7540 {
7541  if (len != 1) {
7542  grfmsg(2, "StaticGRFInfo: expected only 1 byte for 'INFO'->'BLTR' but got " PRINTF_SIZE ", ignoring this field", len);
7543  buf->Skip(len);
7544  } else {
7545  char data = buf->ReadByte();
7546  GRFPalette pal = GRFP_BLT_UNSET;
7547  switch (data) {
7548  case '8': pal = GRFP_BLT_UNSET; break;
7549  case '3': pal = GRFP_BLT_32BPP; break;
7550  default:
7551  grfmsg(2, "StaticGRFInfo: unexpected value '%02x' for 'INFO'->'BLTR', ignoring this field", data);
7552  return true;
7553  }
7554  _cur.grfconfig->palette &= ~GRFP_BLT_MASK;
7555  _cur.grfconfig->palette |= pal;
7556  }
7557  return true;
7558 }
7559 
7561 static bool ChangeGRFVersion(size_t len, ByteReader *buf)
7562 {
7563  if (len != 4) {
7564  grfmsg(2, "StaticGRFInfo: expected 4 bytes for 'INFO'->'VRSN' but got " PRINTF_SIZE ", ignoring this field", len);
7565  buf->Skip(len);
7566  } else {
7567  /* Set min_loadable_version as well (default to minimal compatibility) */
7568  _cur.grfconfig->version = _cur.grfconfig->min_loadable_version = buf->ReadDWord();
7569  }
7570  return true;
7571 }
7572 
7574 static bool ChangeGRFMinVersion(size_t len, ByteReader *buf)
7575 {
7576  if (len != 4) {
7577  grfmsg(2, "StaticGRFInfo: expected 4 bytes for 'INFO'->'MINV' but got " PRINTF_SIZE ", ignoring this field", len);
7578  buf->Skip(len);
7579  } else {
7580  _cur.grfconfig->min_loadable_version = buf->ReadDWord();
7581  if (_cur.grfconfig->version == 0) {
7582  grfmsg(2, "StaticGRFInfo: 'MINV' defined before 'VRSN' or 'VRSN' set to 0, ignoring this field");
7583  _cur.grfconfig->min_loadable_version = 0;
7584  }
7585  if (_cur.grfconfig->version < _cur.grfconfig->min_loadable_version) {
7586  grfmsg(2, "StaticGRFInfo: 'MINV' defined as %d, limiting it to 'VRSN'", _cur.grfconfig->min_loadable_version);
7588  }
7589  }
7590  return true;
7591 }
7592 
7594 
7596 static bool ChangeGRFParamName(byte langid, const char *str)
7597 {
7598  AddGRFTextToList(&_cur_parameter->name, langid, _cur.grfconfig->ident.grfid, false, str);
7599  return true;
7600 }
7601 
7603 static bool ChangeGRFParamDescription(byte langid, const char *str)
7604 {
7605  AddGRFTextToList(&_cur_parameter->desc, langid, _cur.grfconfig->ident.grfid, true, str);
7606  return true;
7607 }
7608 
7610 static bool ChangeGRFParamType(size_t len, ByteReader *buf)
7611 {
7612  if (len != 1) {
7613  grfmsg(2, "StaticGRFInfo: expected 1 byte for 'INFO'->'PARA'->'TYPE' but got " PRINTF_SIZE ", ignoring this field", len);
7614  buf->Skip(len);
7615  } else {
7616  GRFParameterType type = (GRFParameterType)buf->ReadByte();
7617  if (type < PTYPE_END) {
7618  _cur_parameter->type = type;
7619  } else {
7620  grfmsg(3, "StaticGRFInfo: unknown parameter type %d, ignoring this field", type);
7621  }
7622  }
7623  return true;
7624 }
7625 
7627 static bool ChangeGRFParamLimits(size_t len, ByteReader *buf)
7628 {
7629  if (_cur_parameter->type != PTYPE_UINT_ENUM) {
7630  grfmsg(2, "StaticGRFInfo: 'INFO'->'PARA'->'LIMI' is only valid for parameters with type uint/enum, ignoring this field");
7631  buf->Skip(len);
7632  } else if (len != 8) {
7633  grfmsg(2, "StaticGRFInfo: expected 8 bytes for 'INFO'->'PARA'->'LIMI' but got " PRINTF_SIZE ", ignoring this field", len);
7634  buf->Skip(len);
7635  } else {
7636  _cur_parameter->min_value = buf->ReadDWord();
7637  _cur_parameter->max_value = buf->ReadDWord();
7638  }
7639  return true;
7640 }
7641 
7643 static bool ChangeGRFParamMask(size_t len, ByteReader *buf)
7644 {
7645  if (len < 1 || len > 3) {
7646  grfmsg(2, "StaticGRFInfo: expected 1 to 3 bytes for 'INFO'->'PARA'->'MASK' but got " PRINTF_SIZE ", ignoring this field", len);
7647  buf->Skip(len);
7648  } else {
7649  byte param_nr = buf->ReadByte();
7650  if (param_nr >= lengthof(_cur.grfconfig->param)) {
7651  grfmsg(2, "StaticGRFInfo: invalid parameter number in 'INFO'->'PARA'->'MASK', param %d, ignoring this field", param_nr);
7652  buf->Skip(len - 1);
7653  } else {
7654  _cur_parameter->param_nr = param_nr;
7655  if (len >= 2) _cur_parameter->first_bit = min(buf->ReadByte(), 31);
7656  if (len >= 3) _cur_parameter->num_bit = min(buf->ReadByte(), 32 - _cur_parameter->first_bit);
7657  }
7658  }
7659 
7660  return true;
7661 }
7662 
7664 static bool ChangeGRFParamDefault(size_t len, ByteReader *buf)
7665 {
7666  if (len != 4) {
7667  grfmsg(2, "StaticGRFInfo: expected 4 bytes for 'INFO'->'PARA'->'DEFA' but got " PRINTF_SIZE ", ignoring this field", len);
7668  buf->Skip(len);
7669  } else {
7670  _cur_parameter->def_value = buf->ReadDWord();
7671  }
7672  _cur.grfconfig->has_param_defaults = true;
7673  return true;
7674 }
7675 
7676 typedef bool (*DataHandler)(size_t, ByteReader *);
7677 typedef bool (*TextHandler)(byte, const char *str);
7678 typedef bool (*BranchHandler)(ByteReader *);
7679 
7690  id(0),
7691  type(0)
7692  {}
7693 
7699  AllowedSubtags(uint32 id, DataHandler handler) :
7700  id(id),
7701  type('B')
7702  {
7703  this->handler.data = handler;
7704  }
7705 
7711  AllowedSubtags(uint32 id, TextHandler handler) :
7712  id(id),
7713  type('T')
7714  {
7715  this->handler.text = handler;
7716  }
7717 
7723  AllowedSubtags(uint32 id, BranchHandler handler) :
7724  id(id),
7725  type('C')
7726  {
7727  this->handler.call_handler = true;
7728  this->handler.u.branch = handler;
7729  }
7730 
7736  AllowedSubtags(uint32 id, AllowedSubtags *subtags) :
7737  id(id),
7738  type('C')
7739  {
7740  this->handler.call_handler = false;
7741  this->handler.u.subtags = subtags;
7742  }
7743 
7744  uint32 id;
7745  byte type;
7746  union {
7749  struct {
7750  union {
7753  } u;
7755  };
7756  } handler;
7757 };
7758 
7759 static bool SkipUnknownInfo(ByteReader *buf, byte type);
7760 static bool HandleNodes(ByteReader *buf, AllowedSubtags *tags);
7761 
7769 {
7770  byte type = buf->ReadByte();
7771  while (type != 0) {
7772  uint32 id = buf->ReadDWord();
7773  if (type != 'T' || id > _cur_parameter->max_value) {
7774  grfmsg(2, "StaticGRFInfo: all child nodes of 'INFO'->'PARA'->param_num->'VALU' should have type 't' and the value/bit number as id");
7775  if (!SkipUnknownInfo(buf, type)) return false;
7776  type = buf->ReadByte();
7777  continue;
7778  }
7779 
7780  byte langid = buf->ReadByte();
7781  const char *name_string = buf->ReadString();
7782 
7783  SmallPair<uint32, GRFText *> *val_name = _cur_parameter->value_names.Find(id);
7784  if (val_name != _cur_parameter->value_names.End()) {
7785  AddGRFTextToList(&val_name->second, langid, _cur.grfconfig->ident.grfid, false, name_string);
7786  } else {
7787  GRFText *list = NULL;
7788  AddGRFTextToList(&list, langid, _cur.grfconfig->ident.grfid, false, name_string);
7789  _cur_parameter->value_names.Insert(id, list);
7790  }
7791 
7792  type = buf->ReadByte();
7793  }
7794  return true;
7795 }
7796 
7806  AllowedSubtags()
7807 };
7808 
7816 {
7817  byte type = buf->ReadByte();
7818  while (type != 0) {
7819  uint32 id = buf->ReadDWord();
7820  if (type != 'C' || id >= _cur.grfconfig->num_valid_params) {
7821  grfmsg(2, "StaticGRFInfo: all child nodes of 'INFO'->'PARA' should have type 'C' and their parameter number as id");
7822  if (!SkipUnknownInfo(buf, type)) return false;
7823  type = buf->ReadByte();
7824  continue;
7825  }
7826 
7827  if (id >= _cur.grfconfig->param_info.Length()) {
7828  uint num_to_add = id - _cur.grfconfig->param_info.Length() + 1;
7829  GRFParameterInfo **newdata = _cur.grfconfig->param_info.Append(num_to_add);
7830  MemSetT<GRFParameterInfo *>(newdata, 0, num_to_add);
7831  }
7832  if (_cur.grfconfig->param_info[id] == NULL) {
7833  _cur.grfconfig->param_info[id] = new GRFParameterInfo(id);
7834  }
7835  _cur_parameter = _cur.grfconfig->param_info[id];
7836  /* Read all parameter-data and process each node. */
7837  if (!HandleNodes(buf, _tags_parameters)) return false;
7838  type = buf->ReadByte();
7839  }
7840  return true;
7841 }
7842 
7845  AllowedSubtags('NAME', ChangeGRFName),
7847  AllowedSubtags('URL_', ChangeGRFURL),
7854  AllowedSubtags()
7855 };
7856 
7859  AllowedSubtags('INFO', _tags_info),
7860  AllowedSubtags()
7861 };
7862 
7863 
7870 static bool SkipUnknownInfo(ByteReader *buf, byte type)
7871 {
7872  /* type and id are already read */
7873  switch (type) {
7874  case 'C': {
7875  byte new_type = buf->ReadByte();
7876  while (new_type != 0) {
7877  buf->ReadDWord(); // skip the id
7878  if (!SkipUnknownInfo(buf, new_type)) return false;
7879  new_type = buf->ReadByte();
7880  }
7881  break;
7882  }
7883 
7884  case 'T':
7885  buf->ReadByte(); // lang
7886  buf->ReadString(); // actual text
7887  break;
7888 
7889  case 'B': {
7890  uint16 size = buf->ReadWord();
7891  buf->Skip(size);
7892  break;
7893  }
7894 
7895  default:
7896  return false;
7897  }
7898 
7899  return true;
7900 }
7901 
7910 static bool HandleNode(byte type, uint32 id, ByteReader *buf, AllowedSubtags subtags[])
7911 {
7912  uint i = 0;
7913  AllowedSubtags *tag;
7914  while ((tag = &subtags[i++])->type != 0) {
7915  if (tag->id != BSWAP32(id) || tag->type != type) continue;
7916  switch (type) {
7917  default: NOT_REACHED();
7918 
7919  case 'T': {
7920  byte langid = buf->ReadByte();
7921  return tag->handler.text(langid, buf->ReadString());
7922  }
7923 
7924  case 'B': {
7925  size_t len = buf->ReadWord();
7926  if (buf->Remaining() < len) return false;
7927  return tag->handler.data(len, buf);
7928  }
7929 
7930  case 'C': {
7931  if (tag->handler.call_handler) {
7932  return tag->handler.u.branch(buf);
7933  }
7934  return HandleNodes(buf, tag->handler.u.subtags);
7935  }
7936  }
7937  }
7938  grfmsg(2, "StaticGRFInfo: unknown type/id combination found, type=%c, id=%x", type, id);
7939  return SkipUnknownInfo(buf, type);
7940 }
7941 
7948 static bool HandleNodes(ByteReader *buf, AllowedSubtags subtags[])
7949 {
7950  byte type = buf->ReadByte();
7951  while (type != 0) {
7952  uint32 id = buf->ReadDWord();
7953  if (!HandleNode(type, id, buf, subtags)) return false;
7954  type = buf->ReadByte();
7955  }
7956  return true;
7957 }
7958 
7963 static void StaticGRFInfo(ByteReader *buf)
7964 {
7965  /* <14> <type> <id> <text/data...> */
7966  HandleNodes(buf, _tags_root);
7967 }
7968 
7974 static void GRFUnsafe(ByteReader *buf)
7975 {
7976  SetBit(_cur.grfconfig->flags, GCF_UNSAFE);
7977 
7978  /* Skip remainder of GRF */
7979  _cur.skip_sprites = -1;
7980 }
7981 
7982 
7985 {
7986  _ttdpatch_flags[0] = ((_settings_game.station.never_expire_airports ? 1 : 0) << 0x0C) // keepsmallairport
7987  | (1 << 0x0D) // newairports
7988  | (1 << 0x0E) // largestations
7989  | ((_settings_game.construction.max_bridge_length > 16 ? 1 : 0) << 0x0F) // longbridges
7990  | (0 << 0x10) // loadtime
7991  | (1 << 0x12) // presignals
7992  | (1 << 0x13) // extpresignals
7993  | ((_settings_game.vehicle.never_expire_vehicles ? 1 : 0) << 0x16) // enginespersist
7994  | (1 << 0x1B) // multihead
7995  | (1 << 0x1D) // lowmemory
7996  | (1 << 0x1E); // generalfixes
7997 
7998  _ttdpatch_flags[1] = ((_settings_game.economy.station_noise_level ? 1 : 0) << 0x07) // moreairports - based on units of noise
7999  | (1 << 0x08) // mammothtrains
8000  | (1 << 0x09) // trainrefit
8001  | (0 << 0x0B) // subsidiaries
8002  | ((_settings_game.order.gradual_loading ? 1 : 0) << 0x0C) // gradualloading
8003  | (1 << 0x12) // unifiedmaglevmode - set bit 0 mode. Not revelant to OTTD
8004  | (1 << 0x13) // unifiedmaglevmode - set bit 1 mode
8005  | (1 << 0x14) // bridgespeedlimits
8006  | (1 << 0x16) // eternalgame
8007  | (1 << 0x17) // newtrains
8008  | (1 << 0x18) // newrvs
8009  | (1 << 0x19) // newships
8010  | (1 << 0x1A) // newplanes
8011  | ((_settings_game.construction.train_signal_side == 1 ? 1 : 0) << 0x1B) // signalsontrafficside
8012  | ((_settings_game.vehicle.disable_elrails ? 0 : 1) << 0x1C); // electrifiedrailway
8013 
8014  _ttdpatch_flags[2] = (1 << 0x01) // loadallgraphics - obsolote
8015  | (1 << 0x03) // semaphores
8016  | (1 << 0x0A) // newobjects
8017  | (0 << 0x0B) // enhancedgui
8018  | (0 << 0x0C) // newagerating
8019  | ((_settings_game.construction.build_on_slopes ? 1 : 0) << 0x0D) // buildonslopes
8020  | (1 << 0x0E) // fullloadany
8021  | (1 << 0x0F) // planespeed
8022  | (0 << 0x10) // moreindustriesperclimate - obsolete
8023  | (0 << 0x11) // moretoylandfeatures
8024  | (1 << 0x12) // newstations
8025  | (1 << 0x13) // tracktypecostdiff
8026  | (1 << 0x14) // manualconvert
8027  | ((_settings_game.construction.build_on_slopes ? 1 : 0) << 0x15) // buildoncoasts
8028  | (1 << 0x16) // canals
8029  | (1 << 0x17) // newstartyear
8030  | ((_settings_game.vehicle.freight_trains > 1 ? 1 : 0) << 0x18) // freighttrains
8031  | (1 << 0x19) // newhouses
8032  | (1 << 0x1A) // newbridges
8033  | (1 << 0x1B) // newtownnames
8034  | (1 << 0x1C) // moreanimation
8035  | ((_settings_game.vehicle.wagon_speed_limits ? 1 : 0) << 0x1D) // wagonspeedlimits
8036  | (1 << 0x1E) // newshistory
8037  | (0 << 0x1F); // custombridgeheads
8038 
8039  _ttdpatch_flags[3] = (0 << 0x00) // newcargodistribution
8040  | (1 << 0x01) // windowsnap
8041  | ((_settings_game.economy.allow_town_roads || _generating_world ? 0 : 1) << 0x02) // townbuildnoroad
8042  | (1 << 0x03) // pathbasedsignalling
8043  | (0 << 0x04) // aichoosechance
8044  | (1 << 0x05) // resolutionwidth
8045  | (1 << 0x06) // resolutionheight
8046  | (1 << 0x07) // newindustries
8047  | ((_settings_game.order.improved_load ? 1 : 0) << 0x08) // fifoloading
8048  | (0 << 0x09) // townroadbranchprob
8049  | (0 << 0x0A) // tempsnowline
8050  | (1 << 0x0B) // newcargo
8051  | (1 << 0x0C) // enhancemultiplayer
8052  | (1 << 0x0D) // onewayroads
8053  | (1 << 0x0E) // irregularstations
8054  | (1 << 0x0F) // statistics
8055  | (1 << 0x10) // newsounds
8056  | (1 << 0x11) // autoreplace
8057  | (1 << 0x12) // autoslope
8058  | (0 << 0x13) // followvehicle
8059  | (1 << 0x14) // trams
8060  | (0 << 0x15) // enhancetunnels
8061  | (1 << 0x16) // shortrvs
8062  | (1 << 0x17) // articulatedrvs
8063  | ((_settings_game.vehicle.dynamic_engines ? 1 : 0) << 0x18) // dynamic engines
8064  | (1 << 0x1E) // variablerunningcosts
8065  | (1 << 0x1F); // any switch is on
8066 
8067  _ttdpatch_flags[4] = (1 << 0x00); // larger persistent storage
8068 }
8069 
8071 static void ResetCustomStations()
8072 {
8073  const GRFFile * const *end = _grf_files.End();
8074  for (GRFFile **file = _grf_files.Begin(); file != end; file++) {
8075  StationSpec **&stations = (*file)->stations;
8076  if (stations == NULL) continue;
8077  for (uint i = 0; i < NUM_STATIONS_PER_GRF; i++) {
8078  if (stations[i] == NULL) continue;
8079  StationSpec *statspec = stations[i];
8080 
8081  delete[] statspec->renderdata;
8082 
8083  /* Release platforms and layouts */
8084  if (!statspec->copied_layouts) {
8085  for (uint l = 0; l < statspec->lengths; l++) {
8086  for (uint p = 0; p < statspec->platforms[l]; p++) {
8087  free(statspec->layouts[l][p]);
8088  }
8089  free(statspec->layouts[l]);
8090  }
8091  free(statspec->layouts);
8092  free(statspec->platforms);
8093  }
8094 
8095  /* Release this station */
8096  free(statspec);
8097  }
8098 
8099  /* Free and reset the station data */
8100  free(stations);
8101  stations = NULL;
8102  }
8103 }
8104 
8106 static void ResetCustomHouses()
8107 {
8108  const GRFFile * const *end = _grf_files.End();
8109  for (GRFFile **file = _grf_files.Begin(); file != end; file++) {
8110  HouseSpec **&housespec = (*file)->housespec;
8111  if (housespec == NULL) continue;
8112  for (uint i = 0; i < NUM_HOUSES_PER_GRF; i++) {
8113  free(housespec[i]);
8114  }
8115 
8116  free(housespec);
8117  housespec = NULL;
8118  }
8119 }
8120 
8122 static void ResetCustomAirports()
8123 {
8124  const GRFFile * const *end = _grf_files.End();
8125  for (GRFFile **file = _grf_files.Begin(); file != end; file++) {
8126  AirportSpec **aslist = (*file)->airportspec;
8127  if (aslist != NULL) {
8128  for (uint i = 0; i < NUM_AIRPORTS_PER_GRF; i++) {
8129  AirportSpec *as = aslist[i];
8130 
8131  if (as != NULL) {
8132  /* We need to remove the tiles layouts */
8133  for (int j = 0; j < as->num_table; j++) {
8134  /* remove the individual layouts */
8135  free(as->table[j]);
8136  }
8137  free(as->table);
8138  free(as->depot_table);
8139  free(as->rotation);
8140 
8141  free(as);
8142  }
8143  }
8144  free(aslist);
8145  (*file)->airportspec = NULL;
8146  }
8147 
8148  AirportTileSpec **&airporttilespec = (*file)->airtspec;
8149  if (airporttilespec != NULL) {
8150  for (uint i = 0; i < NUM_AIRPORTTILES_PER_GRF; i++) {
8151  free(airporttilespec[i]);
8152  }
8153  free(airporttilespec);
8154  airporttilespec = NULL;
8155  }
8156  }
8157 }
8158 
8161 {
8162  const GRFFile * const *end = _grf_files.End();
8163  for (GRFFile **file = _grf_files.Begin(); file != end; file++) {
8164  IndustrySpec **&industryspec = (*file)->industryspec;
8165  IndustryTileSpec **&indtspec = (*file)->indtspec;
8166 
8167  /* We are verifiying both tiles and industries specs loaded from the grf file
8168  * First, let's deal with industryspec */
8169  if (industryspec != NULL) {
8170  for (uint i = 0; i < NUM_INDUSTRYTYPES_PER_GRF; i++) {
8171  IndustrySpec *ind = industryspec[i];
8172  if (ind == NULL) continue;
8173 
8174  /* We need to remove the sounds array */
8175  if (HasBit(ind->cleanup_flag, CLEAN_RANDOMSOUNDS)) {
8176  free(ind->random_sounds);
8177  }
8178 
8179  /* We need to remove the tiles layouts */
8181 
8182  free(ind);
8183  }
8184 
8185  free(industryspec);
8186  industryspec = NULL;
8187  }
8188 
8189  if (indtspec == NULL) continue;
8190  for (uint i = 0; i < NUM_INDUSTRYTILES_PER_GRF; i++) {
8191  free(indtspec[i]);
8192  }
8193 
8194  free(indtspec);
8195  indtspec = NULL;
8196  }
8197 }
8198 
8200 static void ResetCustomObjects()
8201 {
8202  const GRFFile * const *end = _grf_files.End();
8203  for (GRFFile **file = _grf_files.Begin(); file != end; file++) {
8204  ObjectSpec **&objectspec = (*file)->objectspec;
8205  if (objectspec == NULL) continue;
8206  for (uint i = 0; i < NUM_OBJECTS_PER_GRF; i++) {
8207  free(objectspec[i]);
8208  }
8209 
8210  free(objectspec);
8211  objectspec = NULL;
8212  }
8213 }
8214 
8216 static void ResetNewGRF()
8217 {
8218  const GRFFile * const *end = _grf_files.End();
8219  for (GRFFile **file = _grf_files.Begin(); file != end; file++) {
8220  delete *file;
8221  }
8222 
8223  _grf_files.Clear();
8224  _cur.grffile = NULL;
8225 }
8226 
8228 static void ResetNewGRFErrors()
8229 {
8230  for (GRFConfig *c = _grfconfig; c != NULL; c = c->next) {
8231  if (!HasBit(c->flags, GCF_COPY) && c->error != NULL) {
8232  delete c->error;
8233  c->error = NULL;
8234  }
8235  }
8236 }
8237 
8243 {
8244  CleanUpStrings();
8245  CleanUpGRFTownNames();
8246 
8247  /* Copy/reset original engine info data */
8248  SetupEngines();
8249 
8250  /* Copy/reset original bridge info data */
8251  ResetBridges();
8252 
8253  /* Reset rail type information */
8254  ResetRailTypes();
8255 
8256  /* Allocate temporary refit/cargo class data */
8257  _gted = CallocT<GRFTempEngineData>(Engine::GetPoolSize());
8258 
8259  /* Fill rail type label temporary data for default trains */
8260  Engine *e;
8261  FOR_ALL_ENGINES_OF_TYPE(e, VEH_TRAIN) {
8262  _gted[e->index].railtypelabel = GetRailTypeInfo(e->u.rail.railtype)->label;
8263  }
8264 
8265  /* Reset GRM reservations */
8266  memset(&_grm_engines, 0, sizeof(_grm_engines));
8267  memset(&_grm_cargoes, 0, sizeof(_grm_cargoes));
8268 
8269  /* Reset generic feature callback lists */
8271 
8272  /* Reset price base data */
8274 
8275  /* Reset the curencies array */
8276  ResetCurrencies();
8277 
8278  /* Reset the house array */
8280  ResetHouses();
8281 
8282  /* Reset the industries structures*/
8284  ResetIndustries();
8285 
8286  /* Reset the objects. */
8287  ObjectClass::Reset();
8289  ResetObjects();
8290 
8291  /* Reset station classes */
8292  StationClass::Reset();
8294 
8295  /* Reset airport-related structures */
8296  AirportClass::Reset();
8300 
8301  /* Reset canal sprite groups and flags */
8302  memset(_water_feature, 0, sizeof(_water_feature));
8303 
8304  /* Reset the snowline table. */
8305  ClearSnowLine();
8306 
8307  /* Reset NewGRF files */
8308  ResetNewGRF();
8309 
8310  /* Reset NewGRF errors. */
8312 
8313  /* Set up the default cargo types */
8315 
8316  /* Reset misc GRF features and train list display variables */
8317  _misc_grf_features = 0;
8318 
8319  _loaded_newgrf_features.has_2CC = false;
8320  _loaded_newgrf_features.used_liveries = 1 << LS_DEFAULT;
8321  _loaded_newgrf_features.has_newhouses = false;
8322  _loaded_newgrf_features.has_newindustries = false;
8323  _loaded_newgrf_features.shore = SHORE_REPLACE_NONE;
8324 
8325  /* Clear all GRF overrides */
8326  _grf_id_overrides.clear();
8327 
8328  InitializeSoundPool();
8329  _spritegroup_pool.CleanPool();
8330 }
8331 
8336 {
8337  /* Reset override managers */
8338  _engine_mngr.ResetToDefaultMapping();
8339  _house_mngr.ResetMapping();
8340  _industry_mngr.ResetMapping();
8341  _industile_mngr.ResetMapping();
8342  _airport_mngr.ResetMapping();
8343  _airporttile_mngr.ResetMapping();
8344 }
8345 
8351 {
8352  memset(_cur.grffile->cargo_map, 0xFF, sizeof(_cur.grffile->cargo_map));
8353 
8354  for (CargoID c = 0; c < NUM_CARGO; c++) {
8355  const CargoSpec *cs = CargoSpec::Get(c);
8356  if (!cs->IsValid()) continue;
8357 
8358  if (_cur.grffile->cargo_list.Length() == 0) {
8359  /* Default translation table, so just a straight mapping to bitnum */
8360  _cur.grffile->cargo_map[c] = cs->bitnum;
8361  } else {
8362  /* Check the translation table for this cargo's label */
8363  int index = _cur.grffile->cargo_list.FindIndex(cs->label);
8364  if (index >= 0) _cur.grffile->cargo_map[c] = index;
8365  }
8366  }
8367 }
8368 
8373 static void InitNewGRFFile(const GRFConfig *config)
8374 {
8375  GRFFile *newfile = GetFileByFilename(config->filename);
8376  if (newfile != NULL) {
8377  /* We already loaded it once. */
8378  _cur.grffile = newfile;
8379  return;
8380  }
8381 
8382  newfile = new GRFFile(config);
8383  *_grf_files.Append() = _cur.grffile = newfile;
8384 }
8385 
8391 {
8392  this->filename = stredup(config->filename);
8393  this->grfid = config->ident.grfid;
8394 
8395  /* Initialise local settings to defaults */
8396  this->traininfo_vehicle_pitch = 0;
8397  this->traininfo_vehicle_width = TRAININFO_DEFAULT_VEHICLE_WIDTH;
8398 
8399  /* Mark price_base_multipliers as 'not set' */
8400  for (Price i = PR_BEGIN; i < PR_END; i++) {
8401  this->price_base_multipliers[i] = INVALID_PRICE_MODIFIER;
8402  }
8403 
8404  /* Initialise rail type map with default rail types */
8405  memset(this->railtype_map, INVALID_RAILTYPE, sizeof(this->railtype_map));
8406  this->railtype_map[0] = RAILTYPE_RAIL;
8407  this->railtype_map[1] = RAILTYPE_ELECTRIC;
8408  this->railtype_map[2] = RAILTYPE_MONO;
8409  this->railtype_map[3] = RAILTYPE_MAGLEV;
8410 
8411  /* Copy the initial parameter list
8412  * 'Uninitialised' parameters are zeroed as that is their default value when dynamically creating them. */
8413  assert_compile(lengthof(this->param) == lengthof(config->param) && lengthof(this->param) == 0x80);
8414 
8415  assert(config->num_params <= lengthof(config->param));
8416  this->param_end = config->num_params;
8417  if (this->param_end > 0) {
8418  MemCpyT(this->param, config->param, this->param_end);
8419  }
8420 }
8421 
8422 GRFFile::~GRFFile()
8423 {
8424  free(this->filename);
8425  delete[] this->language_map;
8426 }
8427 
8428 
8434  'PASS', 'COAL', 'MAIL', 'LVST', 'GOOD', 'GRAI', 'WHEA', 'MAIZ', 'WOOD',
8435  'IORE', 'STEL', 'VALU', 'GOLD', 'DIAM', 'PAPR', 'FOOD', 'FRUT', 'CORE',
8436  'WATR', 'SUGR', 'TOYS', 'BATT', 'SWET', 'TOFF', 'COLA', 'CTCD', 'BUBL',
8437  'PLST', 'FZDR',
8438  0 };
8439 
8440 static const CargoLabel _default_refitmasks_road[] = {
8441  0 };
8442 
8443 static const CargoLabel _default_refitmasks_ships[] = {
8444  'COAL', 'MAIL', 'LVST', 'GOOD', 'GRAI', 'WHEA', 'MAIZ', 'WOOD', 'IORE',
8445  'STEL', 'VALU', 'GOLD', 'DIAM', 'PAPR', 'FOOD', 'FRUT', 'CORE', 'WATR',
8446  'RUBR', 'SUGR', 'TOYS', 'BATT', 'SWET', 'TOFF', 'COLA', 'CTCD', 'BUBL',
8447  'PLST', 'FZDR',
8448  0 };
8449 
8450 static const CargoLabel _default_refitmasks_aircraft[] = {
8451  'PASS', 'MAIL', 'GOOD', 'VALU', 'GOLD', 'DIAM', 'FOOD', 'FRUT', 'SUGR',
8452  'TOYS', 'BATT', 'SWET', 'TOFF', 'COLA', 'CTCD', 'BUBL', 'PLST', 'FZDR',
8453  0 };
8454 
8455 static const CargoLabel * const _default_refitmasks[] = {
8457  _default_refitmasks_road,
8458  _default_refitmasks_ships,
8459  _default_refitmasks_aircraft,
8460 };
8461 
8462 
8466 static void CalculateRefitMasks()
8467 {
8468  Engine *e;
8469 
8470  FOR_ALL_ENGINES(e) {
8471  EngineID engine = e->index;
8472  EngineInfo *ei = &e->info;
8473  bool only_defaultcargo;
8474 
8475  /* Did the newgrf specify any refitting? If not, use defaults. */
8476  if (_gted[engine].refittability != GRFTempEngineData::UNSET) {
8477  CargoTypes mask = 0;
8478  CargoTypes not_mask = 0;
8479  CargoTypes xor_mask = ei->refit_mask;
8480 
8481  /* If the original masks set by the grf are zero, the vehicle shall only carry the default cargo.
8482  * Note: After applying the translations, the vehicle may end up carrying no defined cargo. It becomes unavailable in that case. */
8483  only_defaultcargo = _gted[engine].refittability == GRFTempEngineData::EMPTY;
8484 
8485  if (_gted[engine].cargo_allowed != 0) {
8486  /* Build up the list of cargo types from the set cargo classes. */
8487  const CargoSpec *cs;
8488  FOR_ALL_CARGOSPECS(cs) {
8489  if (_gted[engine].cargo_allowed & cs->classes) SetBit(mask, cs->Index());
8490  if (_gted[engine].cargo_disallowed & cs->classes) SetBit(not_mask, cs->Index());
8491  }
8492  }
8493 
8494  ei->refit_mask = ((mask & ~not_mask) ^ xor_mask) & _cargo_mask;
8495 
8496  /* Apply explicit refit includes/excludes. */
8497  ei->refit_mask |= _gted[engine].ctt_include_mask;
8498  ei->refit_mask &= ~_gted[engine].ctt_exclude_mask;
8499  } else {
8500  CargoTypes xor_mask = 0;
8501 
8502  /* Don't apply default refit mask to wagons nor engines with no capacity */
8503  if (e->type != VEH_TRAIN || (e->u.rail.capacity != 0 && e->u.rail.railveh_type != RAILVEH_WAGON)) {
8504  const CargoLabel *cl = _default_refitmasks[e->type];
8505  for (uint i = 0;; i++) {
8506  if (cl[i] == 0) break;
8507 
8508  CargoID cargo = GetCargoIDByLabel(cl[i]);
8509  if (cargo == CT_INVALID) continue;
8510 
8511  SetBit(xor_mask, cargo);
8512  }
8513  }
8514 
8515  ei->refit_mask = xor_mask & _cargo_mask;
8516 
8517  /* If the mask is zero, the vehicle shall only carry the default cargo */
8518  only_defaultcargo = (ei->refit_mask == 0);
8519  }
8520 
8521  /* Clear invalid cargoslots (from default vehicles or pre-NewCargo GRFs) */
8522  if (!HasBit(_cargo_mask, ei->cargo_type)) ei->cargo_type = CT_INVALID;
8523 
8524  /* Ensure that the vehicle is either not refittable, or that the default cargo is one of the refittable cargoes.
8525  * Note: Vehicles refittable to no cargo are handle differently to vehicle refittable to a single cargo. The latter might have subtypes. */
8526  if (!only_defaultcargo && (e->type != VEH_SHIP || e->u.ship.old_refittable) && ei->cargo_type != CT_INVALID && !HasBit(ei->refit_mask, ei->cargo_type)) {
8527  ei->cargo_type = CT_INVALID;
8528  }
8529 
8530  /* Check if this engine's cargo type is valid. If not, set to the first refittable
8531  * cargo type. Finally disable the vehicle, if there is still no cargo. */
8532  if (ei->cargo_type == CT_INVALID && ei->refit_mask != 0) {
8533  /* Figure out which CTT to use for the default cargo, if it is 'first refittable'. */
8534  const uint8 *cargo_map_for_first_refittable = NULL;
8535  {
8536  const GRFFile *file = _gted[engine].defaultcargo_grf;
8537  if (file == NULL) file = e->GetGRF();
8538  if (file != NULL && file->grf_version >= 8 && file->cargo_list.Length() != 0) {
8539  cargo_map_for_first_refittable = file->cargo_map;
8540  }
8541  }
8542 
8543  if (cargo_map_for_first_refittable != NULL) {
8544  /* Use first refittable cargo from cargo translation table */
8545  byte best_local_slot = 0xFF;
8546  CargoID cargo_type;
8547  FOR_EACH_SET_CARGO_ID(cargo_type, ei->refit_mask) {
8548  byte local_slot = cargo_map_for_first_refittable[cargo_type];
8549  if (local_slot < best_local_slot) {
8550  best_local_slot = local_slot;
8551  ei->cargo_type = cargo_type;
8552  }
8553  }
8554  }
8555 
8556  if (ei->cargo_type == CT_INVALID) {
8557  /* Use first refittable cargo slot */
8558  ei->cargo_type = (CargoID)FindFirstBit(ei->refit_mask);
8559  }
8560  }
8561  if (ei->cargo_type == CT_INVALID) ei->climates = 0;
8562 
8563  /* Clear refit_mask for not refittable ships */
8564  if (e->type == VEH_SHIP && !e->u.ship.old_refittable) {
8565  ei->refit_mask = 0;
8566  }
8567  }
8568 }
8569 
8571 static void FinaliseCanals()
8572 {
8573  for (uint i = 0; i < CF_END; i++) {
8574  if (_water_feature[i].grffile != NULL) {
8577  }
8578  }
8579 }
8580 
8582 static void FinaliseEngineArray()
8583 {
8584  Engine *e;
8585 
8586  FOR_ALL_ENGINES(e) {
8587  if (e->GetGRF() == NULL) {
8588  const EngineIDMapping &eid = _engine_mngr[e->index];
8589  if (eid.grfid != INVALID_GRFID || eid.internal_id != eid.substitute_id) {
8590  e->info.string_id = STR_NEWGRF_INVALID_ENGINE;
8591  }
8592  }
8593 
8594  if (!HasBit(e->info.climates, _settings_game.game_creation.landscape)) continue;
8595 
8596  /* When the train does not set property 27 (misc flags), but it
8597  * is overridden by a NewGRF graphically we want to disable the
8598  * flipping possibility. */
8599  if (e->type == VEH_TRAIN && !_gted[e->index].prop27_set && e->GetGRF() != NULL && is_custom_sprite(e->u.rail.image_index)) {
8600  ClrBit(e->info.misc_flags, EF_RAIL_FLIPS);
8601  }
8602 
8603  /* Skip wagons, there livery is defined via the engine */
8604  if (e->type != VEH_TRAIN || e->u.rail.railveh_type != RAILVEH_WAGON) {
8606  SetBit(_loaded_newgrf_features.used_liveries, ls);
8607  /* Note: For ships and roadvehicles we assume that they cannot be refitted between passenger and freight */
8608 
8609  if (e->type == VEH_TRAIN) {
8610  SetBit(_loaded_newgrf_features.used_liveries, LS_FREIGHT_WAGON);
8611  switch (ls) {
8612  case LS_STEAM:
8613  case LS_DIESEL:
8614  case LS_ELECTRIC:
8615  case LS_MONORAIL:
8616  case LS_MAGLEV:
8617  SetBit(_loaded_newgrf_features.used_liveries, LS_PASSENGER_WAGON_STEAM + ls - LS_STEAM);
8618  break;
8619 
8620  case LS_DMU:
8621  case LS_EMU:
8622  SetBit(_loaded_newgrf_features.used_liveries, LS_PASSENGER_WAGON_DIESEL + ls - LS_DMU);
8623  break;
8624 
8625  default: NOT_REACHED();
8626  }
8627  }
8628  }
8629  }
8630 }
8631 
8633 static void FinaliseCargoArray()
8634 {
8635  for (CargoID c = 0; c < NUM_CARGO; c++) {
8636  CargoSpec *cs = CargoSpec::Get(c);
8637  if (!cs->IsValid()) {
8638  cs->name = cs->name_single = cs->units_volume = STR_NEWGRF_INVALID_CARGO;
8639  cs->quantifier = STR_NEWGRF_INVALID_CARGO_QUANTITY;
8640  cs->abbrev = STR_NEWGRF_INVALID_CARGO_ABBREV;
8641  }
8642  }
8643 }
8644 
8656 static bool IsHouseSpecValid(HouseSpec *hs, const HouseSpec *next1, const HouseSpec *next2, const HouseSpec *next3, const char *filename)
8657 {
8658  if (((hs->building_flags & BUILDING_HAS_2_TILES) != 0 &&
8659  (next1 == NULL || !next1->enabled || (next1->building_flags & BUILDING_HAS_1_TILE) != 0)) ||
8660  ((hs->building_flags & BUILDING_HAS_4_TILES) != 0 &&
8661  (next2 == NULL || !next2->enabled || (next2->building_flags & BUILDING_HAS_1_TILE) != 0 ||
8662  next3 == NULL || !next3->enabled || (next3->building_flags & BUILDING_HAS_1_TILE) != 0))) {
8663  hs->enabled = false;
8664  if (filename != NULL) DEBUG(grf, 1, "FinaliseHouseArray: %s defines house %d as multitile, but no suitable tiles follow. Disabling house.", filename, hs->grf_prop.local_id);
8665  return false;
8666  }
8667 
8668  /* Some places sum population by only counting north tiles. Other places use all tiles causing desyncs.
8669  * As the newgrf specs define population to be zero for non-north tiles, we just disable the offending house.
8670  * If you want to allow non-zero populations somewhen, make sure to sum the population of all tiles in all places. */
8671  if (((hs->building_flags & BUILDING_HAS_2_TILES) != 0 && next1->population != 0) ||
8672  ((hs->building_flags & BUILDING_HAS_4_TILES) != 0 && (next2->population != 0 || next3->population != 0))) {
8673  hs->enabled = false;
8674  if (filename != NULL) DEBUG(grf, 1, "FinaliseHouseArray: %s defines multitile house %d with non-zero population on additional tiles. Disabling house.", filename, hs->grf_prop.local_id);
8675  return false;
8676  }
8677 
8678  /* Substitute type is also used for override, and having an override with a different size causes crashes.
8679  * This check should only be done for NewGRF houses because grf_prop.subst_id is not set for original houses.*/
8680  if (filename != NULL && (hs->building_flags & BUILDING_HAS_1_TILE) != (HouseSpec::Get(hs->grf_prop.subst_id)->building_flags & BUILDING_HAS_1_TILE)) {
8681  hs->enabled = false;
8682  DEBUG(grf, 1, "FinaliseHouseArray: %s defines house %d with different house size then it's substitute type. Disabling house.", filename, hs->grf_prop.local_id);
8683  return false;
8684  }
8685 
8686  /* Make sure that additional parts of multitile houses are not available. */
8687  if ((hs->building_flags & BUILDING_HAS_1_TILE) == 0 && (hs->building_availability & HZ_ZONALL) != 0 && (hs->building_availability & HZ_CLIMALL) != 0) {
8688  hs->enabled = false;
8689  if (filename != NULL) DEBUG(grf, 1, "FinaliseHouseArray: %s defines house %d without a size but marked it as available. Disabling house.", filename, hs->grf_prop.local_id);
8690  return false;
8691  }
8692 
8693  return true;
8694 }
8695 
8702 static void EnsureEarlyHouse(HouseZones bitmask)
8703 {
8704  Year min_year = MAX_YEAR;
8705 
8706  for (int i = 0; i < NUM_HOUSES; i++) {
8707  HouseSpec *hs = HouseSpec::Get(i);
8708  if (hs == NULL || !hs->enabled) continue;
8709  if ((hs->building_availability & bitmask) != bitmask) continue;
8710  if (hs->min_year < min_year) min_year = hs->min_year;
8711  }
8712 
8713  if (min_year == 0) return;
8714 
8715  for (int i = 0; i < NUM_HOUSES; i++) {
8716  HouseSpec *hs = HouseSpec::Get(i);
8717  if (hs == NULL || !hs->enabled) continue;
8718  if ((hs->building_availability & bitmask) != bitmask) continue;
8719  if (hs->min_year == min_year) hs->min_year = 0;
8720  }
8721 }
8722 
8729 static void FinaliseHouseArray()
8730 {
8731  /* If there are no houses with start dates before 1930, then all houses
8732  * with start dates of 1930 have them reset to 0. This is in order to be
8733  * compatible with TTDPatch, where if no houses have start dates before
8734  * 1930 and the date is before 1930, the game pretends that this is 1930.
8735  * If there have been any houses defined with start dates before 1930 then
8736  * the dates are left alone.
8737  * On the other hand, why 1930? Just 'fix' the houses with the lowest
8738  * minimum introduction date to 0.
8739  */
8740  const GRFFile * const *end = _grf_files.End();
8741  for (GRFFile **file = _grf_files.Begin(); file != end; file++) {
8742  HouseSpec **&housespec = (*file)->housespec;
8743  if (housespec == NULL) continue;
8744 
8745  for (int i = 0; i < NUM_HOUSES_PER_GRF; i++) {
8746  HouseSpec *hs = housespec[i];
8747 
8748  if (hs == NULL) continue;
8749 
8750  const HouseSpec *next1 = (i + 1 < NUM_HOUSES_PER_GRF ? housespec[i + 1] : NULL);
8751  const HouseSpec *next2 = (i + 2 < NUM_HOUSES_PER_GRF ? housespec[i + 2] : NULL);
8752  const HouseSpec *next3 = (i + 3 < NUM_HOUSES_PER_GRF ? housespec[i + 3] : NULL);
8753 
8754  if (!IsHouseSpecValid(hs, next1, next2, next3, (*file)->filename)) continue;
8755 
8756  _house_mngr.SetEntitySpec(hs);
8757  }
8758  }
8759 
8760  for (int i = 0; i < NUM_HOUSES; i++) {
8761  HouseSpec *hs = HouseSpec::Get(i);
8762  const HouseSpec *next1 = (i + 1 < NUM_HOUSES ? HouseSpec::Get(i + 1) : NULL);
8763  const HouseSpec *next2 = (i + 2 < NUM_HOUSES ? HouseSpec::Get(i + 2) : NULL);
8764  const HouseSpec *next3 = (i + 3 < NUM_HOUSES ? HouseSpec::Get(i + 3) : NULL);
8765 
8766  /* We need to check all houses again to we are sure that multitile houses
8767  * did get consecutive IDs and none of the parts are missing. */
8768  if (!IsHouseSpecValid(hs, next1, next2, next3, NULL)) {
8769  /* GetHouseNorthPart checks 3 houses that are directly before
8770  * it in the house pool. If any of those houses have multi-tile
8771  * flags set it assumes it's part of a multitile house. Since
8772  * we can have invalid houses in the pool marked as disabled, we
8773  * don't want to have them influencing valid tiles. As such set
8774  * building_flags to zero here to make sure any house following
8775  * this one in the pool is properly handled as 1x1 house. */
8776  hs->building_flags = TILE_NO_FLAG;
8777  }
8778  }
8779 
8780  HouseZones climate_mask = (HouseZones)(1 << (_settings_game.game_creation.landscape + 12));
8781  EnsureEarlyHouse(HZ_ZON1 | climate_mask);
8782  EnsureEarlyHouse(HZ_ZON2 | climate_mask);
8783  EnsureEarlyHouse(HZ_ZON3 | climate_mask);
8784  EnsureEarlyHouse(HZ_ZON4 | climate_mask);
8785  EnsureEarlyHouse(HZ_ZON5 | climate_mask);
8786 
8787  if (_settings_game.game_creation.landscape == LT_ARCTIC) {
8793  }
8794 }
8795 
8802 {
8803  const GRFFile * const *end = _grf_files.End();
8804  for (GRFFile **file = _grf_files.Begin(); file != end; file++) {
8805  IndustrySpec **&industryspec = (*file)->industryspec;
8806  IndustryTileSpec **&indtspec = (*file)->indtspec;
8807  if (industryspec != NULL) {
8808  for (int i = 0; i < NUM_INDUSTRYTYPES_PER_GRF; i++) {
8809  IndustrySpec *indsp = industryspec[i];
8810 
8811  if (indsp != NULL && indsp->enabled) {
8812  StringID strid;
8813  /* process the conversion of text at the end, so to be sure everything will be fine
8814  * and available. Check if it does not return undefind marker, which is a very good sign of a
8815  * substitute industry who has not changed the string been examined, thus using it as such */
8816  strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->name);
8817  if (strid != STR_UNDEFINED) indsp->name = strid;
8818 
8819  strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->closure_text);
8820  if (strid != STR_UNDEFINED) indsp->closure_text = strid;
8821 
8822  strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->production_up_text);
8823  if (strid != STR_UNDEFINED) indsp->production_up_text = strid;
8824 
8825  strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->production_down_text);
8826  if (strid != STR_UNDEFINED) indsp->production_down_text = strid;
8827 
8828  strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->new_industry_text);
8829  if (strid != STR_UNDEFINED) indsp->new_industry_text = strid;
8830 
8831  if (indsp->station_name != STR_NULL) {
8832  /* STR_NULL (0) can be set by grf. It has a meaning regarding assignation of the
8833  * station's name. Don't want to lose the value, therefore, do not process. */
8834  strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->station_name);
8835  if (strid != STR_UNDEFINED) indsp->station_name = strid;
8836  }
8837 
8838  _industry_mngr.SetEntitySpec(indsp);
8839  _loaded_newgrf_features.has_newindustries = true;
8840  }
8841  }
8842  }
8843 
8844  if (indtspec != NULL) {
8845  for (int i = 0; i < NUM_INDUSTRYTILES_PER_GRF; i++) {
8846  IndustryTileSpec *indtsp = indtspec[i];
8847  if (indtsp != NULL) {
8848  _industile_mngr.SetEntitySpec(indtsp);
8849  }
8850  }
8851  }
8852  }
8853 
8854  for (uint j = 0; j < NUM_INDUSTRYTYPES; j++) {
8855  IndustrySpec *indsp = &_industry_specs[j];
8856  if (indsp->enabled && indsp->grf_prop.grffile != NULL) {
8857  for (uint i = 0; i < 3; i++) {
8858  indsp->conflicting[i] = MapNewGRFIndustryType(indsp->conflicting[i], indsp->grf_prop.grffile->grfid);
8859  }
8860  }
8861  if (!indsp->enabled) {
8862  indsp->name = STR_NEWGRF_INVALID_INDUSTRYTYPE;
8863  }
8864  }
8865 }
8866 
8873 {
8874  const GRFFile * const *end = _grf_files.End();
8875  for (GRFFile **file = _grf_files.Begin(); file != end; file++) {
8876  ObjectSpec **&objectspec = (*file)->objectspec;
8877  if (objectspec != NULL) {
8878  for (int i = 0; i < NUM_OBJECTS_PER_GRF; i++) {
8879  if (objectspec[i] != NULL && objectspec[i]->grf_prop.grffile != NULL && objectspec[i]->enabled) {
8880  _object_mngr.SetEntitySpec(objectspec[i]);
8881  }
8882  }
8883  }
8884  }
8885 }
8886 
8893 {
8894  const GRFFile * const *end = _grf_files.End();
8895  for (GRFFile **file = _grf_files.Begin(); file != end; file++) {
8896  AirportSpec **&airportspec = (*file)->airportspec;
8897  if (airportspec != NULL) {
8898  for (int i = 0; i < NUM_AIRPORTS_PER_GRF; i++) {
8899  if (airportspec[i] != NULL && airportspec[i]->enabled) {
8900  _airport_mngr.SetEntitySpec(airportspec[i]);
8901  }
8902  }
8903  }
8904 
8905  AirportTileSpec **&airporttilespec = (*file)->airtspec;
8906  if (airporttilespec != NULL) {
8907  for (uint i = 0; i < NUM_AIRPORTTILES_PER_GRF; i++) {
8908  if (airporttilespec[i] != NULL && airporttilespec[i]->enabled) {
8909  _airporttile_mngr.SetEntitySpec(airporttilespec[i]);
8910  }
8911  }
8912  }
8913  }
8914 }
8915 
8916 /* Here we perform initial decoding of some special sprites (as are they
8917  * described at http://www.ttdpatch.net/src/newgrf.txt, but this is only a very
8918  * partial implementation yet).
8919  * XXX: We consider GRF files trusted. It would be trivial to exploit OTTD by
8920  * a crafted invalid GRF file. We should tell that to the user somehow, or
8921  * better make this more robust in the future. */
8922 static void DecodeSpecialSprite(byte *buf, uint num, GrfLoadingStage stage)
8923 {
8924  /* XXX: There is a difference between staged loading in TTDPatch and
8925  * here. In TTDPatch, for some reason actions 1 and 2 are carried out
8926  * during stage 1, whilst action 3 is carried out during stage 2 (to
8927  * "resolve" cargo IDs... wtf). This is a little problem, because cargo
8928  * IDs are valid only within a given set (action 1) block, and may be
8929  * overwritten after action 3 associates them. But overwriting happens
8930  * in an earlier stage than associating, so... We just process actions
8931  * 1 and 2 in stage 2 now, let's hope that won't get us into problems.
8932  * --pasky
8933  * We need a pre-stage to set up GOTO labels of Action 0x10 because the grf
8934  * is not in memory and scanning the file every time would be too expensive.
8935  * In other stages we skip action 0x10 since it's already dealt with. */
8936  static const SpecialSpriteHandler handlers[][GLS_END] = {
8937  /* 0x00 */ { NULL, SafeChangeInfo, NULL, NULL, ReserveChangeInfo, FeatureChangeInfo, },
8938  /* 0x01 */ { SkipAct1, SkipAct1, SkipAct1, SkipAct1, SkipAct1, NewSpriteSet, },
8939  /* 0x02 */ { NULL, NULL, NULL, NULL, NULL, NewSpriteGroup, },
8940  /* 0x03 */ { NULL, GRFUnsafe, NULL, NULL, NULL, FeatureMapSpriteGroup, },
8941  /* 0x04 */ { NULL, NULL, NULL, NULL, NULL, FeatureNewName, },
8942  /* 0x05 */ { SkipAct5, SkipAct5, SkipAct5, SkipAct5, SkipAct5, GraphicsNew, },
8943  /* 0x06 */ { NULL, NULL, NULL, CfgApply, CfgApply, CfgApply, },
8944  /* 0x07 */ { NULL, NULL, NULL, NULL, SkipIf, SkipIf, },
8945  /* 0x08 */ { ScanInfo, NULL, NULL, GRFInfo, GRFInfo, GRFInfo, },
8946  /* 0x09 */ { NULL, NULL, NULL, SkipIf, SkipIf, SkipIf, },
8947  /* 0x0A */ { SkipActA, SkipActA, SkipActA, SkipActA, SkipActA, SpriteReplace, },
8948  /* 0x0B */ { NULL, NULL, NULL, GRFLoadError, GRFLoadError, GRFLoadError, },
8949  /* 0x0C */ { NULL, NULL, NULL, GRFComment, NULL, GRFComment, },
8950  /* 0x0D */ { NULL, SafeParamSet, NULL, ParamSet, ParamSet, ParamSet, },
8951  /* 0x0E */ { NULL, SafeGRFInhibit, NULL, GRFInhibit, GRFInhibit, GRFInhibit, },
8952  /* 0x0F */ { NULL, GRFUnsafe, NULL, FeatureTownName, NULL, NULL, },
8953  /* 0x10 */ { NULL, NULL, DefineGotoLabel, NULL, NULL, NULL, },
8954  /* 0x11 */ { SkipAct11,GRFUnsafe, SkipAct11, GRFSound, SkipAct11, GRFSound, },
8956  /* 0x13 */ { NULL, NULL, NULL, NULL, NULL, TranslateGRFStrings, },
8957  /* 0x14 */ { StaticGRFInfo, NULL, NULL, NULL, NULL, NULL, },
8958  };
8959 
8960  GRFLocation location(_cur.grfconfig->ident.grfid, _cur.nfo_line);
8961 
8962  GRFLineToSpriteOverride::iterator it = _grf_line_to_action6_sprite_override.find(location);
8963  if (it == _grf_line_to_action6_sprite_override.end()) {
8964  /* No preloaded sprite to work with; read the
8965  * pseudo sprite content. */
8966  FioReadBlock(buf, num);
8967  } else {
8968  /* Use the preloaded sprite data. */
8969  buf = _grf_line_to_action6_sprite_override[location];
8970  grfmsg(7, "DecodeSpecialSprite: Using preloaded pseudo sprite data");
8971 
8972  /* Skip the real (original) content of this action. */
8973  FioSeekTo(num, SEEK_CUR);
8974  }
8975 
8976  ByteReader br(buf, buf + num);
8977  ByteReader *bufp = &br;
8978 
8979  try {
8980  byte action = bufp->ReadByte();
8981 
8982  if (action == 0xFF) {
8983  grfmsg(2, "DecodeSpecialSprite: Unexpected data block, skipping");
8984  } else if (action == 0xFE) {
8985  grfmsg(2, "DecodeSpecialSprite: Unexpected import block, skipping");
8986  } else if (action >= lengthof(handlers)) {
8987  grfmsg(7, "DecodeSpecialSprite: Skipping unknown action 0x%02X", action);
8988  } else if (handlers[action][stage] == NULL) {
8989  grfmsg(7, "DecodeSpecialSprite: Skipping action 0x%02X in stage %d", action, stage);
8990  } else {
8991  grfmsg(7, "DecodeSpecialSprite: Handling action 0x%02X in stage %d", action, stage);
8992  handlers[action][stage](bufp);
8993  }
8994  } catch (...) {
8995  grfmsg(1, "DecodeSpecialSprite: Tried to read past end of pseudo-sprite data");
8996  DisableGrf(STR_NEWGRF_ERROR_READ_BOUNDS);
8997  }
8998 }
8999 
9000 
9002 extern const byte _grf_cont_v2_sig[8] = {'G', 'R', 'F', 0x82, 0x0D, 0x0A, 0x1A, 0x0A};
9003 
9009 {
9010  size_t pos = FioGetPos();
9011 
9012  if (FioReadWord() == 0) {
9013  /* Check for GRF container version 2, which is identified by the bytes
9014  * '47 52 46 82 0D 0A 1A 0A' at the start of the file. */
9015  for (uint i = 0; i < lengthof(_grf_cont_v2_sig); i++) {
9016  if (FioReadByte() != _grf_cont_v2_sig[i]) return 0; // Invalid format
9017  }
9018 
9019  return 2;
9020  }
9021 
9022  /* Container version 1 has no header, rewind to start. */
9023  FioSeekTo(pos, SEEK_SET);
9024  return 1;
9025 }
9026 
9034 void LoadNewGRFFile(GRFConfig *config, uint file_index, GrfLoadingStage stage, Subdirectory subdir)
9035 {
9036  const char *filename = config->filename;
9037 
9038  /* A .grf file is activated only if it was active when the game was
9039  * started. If a game is loaded, only its active .grfs will be
9040  * reactivated, unless "loadallgraphics on" is used. A .grf file is
9041  * considered active if its action 8 has been processed, i.e. its
9042  * action 8 hasn't been skipped using an action 7.
9043  *
9044  * During activation, only actions 0, 1, 2, 3, 4, 5, 7, 8, 9, 0A and 0B are
9045  * carried out. All others are ignored, because they only need to be
9046  * processed once at initialization. */
9047  if (stage != GLS_FILESCAN && stage != GLS_SAFETYSCAN && stage != GLS_LABELSCAN) {
9048  _cur.grffile = GetFileByFilename(filename);
9049  if (_cur.grffile == NULL) usererror("File '%s' lost in cache.\n", filename);
9050  if (stage == GLS_RESERVE && config->status != GCS_INITIALISED) return;
9051  if (stage == GLS_ACTIVATION && !HasBit(config->flags, GCF_RESERVED)) return;
9052  }
9053 
9054  if (file_index >= MAX_FILE_SLOTS) {
9055  DEBUG(grf, 0, "'%s' is not loaded as the maximum number of file slots has been reached", filename);
9056  config->status = GCS_DISABLED;
9057  config->error = new GRFError(STR_NEWGRF_ERROR_MSG_FATAL, STR_NEWGRF_ERROR_TOO_MANY_NEWGRFS_LOADED);
9058  return;
9059  }
9060 
9061  FioOpenFile(file_index, filename, subdir);
9062  _cur.file_index = file_index; // XXX
9063  _palette_remap_grf[_cur.file_index] = (config->palette & GRFP_USE_MASK);
9064 
9065  _cur.grfconfig = config;
9066 
9067  DEBUG(grf, 2, "LoadNewGRFFile: Reading NewGRF-file '%s'", filename);
9068 
9070  if (_cur.grf_container_ver == 0) {
9071  DEBUG(grf, 7, "LoadNewGRFFile: Custom .grf has invalid format");
9072  return;
9073  }
9074 
9075  if (stage == GLS_INIT || stage == GLS_ACTIVATION) {
9076  /* We need the sprite offsets in the init stage for NewGRF sounds
9077  * and in the activation stage for real sprites. */
9079  } else {
9080  /* Skip sprite section offset if present. */
9081  if (_cur.grf_container_ver >= 2) FioReadDword();
9082  }
9083 
9084  if (_cur.grf_container_ver >= 2) {
9085  /* Read compression value. */
9086  byte compression = FioReadByte();
9087  if (compression != 0) {
9088  DEBUG(grf, 7, "LoadNewGRFFile: Unsupported compression format");
9089  return;
9090  }
9091  }
9092 
9093  /* Skip the first sprite; we don't care about how many sprites this
9094  * does contain; newest TTDPatches and George's longvehicles don't
9095  * neither, apparently. */
9096  uint32 num = _cur.grf_container_ver >= 2 ? FioReadDword() : FioReadWord();
9097  if (num == 4 && FioReadByte() == 0xFF) {
9098  FioReadDword();
9099  } else {
9100  DEBUG(grf, 7, "LoadNewGRFFile: Custom .grf has invalid format");
9101  return;
9102  }
9103 
9104  _cur.ClearDataForNextFile();
9105 
9107 
9108  while ((num = (_cur.grf_container_ver >= 2 ? FioReadDword() : FioReadWord())) != 0) {
9109  byte type = FioReadByte();
9110  _cur.nfo_line++;
9111 
9112  if (type == 0xFF) {
9113  if (_cur.skip_sprites == 0) {
9114  DecodeSpecialSprite(buf.Allocate(num), num, stage);
9115 
9116  /* Stop all processing if we are to skip the remaining sprites */
9117  if (_cur.skip_sprites == -1) break;
9118 
9119  continue;
9120  } else {
9121  FioSkipBytes(num);
9122  }
9123  } else {
9124  if (_cur.skip_sprites == 0) {
9125  grfmsg(0, "LoadNewGRFFile: Unexpected sprite, disabling");
9126  DisableGrf(STR_NEWGRF_ERROR_UNEXPECTED_SPRITE);
9127  break;
9128  }
9129 
9130  if (_cur.grf_container_ver >= 2 && type == 0xFD) {
9131  /* Reference to data section. Container version >= 2 only. */
9132  FioSkipBytes(num);
9133  } else {
9134  FioSkipBytes(7);
9135  SkipSpriteData(type, num - 8);
9136  }
9137  }
9138 
9139  if (_cur.skip_sprites > 0) _cur.skip_sprites--;
9140  }
9141 }
9142 
9150 static void ActivateOldShore()
9151 {
9152  /* Use default graphics, if no shore sprites were loaded.
9153  * Should not happen, as the base set's extra grf should include some. */
9154  if (_loaded_newgrf_features.shore == SHORE_REPLACE_NONE) _loaded_newgrf_features.shore = SHORE_REPLACE_ACTION_A;
9155 
9156  if (_loaded_newgrf_features.shore != SHORE_REPLACE_ACTION_5) {
9157  DupSprite(SPR_ORIGINALSHORE_START + 1, SPR_SHORE_BASE + 1); // SLOPE_W
9158  DupSprite(SPR_ORIGINALSHORE_START + 2, SPR_SHORE_BASE + 2); // SLOPE_S
9159  DupSprite(SPR_ORIGINALSHORE_START + 6, SPR_SHORE_BASE + 3); // SLOPE_SW
9160  DupSprite(SPR_ORIGINALSHORE_START + 0, SPR_SHORE_BASE + 4); // SLOPE_E
9161  DupSprite(SPR_ORIGINALSHORE_START + 4, SPR_SHORE_BASE + 6); // SLOPE_SE
9162  DupSprite(SPR_ORIGINALSHORE_START + 3, SPR_SHORE_BASE + 8); // SLOPE_N
9163  DupSprite(SPR_ORIGINALSHORE_START + 7, SPR_SHORE_BASE + 9); // SLOPE_NW
9164  DupSprite(SPR_ORIGINALSHORE_START + 5, SPR_SHORE_BASE + 12); // SLOPE_NE
9165  }
9166 
9167  if (_loaded_newgrf_features.shore == SHORE_REPLACE_ACTION_A) {
9168  DupSprite(SPR_FLAT_GRASS_TILE + 16, SPR_SHORE_BASE + 0); // SLOPE_STEEP_S
9169  DupSprite(SPR_FLAT_GRASS_TILE + 17, SPR_SHORE_BASE + 5); // SLOPE_STEEP_W
9170  DupSprite(SPR_FLAT_GRASS_TILE + 7, SPR_SHORE_BASE + 7); // SLOPE_WSE
9171  DupSprite(SPR_FLAT_GRASS_TILE + 15, SPR_SHORE_BASE + 10); // SLOPE_STEEP_N
9172  DupSprite(SPR_FLAT_GRASS_TILE + 11, SPR_SHORE_BASE + 11); // SLOPE_NWS
9173  DupSprite(SPR_FLAT_GRASS_TILE + 13, SPR_SHORE_BASE + 13); // SLOPE_ENW
9174  DupSprite(SPR_FLAT_GRASS_TILE + 14, SPR_SHORE_BASE + 14); // SLOPE_SEN
9175  DupSprite(SPR_FLAT_GRASS_TILE + 18, SPR_SHORE_BASE + 15); // SLOPE_STEEP_E
9176 
9177  /* XXX - SLOPE_EW, SLOPE_NS are currently not used.
9178  * If they would be used somewhen, then these grass tiles will most like not look as needed */
9179  DupSprite(SPR_FLAT_GRASS_TILE + 5, SPR_SHORE_BASE + 16); // SLOPE_EW
9180  DupSprite(SPR_FLAT_GRASS_TILE + 10, SPR_SHORE_BASE + 17); // SLOPE_NS
9181  }
9182 }
9183 
9188 {
9189  extern const PriceBaseSpec _price_base_specs[];
9191  static const uint32 override_features = (1 << GSF_TRAINS) | (1 << GSF_ROADVEHICLES) | (1 << GSF_SHIPS) | (1 << GSF_AIRCRAFT);
9192 
9193  /* Evaluate grf overrides */
9194  int num_grfs = _grf_files.Length();
9195  int *grf_overrides = AllocaM(int, num_grfs);
9196  for (int i = 0; i < num_grfs; i++) {
9197  grf_overrides[i] = -1;
9198 
9199  GRFFile *source = _grf_files[i];
9200  uint32 override = _grf_id_overrides[source->grfid];
9201  if (override == 0) continue;
9202 
9203  GRFFile *dest = GetFileByGRFID(override);
9204  if (dest == NULL) continue;
9205 
9206  grf_overrides[i] = _grf_files.FindIndex(dest);
9207  assert(grf_overrides[i] >= 0);
9208  }
9209 
9210  /* Override features and price base multipliers of earlier loaded grfs */
9211  for (int i = 0; i < num_grfs; i++) {
9212  if (grf_overrides[i] < 0 || grf_overrides[i] >= i) continue;
9213  GRFFile *source = _grf_files[i];
9214  GRFFile *dest = _grf_files[grf_overrides[i]];
9215 
9216  uint32 features = (source->grf_features | dest->grf_features) & override_features;
9217  source->grf_features |= features;
9218  dest->grf_features |= features;
9219 
9220  for (Price p = PR_BEGIN; p < PR_END; p++) {
9221  /* No price defined -> nothing to do */
9222  if (!HasBit(features, _price_base_specs[p].grf_feature) || source->price_base_multipliers[p] == INVALID_PRICE_MODIFIER) continue;
9223  DEBUG(grf, 3, "'%s' overrides price base multiplier %d of '%s'", source->filename, p, dest->filename);
9224  dest->price_base_multipliers[p] = source->price_base_multipliers[p];
9225  }
9226  }
9227 
9228  /* Propagate features and price base multipliers of afterwards loaded grfs, if none is present yet */
9229  for (int i = num_grfs - 1; i >= 0; i--) {
9230  if (grf_overrides[i] < 0 || grf_overrides[i] <= i) continue;
9231  GRFFile *source = _grf_files[i];
9232  GRFFile *dest = _grf_files[grf_overrides[i]];
9233 
9234  uint32 features = (source->grf_features | dest->grf_features) & override_features;
9235  source->grf_features |= features;
9236  dest->grf_features |= features;
9237 
9238  for (Price p = PR_BEGIN; p < PR_END; p++) {
9239  /* Already a price defined -> nothing to do */
9240  if (!HasBit(features, _price_base_specs[p].grf_feature) || dest->price_base_multipliers[p] != INVALID_PRICE_MODIFIER) continue;
9241  DEBUG(grf, 3, "Price base multiplier %d from '%s' propagated to '%s'", p, source->filename, dest->filename);
9242  dest->price_base_multipliers[p] = source->price_base_multipliers[p];
9243  }
9244  }
9245 
9246  /* The 'master grf' now have the correct multipliers. Assign them to the 'addon grfs' to make everything consistent. */
9247  for (int i = 0; i < num_grfs; i++) {
9248  if (grf_overrides[i] < 0) continue;
9249  GRFFile *source = _grf_files[i];
9250  GRFFile *dest = _grf_files[grf_overrides[i]];
9251 
9252  uint32 features = (source->grf_features | dest->grf_features) & override_features;
9253  source->grf_features |= features;
9254  dest->grf_features |= features;
9255 
9256  for (Price p = PR_BEGIN; p < PR_END; p++) {
9257  if (!HasBit(features, _price_base_specs[p].grf_feature)) continue;
9258  if (source->price_base_multipliers[p] != dest->price_base_multipliers[p]) {
9259  DEBUG(grf, 3, "Price base multiplier %d from '%s' propagated to '%s'", p, dest->filename, source->filename);
9260  }
9261  source->price_base_multipliers[p] = dest->price_base_multipliers[p];
9262  }
9263  }
9264 
9265  /* Apply fallback prices for grf version < 8 */
9266  const GRFFile * const *end = _grf_files.End();
9267  for (GRFFile **file = _grf_files.Begin(); file != end; file++) {
9268  if ((*file)->grf_version >= 8) continue;
9269  PriceMultipliers &price_base_multipliers = (*file)->price_base_multipliers;
9270  for (Price p = PR_BEGIN; p < PR_END; p++) {
9271  Price fallback_price = _price_base_specs[p].fallback_price;
9272  if (fallback_price != INVALID_PRICE && price_base_multipliers[p] == INVALID_PRICE_MODIFIER) {
9273  /* No price multiplier has been set.
9274  * So copy the multiplier from the fallback price, maybe a multiplier was set there. */
9275  price_base_multipliers[p] = price_base_multipliers[fallback_price];
9276  }
9277  }
9278  }
9279 
9280  /* Decide local/global scope of price base multipliers */
9281  for (GRFFile **file = _grf_files.Begin(); file != end; file++) {
9282  PriceMultipliers &price_base_multipliers = (*file)->price_base_multipliers;
9283  for (Price p = PR_BEGIN; p < PR_END; p++) {
9284  if (price_base_multipliers[p] == INVALID_PRICE_MODIFIER) {
9285  /* No multiplier was set; set it to a neutral value */
9286  price_base_multipliers[p] = 0;
9287  } else {
9288  if (!HasBit((*file)->grf_features, _price_base_specs[p].grf_feature)) {
9289  /* The grf does not define any objects of the feature,
9290  * so it must be a difficulty setting. Apply it globally */
9291  DEBUG(grf, 3, "'%s' sets global price base multiplier %d", (*file)->filename, p);
9292  SetPriceBaseMultiplier(p, price_base_multipliers[p]);
9293  price_base_multipliers[p] = 0;
9294  } else {
9295  DEBUG(grf, 3, "'%s' sets local price base multiplier %d", (*file)->filename, p);
9296  }
9297  }
9298  }
9299  }
9300 }
9301 
9302 extern void InitGRFTownGeneratorNames();
9303 
9305 static void AfterLoadGRFs()
9306 {
9307  for (StringIDMapping *it = _string_to_grf_mapping.Begin(); it != _string_to_grf_mapping.End(); it++) {
9308  *it->target = MapGRFStringID(it->grfid, it->source);
9309  }
9310  _string_to_grf_mapping.Clear();
9311 
9312  /* Free the action 6 override sprites. */
9313  for (GRFLineToSpriteOverride::iterator it = _grf_line_to_action6_sprite_override.begin(); it != _grf_line_to_action6_sprite_override.end(); it++) {
9314  free((*it).second);
9315  }
9316  _grf_line_to_action6_sprite_override.clear();
9317 
9318  /* Polish cargoes */
9320 
9321  /* Pre-calculate all refit masks after loading GRF files. */
9323 
9324  /* Polish engines */
9326 
9327  /* Set the actually used Canal properties */
9328  FinaliseCanals();
9329 
9330  /* Add all new houses to the house array. */
9332 
9333  /* Add all new industries to the industry array. */
9335 
9336  /* Add all new objects to the object array. */
9338 
9340 
9341  /* Sort the list of industry types. */
9343 
9344  /* Create dynamic list of industry legends for smallmap_gui.cpp */
9346 
9347  /* Build the routemap legend, based on the available cargos */
9349 
9350  /* Add all new airports to the airports array. */
9352  BindAirportSpecs();
9353 
9354  /* Update the townname generators list */
9356 
9357  /* Run all queued vehicle list order changes */
9359 
9360  /* Load old shore sprites in new position, if they were replaced by ActionA */
9361  ActivateOldShore();
9362 
9363  /* Set up custom rail types */
9364  InitRailTypes();
9365 
9366  Engine *e;
9367  FOR_ALL_ENGINES_OF_TYPE(e, VEH_ROAD) {
9368  if (_gted[e->index].rv_max_speed != 0) {
9369  /* Set RV maximum speed from the mph/0.8 unit value */
9370  e->u.road.max_speed = _gted[e->index].rv_max_speed * 4;
9371  }
9372  }
9373 
9374  FOR_ALL_ENGINES_OF_TYPE(e, VEH_TRAIN) {
9375  RailType railtype = GetRailTypeByLabel(_gted[e->index].railtypelabel);
9376  if (railtype == INVALID_RAILTYPE) {
9377  /* Rail type is not available, so disable this engine */
9378  e->info.climates = 0;
9379  } else {
9380  e->u.rail.railtype = railtype;
9381  }
9382  }
9383 
9385 
9387 
9388  /* Deallocate temporary loading data */
9389  free(_gted);
9390  _grm_sprites.clear();
9391 }
9392 
9399 void LoadNewGRF(uint load_index, uint file_index, uint num_baseset)
9400 {
9401  /* In case of networking we need to "sync" the start values
9402  * so all NewGRFs are loaded equally. For this we use the
9403  * start date of the game and we set the counters, etc. to
9404  * 0 so they're the same too. */
9405  Date date = _date;
9406  Year year = _cur_year;
9407  DateFract date_fract = _date_fract;
9408  uint16 tick_counter = _tick_counter;
9409  byte display_opt = _display_opt;
9410 
9411  if (_networking) {
9413  _date = ConvertYMDToDate(_cur_year, 0, 1);
9414  _date_fract = 0;
9415  _tick_counter = 0;
9416  _display_opt = 0;
9417  }
9418 
9420 
9421  ResetNewGRFData();
9422 
9423  /*
9424  * Reset the status of all files, so we can 'retry' to load them.
9425  * This is needed when one for example rearranges the NewGRFs in-game
9426  * and a previously disabled NewGRF becomes useable. If it would not
9427  * be reset, the NewGRF would remain disabled even though it should
9428  * have been enabled.
9429  */
9430  for (GRFConfig *c = _grfconfig; c != NULL; c = c->next) {
9431  if (c->status != GCS_NOT_FOUND) c->status = GCS_UNKNOWN;
9432  }
9433 
9434  _cur.spriteid = load_index;
9435 
9436  /* Load newgrf sprites
9437  * in each loading stage, (try to) open each file specified in the config
9438  * and load information from it. */
9439  for (GrfLoadingStage stage = GLS_LABELSCAN; stage <= GLS_ACTIVATION; stage++) {
9440  /* Set activated grfs back to will-be-activated between reservation- and activation-stage.
9441  * This ensures that action7/9 conditions 0x06 - 0x0A work correctly. */
9442  for (GRFConfig *c = _grfconfig; c != NULL; c = c->next) {
9443  if (c->status == GCS_ACTIVATED) c->status = GCS_INITIALISED;
9444  }
9445 
9446  if (stage == GLS_RESERVE) {
9447  static const uint32 overrides[][2] = {
9448  { 0x44442202, 0x44440111 }, // UKRS addons modifies UKRS
9449  { 0x6D620402, 0x6D620401 }, // DBSetXL ECS extension modifies DBSetXL
9450  { 0x4D656f20, 0x4D656F17 }, // LV4cut modifies LV4
9451  };
9452  for (size_t i = 0; i < lengthof(overrides); i++) {
9453  SetNewGRFOverride(BSWAP32(overrides[i][0]), BSWAP32(overrides[i][1]));
9454  }
9455  }
9456 
9457  uint slot = file_index;
9458  uint num_non_static = 0;
9459 
9460  _cur.stage = stage;
9461  for (GRFConfig *c = _grfconfig; c != NULL; c = c->next) {
9462  if (c->status == GCS_DISABLED || c->status == GCS_NOT_FOUND) continue;
9463  if (stage > GLS_INIT && HasBit(c->flags, GCF_INIT_ONLY)) continue;
9464 
9465  Subdirectory subdir = slot < file_index + num_baseset ? BASESET_DIR : NEWGRF_DIR;
9466  if (!FioCheckFileExists(c->filename, subdir)) {
9467  DEBUG(grf, 0, "NewGRF file is missing '%s'; disabling", c->filename);
9468  c->status = GCS_NOT_FOUND;
9469  continue;
9470  }
9471 
9472  if (stage == GLS_LABELSCAN) InitNewGRFFile(c);
9473 
9474  if (!HasBit(c->flags, GCF_STATIC) && !HasBit(c->flags, GCF_SYSTEM)) {
9475  if (num_non_static == NETWORK_MAX_GRF_COUNT) {
9476  DEBUG(grf, 0, "'%s' is not loaded as the maximum number of non-static GRFs has been reached", c->filename);
9477  c->status = GCS_DISABLED;
9478  c->error = new GRFError(STR_NEWGRF_ERROR_MSG_FATAL, STR_NEWGRF_ERROR_TOO_MANY_NEWGRFS_LOADED);
9479  continue;
9480  }
9481  num_non_static++;
9482  }
9483  LoadNewGRFFile(c, slot++, stage, subdir);
9484  if (stage == GLS_RESERVE) {
9485  SetBit(c->flags, GCF_RESERVED);
9486  } else if (stage == GLS_ACTIVATION) {
9487  ClrBit(c->flags, GCF_RESERVED);
9488  assert(GetFileByGRFID(c->ident.grfid) == _cur.grffile);
9491  DEBUG(sprite, 2, "LoadNewGRF: Currently %i sprites are loaded", _cur.spriteid);
9492  } else if (stage == GLS_INIT && HasBit(c->flags, GCF_INIT_ONLY)) {
9493  /* We're not going to activate this, so free whatever data we allocated */
9495  }
9496  }
9497  }
9498 
9499  /* Pseudo sprite processing is finished; free temporary stuff */
9500  _cur.ClearDataForNextFile();
9501 
9502  /* Call any functions that should be run after GRFs have been loaded. */
9503  AfterLoadGRFs();
9504 
9505  /* Now revert back to the original situation */
9506  _cur_year = year;
9507  _date = date;
9508  _date_fract = date_fract;
9509  _tick_counter = tick_counter;
9510  _display_opt = display_opt;
9511 }
CargoID accepts_cargo[INDUSTRY_NUM_INPUTS]
16 accepted cargoes.
Definition: industrytype.h:118
void ResetBridges()
Reset the data been eventually changed by the grf loaded.
bool disable_elrails
when true, the elrails are disabled
bool enabled
the house is available to build (true by default, but can be disabled by newgrf)
Definition: house.h:113
const struct GRFFile * grffile
NewGRF where #group belongs to.
Definition: cargotype.h:80
Information about a ship vehicle.
Definition: engine_type.h:66
TextHandler text
Callback function for a text node, only valid if type == &#39;T&#39;.
Definition: newgrf.cpp:7748
Used for iterations.
Definition: rail_type.h:35
Functions related to OTTD&#39;s strings.
VehicleSettings vehicle
options for vehicles
static void FinaliseEngineArray()
Check for invalid engines.
Definition: newgrf.cpp:8582
TTDPAirportType ttd_airport_type
ttdpatch airport type (Small/Large/Helipad/Oilrig)
uint32 PaletteID
The number of the palette.
Definition: gfx_type.h:20
void ClearDataForNextFile()
Clear temporary data before processing the next file in the current loading stage.
Definition: newgrf.cpp:112
Class to read from a NewGRF file.
Definition: newgrf.cpp:210
static ChangeInfoResult IgnoreIndustryTileProperty(int prop, ByteReader *buf)
Ignore an industry tile property.
Definition: newgrf.cpp:3091
static const SpriteID SPR_SHORE_BASE
shore tiles - action 05-0D
Definition: sprites.h:218
const SpriteGroup * group[RTSG_END]
Sprite groups for resolving sprites.
Definition: rail.h:272
uint8 max_heightlevel
maximum allowed heightlevel
RailTypeFlags
Railtype flags.
Definition: rail.h:26
byte probability
Relative probability of appearing (16 is the standard value)
Definition: house.h:119
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition: settings.cpp:77
SmallVector< Mapping, 1 > case_map
Mapping of NewGRF and OpenTTD IDs for cases.
Definition: newgrf_text.h:61
GRF was disabled due to error.
Definition: newgrf.cpp:988
const SpriteGroup ** groups
Take the group with appropriate index:
bool _networking
are we in networking mode?
Definition: network.cpp:56
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:298
void SetEntitySpec(ObjectSpec *spec)
Method to install the new object data in its proper slot The slot assignment is internal of this meth...
CargoID cargo_output[INDUSTRY_NUM_OUTPUTS]
Which output cargoes to add to (only cb version 2)
Functions for NewGRF engines.
uint8 GetCaseIndex(const char *case_str) const
Get the index for the given case.
Definition: language.h:82
bool enabled
entity still available (by default true).newgrf can disable it, though
Definition: industrytype.h:137
ObjectFlags
Various object behaviours.
Definition: newgrf_object.h:26
Object wants 2CC colour mapping.
Definition: newgrf_object.h:36
void SortIndustryTypes()
Initialize the list of sorted industry types.
static const RailtypeInfo * GetRailTypeInfo(RailType railtype)
Returns a pointer to the Railtype information for a given railtype.
Definition: rail.h:298
Year avail_year
the year where it becomes available
Definition: bridge.h:44
static void ResetCustomObjects()
Reset and clear all NewObjects.
Definition: newgrf.cpp:8200
const GRFFile * grffile[RTSG_END]
NewGRF providing the Action3 for the railtype.
Definition: rail.h:267
ObjectFlags flags
Flags/settings related to the object.
Definition: newgrf_object.h:72
static void FinaliseIndustriesArray()
Add all new industries to the industry array.
Definition: newgrf.cpp:8801
struct LanguageMap * language_map
Mappings related to the languages.
Definition: newgrf.h:133
Add signed offset to child sprite Y positions from register TileLayoutRegisters::delta.child[1].
int16 subtract_input[INDUSTRY_NUM_INPUTS]
Take this much of the input cargo (can be negative, is indirect in cb version 1+) ...
static void AfterLoadGRFs()
Finish loading NewGRFs and execute needed post-processing.
Definition: newgrf.cpp:9305
static const SpriteID SPR_TRACKS_FOR_SLOPES_BASE
Sprites for &#39;highlighting&#39; tracks on sloped land.
Definition: sprites.h:192
uint32 param_value[2]
Values of GRF parameters to show for message and custom_message.
uint8 weight
Weight of a single unit of this cargo type in 1/16 ton (62.5 kg).
Definition: cargotype.h:61
CargoTypes _cargo_mask
Bitmask of cargo types available.
Definition: cargotype.cpp:31
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.
void AlterVehicleListOrder(EngineID engine, uint target)
Record a vehicle ListOrderChange.
static void ResetCustomAirports()
Reset and clear all NewGRF airports.
Definition: newgrf.cpp:8122
AllowedSubtags(uint32 id, DataHandler handler)
Create a binary leaf node.
Definition: newgrf.cpp:7699
LiveryScheme
List of different livery schemes.
Definition: livery.h:22
The parameter allows a range of numbers, each of which can have a special name.
Monorail.
Definition: rail_type.h:33
GRFConfig * _grfconfig
First item in list of current GRF set up.
byte landscape
the landscape we&#39;re currently in
void ResetCurrencies(bool preserve_custom)
Will fill _currency_specs array with default values from origin_currency_specs Called only from newgr...
Definition: currency.cpp:153
byte size_y
size of airport in y direction
RailType
Enumeration for all possible railtypes.
Definition: rail_type.h:29
Aircraft range.
Subdirectory
The different kinds of subdirectories OpenTTD uses.
Definition: fileio_type.h:110
byte map_colour
colour used for the small map
Definition: industrytype.h:123
static void ResetNewGRF()
Reset and clear all NewGRFs.
Definition: newgrf.cpp:8216
int plural_form
The plural form used for this language.
Definition: newgrf_text.h:62
static AirportSpec * GetWithoutOverride(byte type)
Retrieve airport spec for the given airport.
uint16 triggers
The triggers that trigger animation.
East.
StringID toolbar_caption
Caption in the construction toolbar GUI for this rail type.
Definition: rail.h:168
GRF file is processed up to GLS_INIT.
Definition: newgrf_config.h:29
uint32 grfid
The GRF ID of the file the entity belongs to.
Definition: engine_base.h:149
byte newgrf_id
NewGRF&#39;s internal ID for a case/gender.
Definition: newgrf_text.h:50
Action5BlockType block_type
How is this Action5 type processed?
Definition: newgrf.cpp:5786
const Pair * Find(const T &key) const
Finds given key in this map.
byte _display_opt
What do we want to draw/do?
CargoTypes watched_cargoes
Cargo types watched for acceptance.
Definition: house.h:125
EconomySettings economy
settings to change the economy
uint8 build_cost_multiplier
Build cost multiplier per tile.
Definition: newgrf_object.h:68
bool is_freight
Cargo type is considered to be freight (affects train freight multiplier).
Definition: cargotype.h:66
uint32 nfo_line
Currently processed pseudo sprite number in the GRF.
Definition: newgrf.cpp:102
#define DAYS_TILL_ORIGINAL_BASE_YEAR
The offset in days from the &#39;_date == 0&#39; till &#39;ConvertYMDToDate(ORIGINAL_BASE_YEAR, 0, 1)&#39;.
Definition: date_type.h:82
void Allocate(uint num_sprites)
Allocate a spritelayout for num_sprites building sprites.
TileLayoutFlags
Flags to enable register usage in sprite layouts.
byte curve_speed
Multiplier for curve maximum speed advantage.
Definition: rail.h:197
uint16 max_sprites
If the Action5 contains more sprites, only the first max_sprites sprites will be used.
Definition: newgrf.cpp:5789
static void FinaliseObjectsArray()
Add all new objects to the object array.
Definition: newgrf.cpp:8872
Max. speed: 1 unit = 1/1.6 mph = 1 km-ish/h.
static Titem * Get(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:246
const GRFFile * grffile
NewGRF where &#39;group&#39; belongs to.
Definition: newgrf_canal.h:26
AllowedSubtags(uint32 id, AllowedSubtags *subtags)
Create a branch node with a list of sub-nodes.
Definition: newgrf.cpp:7736
static const SpriteID SPR_ONEWAY_BASE
One way road sprites.
Definition: sprites.h:285
byte ocean_speed_frac
Fraction of maximum speed for ocean tiles.
Definition: engine_type.h:75
Functions related to dates.
Power in hp (if dualheaded: sum of both vehicles)
static bool IsInsideMM(const T x, const uint min, const uint max)
Checks if a value is in an interval.
Definition: math_func.hpp:266
Day day
Day (1..31)
Definition: date_type.h:106
CargoID GetCargoIDByLabel(CargoLabel cl)
Get the cargo ID by cargo label.
Definition: cargotype.cpp:88
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:2587
static const Year ORIGINAL_MAX_YEAR
The maximum year of the original TTD.
Definition: date_type.h:55
CurrencySpec _currency_specs[CURRENCY_END]
Array of currencies used by the system.
Definition: currency.cpp:70
Functions for NewGRF industries.
Maglev.
Definition: rail_type.h:34
Functions to handle different currencies.
const uint8 _engine_offsets[4]
Offset of the first engine of each vehicle type in original engine data.
Definition: engine.cpp:60
SpriteID sprite
SpriteID of the first sprite of the set.
Definition: newgrf.cpp:86
GRFParameterType type
The type of this parameter.
void UpdateRefittability(bool non_empty)
Update the summary refittability on setting a refittability property.
Definition: newgrf.cpp:323
RailTypes introduction_required_railtypes
Bitmask of railtypes that are required for this railtype to be introduced at a given introduction_dat...
Definition: rail.h:252
static uint MapLogX()
Logarithm of the map size along the X side.
Definition: map_func.h:53
uint32 prospecting_chance
Chance prospecting succeeds.
Definition: industrytype.h:108
PalSpriteID ** sprite_table
table of sprites for drawing the bridge
Definition: bridge.h:53
static ChangeInfoResult ShipVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader *buf)
Define properties for ships.
Definition: newgrf.cpp:1528
RailTypeFlags flags
Bit mask of rail type flags.
Definition: rail.h:202
const byte _grf_cont_v2_sig[8]
Signature of a container version 2 GRF.
static bool ChangeGRFParamMask(size_t len, ByteReader *buf)
Callback function for &#39;INFO&#39;->&#39;PARAM&#39;->param_num->&#39;MASK&#39; to set the parameter and bits to use...
Definition: newgrf.cpp:7643
static ChangeInfoResult IgnoreObjectProperty(uint prop, ByteReader *buf)
Ignore properties for objects.
Definition: newgrf.cpp:3987
Free the dynamically allocated sounds table.
Definition: industrytype.h:24
Functions related to debugging.
static T SetBit(T &x, const uint8 y)
Set a bit in a variable.
uint32 grfid
Source NewGRF.
Definition: newgrf.cpp:460
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.
GRFConfig * grfconfig
Config of the currently processed GRF file.
Definition: newgrf.cpp:101
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:600
char * text
If probability bit 7 is clear.
static const IndustryGfx INVALID_INDUSTRYTILE
one above amount is considered invalid
Definition: industry_type.h:36
Add signed offset to bounding box X and Y positions from register TileLayoutRegisters::delta.parent[0..1].
CargoID GetCargoTranslation(uint8 cargo, const GRFFile *grffile, bool usebit)
Translate a GRF-local cargo slot/bitnum into a CargoID.
static void ImportGRFSound(SoundEntry *sound)
Process a sound import from another GRF file.
Definition: newgrf.cpp:7219
static void FinaliseCanals()
Set to use the correct action0 properties for each canal feature.
Definition: newgrf.cpp:8571
GRFPalette
Information that can/has to be stored about a GRF&#39;s palette.
Definition: newgrf_config.h:60
byte flags
bit 0 set: disable drawing of far pillars.
Definition: bridge.h:54
char * TranslateTTDPatchCodes(uint32 grfid, uint8 language_id, bool allow_newlines, const char *str, int *olen, StringControlCode byte80)
Translate TTDPatch string codes into something OpenTTD can handle (better).
uint16 FioReadWord()
Read a word (16 bits) from the file (in low endian format).
Definition: fileio.cpp:166
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...
GRFFilePropsBase< NUM_CARGO+2 > grf_prop
Properties related the the grf file.
Definition: engine_base.h:60
GRFFilePropsBase< 2 > grf_prop
Properties related the the grf file.
Definition: newgrf_object.h:62
Maximal number of cargo types in a game.
Definition: cargo_type.h:66
Rail vehicle can be flipped in the depot.
Definition: engine_type.h:157
The NewGRF prefers a 32 bpp blitter.
Definition: newgrf_config.h:78
byte cargo_acceptance[HOUSE_NUM_ACCEPTS]
acceptance level for the cargo slots
Definition: house.h:109
GRFFile(const struct GRFConfig *config)
Constructor for GRFFile.
Definition: newgrf.cpp:8390
static const uint ORIGINAL_SAMPLE_COUNT
The number of sounds in the original sample.cat.
Definition: sound_type.h:118
GRF file has been initialised.
Definition: newgrf_config.h:39
Specification of a cargo type.
Definition: cargotype.h:56
Station specification.
static bool ChangeGRFParamLimits(size_t len, ByteReader *buf)
Callback function for &#39;INFO&#39;->&#39;PARAM&#39;->param_num->&#39;LIMI&#39; to set the min/max value of a parameter...
Definition: newgrf.cpp:7627
CanalFeature
List of different canal &#39;features&#39;.
Definition: newgrf.h:26
static void GRFUnsafe(ByteReader *buf)
Set the current NewGRF as unsafe for static use.
Definition: newgrf.cpp:7974
void SetSnowLine(byte table[SNOW_LINE_MONTHS][SNOW_LINE_DAYS])
Set a variable snow line, as loaded from a newgrf file.
Definition: landscape.cpp:627
uint32 def_value
Default value of this parameter.
Yearly runningcost (if dualheaded: sum of both vehicles)
IndustryLifeType life_type
This is also known as Industry production flag, in newgrf specs.
Definition: industrytype.h:120
byte visual_effect
Bitstuffed NewGRF visual effect data.
Definition: engine_type.h:124
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
bool IsSnowLineSet()
Has a snow line table already been loaded.
Definition: landscape.cpp:617
GRFStatus status
NOSAVE: GRFStatus, enum.
uint16 max_palette_offset
Maximum offset to add to the palette. (limited by size of the spriteset)
Functions related to vehicles.
struct GRFText * text
The actual text.
Resolve sprite with a specific value in variable 10.
static void BuildCargoTranslationMap()
Construct the Cargo Mapping.
Definition: newgrf.cpp:8350
const HangarTileTable * depot_table
gives the position of the depots on the airports
CargoID accepts_cargo[HOUSE_NUM_ACCEPTS]
input cargo slots
Definition: house.h:110
static const uint INVALID_AIRPORTTILE
id for an invalid airport tile
Definition: airport.h:27
Flags which require resolving the action-1-2-3 chain for the sprite, even if it is no action-1 sprite...
uint16 callback_mask
Bitmask of industry callbacks that have to be called.
Definition: industrytype.h:135
Allow replacing any subset by specifiing an offset.
Definition: newgrf.cpp:5781
uint32 grf_features
Bitset of GrfSpecFeature the grf uses.
Definition: newgrf.h:138
Always succeeds.
Definition: industrytype.h:41
Price
Enumeration of all base prices for use with Prices.
Definition: economy_type.h:67
Combination of a palette sprite and a &#39;real&#39; sprite.
Definition: gfx_type.h:24
No profile, special "custom" highscore.
Definition: settings_type.h:35
byte removal_cost
cost multiplier for removing it
Definition: house.h:105
bool HasValidSpriteSets(byte feature) const
Check whether there are any valid spritesets for a feature.
Definition: newgrf.cpp:148
uint32 removal_cost_multiplier
Base removal cost multiplier.
Definition: industrytype.h:107
void Clear()
Remove all items from the list.
Purchase cost (if dualheaded: sum of both vehicles)
GRF file is used statically (can be used in any MP game)
Definition: newgrf_config.h:26
Header of Action 0F "universal holder" structure and functions.
bool never_expire_airports
never expire airports
uint8 flags
Flags controlling display.
Definition: newgrf_canal.h:28
uint GetNumEnts(byte feature, uint set) const
Returns the number of sprites in a spriteset.
Definition: newgrf.cpp:185
AllowedSubtags _tags_info[]
Action14 tags for the INFO node.
Definition: newgrf.cpp:7844
uint8 num_valid_params
NOSAVE: Number of valid parameters (action 0x14)
char * custom_message
Custom message (if present)
const T * Begin() const
Get the pointer to the first item (const)
Add signed offset to palette from register TileLayoutRegisters::palette.
Flags which do not work for the (first) ground sprite.
RailTypeLabelList alternate_labels
Rail type labels this type provides in addition to the main label.
Definition: rail.h:232
Maximum number of slots.
Definition: fios.h:101
Tindex index
Index of this pool item.
Definition: pool_type.hpp:147
static void FinaliseCargoArray()
Check for invalid cargoes.
Definition: newgrf.cpp:8633
int8 acceptance[INDUSTRY_NUM_INPUTS]
Level of acceptance per cargo type (signed, may be negative!)
Definition: industrytype.h:153
EngineID GetID(VehicleType type, uint16 grf_local_id, uint32 grfid)
Looks up an EngineID in the EngineOverrideManager.
Definition: engine.cpp:511
bool Insert(const T &key, const U &data)
Adds new item to this map.
EngineClass
Type of rail engine.
Definition: engine_type.h:34
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.net/tiki-index.php?page=BaseCosts.
Definition: newgrf.cpp:966
void CommitVehicleListOrderChanges()
Deternine default engine sorting and execute recorded ListOrderChanges from AlterVehicleListOrder.
void ResetPersistentNewGRFData()
Reset NewGRF data which is stored persistently in savegames.
Definition: newgrf.cpp:8335
StringID name_single
Name of a single entity of this type of cargo.
Definition: cargotype.h:72
GRFError * error
NOSAVE: Error/Warning during GRF loading (Action 0x0B)
static const uint SNOW_LINE_MONTHS
Number of months in the snow line table.
Definition: landscape.h:18
uint16 speed
maximum travel speed (1 unit = 1/1.6 mph = 1 km-ish/h)
Definition: bridge.h:48
Add signed offset to sprite from register TileLayoutRegisters::sprite.
Allow incrementing of ObjectClassID variables.
Definition: newgrf_object.h:60
Functions for Standard In/Out file operations.
Date end_of_life_date
When can&#39;t this object be built anymore.
Definition: newgrf_object.h:71
static void ActivateOldShore()
Relocates the old shore sprites at new positions.
Definition: newgrf.cpp:9150
A list of all hangar tiles in an airport.
Industry type specs.
size_t Utf8Decode(WChar *c, const char *s)
Decode and consume the next UTF-8 encoded character.
Definition: string.cpp:448
The NewGRF provided no information.
Definition: newgrf_config.h:71
static const CargoID CT_PURCHASE_OBJECT
Mapping of purchase for objects.
byte param_nr
GRF parameter to store content in.
Cargo behaves water-like.
Definition: cargotype.h:31
StringID abbrev
Two letter abbreviation for this cargo type.
Definition: cargotype.h:75
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:119
#define lastof(x)
Get the last element of an fixed size array.
Definition: depend.cpp:50
static bool ChangeGRFParamName(byte langid, const char *str)
Callback function for &#39;INFO&#39;->&#39;PARAM&#39;->param_num->&#39;NAME&#39; to set the name of a parameter.
Definition: newgrf.cpp:7596
static const SpriteID SPR_AQUEDUCT_BASE
Sprites for the Aqueduct.
Definition: sprites.h:180
Simple vector template class.
StringID GetGRFStringID(uint32 grfid, StringID stringid)
Returns the index for this stringid associated with its grfID.
ChangeInfoResult
Possible return values for the FeatureChangeInfo functions.
Definition: newgrf.cpp:986
static void CleanIndustryTileTable(IndustrySpec *ind)
Clean the tile table of the IndustrySpec if it&#39;s needed.
Definition: newgrf.cpp:3374
GRF file was not found in the local cache.
Definition: newgrf_config.h:38
Functions related to world/map generation.
RailTypes compatible_railtypes
bitmask to the OTHER railtypes on which an engine of THIS railtype can physically travel ...
Definition: rail.h:182
No properties assigned. Default refit masks shall be activated.
Definition: newgrf.cpp:304
Number of ticks before carried cargo is aged.
Cargo behaves goods/candy-like.
Definition: cargotype.h:30
StringID quantifier
Text for multiple units of cargo of this type.
Definition: cargotype.h:74
static uint MapLogY()
Logarithm of the map size along the y side.
Definition: map_func.h:64
Relative position (vehicles only)
static ChangeInfoResult RailTypeChangeInfo(uint id, int numinfo, int prop, ByteReader *buf)
Define properties for railtypes.
Definition: newgrf.cpp:4164
Date introduction_date
From when can this object be built.
Definition: newgrf_object.h:70
const IndustryTileTable *const * table
List of the tiles composing the industry.
Definition: industrytype.h:104
Standard non-electric rails.
Definition: rail_type.h:31
void AllocateRegisters()
Allocate memory for register modifiers.
uint8 flags
Flags controlling display.
Definition: newgrf.h:42
byte num_loaded
Number of loaded groups.
LiveryScheme GetEngineLiveryScheme(EngineID engine_type, EngineID parent_engine_type, const Vehicle *v)
Determines the LiveryScheme for a vehicle.
Definition: vehicle.cpp:1802
#define FOR_EACH_SET_BIT(bitpos_var, bitset_value)
Do an operation for each set set bit in a value.
#define AllocaM(T, num_elements)
alloca() has to be called in the parent function, so define AllocaM() as a macro
Definition: alloc_func.hpp:134
Tractive effort coefficient in 1/256.
Refittability refittability
Did the newgrf set any refittability property? If not, default refittability will be applied...
Definition: newgrf.cpp:313
GRFIdentifier ident
grfid and md5sum to uniquely identify newgrfs
static ChangeInfoResult AirportChangeInfo(uint airport, int numinfo, int prop, ByteReader *buf)
Define properties for airports.
Definition: newgrf.cpp:3815
void LoadNewGRF(uint load_index, uint file_index, uint num_baseset)
Load all the NewGRFs.
Definition: newgrf.cpp:9399
byte pow_wag_weight
Extra weight applied to consist if wagon should be powered.
Definition: engine_type.h:57
int32 Year
Type for the year, note: 0 based, i.e. starts at the year 0.
Definition: date_type.h:20
static GRFError * DisableGrf(StringID message=STR_NULL, GRFConfig *config=NULL)
Disable a GRF.
Definition: newgrf.cpp:433
uint16 callback_mask
Bitmask of house callbacks that have to be called.
Definition: house.h:117
StringID source
Source StringID (GRF local).
Definition: newgrf.cpp:461
Subdirectory for all base data (base sets, intro game)
Definition: fileio_type.h:118
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:5757
static T max(const T a, const T b)
Returns the maximum of two values.
Definition: math_func.hpp:26
uint16 classes
Classes of this cargo type.
Definition: cargotype.h:79
static bool ChangeGRFPalette(size_t len, ByteReader *buf)
Callback function for &#39;INFO&#39;->&#39;PALS&#39; to set the number of valid parameters.
Definition: newgrf.cpp:7513
bool allow_town_roads
towns are allowed to build roads (always allowed when generating world / in SE)
static bool ChangeGRFDescription(byte langid, const char *str)
Callback function for &#39;INFO&#39;->&#39;DESC&#39; to add a translation to the newgrf description.
Definition: newgrf.cpp:7487
byte FioReadByte()
Read a byte from the file.
Definition: fileio.cpp:133
GRFLabel * label
Pointer to the first label. This is a linked list, not an array.
Definition: newgrf.h:123
uint8 status
Status; 0: no looping, 1: looping, 0xFF: no animation.
bool never_expire_vehicles
never expire vehicles
Year _cur_year
Current year, starting at 0.
Definition: date.cpp:26
Struct containing information about a single bridge type.
Definition: bridge.h:43
uint32 GetParam(uint number) const
Get GRF Parameter with range checking.
Definition: newgrf.h:145
uint tiles
Number of tile layouts.
bool improved_load
improved loading algorithm
static void DefineGotoLabel(ByteReader *buf)
Action 0x10 - Define goto label.
Definition: newgrf.cpp:7187
GRF file is disabled.
Definition: newgrf_config.h:37
Year min_year
first year the airport is available
const T * End() const
Get the pointer behind the last valid item (const)
SmallVector< GRFParameterInfo *, 4 > param_info
NOSAVE: extra information about the parameters.
static void LoadGRFSound(size_t offs, SoundEntry *sound)
Load a sound from a file.
Definition: newgrf.cpp:7250
Date base_intro
Basic date of engine introduction (without random parts).
Definition: engine_type.h:133
static StringID TTDPStringIDToOTTDStringIDMapping(StringID str)
Perform a mapping from TTDPatch&#39;s string IDs to OpenTTD&#39;s string IDs, but only for the ones we are aw...
Definition: newgrf.cpp:488
GRFParameterType
The possible types of a newgrf parameter.
byte nof_depots
the number of hangar tiles in this airport
Tables with default industry layouts and behaviours.
StringID menu_text
Name of this rail type in the main toolbar dropdown.
Definition: rail.h:169
StationSettings station
settings related to station management
void AddGenericCallback(uint8 feature, const GRFFile *file, const SpriteGroup *group)
Add a generic feature callback sprite group to the appropriate feature list.
StringID production_down_text
Message appearing when the industry&#39;s production is decreasing.
Definition: industrytype.h:128
StringID new_loco
Name of an engine for this type of rail in the engine preview GUI.
Definition: rail.h:172
struct GRFConfig * next
NOSAVE: Next item in the linked list.
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:24
StringID name
Name of this type of cargo.
Definition: cargotype.h:71
uint16 maintenance_cost
maintenance cost multiplier
Year lifelength
Lifetime of a single vehicle.
Definition: engine_type.h:134
static const HouseID NUM_HOUSES
Total number of houses.
Definition: house.h:31
Metadata about a single language.
Definition: language.h:94
void InitGRFTownGeneratorNames()
Allocate memory for the NewGRF town names.
Definition of a single Action1 spriteset.
Definition: newgrf.cpp:85
byte grf_container_ver
NewGRF container version if the sound is from a NewGRF.
Definition: sound_type.h:24
Direction
Defines the 8 directions on the map.
StringID name
Displayed name of the industry.
Definition: industrytype.h:124
Maglev engine.
Definition: engine_type.h:39
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.
HouseZones
Definition: house.h:73
uint num_sprites
Number of sprites in the set.
Definition: newgrf.cpp:87
const DrawTileSeqStruct * seq
Array of child sprites. Terminated with a terminator entry.
Definition: sprite.h:62
const AirportTileTable *const * table
list of the tiles composing the airport
uint16 max_speed
Maximum speed (1 unit = 8 mph = 12.8 km-ish/h)
Definition: engine_type.h:105
uint16 max_speed
Maximum speed (1 unit = 1/3.2 mph = 0.5 km-ish/h)
Definition: engine_type.h:69
No shore sprites were replaced.
Definition: newgrf.h:155
byte lowest_randbit
Look for this in the per-object randomized bitmask:
Temporary data during loading of GRFs.
Definition: newgrf.cpp:82
BridgeSpec _bridge[MAX_BRIDGES]
The specification of all bridges.
CargoTypes cargo_triggers
Bitmask of cargo types which cause trigger re-randomizing.
size_t GetGRFSpriteOffset(uint32 id)
Get the file offset for a specific sprite in the sprite section of a GRF.
IndustryTileSpecialFlags special_flags
Bitmask of extra flags used by the tile.
Definition: industrytype.h:165
SpriteID sprite_base
Load the sprites starting from this sprite.
Definition: newgrf.cpp:5787
StringID build_caption
Caption of the build vehicle GUI for this rail type.
Definition: rail.h:170
This struct contains all the info that is needed to draw and construct tracks.
Definition: rail.h:118
Mono rail engine.
Definition: engine_type.h:38
const LanguageMetadata * GetLanguage(byte newgrflangid)
Get the language with the given NewGRF language ID.
Definition: strings.cpp:1885
NewGRF handling of airports.
T * Append(uint to_add=1)
Append an item and return it.
static void FinaliseAirportsArray()
Add all new airports to the airport array.
Definition: newgrf.cpp:8892
HouseZones building_availability
where can it be built (climates, zones)
Definition: house.h:112
static const LanguageMap * GetLanguageMap(uint32 grfid, uint8 language_id)
Get the language map associated with a given NewGRF and language.
Definition: newgrf.cpp:2570
IndustryLifeType
Available types of industry lifetimes.
Definition: industrytype.h:29
Diesel rail engine.
Definition: engine_type.h:36
GRFFile * grffile
Currently processed GRF file.
Definition: newgrf.cpp:100
byte population
population (Zero on other tiles in multi tile house.)
Definition: house.h:104
uint8 size
The size of this objects; low nibble for X, high nibble for Y.
Definition: newgrf_object.h:67
Functions related to NewGRF objects.
void ResetIndustries()
This function initialize the spec arrays of both industry and industry tiles.
uint16 multiplier
Capacity multiplier for vehicles. (8 fractional bits)
Definition: cargotype.h:62
PriceMultipliers price_base_multipliers
Price base multipliers as set by the grf.
Definition: newgrf.h:139
Invalid cargo type.
Definition: cargo_type.h:70
int16 y
The y value of the coordinate.
Definition: map_type.h:61
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:27
uint8 cleanup_flag
flags indicating which data should be freed upon cleaning up
Definition: industrytype.h:136
virtual uint16 GetID(uint8 grf_local_id, uint32 grfid) const
Return the ID (if ever available) of a previously inserted entity.
byte grf_container_ver
Container format of the current GRF file.
Definition: newgrf.cpp:103
Slope slopes_refused
slope pattern on which this tile cannot be built
Definition: industrytype.h:154
static ChangeInfoResult CommonVehicleChangeInfo(EngineInfo *ei, int prop, ByteReader *buf)
Define properties common to all vehicles.
Definition: newgrf.cpp:1003
Functions to read fonts from files and cache them.
const uint8 * random_sounds
array of random sounds.
Definition: industrytype.h:133
StringID * target
Destination for mapping result.
Definition: newgrf.cpp:462
static ChangeInfoResult AircraftVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader *buf)
Define properties for aircraft.
Definition: newgrf.cpp:1700
Only draw sprite if value of register TileLayoutRegisters::dodraw is non-zero.
void SetPriceBaseMultiplier(Price price, int factor)
Change a price base by the given factor.
Definition: economy.cpp:900
byte symbol_pos
The currency symbol is represented by two possible values, prefix and suffix Usage of one or the othe...
Definition: currency.h:82
uint16 add_output[INDUSTRY_NUM_OUTPUTS]
Add this much output cargo when successful (unsigned, is indirect in cb version 1+) ...
struct GRFText * desc
The description of this parameter.
Mapping between NewGRF and OpenTTD IDs.
Definition: newgrf_text.h:49
byte catchment
catchment area of this airport
Header of Action 04 "universal holder" structure and functions.
uint8 height
The height of this structure, in heightlevels; max MAX_TILE_HEIGHT.
Definition: newgrf_object.h:75
GrfLoadingStage stage
Current loading stage.
Definition: newgrf.cpp:95
void ResetObjects()
This function initialize the spec arrays of objects.
void ReadGRFSpriteOffsets(byte container_version)
Parse the sprite section of GRFs.
User defined data for vehicle variable 0x42.
Aircraft vehicle type.
Definition: vehicle_type.h:29
byte noise_level
noise that this airport generates
Struct containing information relating to NewGRF classes for stations and airports.
Definition: newgrf_class.h:21
struct RailtypeInfo::@40 strings
Strings associated with the rail type.
ShoreReplacement shore
It which way shore sprites were replaced.
Definition: newgrf.h:166
Functions related to low-level strings.
byte pylons
Bitmask of base tiles (0 - 7) which should contain elrail pylons.
uint8 freight_trains
value to multiply the weight of cargo by
bool prop27_set
Did the NewGRF set property 27 (misc flags)?
Definition: newgrf.cpp:314
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:800
uint8 num_output
How many add_output values are valid.
uint8 palette_var10
Value for variable 10 when resolving the palette.
uint param_end
one more than the highest set parameter
Definition: newgrf.h:121
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=NULL, uint16 *max_palette_offset=NULL)
Read a sprite and a palette from the GRF and convert them into a format suitable to OpenTTD...
Definition: newgrf.cpp:742
void Clone(const DrawTileSeqStruct *source)
Clone the building sprites of a spritelayout.
First bit used for the type of effect.
Definition: vehicle_base.h:83
int traininfo_vehicle_pitch
Vertical offset for draing train images in depot GUI and vehicle details.
Definition: newgrf.h:135
bool enabled
Is this spec enabled?
Definition: newgrf_object.h:78
Information about a vehicle.
Definition: engine_type.h:132
static void FinaliseHouseArray()
Add all new houses to the house array.
Definition: newgrf.cpp:8729
uint16 internal_id
The internal ID within the GRF file.
Definition: engine_base.h:150
uint8 num_params
Number of used parameters.
static void CalculateRefitMasks()
Precalculate refit masks from cargo classes for all vehicles.
Definition: newgrf.cpp:8466
byte mail_generation
mail generation multiplier (tile based, as the acceptances below)
Definition: house.h:108
bool(* BranchHandler)(ByteReader *)
Type of callback function for branch nodes.
Definition: newgrf.cpp:7678
Functions related to errors.
RailType AllocateRailType(RailTypeLabel label)
Allocate a new rail type label.
Definition: rail_cmd.cpp:161
bool IsTerminator() const
Check whether this is a sequence terminator.
Definition: sprite.h:43
static SmallVector< GRFFile *, 16 > _grf_files
List of all loaded GRF files.
Definition: newgrf.cpp:68
const SpriteGroup ** loaded
List of loaded groups (can be SpriteIDs or Callback results)
uint Length() const
Get the number of items in the list.
byte subtype
Type of aircraft.
Definition: engine_type.h:102
uint16 max_sprite_offset
Maximum offset to add to the sprite. (limited by size of the spriteset)
void SetupEngines()
Initialise the engine pool with the data from the original vehicles.
Definition: engine.cpp:545
DateFract _date_fract
Fractional part of the day.
Definition: date.cpp:29
static uint32 _grm_engines[256]
Contains the GRF ID of the owner of a vehicle if it has been reserved.
Definition: newgrf.cpp:339
byte train_signal_side
show signals on left / driving / right side
The NewGRF says any palette can be used.
Definition: newgrf_config.h:74
Shore sprites were replaced by Action5.
Definition: newgrf.h:156
GRF file is an openttd-internal system grf.
Definition: newgrf_config.h:24
static size_t GetPoolSize()
Returns first unused index.
Definition: pool_type.hpp:267
West.
HouseClassID class_id
defines the class this house has (not grf file based)
Definition: house.h:121
Information about GRF, used in the game and (part of it) in savegames.
void SetYearEngineAgingStops()
Compute the value for _year_engine_aging_stops.
Definition: engine.cpp:617
int8 retire_early
Number of years early to retire vehicle.
Definition: engine_type.h:144
Ground palette sprite of a tile, together with its sprite layout.
Definition: sprite.h:60
byte ReadByte(LoadgameState *ls)
Reads a byte from the buffer and decompress if needed.
Definition: oldloader.cpp:77
Number of the first newgrf airport.
Definition: airport.h:41
void AddGRFTextToList(GRFText **list, GRFText *text_to_add)
Add a GRFText to a GRFText list.
Simple pair of data.
Functions related to engines.
byte road_side
the side of the road vehicles drive on
uint32 id
The identifier for this node.
Definition: newgrf.cpp:7744
static ChangeInfoResult StationChangeInfo(uint stid, int numinfo, int prop, ByteReader *buf)
Define properties for stations.
Definition: newgrf.cpp:1854
VehicleType
Available vehicle types.
Definition: vehicle_type.h:23
SmallVector< RailTypeLabel, 4 > railtype_list
Railtype translation table.
Definition: newgrf.h:128
static ChangeInfoResult BridgeChangeInfo(uint brid, int numinfo, int prop, ByteReader *buf)
Define properties for bridges.
Definition: newgrf.cpp:2139
EngineClass engclass
Class of engine for this vehicle.
Definition: engine_type.h:53
uint consistent_max_offset
Number of sprites in all referenced spritesets.
static bool ChangeGRFURL(byte langid, const char *str)
Callback function for &#39;INFO&#39;->&#39;URL_&#39; to set the newgrf url.
Definition: newgrf.cpp:7494
const Direction * rotation
the rotation of each tiletable
static ChangeInfoResult ObjectChangeInfo(uint id, int numinfo, int prop, ByteReader *buf)
Define properties for objects.
Definition: newgrf.cpp:4033
uint16 pow_wag_power
Extra power applied to consist if wagon should be powered.
Definition: engine_type.h:56
uint16 max_speed
Maximum speed (1 unit = 1/1.6 mph = 1 km-ish/h)
Definition: engine_type.h:48
Functions related to NewGRF houses.
Bitmask to get only the use palette use states.
Definition: newgrf_config.h:69
bool has_param_defaults
NOSAVE: did this newgrf specify any defaults for it&#39;s parameters.
static void DuplicateTileTable(AirportSpec *as)
Create a copy of the tile table so it can be freed later without problems.
Definition: newgrf.cpp:3786
void ClearSnowLine()
Clear the variable snow line table and free the memory.
Definition: landscape.cpp:679
byte callback_mask
Bitmask of vehicle callbacks that have to be called.
Definition: engine_type.h:143
simple wagon, not motorized
Definition: engine_type.h:30
GRFFilePropsBase< NUM_CARGO+3 > grf_prop
Properties related the the grf file.
DeterministicSpriteGroupAdjustOperation
SoundID GetNewGRFSoundID(const GRFFile *file, SoundID sound_id)
Resolve NewGRF sound ID.
byte num_bit
Number of bits to use for this parameter.
SmallMap< uint32, struct GRFText *, 8 > value_names
Names for each value.
static void ResetAirports()
This function initializes the airportspec array.
AnimationInfo animation
Information about the animation.
Definition: newgrf_object.h:73
Capacity (if dualheaded: for each single vehicle)
static void StaticGRFInfo(ByteReader *buf)
Handle Action 0x14.
Definition: newgrf.cpp:7963
Mapping of language data between a NewGRF and OpenTTD.
Definition: newgrf_text.h:47
Definition of base types and functions in a cross-platform compatible way.
static void ResetAirportTiles()
This function initializes the tile array of AirportTileSpec.
static void ResetCustomIndustries()
Reset and clear all NewGRF industries.
Definition: newgrf.cpp:8160
The data is copied from a grf in _all_grfs.
Definition: newgrf_config.h:28
Weight in 1/4 t.
Data structure to convert between Date and triplet (year, month, and day).
Definition: date_type.h:103
bool IsValidSpriteSet(byte feature, uint set) const
Check whether a specific set is defined.
Definition: newgrf.cpp:161
byte processing_time
Periodic refresh multiplier.
Definition: house.h:123
void SetEntitySpec(const HouseSpec *hs)
Install the specs into the HouseSpecs array It will find itself the proper slot on which it will go...
void CDECL usererror(const char *s,...)
Error handling for fatal user errors.
Definition: openttd.cpp:91
A number of safeguards to prevent using unsafe methods.
int16 x
The x value of the coordinate.
Definition: map_type.h:60
static void FeatureTownName(ByteReader *buf)
Action 0x0F - Define Town names.
Definition: newgrf.cpp:7103
uint16 callback_mask
Bitmask of requested/allowed callbacks.
Definition: newgrf_object.h:74
uint8 acceleration_type
Acceleration type of this rail type.
Definition: rail.h:217
void FioSeekTo(size_t pos, int mode)
Seek in the current file.
Definition: fileio.cpp:88
Information about why GRF had problems during initialisation.
uint32 max_value
The maximal value of this parameter.
Cargo has no effect.
Definition: cargotype.h:27
IndustryType MapNewGRFIndustryType(IndustryType grf_type, uint32 grf_id)
Map the GRF local type to an industry type.
RailTypes introduces_railtypes
Bitmask of which other railtypes are introduced when this railtype is introduced. ...
Definition: rail.h:257
Vehicle uses two company colours.
Definition: engine_type.h:155
static const IndustryGfx NEW_INDUSTRYTILEOFFSET
original number of tiles
Definition: industry_type.h:34
StringID new_industry_text
Message appearing when the industry is built.
Definition: industrytype.h:125
Max. speed: 1 unit = 1/0.8 mph = 2 km-ish/h.
const SpriteGroup * group
Sprite group to start resolving.
Definition: newgrf_canal.h:25
void LoadNewGRFFile(GRFConfig *config, uint file_index, GrfLoadingStage stage, Subdirectory subdir)
Load a particular NewGRF.
Definition: newgrf.cpp:9034
bool dynamic_engines
enable dynamic allocation of engine data
T * Allocate(size_t count)
Get buffer of at least count times T.
Definition: alloc_type.hpp:107
static ChangeInfoResult RailVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader *buf)
Define properties for rail vehicles.
Definition: newgrf.cpp:1046
StringID MapGRFStringID(uint32 grfid, StringID str)
Used when setting an object&#39;s property to map to the GRF&#39;s strings while taking in consideration the ...
Definition: newgrf.cpp:552
byte random_colour[4]
4 "random" colours
Definition: house.h:118
static const Action5Type _action5_types[]
The information about action 5 types.
Definition: newgrf.cpp:5794
uint8 callback_mask
Bitmask of cargo callbacks that have to be called.
Definition: cargotype.h:69
byte visual_effect
Bitstuffed NewGRF visual effect data.
Definition: engine_type.h:74
int skip_sprites
Number of psuedo sprites to skip before processing the next one. (-1 to skip to end of file) ...
Definition: newgrf.cpp:106
byte sorting_order
The sorting order of this railtype for the toolbar dropdown.
Definition: rail.h:262
VehicleType type
Vehicle type, ie VEH_ROAD, VEH_TRAIN, etc.
Definition: engine_base.h:42
Refittability
Summary state of refittability properties.
Definition: newgrf.cpp:303
CargoLabel label
Unique label of the cargo type.
Definition: cargotype.h:58
byte num_table
number of elements in the table
static bool ChangeGRFParamValueNames(ByteReader *buf)
Callback function for &#39;INFO&#39;->&#39;PARA&#39;->param_num->&#39;VALU&#39; to set the names of some parameter values (ty...
Definition: newgrf.cpp:7768
static void LoadFontGlyph(ByteReader *buf)
Action 0x12.
Definition: newgrf.cpp:7368
uint8 views
The number of views.
Definition: newgrf_object.h:76
bool operator==(const MultiMapIterator< Tmap_iter1, Tlist_iter1, Tkey, Tvalue1, Tcompare > &iter1, const MultiMapIterator< Tmap_iter2, Tlist_iter2, Tkey, Tvalue2, Tcompare > &iter2)
Compare two MultiMap iterators.
Definition: multimap.hpp:205
void CleanUpStrings()
House cleaning.
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
Information about languages and their files.
static ChangeInfoResult CargoChangeInfo(uint cid, int numinfo, int prop, ByteReader *buf)
Define properties for cargoes.
Definition: newgrf.cpp:2897
byte capacity
Cargo capacity of vehicle; For multiheaded engines the capacity of each single engine.
Definition: engine_type.h:54
uint8 flags
NOSAVE: GCF_Flags, bitset.
char * stredup(const char *s, const char *last)
Create a duplicate of the given string.
Definition: string.cpp:138
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:113
uint8 tractive_effort
Coefficient of tractive effort.
Definition: engine_type.h:122
static bool ChangeGRFParamDefault(size_t len, ByteReader *buf)
Callback function for &#39;INFO&#39;->&#39;PARAM&#39;->param_num->&#39;DFLT&#39; to set the default value.
Definition: newgrf.cpp:7664
Number of ticks before carried cargo is aged.
uint8 sprite_var10
Value for variable 10 when resolving the sprite.
uint16 DateFract
The fraction of a date we&#39;re in, i.e. the number of ticks since the last date changeover.
Definition: date_type.h:17
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:23
GRF is unusable with this version of OpenTTD.
Definition: newgrf_config.h:31
uint traininfo_vehicle_width
Width (in pixels) of a 8/8 train vehicle in depot GUI and vehicle details.
Definition: newgrf.h:136
byte cost_factor
Purchase cost factor; For multiheaded engines the sum of both engine prices.
Definition: engine_type.h:46
AllowedSubtags(uint32 id, TextHandler handler)
Create a text leaf node.
Definition: newgrf.cpp:7711
StringID name
Tile Subname string, land information on this tile will give you "AirportName (TileSubname)".
static ChangeInfoResult CanalChangeInfo(uint id, int numinfo, int prop, ByteReader *buf)
Define properties for water features.
Definition: newgrf.cpp:2101
uint16 max_bridge_length
maximum length of bridges
The NewGRF provided no information or doesn&#39;t care about a 32 bpp blitter.
Definition: newgrf_config.h:77
uint16 max_speed
Maximum speed for vehicles travelling on this rail type.
Definition: rail.h:222
static bool IsValidNewGRFImageIndex(uint8 image_index)
Helper to check whether an image index is valid for a particular NewGRF vehicle.
Definition: newgrf.cpp:202
byte min_length
the minimum length (not counting start and end tile)
Definition: bridge.h:45
byte misc_flags
Miscellaneous flags.
Definition: engine_type.h:142
Set when a sprite originates from an Action 1.
Definition: sprites.h:1511
static ChangeInfoResult IndustriesChangeInfo(uint indid, int numinfo, int prop, ByteReader *buf)
Define properties for industries.
Definition: newgrf.cpp:3395
Defines the data structure for constructing industry.
Definition: industrytype.h:103
byte shorten_factor
length on main map for this type is 8 - shorten_factor
Definition: engine_type.h:59
uint8 sprite
Register specifying a signed offset for the sprite.
Add signed offset to bounding box Z positions from register TileLayoutRegisters::delta.parent[2].
static bool HandleNode(byte type, uint32 id, ByteReader *buf, AllowedSubtags subtags[])
Handle the nodes of an Action14.
Definition: newgrf.cpp:7910
bool call_handler
True if there is a callback function for this node, false if there is a list of subnodes.
Definition: newgrf.cpp:7754
A reusable buffer that can be used for places that temporary allocate a bit of memory and do that ver...
Definition: alloc_type.hpp:89
Year year
Year (0...)
Definition: date_type.h:104
static const uint8 MAX_NUM_GENDERS
Maximum number of supported genders.
Definition: language.h:22
Power in 10 HP.
byte air_drag
Coefficient of air drag.
Definition: engine_type.h:61
GRFFileProps grf_prop
properties related to the grf file
Definition: industrytype.h:167
static void AddStringForMapping(StringID source, StringID *target)
Record a static StringID for getting translated later.
Definition: newgrf.cpp:472
static const AirportTileSpec * Get(StationGfx gfx)
Retrieve airport tile spec for the given airport tile.
void FioReadBlock(void *ptr, size_t size)
Read a block.
Definition: fileio.cpp:187
static bool ChangeGRFVersion(size_t len, ByteReader *buf)
Callback function for &#39;INFO&#39;->&#39;VRSN&#39; to the version of the NewGRF.
Definition: newgrf.cpp:7561
bool _palette_remap_grf[]
Whether the given NewGRFs must get a palette remap from windows to DOS or not.
Definition: gfxinit.cpp:32
StationGfx gfx
AirportTile to use for this tile.
EngineID GetNewEngineID(const GRFFile *file, VehicleType type, uint16 internal_id)
Return the ID of a new engine.
Definition: newgrf.cpp:695
uint8 weight
Weight in 1/4t units.
Definition: engine_type.h:120
byte wires
Bitmask of base tiles (0 - 7) which should contain elrail wires.
bool IsParentSprite() const
Check whether this is a parent sprite with a boundingbox.
Definition: sprite.h:49
StringID building_name
building name
Definition: house.h:106
Basic functions/variables used all over the place.
const SpriteGroup ** loading
List of loading groups (can be SpriteIDs or Callback results)
unknown/not-implemented type
Definition: newgrf.cpp:5782
byte openttd_id
OpenTTD&#39;s internal ID for a case/gender.
Definition: newgrf_text.h:51
Flags which are still required after loading the GRF.
static const uint8 ANIM_STATUS_NO_ANIMATION
There is no animation.
static bool ChangeGRFMinVersion(size_t len, ByteReader *buf)
Callback function for &#39;INFO&#39;->&#39;MINV&#39; to the minimum compatible version of the NewGRF.
Definition: newgrf.cpp:7574
SpriteID GetSprite(byte feature, uint set) const
Returns the first sprite of a spriteset.
Definition: newgrf.cpp:173
AllowedSubtags()
Create empty subtags object used to identify the end of a list.
Definition: newgrf.cpp:7689
uint8 cargo_map[NUM_CARGO]
Inverse cargo translation table (CargoID -> local ID)
Definition: newgrf.h:126
static CargoTypes TranslateRefitMask(uint32 refit_mask)
Translate the refit mask.
Definition: newgrf.cpp:948
static void SetNewGRFOverride(uint32 source_grfid, uint32 target_grfid)
Set the override for a NewGRF.
Definition: newgrf.cpp:586
#define lengthof(x)
Return the length of an fixed size array.
Definition: depend.cpp:42
Road vehicle type.
Definition: vehicle_type.h:27
IndustryBehaviour behaviour
How this industry will behave, and how others entities can use it.
Definition: industrytype.h:122
static const uint8 MAX_NUM_CASES
Maximum number of supported cases.
Definition: language.h:23
always the last item
Definition: currency.h:63
static uint32 _ttdpatch_flags[8]
32 * 8 = 256 flags.
Definition: newgrf.cpp:74
byte appear_ingame[NUM_LANDSCAPE]
Probability of appearance in game.
Definition: industrytype.h:130
GRFFileProps grf_prop
properties related to the grf file
Definition: industrytype.h:138
StringID message
Default message.
static T min(const T a, const T b)
Returns the minimum of two values.
Definition: math_func.hpp:42
byte GetNewgrfCurrencyIdConverted(byte grfcurr_id)
Will return the ottd&#39;s index correspondence to the ttdpatch&#39;s id.
Definition: currency.cpp:109
number of bits for the sprite number
Definition: sprites.h:1499
Resolved object itself.
RailTypeLabel label
Unique 32 bit rail type identifier.
Definition: rail.h:227
Element of the linked list.
Definition: newgrf_text.cpp:66
uint8 plane_speed
divisor for speed of aircraft
bool FioCheckFileExists(const char *filename, Subdirectory subdir)
Check whether the given file exists.
Definition: fileio.cpp:312
Year max_year
last year it can be built
Definition: house.h:103
NewGRF supplied spritelayout.
StringID transport_name[2]
description of the bridge, when built for road or rail
Definition: bridge.h:52
static const Year ORIGINAL_BASE_YEAR
The minimum starting year/base year of the original TTD.
Definition: date_type.h:51
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:31
Bitmask of all climate bits.
Definition: house.h:86
uint32 StringID
Numeric value that represents a string, independent of the selected language.
Definition: strings_type.h:18
const uint8 _engine_counts[4]
Number of engines of each vehicle type in original engine data.
Definition: engine.cpp:52
bool build_on_slopes
allow building on slopes
bool SkipSpriteData(byte type, uint16 num)
Skip the given amount of sprite graphics data.
Definition: spritecache.cpp:98
uint16 power
Power of engine (hp); For multiheaded engines the sum of both engine powers.
Definition: engine_type.h:49
Month month
Month (0..11)
Definition: date_type.h:105
Flags which require resolving the action-1-2-3 chain for the palette, even if it is no action-1 palet...
Known flags. Any unknown set flag will disable the GRF.
const struct SpriteGroup * spritegroup[Tcnt]
pointer to the different sprites of the entity
void BuildLinkStatsLegend()
Populate legend table for the link stat view.
static bool ChangeGRFBlitter(size_t len, ByteReader *buf)
Callback function for &#39;INFO&#39;->&#39;BLTR&#39; to set the blitter info.
Definition: newgrf.cpp:7539
BuildingFlags building_flags
some flags that describe the house (size, stadium etc...)
Definition: house.h:111
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:4708
static ChangeInfoResult IndustrytilesChangeInfo(uint indtid, int numinfo, int prop, ByteReader *buf)
Define properties for industry tiles.
Definition: newgrf.cpp:3131
SpriteID spriteid
First available SpriteID for loading realsprites.
Definition: newgrf.cpp:96
Price fallback_price
Fallback price multiplier for new prices but old grfs.
Definition: economy_type.h:188
Year to_euro
Year of switching to the Euro. May also be CF_NOEURO or CF_ISEURO.
Definition: currency.h:70
bool has_newhouses
Set if there are any newhouses loaded.
Definition: newgrf.h:164
WaterFeature _water_feature[CF_END]
Table of canal &#39;feature&#39; sprite groups.
NewGRF handling of airport tiles.
SoundEntry * AllocateSound(uint num)
Allocate sound slots.
Subdirectory for all NewGRFs.
Definition: fileio_type.h:119
AllowedSubtags _tags_parameters[]
Action14 parameter tags.
Definition: newgrf.cpp:7798
uint8 GetGenderIndex(const char *gender_str) const
Get the index for the given gender.
Definition: language.h:69
uint16 price
the price multiplier
Definition: bridge.h:47
Information about a rail vehicle.
Definition: engine_type.h:43
static bool IsLeapYear(Year yr)
Checks whether the given year is a leap year or not.
Definition: date_func.h:32
The status of this grf file is unknown.
Definition: newgrf_config.h:36
Shore sprites were replaced by ActionA (using grass tiles for the corner-shores). ...
Definition: newgrf.h:157
static const SpriteID SPR_RAILTYPE_TUNNEL_BASE
Tunnel sprites with grass only for custom railtype tunnel.
Definition: sprites.h:293
Ship vehicle type.
Definition: vehicle_type.h:28
static T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Definition: math_func.hpp:139
StringID replace_text
Text used in the autoreplace GUI.
Definition: rail.h:171
uint32 version
NOSAVE: Version a NewGRF can set so only the newest NewGRF is shown.
static void MemCpyT(T *destination, const T *source, size_t num=1)
Type-safe version of memcpy().
Definition: mem_func.hpp:25
StringID name
The name for this object.
Definition: newgrf_object.h:64
static void FinalisePriceBaseMultipliers()
Decide whether price base multipliers of grfs shall apply globally or only to the grf specifying them...
Definition: newgrf.cpp:9187
#define DEBUG(name, level,...)
Output a line of debugging information.
Definition: debug.h:36
uint8 FindFirstBit(uint32 x)
Search the first set bit in a 32 bit variable.
static const uint MAX_LANG
Maximum number of languages supported by the game, and the NewGRF specs.
Definition: strings_type.h:21
uint8 callback_mask
Bitmask of industry tile callbacks that have to be called.
Definition: industrytype.h:163
uint16 override
id of the entity been replaced by
HouseExtraFlags
Definition: house.h:90
void FioOpenFile(int slot, const char *filename, Subdirectory subdir)
Open a slotted file.
Definition: fileio.cpp:250
Variable is unknown.
Definition: newgrf.cpp:990
uint8 callback_mask
Bitmask of canal callbacks that have to be called.
Definition: newgrf.h:41
byte flags
Bitmask of flags, bit 0: use different sprite set; bit 1: divide cargo about by station size...
GRFTextWrapper * url
NOSAVE: URL belonging to this GRF.
void BindAirportSpecs()
Tie all airportspecs to their class.
uint16 _tick_counter
Ever incrementing (and sometimes wrapping) tick counter for setting off various events.
Definition: date.cpp:30
GRF file passed GLS_RESERVE stage.
Definition: newgrf_config.h:30
static void ResetCustomHouses()
Reset and clear all NewGRF houses.
Definition: newgrf.cpp:8106
static void ParamSet(ByteReader *buf)
Action 0x0D: Set parameter.
Definition: newgrf.cpp:6747
AllowedSubtags * subtags
Pointer to a list of subtags, only valid if type == &#39;C&#39; && !call_handler.
Definition: newgrf.cpp:7752
Resolve palette with a specific value in variable 10.
byte num_loading
Number of loading groups.
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&#39;s not.
Definition: newgrf.cpp:8656
Cargo behaves passenger-like.
Definition: cargotype.h:28
Additional modifiers for items in sprite layouts.
static bool ChangeGRFNumUsedParams(size_t len, ByteReader *buf)
Callback function for &#39;INFO&#39;->&#39;NPAR&#39; to set the number of valid parameters.
Definition: newgrf.cpp:7501
The NewGRF says the Windows palette can be used.
Definition: newgrf_config.h:73
Handling of NewGRF canals.
Describes properties of price bases.
Definition: economy_type.h:184
uint32 FioReadDword()
Read a double word (32 bits) from the file (in low endian format).
Definition: fileio.cpp:176
byte num_table
Number of elements in the table.
Definition: industrytype.h:105
Flag to disable visual effect.
Definition: vehicle_base.h:90
Cargo behaves mail-like.
Definition: cargotype.h:29
static const EngineID INVALID_ENGINE
Constant denoting an invalid engine.
Definition: engine_type.h:174
byte first_bit
First bit to use in the GRF parameter.
StringID material
the string that contains the bridge description
Definition: bridge.h:51
uint grf_feature
GRF Feature that decides whether price multipliers apply locally or globally, #GSF_END if none...
Definition: economy_type.h:187
CargoID accepts_cargo[INDUSTRY_NUM_INPUTS]
Cargo accepted by this tile.
Definition: industrytype.h:152
Smallmap GUI functions.
uint8 clear_cost_multiplier
Clear cost multiplier per tile.
Definition: newgrf_object.h:69
bool old_refittable
Is ship refittable; only used during initialisation. Later use EngineInfo::refit_mask.
Definition: engine_type.h:73
IndustryTileSpecialFlags
Flags for miscellaneous industry tile specialities.
Definition: industrytype.h:88
Date introduction_date
Introduction date.
Definition: rail.h:246
uint16 cost_multiplier
Cost multiplier for building this rail type.
Definition: rail.h:207
static GRFFile * GetFileByGRFID(uint32 grfid)
Obtain a NewGRF file by its grfID.
Definition: newgrf.cpp:392
PalSpriteID ground
Palette and sprite for the ground.
Definition: sprite.h:61
GRFConfig * GetGRFConfig(uint32 grfid, uint32 mask)
Retrieve a NewGRF from the current config by its grfid.
uint8 child[2]
Registers for signed offsets for the position of child sprites.
TownEffect town_effect
The effect that delivering this cargo type has on towns. Also affects destination of subsidies...
Definition: cargotype.h:67
this bit is set when a recolouring process is in action
Definition: sprites.h:1514
bool _generating_world
Whether we are generating the map or not.
Definition: genworld.cpp:61
1F This is just to englobe all above types at once
Definition: house.h:80
Base class for engines.
int FindIndex(const T &item) const
Search for the first occurrence of an item.
Information about a road vehicle.
Definition: engine_type.h:112
Header file for NewGRF stations.
uint8 callback_mask
Bitmask of canal callbacks that have to be called.
Definition: newgrf_canal.h:27
uint16 max_speed
Maximum speed (1 unit = 1/3.2 mph = 0.5 km-ish/h)
Definition: engine_type.h:118
static T ClrBit(T &x, const uint8 y)
Clears a bit in a variable.
AllowedSubtags(uint32 id, BranchHandler handler)
Create a branch node with a callback handler.
Definition: newgrf.cpp:7723
Variable was parsed but unread.
Definition: newgrf.cpp:989
static const WChar NFO_UTF8_IDENTIFIER
This character, the thorn (&#39;þ&#39;), indicates a unicode string to NFO.
Definition: newgrf_text.h:21
const GRFFile * GetGRF() const
Retrieve the NewGRF the engine is tied to.
Definition: engine_base.h:140
HouseExtraFlags extra_flags
some more flags
Definition: house.h:120
bool GetGlobalVariable(byte param, uint32 *value, const GRFFile *grffile)
Reads a variable common to VarAction2 and Action7/9/D.
Definition: newgrf.cpp:5921
byte minimal_cargo
minimum amount of cargo transported to the stations.
Definition: industrytype.h:117
byte prob
The relative probability of the following name to appear in the bottom 7 bits.
uint8 cost_multiplier
Base construction cost multiplier.
Definition: industrytype.h:106
Information about one grf parameter.
Electric rails.
Definition: rail_type.h:32
bool station_noise_level
build new airports when the town noise level is still within accepted limits
Base class for all vehicles.
indicates a "standalone" locomotive
Definition: engine_type.h:28
byte appear_creation[NUM_LANDSCAPE]
Probability of appearance during map creation.
Definition: industrytype.h:131
bool(* TextHandler)(byte, const char *str)
Type of callback function for text nodes.
Definition: newgrf.cpp:7677
void ResetMapping()
Resets the mapping, which is used while initializing game.
uint16 max_length
the maximum length (not counting start and end tile)
Definition: bridge.h:46
Maximal number of airports per NewGRF.
Definition: airport.h:42
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:71
Temporary engine data used when loading only.
Definition: newgrf.cpp:301
uint32 SpriteID
The number of a sprite, without mapping bits and colourtables.
Definition: gfx_type.h:19
static bool StrEmpty(const char *s)
Check if a string buffer is empty.
Definition: string_func.h:59
void ResetNewGRFData()
Reset all NewGRF loaded data TODO.
Definition: newgrf.cpp:8242
Declarations for savegames operations.
uint16 EngineID
Unique identification number of an engine.
Definition: engine_type.h:22
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo ID.
Definition: cargotype.h:118
bool gradual_loading
load vehicles gradually
Number of bits used for the effect type.
Definition: vehicle_base.h:84
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:6202
static void ResetNewGRFErrors()
Clear all NewGRF errors.
Definition: newgrf.cpp:8228
RandomizedSpriteGroupCompareMode cmp_mode
Check for these triggers:
AnimationInfo animation
Information about the animation (is it looping, how many loops etc)
Definition: industrytype.h:164
Max. speed: 1 unit = 1/3.2 mph = 0.5 km-ish/h.
byte tractive_effort
Tractive effort coefficient.
Definition: engine_type.h:60
Cargo support for NewGRFs.
uint8 palette
GRFPalette, bitset.
static ChangeInfoResult RoadVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader *buf)
Define properties for road vehicles.
Definition: newgrf.cpp:1340
Number of ticks before carried cargo is aged.
byte minimum_life
The minimum number of years this house will survive before the town rebuilds it.
Definition: house.h:124
StringID name
name of this airport
Canal properties local to the NewGRF.
Definition: newgrf.h:40
SmallVector< CargoLabel, 4 > cargo_list
Cargo translation table (local ID -> label)
Definition: newgrf.h:125
Information about a aircraft vehicle.
Definition: engine_type.h:98
uint16 remove_rating_decrease
rating decrease if removed
Definition: house.h:107
bool has_newindustries
Set if there are any newindustries loaded.
Definition: newgrf.h:165
GRF file is unsafe for static usage.
Definition: newgrf_config.h:25
byte fallback_railtype
Original railtype number to use when drawing non-newgrf railtypes, or when drawing stations...
Definition: rail.h:192
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:28
OrderSettings order
settings related to orders
AnimationInfo animation
Information about the animation.
bool wagon_speed_limits
enable wagon speed limits
static void MapSpriteMappingRecolour(PalSpriteID *grf_sprite)
Map the colour modifiers of TTDPatch to those that Open is using.
Definition: newgrf.cpp:711
static void InitNewGRFFile(const GRFConfig *config)
Prepare loading a NewGRF file with its config.
Definition: newgrf.cpp:8373
Add signed offset to child sprite X positions from register TileLayoutRegisters::delta.child[0].
StringID closure_text
Message appearing when the industry closes.
Definition: industrytype.h:126
Related object of the resolved one.
GRF defined the vehicle as refittable. If the refitmask is empty after translation (cargotypes not av...
Definition: newgrf.cpp:306
void FioSkipBytes(int n)
Skip n bytes ahead in the file.
Definition: fileio.cpp:150
VehicleTypeByte type
The engine type.
Definition: engine_base.h:151
Year min_year
introduction year of the house
Definition: house.h:102
byte map_colour
Colour on mini-map.
Definition: rail.h:237
when a sprite is to be displayed transparently, this bit needs to be set.
Definition: sprites.h:1513
void CDECL error(const char *s,...)
Error handling for fatal non-user errors.
Definition: openttd.cpp:111
Action5BlockType
The type of action 5 type.
Definition: newgrf.cpp:5779
int8 delta_z
0x80 identifies child sprites
Definition: sprite.h:30
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:375
static T abs(const T a)
Returns the absolute value of (scalar) variable.
Definition: math_func.hpp:83
byte size_x
size of airport in x direction
indicates a combination of two locomotives
Definition: engine_type.h:29
uint8 power
Power in 10hp units.
Definition: engine_type.h:121
void InitializeSortedCargoSpecs()
Initialize the list of sorted cargo specifications.
Definition: cargotype.cpp:173
0..4 1,2,4,8,10 which town zones the building can be built in, Zone1 been the further suburb ...
Definition: house.h:75
uint8 rv_max_speed
Temporary storage of RV prop 15, maximum speed in mph/0.8.
Definition: newgrf.cpp:315
void InitRailTypes()
Resolve sprites of custom rail types.
Definition: rail_cmd.cpp:141
static const uint MAX_BRIDGES
Maximal number of available bridge specs.
Definition: bridge.h:36
static uint GB(const T x, const uint8 s, const uint8 n)
Fetch n bits from x, started at bit s.
uint16 max_range
Maximum range of this aircraft.
Definition: engine_type.h:108
Tile-offset / AirportTileID pair.
static bool HandleNodes(ByteReader *buf, AllowedSubtags subtags[])
Handle the contents of a &#39;C&#39; choice of an Action14.
Definition: newgrf.cpp:7948
StringID string_id
Default name of engine.
Definition: engine_type.h:145
CanalProperties canal_local_properties[CF_END]
Canal properties as set by this NewGRF.
Definition: newgrf.h:131
bool(* DataHandler)(size_t, ByteReader *)
Type of callback function for binary nodes.
Definition: newgrf.cpp:7676
FontSize
Available font sizes.
Definition: gfx_type.h:203
static const SpriteID SPR_AIRPORT_PREVIEW_BASE
Airport preview sprites.
Definition: sprites.h:242
Slope
Enumeration for the slope-type.
Definition: slope_type.h:50
static GRFTempEngineData * _gted
Temporary engine data used during NewGRF loading.
Definition: newgrf.cpp:333
void ResetPriceBaseMultipliers()
Reset changes to the price base multipliers.
Definition: economy.cpp:888
char * filename
Filename - either with or without full path.
static const CargoLabel _default_refitmasks_rail[]
List of what cargo labels are refittable for the given the vehicle-type.
Definition: newgrf.cpp:8433
uint32 CargoLabel
Globally unique label of a cargo type.
Definition: cargotype.h:22
static const HouseID NEW_HOUSE_OFFSET
Offset for new houses.
Definition: house.h:30
Only corner-shores were loaded by Action5 (openttd(w/d).grf only).
Definition: newgrf.h:158
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:25
Bitmask to only get the blitter information.
Definition: newgrf_config.h:79
bool LoadNextSprite(int load_index, byte file_slot, uint file_sprite_id, byte container_version)
Load a real or recolour sprite.
static const IndustryType NEW_INDUSTRYOFFSET
original number of industry types
Definition: industry_type.h:27
static const SpriteID SPR_OPENTTD_BASE
Extra graphic spritenumbers.
Definition: sprites.h:58
uint16 weight
Weight of vehicle (tons); For multiheaded engines the weight of each single engine.
Definition: engine_type.h:50
uint16 cargo_threshold
Cargo threshold for choosing between little and lots of cargo.
byte type
The type of the node, must be one of &#39;C&#39;, &#39;B&#39; or &#39;T&#39;.
Definition: newgrf.cpp:7745
bool has_2CC
Set if any vehicle is loaded which uses 2cc (two company colours).
Definition: newgrf.h:162
uint8 generate_amount
Number of objects which are attempted to be generated per 256^2 map during world generation.
Definition: newgrf_object.h:77
static NewGRFClass * Get(Tid cls_id)
Get a particular class.
static bool CanAllocateItem(size_t n=1)
Helper functions so we can use PoolItem::Function() instead of _poolitem_pool.Function() ...
Definition: pool_type.hpp:216
Number of ticks before carried cargo is aged.
RailTypes powered_railtypes
bitmask to the OTHER railtypes on which an engine of THIS railtype generates power ...
Definition: rail.h:179
Functions related to OTTD&#39;s landscape.
Default value to indicate that visual effect should be based on engine class.
Definition: vehicle_base.h:94
void ResetRailTypes()
Reset all rail type information to its default values.
Definition: rail_cmd.cpp:66
GRFTextWrapper * name
NOSAVE: GRF name (Action 0x08)
void ResetGenericCallbacks()
Reset all generic feature callback sprite groups.
Data structure to store the allowed id/type combinations for action 14.
Definition: newgrf.cpp:7687
uint8 substitute_id
The (original) entity ID to use if this GRF is not available (currently not used) ...
Definition: engine_base.h:152
Attempt to modify an invalid ID.
Definition: newgrf.cpp:991
Defines the data structure of each individual tile of an airport.
const GRFFile * defaultcargo_grf
GRF defining the cargo translation table to use if the default cargo is the &#39;first refittable&#39;...
Definition: newgrf.cpp:312
IndustryBehaviour
Various industry behaviours mostly to represent original TTD specialities.
Definition: industrytype.h:62
static void InitializeGRFSpecial()
Initialize the TTDPatch flags.
Definition: newgrf.cpp:7984
The NewGRF says the DOS palette can be used.
Definition: newgrf_config.h:72
AnimationInfo animation
information about the animation.
Definition: house.h:122
static void ClearTemporaryNewGRFData(GRFFile *gf)
Reset all NewGRFData that was used only while processing data.
Definition: newgrf.cpp:416
CargoID Index() const
Determines index of this cargospec.
Definition: cargotype.h:89
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:8702
byte GetGRFContainerVersion()
Get the container version of the currently opened GRF file.
Definition: newgrf.cpp:9008
uint8 callback_mask
Bitmask telling which grf callback is set.
IndustryType conflicting[3]
Industries this industry cannot be close to.
Definition: industrytype.h:109
byte GetSnowLine()
Get the current snow line, either variable or static.
Definition: landscape.cpp:646
uint16 local_id
id defined by the grf file for this entity
uint32 min_loadable_version
NOSAVE: Minimum compatible version a NewGRF can define.
static ChangeInfoResult IgnoreTownHouseProperty(int prop, ByteReader *buf)
Ignore a house property.
Definition: newgrf.cpp:2249
static bool SkipUnknownInfo(ByteReader *buf, byte type)
Try to skip the current node and all subnodes (if it&#39;s a branch node).
Definition: newgrf.cpp:7870
uint64 used_liveries
Bitmask of LiveryScheme used by the defined engines.
Definition: newgrf.h:163
byte shorten_factor
length on main map for this type is 8 - shorten_factor
Definition: engine_type.h:125
static const SpriteID SPR_TRAMWAY_BASE
Tramway sprites.
Definition: sprites.h:266
Cargo behaves food/fizzy-drinks-like.
Definition: cargotype.h:32
static const uint TLR_MAX_VAR10
Maximum value for var 10.
Max. speed: 1 unit = 8 mph = 12.8 km-ish/h.
ConstructionSettings construction
construction of things in-game
static const uint SNOW_LINE_DAYS
Number of days in each month in the snow line table.
Definition: landscape.h:19
Variable was parsed and read.
Definition: newgrf.cpp:987
Steam rail engine.
Definition: engine_type.h:35
DataHandler data
Callback function for a binary node, only valid if type == &#39;B&#39;.
Definition: newgrf.cpp:7747
static const Year MIN_YEAR
The absolute minimum & maximum years in OTTD.
Definition: date_type.h:85
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:342
static const uint MAX_SPRITEGROUP
Maximum GRF-local ID for a spritegroup.
Definition: newgrf.cpp:79
uint8 air_drag
Coefficient of air drag.
Definition: engine_type.h:123
uint32 min_value
The minimal value this parameter can have.
const char * GetName() const
Get the name of this grf.
int32 Date
The type to store our dates in.
Definition: date_type.h:16
uint32 grfid
GRF ID (defined by Action 0x08)
Definition: newgrf_config.h:85
char * data
Additional data for message and custom_message.
Tractive effort coefficient in 1/256.
struct GRFText * name
The name of this parameter.
StationClassID
VarSpriteGroupScope var_scope
Take this object:
static void free(const void *ptr)
Version of the standard free that accepts const pointers.
Definition: depend.cpp:114
GRF defined vehicle as not-refittable. The vehicle shall only carry the default cargo.
Definition: newgrf.cpp:305
GRFFileProps grf_prop
Properties related the the grf file.
Definition: house.h:116
StringID name
Name of this rail type.
Definition: rail.h:167
uint file_index
File index of currently processed GRF file.
Definition: newgrf.cpp:99
declaration of OTTD revision dependent variables
const struct GRFFile * grffile
grf file that introduced this entity
uint8 number_of_sounds
Number of sounds available in the sounds array.
Definition: industrytype.h:132
uint8 bitnum
Cargo bit number, is INVALID_CARGO for a non-used spec.
Definition: cargotype.h:57
bool enabled
Entity still available (by default true). Newgrf can disable it, though.
StringID station_name
Default name for nearby station.
Definition: industrytype.h:129
uint32 param[0x80]
GRF parameters.
GRF file has been activated.
Definition: newgrf_config.h:40
static bool HasBit(const T x, const uint8 y)
Checks if a bit in a value is set.
StringID units_volume
Name of a single unit of cargo of this type.
Definition: cargotype.h:73
bool IsValid() const
Tests for validity of this cargospec.
Definition: cargotype.h:99
StringID production_up_text
Message appearing when the industry&#39;s production is increasing.
Definition: industrytype.h:127
Functions related to NewGRF provided sounds.
byte callback_mask
Bitmask of station callbacks that have to be called.
byte num_groups
must be power of 2
AllowedSubtags _tags_root[]
Action14 root tags.
Definition: newgrf.cpp:7858
byte disallowed_lengths
Bitmask of platform lengths available for the station.
byte _misc_grf_features
Miscellaneous GRF features, set by Action 0x0D, parameter 0x9E.
Definition: newgrf.cpp:71
Base of the town class.
static GRFFile * GetFileByFilename(const char *filename)
Obtain a NewGRF file by its filename.
Definition: newgrf.cpp:406
const T * Get(uint index) const
Get the pointer to item "number" (const)
byte id
If probability bit 7 is set.
BranchHandler branch
Callback function for a branch node, only valid if type == &#39;C&#39; && call_handler.
Definition: newgrf.cpp:7751
static GRFParameterInfo * _cur_parameter
The parameter which info is currently changed by the newgrf.
Definition: newgrf.cpp:7593
static void ResetCustomStations()
Reset and clear all NewGRF stations.
Definition: newgrf.cpp:8071
GameCreationSettings game_creation
settings used during the creation of a game (map)
static const uint NEW_AIRPORTTILE_OFFSET
offset of first newgrf airport tile
Definition: airport.h:26
static bool ChangeGRFParamType(size_t len, ByteReader *buf)
Callback function for &#39;INFO&#39;->&#39;PARAM&#39;->param_num->&#39;TYPE&#39; to set the typeof a parameter.
Definition: newgrf.cpp:7610
byte CargoID
Cargo slots to indicate a cargo type within a game.
Definition: cargo_type.h:22
Free the dynamically allocated tile layout structure.
Definition: industrytype.h:25
uint16 cargo_age_period
Number of ticks before carried cargo is aged.
Definition: engine_type.h:146
static bool ValidateIndustryLayout(const IndustryTileTable *layout, int size)
Validate the industry layout; e.g.
Definition: newgrf.cpp:3360
Defines the data structure of each individual tile of an industry.
Definition: industrytype.h:151
static ChangeInfoResult GlobalVarChangeInfo(uint gvid, int numinfo, int prop, ByteReader *buf)
Define properties for global variables.
Definition: newgrf.cpp:2611
Flag for invalid railtype.
Definition: rail_type.h:36
Bitmask to get only the NewGRF supplied information.
Definition: newgrf_config.h:75
Weight in t (if dualheaded: for each single vehicle)
Year base_life
Basic duration of engine availability (without random parts). 0xFF means infinite life...
Definition: engine_type.h:135
Date ConvertYMDToDate(Year year, Month month, Day day)
Converts a tuple of Year, Month and Day to a Date.
Definition: date.cpp:149
NewGRFSpriteLayout * renderdata
Array of tile layouts.
size_t FioGetPos()
Get position in the current file.
Definition: fileio.cpp:68
int8 delta_x
0x80 is sequence terminator
Definition: sprite.h:28
static uint32 BSWAP32(uint32 x)
Perform a 32 bits endianness bitswap on x.
static void SkipAct12(ByteReader *buf)
Action 0x12 (SKIP)
Definition: newgrf.cpp:7399
static ChangeInfoResult SoundEffectChangeInfo(uint sid, int numinfo, int prop, ByteReader *buf)
Define properties for sound effects.
Definition: newgrf.cpp:3036
StringID name
Name of this station.
Maximum catchment for airports with "modified catchment" enabled.
Definition: station_type.h:88
Defines the data structure for an airport.
GRFLoadedFeatures _loaded_newgrf_features
Indicates which are the newgrf features currently loaded ingame.
Definition: newgrf.cpp:77
Use 32 pixels per train vehicle in depot gui and vehicle details. Never set in the global variable;...
Definition: newgrf.h:61
static void TranslateGRFStrings(ByteReader *buf)
Action 0x13.
Definition: newgrf.cpp:7425
static ChangeInfoResult TownHouseChangeInfo(uint hid, int numinfo, int prop, ByteReader *buf)
Define properties for houses.
Definition: newgrf.cpp:2316
uint16 multipliertowngrowth
Size of the effect.
Definition: cargotype.h:68
byte parameter
Used for variables between 0x60 and 0x7F inclusive.
CargoTypes ctt_include_mask
Cargo types always included in the refit mask.
Definition: newgrf.cpp:316
byte ai_passenger_only
Bit value to tell AI that this engine is for passenger use only.
Definition: engine_type.h:55
uint8 num_input
How many subtract_input values are valid.
RailType GetRailTypeByLabel(RailTypeLabel label, bool allow_alternate_labels)
Get the rail type for a given label.
Definition: rail.cpp:295
SpriteID sprite
The &#39;real&#39; sprite.
Definition: gfx_type.h:25
uint8 parent[3]
Registers for signed offsets for the bounding box position of parent sprites.
byte disallowed_platforms
Bitmask of number of platforms available for the station.
Header file for bridges.
uint8 speed
The speed, i.e. the amount of time between frames.
byte running_cost
Running cost of engine; For multiheaded engines the sum of both running costs.
Definition: engine_type.h:51
ObjectClassID cls_id
The class to which this spec belongs.
Definition: newgrf_object.h:63
StationClassID cls_id
The class to which this spec belongs.
uint8 dodraw
Register deciding whether the sprite shall be drawn at all. Non-zero means drawing.
SmallVector< Mapping, 1 > gender_map
Mapping of NewGRF and OpenTTD IDs for genders.
Definition: newgrf_text.h:60
Action 2 sprite layout for houses, industry tiles, objects and airport tiles.
static bool ChangeGRFParamDescription(byte langid, const char *str)
Callback function for &#39;INFO&#39;->&#39;PARAM&#39;->param_num->&#39;DESC&#39; to set the description of a parameter...
Definition: newgrf.cpp:7603
byte climates
Climates supported by the engine.
Definition: engine_type.h:138
static void SetUnicodeGlyph(FontSize size, WChar key, SpriteID sprite)
Map a SpriteID to the font size and key.
Definition: fontcache.h:166
Date _date
Current date in days (day counter)
Definition: date.cpp:28
A tile child sprite and palette to draw for stations etc, with 3D bounding box.
Definition: sprite.h:27
static ChangeInfoResult IgnoreIndustryProperty(int prop, ByteReader *buf)
Ignore an industry property.
Definition: newgrf.cpp:3269
SpriteID sprite
Icon to display this cargo type, may be 0xFFF (which means to resolve an action123 chain)...
Definition: cargotype.h:77
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:853
uint32 WChar
Type for wide characters, i.e.
Definition: string_type.h:35
TTDPAirportType
Allow incrementing of AirportClassID variables.
Year max_year
last year the airport is available
void ConvertDateToYMD(Date date, YearMonthDay *ymd)
Converts a Date to a Year, Month & Day.
Definition: date.cpp:94
Set when a sprite must not ever be displayed transparently.
Definition: sprites.h:1512
Palette is from Action 1 (moved to SPRITE_MODIFIER_CUSTOM_SPRITE in palette during loading)...
uint8 climate
In which climates is this object available?
Definition: newgrf_object.h:66
GRFFileProps grf_prop
properties related the the grf file
CargoID cargo_input[INDUSTRY_NUM_INPUTS]
Which input cargoes to take from (only cb version 2)
byte canal_speed_frac
Fraction of maximum speed for canal/river tiles.
Definition: engine_type.h:76
static const IndustryGfx INDUSTRYTILE_NOANIM
flag to mark industry tiles as having no animation
Definition: industry_type.h:33
void AddSpriteSets(byte feature, SpriteID first_sprite, uint first_set, uint numsets, uint numents)
Records new spritesets.
Definition: newgrf.cpp:132
byte user_def_data
Property 0x25: "User-defined bit mask" Used only for (very few) NewGRF vehicles.
Definition: engine_type.h:62
uint8 frames
The number of frames.
const char * name
Name for error messages.
Definition: newgrf.cpp:5790
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:94
void SetEntitySpec(IndustrySpec *inds)
Method to install the new industry data in its proper slot The slot assignment is internal of this me...
std::map< uint, SpriteSet > spritesets[GSF_END]
Currently referenceable spritesets.
Definition: newgrf.cpp:91
Year starting_year
starting date
static bool ChangeGRFName(byte langid, const char *str)
Callback function for &#39;INFO&#39;->&#39;NAME&#39; to add a translation to the newgrf name.
Definition: newgrf.cpp:7480
struct GRFFileProps grf_prop
Properties related to the grf file.
ObjectOverrideManager _object_mngr
The override manager for our objects.
center of town
Definition: house.h:79
Only allow replacing a whole block of sprites. (TTDP compatible)
Definition: newgrf.cpp:5780
CargoTypes ctt_exclude_mask
Cargo types always excluded from the refit mask.
Definition: newgrf.cpp:317
byte blocked
Bitmask of base tiles (0 - 7) which are blocked to trains.
uint8 palette
Register specifying a signed offset for the palette.
static const uint NETWORK_MAX_GRF_COUNT
Maximum number of GRFs that can be sent.
Definition: config.h:60
TileLayoutFlags flags
Flags defining which members are valid and to be used.
static const SpriteID SPR_FLAGS_BASE
Flags sprites (in same order as enum NetworkLanguage)
Definition: sprites.h:289
uint16 passenger_capacity
Passenger capacity (persons).
Definition: engine_type.h:107
byte mail_capacity
Mail capacity (bags).
Definition: engine_type.h:106
uint16 min_sprites
If the Action5 contains less sprites, the whole block will be ignored.
Definition: newgrf.cpp:5788
virtual void CleanPool()
Virtual method that deletes all items in the pool.
static void MemSetT(T *ptr, byte value, size_t num=1)
Type-safe version of memset().
Definition: mem_func.hpp:51
void ResetToDefaultMapping()
Initializes the EngineOverrideManager with the default engines.
Definition: engine.cpp:488
byte visual_effect
Bitstuffed NewGRF visual effect data.
Definition: engine_type.h:58
Invalid parameter type.
Electric rail engine.
Definition: engine_type.h:37
Dynamic data of a loaded NewGRF.
Definition: newgrf.h:104
11 800 can appear in sub-arctic climate above the snow line
Definition: house.h:81
uint16 maintenance_multiplier
Cost multiplier for maintenance of this rail type.
Definition: rail.h:212
Train vehicle type.
Definition: vehicle_type.h:26
Information about a single action 5 type.
Definition: newgrf.cpp:5785
Information for mapping static StringIDs.
Definition: newgrf.cpp:459
static bool HandleParameterInfo(ByteReader *buf)
Callback function for &#39;INFO&#39;->&#39;PARA&#39; to set extra information about the parameters.
Definition: newgrf.cpp:7815
GRFTextWrapper * info
NOSAVE: GRF info (author, copyright, ...) (Action 0x08)
void SetupCargoForClimate(LandscapeID l)
Set up the default cargo types for the given landscape type.
Definition: cargotype.cpp:42
Flags which refer to using multiple action-1-2-3 chains.
PaletteID pal
The palette (use PAL_NONE) if not needed)
Definition: gfx_type.h:26
StringID name
Name of this class.
Definition: newgrf_class.h:41
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...
void BuildIndustriesLegend()
Fills an array for the industries legends.