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 0x%02X 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  if (feature >= GSF_END) {
4534  grfmsg(1, "FeatureChangeInfo: Unsupported feature 0x%02X, skipping", feature);
4535  return;
4536  }
4537 
4538  grfmsg(6, "FeatureChangeInfo: Feature 0x%02X, %d properties, to apply to %d+%d",
4539  feature, numprops, engine, numinfo);
4540 
4541  if (feature >= lengthof(handler) || handler[feature] == NULL) {
4542  if (feature != GSF_CARGOES) grfmsg(1, "FeatureChangeInfo: Unsupported feature 0x%02X, skipping", feature);
4543  return;
4544  }
4545 
4546  /* Mark the feature as used by the grf */
4547  SetBit(_cur.grffile->grf_features, feature);
4548 
4549  while (numprops-- && buf->HasData()) {
4550  uint8 prop = buf->ReadByte();
4551 
4552  ChangeInfoResult cir = handler[feature](engine, numinfo, prop, buf);
4553  if (HandleChangeInfoResult("FeatureChangeInfo", cir, feature, prop)) return;
4554  }
4555 }
4556 
4557 /* Action 0x00 (GLS_SAFETYSCAN) */
4558 static void SafeChangeInfo(ByteReader *buf)
4559 {
4560  uint8 feature = buf->ReadByte();
4561  uint8 numprops = buf->ReadByte();
4562  uint numinfo = buf->ReadByte();
4563  buf->ReadExtendedByte(); // id
4564 
4565  if (feature == GSF_BRIDGES && numprops == 1) {
4566  uint8 prop = buf->ReadByte();
4567  /* Bridge property 0x0D is redefinition of sprite layout tables, which
4568  * is considered safe. */
4569  if (prop == 0x0D) return;
4570  } else if (feature == GSF_GLOBALVAR && numprops == 1) {
4571  uint8 prop = buf->ReadByte();
4572  /* Engine ID Mappings are safe, if the source is static */
4573  if (prop == 0x11) {
4574  bool is_safe = true;
4575  for (uint i = 0; i < numinfo; i++) {
4576  uint32 s = buf->ReadDWord();
4577  buf->ReadDWord(); // dest
4578  const GRFConfig *grfconfig = GetGRFConfig(s);
4579  if (grfconfig != NULL && !HasBit(grfconfig->flags, GCF_STATIC)) {
4580  is_safe = false;
4581  break;
4582  }
4583  }
4584  if (is_safe) return;
4585  }
4586  }
4587 
4588  SetBit(_cur.grfconfig->flags, GCF_UNSAFE);
4589 
4590  /* Skip remainder of GRF */
4591  _cur.skip_sprites = -1;
4592 }
4593 
4594 /* Action 0x00 (GLS_RESERVE) */
4595 static void ReserveChangeInfo(ByteReader *buf)
4596 {
4597  uint8 feature = buf->ReadByte();
4598 
4599  if (feature != GSF_CARGOES && feature != GSF_GLOBALVAR && feature != GSF_RAILTYPES) return;
4600 
4601  uint8 numprops = buf->ReadByte();
4602  uint8 numinfo = buf->ReadByte();
4603  uint8 index = buf->ReadExtendedByte();
4604 
4605  while (numprops-- && buf->HasData()) {
4606  uint8 prop = buf->ReadByte();
4608 
4609  switch (feature) {
4610  default: NOT_REACHED();
4611  case GSF_CARGOES:
4612  cir = CargoChangeInfo(index, numinfo, prop, buf);
4613  break;
4614 
4615  case GSF_GLOBALVAR:
4616  cir = GlobalVarReserveInfo(index, numinfo, prop, buf);
4617  break;
4618 
4619  case GSF_RAILTYPES:
4620  cir = RailTypeReserveInfo(index, numinfo, prop, buf);
4621  break;
4622  }
4623 
4624  if (HandleChangeInfoResult("ReserveChangeInfo", cir, feature, prop)) return;
4625  }
4626 }
4627 
4628 /* Action 0x01 */
4629 static void NewSpriteSet(ByteReader *buf)
4630 {
4631  /* Basic format: <01> <feature> <num-sets> <num-ent>
4632  * Extended format: <01> <feature> 00 <first-set> <num-sets> <num-ent>
4633  *
4634  * B feature feature to define sprites for
4635  * 0, 1, 2, 3: veh-type, 4: train stations
4636  * E first-set first sprite set to define
4637  * B num-sets number of sprite sets (extended byte in extended format)
4638  * E num-ent how many entries per sprite set
4639  * For vehicles, this is the number of different
4640  * vehicle directions in each sprite set
4641  * Set num-dirs=8, unless your sprites are symmetric.
4642  * In that case, use num-dirs=4.
4643  */
4644 
4645  uint8 feature = buf->ReadByte();
4646  uint16 num_sets = buf->ReadByte();
4647  uint16 first_set = 0;
4648 
4649  if (num_sets == 0 && buf->HasData(3)) {
4650  /* Extended Action1 format.
4651  * Some GRFs define zero sets of zero sprites, though there is actually no use in that. Ignore them. */
4652  first_set = buf->ReadExtendedByte();
4653  num_sets = buf->ReadExtendedByte();
4654  }
4655  uint16 num_ents = buf->ReadExtendedByte();
4656 
4657  if (feature >= GSF_END) {
4658  _cur.skip_sprites = num_sets * num_ents;
4659  grfmsg(1, "NewSpriteSet: Unsupported feature 0x%02X, skipping %d sprites", feature, _cur.skip_sprites);
4660  return;
4661  }
4662 
4663  _cur.AddSpriteSets(feature, _cur.spriteid, first_set, num_sets, num_ents);
4664 
4665  grfmsg(7, "New sprite set at %d of feature 0x%02X, consisting of %d sets with %d views each (total %d)",
4666  _cur.spriteid, feature, num_sets, num_ents, num_sets * num_ents
4667  );
4668 
4669  for (int i = 0; i < num_sets * num_ents; i++) {
4670  _cur.nfo_line++;
4671  LoadNextSprite(_cur.spriteid++, _cur.file_index, _cur.nfo_line, _cur.grf_container_ver);
4672  }
4673 }
4674 
4675 /* Action 0x01 (SKIP) */
4676 static void SkipAct1(ByteReader *buf)
4677 {
4678  buf->ReadByte();
4679  uint16 num_sets = buf->ReadByte();
4680 
4681  if (num_sets == 0 && buf->HasData(3)) {
4682  /* Extended Action1 format.
4683  * Some GRFs define zero sets of zero sprites, though there is actually no use in that. Ignore them. */
4684  buf->ReadExtendedByte(); // first_set
4685  num_sets = buf->ReadExtendedByte();
4686  }
4687  uint16 num_ents = buf->ReadExtendedByte();
4688 
4689  _cur.skip_sprites = num_sets * num_ents;
4690 
4691  grfmsg(3, "SkipAct1: Skipping %d sprites", _cur.skip_sprites);
4692 }
4693 
4694 /* Helper function to either create a callback or link to a previously
4695  * defined spritegroup. */
4696 static const SpriteGroup *GetGroupFromGroupID(byte setid, byte type, uint16 groupid)
4697 {
4698  if (HasBit(groupid, 15)) {
4700  return new CallbackResultSpriteGroup(groupid, _cur.grffile->grf_version >= 8);
4701  }
4702 
4703  if (groupid > MAX_SPRITEGROUP || _cur.spritegroups[groupid] == NULL) {
4704  grfmsg(1, "GetGroupFromGroupID(0x%02X:0x%02X): Groupid 0x%04X does not exist, leaving empty", setid, type, groupid);
4705  return NULL;
4706  }
4707 
4708  return _cur.spritegroups[groupid];
4709 }
4710 
4719 static const SpriteGroup *CreateGroupFromGroupID(byte feature, byte setid, byte type, uint16 spriteid)
4720 {
4721  if (HasBit(spriteid, 15)) {
4723  return new CallbackResultSpriteGroup(spriteid, _cur.grffile->grf_version >= 8);
4724  }
4725 
4726  if (!_cur.IsValidSpriteSet(feature, spriteid)) {
4727  grfmsg(1, "CreateGroupFromGroupID(0x%02X:0x%02X): Sprite set %u invalid", setid, type, spriteid);
4728  return NULL;
4729  }
4730 
4731  SpriteID spriteset_start = _cur.GetSprite(feature, spriteid);
4732  uint num_sprites = _cur.GetNumEnts(feature, spriteid);
4733 
4734  /* Ensure that the sprites are loeded */
4735  assert(spriteset_start + num_sprites <= _cur.spriteid);
4736 
4738  return new ResultSpriteGroup(spriteset_start, num_sprites);
4739 }
4740 
4741 /* Action 0x02 */
4742 static void NewSpriteGroup(ByteReader *buf)
4743 {
4744  /* <02> <feature> <set-id> <type/num-entries> <feature-specific-data...>
4745  *
4746  * B feature see action 1
4747  * B set-id ID of this particular definition
4748  * B type/num-entries
4749  * if 80 or greater, this is a randomized or variational
4750  * list definition, see below
4751  * otherwise it specifies a number of entries, the exact
4752  * meaning depends on the feature
4753  * V feature-specific-data (huge mess, don't even look it up --pasky) */
4754  SpriteGroup *act_group = NULL;
4755 
4756  uint8 feature = buf->ReadByte();
4757  if (feature >= GSF_END) {
4758  grfmsg(1, "NewSpriteGroup: Unsupported feature 0x%02X, skipping", feature);
4759  return;
4760  }
4761 
4762  uint8 setid = buf->ReadByte();
4763  uint8 type = buf->ReadByte();
4764 
4765  /* Sprite Groups are created here but they are allocated from a pool, so
4766  * we do not need to delete anything if there is an exception from the
4767  * ByteReader. */
4768 
4769  switch (type) {
4770  /* Deterministic Sprite Group */
4771  case 0x81: // Self scope, byte
4772  case 0x82: // Parent scope, byte
4773  case 0x85: // Self scope, word
4774  case 0x86: // Parent scope, word
4775  case 0x89: // Self scope, dword
4776  case 0x8A: // Parent scope, dword
4777  {
4778  byte varadjust;
4779  byte varsize;
4780 
4783  act_group = group;
4784  group->var_scope = HasBit(type, 1) ? VSG_SCOPE_PARENT : VSG_SCOPE_SELF;
4785 
4786  switch (GB(type, 2, 2)) {
4787  default: NOT_REACHED();
4788  case 0: group->size = DSG_SIZE_BYTE; varsize = 1; break;
4789  case 1: group->size = DSG_SIZE_WORD; varsize = 2; break;
4790  case 2: group->size = DSG_SIZE_DWORD; varsize = 4; break;
4791  }
4792 
4794  adjusts.Clear();
4795 
4796  /* Loop through the var adjusts. Unfortunately we don't know how many we have
4797  * from the outset, so we shall have to keep reallocing. */
4798  do {
4799  DeterministicSpriteGroupAdjust *adjust = adjusts.Append();
4800 
4801  /* The first var adjust doesn't have an operation specified, so we set it to add. */
4802  adjust->operation = adjusts.Length() == 1 ? DSGA_OP_ADD : (DeterministicSpriteGroupAdjustOperation)buf->ReadByte();
4803  adjust->variable = buf->ReadByte();
4804  if (adjust->variable == 0x7E) {
4805  /* Link subroutine group */
4806  adjust->subroutine = GetGroupFromGroupID(setid, type, buf->ReadByte());
4807  } else {
4808  adjust->parameter = IsInsideMM(adjust->variable, 0x60, 0x80) ? buf->ReadByte() : 0;
4809  }
4810 
4811  varadjust = buf->ReadByte();
4812  adjust->shift_num = GB(varadjust, 0, 5);
4813  adjust->type = (DeterministicSpriteGroupAdjustType)GB(varadjust, 6, 2);
4814  adjust->and_mask = buf->ReadVarSize(varsize);
4815 
4816  if (adjust->type != DSGA_TYPE_NONE) {
4817  adjust->add_val = buf->ReadVarSize(varsize);
4818  adjust->divmod_val = buf->ReadVarSize(varsize);
4819  } else {
4820  adjust->add_val = 0;
4821  adjust->divmod_val = 0;
4822  }
4823 
4824  /* Continue reading var adjusts while bit 5 is set. */
4825  } while (HasBit(varadjust, 5));
4826 
4827  group->num_adjusts = adjusts.Length();
4828  group->adjusts = MallocT<DeterministicSpriteGroupAdjust>(group->num_adjusts);
4829  MemCpyT(group->adjusts, adjusts.Begin(), group->num_adjusts);
4830 
4831  std::vector<DeterministicSpriteGroupRange> ranges;
4832  ranges.resize(buf->ReadByte());
4833  for (uint i = 0; i < ranges.size(); i++) {
4834  ranges[i].group = GetGroupFromGroupID(setid, type, buf->ReadWord());
4835  ranges[i].low = buf->ReadVarSize(varsize);
4836  ranges[i].high = buf->ReadVarSize(varsize);
4837  }
4838 
4839  group->default_group = GetGroupFromGroupID(setid, type, buf->ReadWord());
4840  group->error_group = ranges.size() > 0 ? ranges[0].group : group->default_group;
4841  /* nvar == 0 is a special case -- we turn our value into a callback result */
4842  group->calculated_result = ranges.size() == 0;
4843 
4844  /* Sort ranges ascending. When ranges overlap, this may required clamping or splitting them */
4845  std::vector<uint32> bounds;
4846  for (uint i = 0; i < ranges.size(); i++) {
4847  bounds.push_back(ranges[i].low);
4848  if (ranges[i].high != UINT32_MAX) bounds.push_back(ranges[i].high + 1);
4849  }
4850  std::sort(bounds.begin(), bounds.end());
4851  bounds.erase(std::unique(bounds.begin(), bounds.end()), bounds.end());
4852 
4853  std::vector<const SpriteGroup *> target;
4854  for (uint j = 0; j < bounds.size(); ++j) {
4855  uint32 v = bounds[j];
4856  const SpriteGroup *t = group->default_group;
4857  for (uint i = 0; i < ranges.size(); i++) {
4858  if (ranges[i].low <= v && v <= ranges[i].high) {
4859  t = ranges[i].group;
4860  break;
4861  }
4862  }
4863  target.push_back(t);
4864  }
4865  assert(target.size() == bounds.size());
4866 
4867  std::vector<DeterministicSpriteGroupRange> optimised;
4868  for (uint j = 0; j < bounds.size(); ) {
4869  if (target[j] != group->default_group) {
4871  r.group = target[j];
4872  r.low = bounds[j];
4873  while (j < bounds.size() && target[j] == r.group) {
4874  j++;
4875  }
4876  r.high = j < bounds.size() ? bounds[j] - 1 : UINT32_MAX;
4877  optimised.push_back(r);
4878  } else {
4879  j++;
4880  }
4881  }
4882 
4883  group->num_ranges = (uint)optimised.size(); // cast is safe, there should never be 2**31 elements here
4884  if (group->num_ranges > 0) {
4885  group->ranges = MallocT<DeterministicSpriteGroupRange>(group->num_ranges);
4886  MemCpyT(group->ranges, &optimised.front(), group->num_ranges);
4887  }
4888  break;
4889  }
4890 
4891  /* Randomized Sprite Group */
4892  case 0x80: // Self scope
4893  case 0x83: // Parent scope
4894  case 0x84: // Relative scope
4895  {
4898  act_group = group;
4899  group->var_scope = HasBit(type, 1) ? VSG_SCOPE_PARENT : VSG_SCOPE_SELF;
4900 
4901  if (HasBit(type, 2)) {
4902  if (feature <= GSF_AIRCRAFT) group->var_scope = VSG_SCOPE_RELATIVE;
4903  group->count = buf->ReadByte();
4904  }
4905 
4906  uint8 triggers = buf->ReadByte();
4907  group->triggers = GB(triggers, 0, 7);
4908  group->cmp_mode = HasBit(triggers, 7) ? RSG_CMP_ALL : RSG_CMP_ANY;
4909  group->lowest_randbit = buf->ReadByte();
4910  group->num_groups = buf->ReadByte();
4911  group->groups = CallocT<const SpriteGroup*>(group->num_groups);
4912 
4913  for (uint i = 0; i < group->num_groups; i++) {
4914  group->groups[i] = GetGroupFromGroupID(setid, type, buf->ReadWord());
4915  }
4916 
4917  break;
4918  }
4919 
4920  /* Neither a variable or randomized sprite group... must be a real group */
4921  default:
4922  {
4923  switch (feature) {
4924  case GSF_TRAINS:
4925  case GSF_ROADVEHICLES:
4926  case GSF_SHIPS:
4927  case GSF_AIRCRAFT:
4928  case GSF_STATIONS:
4929  case GSF_CANALS:
4930  case GSF_CARGOES:
4931  case GSF_AIRPORTS:
4932  case GSF_RAILTYPES:
4933  {
4934  byte num_loaded = type;
4935  byte num_loading = buf->ReadByte();
4936 
4937  if (!_cur.HasValidSpriteSets(feature)) {
4938  grfmsg(0, "NewSpriteGroup: No sprite set to work on! Skipping");
4939  return;
4940  }
4941 
4943  RealSpriteGroup *group = new RealSpriteGroup();
4944  act_group = group;
4945 
4946  group->num_loaded = num_loaded;
4947  group->num_loading = num_loading;
4948  if (num_loaded > 0) group->loaded = CallocT<const SpriteGroup*>(num_loaded);
4949  if (num_loading > 0) group->loading = CallocT<const SpriteGroup*>(num_loading);
4950 
4951  grfmsg(6, "NewSpriteGroup: New SpriteGroup 0x%02X, %u loaded, %u loading",
4952  setid, num_loaded, num_loading);
4953 
4954  for (uint i = 0; i < num_loaded; i++) {
4955  uint16 spriteid = buf->ReadWord();
4956  group->loaded[i] = CreateGroupFromGroupID(feature, setid, type, spriteid);
4957  grfmsg(8, "NewSpriteGroup: + rg->loaded[%i] = subset %u", i, spriteid);
4958  }
4959 
4960  for (uint i = 0; i < num_loading; i++) {
4961  uint16 spriteid = buf->ReadWord();
4962  group->loading[i] = CreateGroupFromGroupID(feature, setid, type, spriteid);
4963  grfmsg(8, "NewSpriteGroup: + rg->loading[%i] = subset %u", i, spriteid);
4964  }
4965 
4966  break;
4967  }
4968 
4969  case GSF_HOUSES:
4970  case GSF_AIRPORTTILES:
4971  case GSF_OBJECTS:
4972  case GSF_INDUSTRYTILES: {
4973  byte num_building_sprites = max((uint8)1, type);
4974 
4977  act_group = group;
4978 
4979  /* On error, bail out immediately. Temporary GRF data was already freed */
4980  if (ReadSpriteLayout(buf, num_building_sprites, true, feature, false, type == 0, &group->dts)) return;
4981  break;
4982  }
4983 
4984  case GSF_INDUSTRIES: {
4985  if (type > 2) {
4986  grfmsg(1, "NewSpriteGroup: Unsupported industry production version %d, skipping", type);
4987  break;
4988  }
4989 
4992  act_group = group;
4993  group->version = type;
4994  if (type == 0) {
4995  group->num_input = 3;
4996  for (uint i = 0; i < 3; i++) {
4997  group->subtract_input[i] = (int16)buf->ReadWord(); // signed
4998  }
4999  group->num_output = 2;
5000  for (uint i = 0; i < 2; i++) {
5001  group->add_output[i] = buf->ReadWord(); // unsigned
5002  }
5003  group->again = buf->ReadByte();
5004  } else if (type == 1) {
5005  group->num_input = 3;
5006  for (uint i = 0; i < 3; i++) {
5007  group->subtract_input[i] = buf->ReadByte();
5008  }
5009  group->num_output = 2;
5010  for (uint i = 0; i < 2; i++) {
5011  group->add_output[i] = buf->ReadByte();
5012  }
5013  group->again = buf->ReadByte();
5014  } else if (type == 2) {
5015  group->num_input = buf->ReadByte();
5016  if (group->num_input > lengthof(group->subtract_input)) {
5017  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK);
5018  error->data = stredup("too many inputs (max 16)");
5019  return;
5020  }
5021  for (uint i = 0; i < group->num_input; i++) {
5022  byte rawcargo = buf->ReadByte();
5023  CargoID cargo = GetCargoTranslation(rawcargo, _cur.grffile);
5024  if (cargo == CT_INVALID) {
5025  /* The mapped cargo is invalid. This is permitted at this point,
5026  * as long as the result is not used. Mark it invalid so this
5027  * can be tested later. */
5028  group->version = 0xFF;
5029  } else if (std::find(group->cargo_input, group->cargo_input + i, cargo) != group->cargo_input + i) {
5030  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK);
5031  error->data = stredup("duplicate input cargo");
5032  return;
5033  }
5034  group->cargo_input[i] = cargo;
5035  group->subtract_input[i] = buf->ReadByte();
5036  }
5037  group->num_output = buf->ReadByte();
5038  if (group->num_output > lengthof(group->add_output)) {
5039  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK);
5040  error->data = stredup("too many outputs (max 16)");
5041  return;
5042  }
5043  for (uint i = 0; i < group->num_output; i++) {
5044  byte rawcargo = buf->ReadByte();
5045  CargoID cargo = GetCargoTranslation(rawcargo, _cur.grffile);
5046  if (cargo == CT_INVALID) {
5047  /* Mark this result as invalid to use */
5048  group->version = 0xFF;
5049  } else if (std::find(group->cargo_output, group->cargo_output + i, cargo) != group->cargo_output + i) {
5050  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK);
5051  error->data = stredup("duplicate output cargo");
5052  return;
5053  }
5054  group->cargo_output[i] = cargo;
5055  group->add_output[i] = buf->ReadByte();
5056  }
5057  group->again = buf->ReadByte();
5058  } else {
5059  NOT_REACHED();
5060  }
5061  break;
5062  }
5063 
5064  /* Loading of Tile Layout and Production Callback groups would happen here */
5065  default: grfmsg(1, "NewSpriteGroup: Unsupported feature 0x%02X, skipping", feature);
5066  }
5067  }
5068  }
5069 
5070  _cur.spritegroups[setid] = act_group;
5071 }
5072 
5073 static CargoID TranslateCargo(uint8 feature, uint8 ctype)
5074 {
5075  if (feature == GSF_OBJECTS) {
5076  switch (ctype) {
5077  case 0: return 0;
5078  case 0xFF: return CT_PURCHASE_OBJECT;
5079  default:
5080  grfmsg(1, "TranslateCargo: Invalid cargo bitnum %d for objects, skipping.", ctype);
5081  return CT_INVALID;
5082  }
5083  }
5084  /* Special cargo types for purchase list and stations */
5085  if (feature == GSF_STATIONS && ctype == 0xFE) return CT_DEFAULT_NA;
5086  if (ctype == 0xFF) return CT_PURCHASE;
5087 
5088  if (_cur.grffile->cargo_list.Length() == 0) {
5089  /* No cargo table, so use bitnum values */
5090  if (ctype >= 32) {
5091  grfmsg(1, "TranslateCargo: Cargo bitnum %d out of range (max 31), skipping.", ctype);
5092  return CT_INVALID;
5093  }
5094 
5095  const CargoSpec *cs;
5096  FOR_ALL_CARGOSPECS(cs) {
5097  if (cs->bitnum == ctype) {
5098  grfmsg(6, "TranslateCargo: Cargo bitnum %d mapped to cargo type %d.", ctype, cs->Index());
5099  return cs->Index();
5100  }
5101  }
5102 
5103  grfmsg(5, "TranslateCargo: Cargo bitnum %d not available in this climate, skipping.", ctype);
5104  return CT_INVALID;
5105  }
5106 
5107  /* Check if the cargo type is out of bounds of the cargo translation table */
5108  if (ctype >= _cur.grffile->cargo_list.Length()) {
5109  grfmsg(1, "TranslateCargo: Cargo type %d out of range (max %d), skipping.", ctype, _cur.grffile->cargo_list.Length() - 1);
5110  return CT_INVALID;
5111  }
5112 
5113  /* Look up the cargo label from the translation table */
5114  CargoLabel cl = _cur.grffile->cargo_list[ctype];
5115  if (cl == 0) {
5116  grfmsg(5, "TranslateCargo: Cargo type %d not available in this climate, skipping.", ctype);
5117  return CT_INVALID;
5118  }
5119 
5120  ctype = GetCargoIDByLabel(cl);
5121  if (ctype == CT_INVALID) {
5122  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));
5123  return CT_INVALID;
5124  }
5125 
5126  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);
5127  return ctype;
5128 }
5129 
5130 
5131 static bool IsValidGroupID(uint16 groupid, const char *function)
5132 {
5133  if (groupid > MAX_SPRITEGROUP || _cur.spritegroups[groupid] == NULL) {
5134  grfmsg(1, "%s: Spritegroup 0x%04X out of range or empty, skipping.", function, groupid);
5135  return false;
5136  }
5137 
5138  return true;
5139 }
5140 
5141 static void VehicleMapSpriteGroup(ByteReader *buf, byte feature, uint8 idcount)
5142 {
5143  static EngineID *last_engines;
5144  static uint last_engines_count;
5145  bool wagover = false;
5146 
5147  /* Test for 'wagon override' flag */
5148  if (HasBit(idcount, 7)) {
5149  wagover = true;
5150  /* Strip off the flag */
5151  idcount = GB(idcount, 0, 7);
5152 
5153  if (last_engines_count == 0) {
5154  grfmsg(0, "VehicleMapSpriteGroup: WagonOverride: No engine to do override with");
5155  return;
5156  }
5157 
5158  grfmsg(6, "VehicleMapSpriteGroup: WagonOverride: %u engines, %u wagons",
5159  last_engines_count, idcount);
5160  } else {
5161  if (last_engines_count != idcount) {
5162  last_engines = ReallocT(last_engines, idcount);
5163  last_engines_count = idcount;
5164  }
5165  }
5166 
5167  EngineID *engines = AllocaM(EngineID, idcount);
5168  for (uint i = 0; i < idcount; i++) {
5169  Engine *e = GetNewEngine(_cur.grffile, (VehicleType)feature, buf->ReadExtendedByte());
5170  if (e == NULL) {
5171  /* No engine could be allocated?!? Deal with it. Okay,
5172  * this might look bad. Also make sure this NewGRF
5173  * gets disabled, as a half loaded one is bad. */
5174  HandleChangeInfoResult("VehicleMapSpriteGroup", CIR_INVALID_ID, 0, 0);
5175  return;
5176  }
5177 
5178  engines[i] = e->index;
5179  if (!wagover) last_engines[i] = engines[i];
5180  }
5181 
5182  uint8 cidcount = buf->ReadByte();
5183  for (uint c = 0; c < cidcount; c++) {
5184  uint8 ctype = buf->ReadByte();
5185  uint16 groupid = buf->ReadWord();
5186  if (!IsValidGroupID(groupid, "VehicleMapSpriteGroup")) continue;
5187 
5188  grfmsg(8, "VehicleMapSpriteGroup: * [%d] Cargo type 0x%X, group id 0x%02X", c, ctype, groupid);
5189 
5190  ctype = TranslateCargo(feature, ctype);
5191  if (ctype == CT_INVALID) continue;
5192 
5193  for (uint i = 0; i < idcount; i++) {
5194  EngineID engine = engines[i];
5195 
5196  grfmsg(7, "VehicleMapSpriteGroup: [%d] Engine %d...", i, engine);
5197 
5198  if (wagover) {
5199  SetWagonOverrideSprites(engine, ctype, _cur.spritegroups[groupid], last_engines, last_engines_count);
5200  } else {
5201  SetCustomEngineSprites(engine, ctype, _cur.spritegroups[groupid]);
5202  }
5203  }
5204  }
5205 
5206  uint16 groupid = buf->ReadWord();
5207  if (!IsValidGroupID(groupid, "VehicleMapSpriteGroup")) return;
5208 
5209  grfmsg(8, "-- Default group id 0x%04X", groupid);
5210 
5211  for (uint i = 0; i < idcount; i++) {
5212  EngineID engine = engines[i];
5213 
5214  if (wagover) {
5215  SetWagonOverrideSprites(engine, CT_DEFAULT, _cur.spritegroups[groupid], last_engines, last_engines_count);
5216  } else {
5217  SetCustomEngineSprites(engine, CT_DEFAULT, _cur.spritegroups[groupid]);
5218  SetEngineGRF(engine, _cur.grffile);
5219  }
5220  }
5221 }
5222 
5223 
5224 static void CanalMapSpriteGroup(ByteReader *buf, uint8 idcount)
5225 {
5226  CanalFeature *cfs = AllocaM(CanalFeature, idcount);
5227  for (uint i = 0; i < idcount; i++) {
5228  cfs[i] = (CanalFeature)buf->ReadByte();
5229  }
5230 
5231  uint8 cidcount = buf->ReadByte();
5232  buf->Skip(cidcount * 3);
5233 
5234  uint16 groupid = buf->ReadWord();
5235  if (!IsValidGroupID(groupid, "CanalMapSpriteGroup")) return;
5236 
5237  for (uint i = 0; i < idcount; i++) {
5238  CanalFeature cf = cfs[i];
5239 
5240  if (cf >= CF_END) {
5241  grfmsg(1, "CanalMapSpriteGroup: Canal subset %d out of range, skipping", cf);
5242  continue;
5243  }
5244 
5245  _water_feature[cf].grffile = _cur.grffile;
5246  _water_feature[cf].group = _cur.spritegroups[groupid];
5247  }
5248 }
5249 
5250 
5251 static void StationMapSpriteGroup(ByteReader *buf, uint8 idcount)
5252 {
5253  uint8 *stations = AllocaM(uint8, idcount);
5254  for (uint i = 0; i < idcount; i++) {
5255  stations[i] = buf->ReadByte();
5256  }
5257 
5258  uint8 cidcount = buf->ReadByte();
5259  for (uint c = 0; c < cidcount; c++) {
5260  uint8 ctype = buf->ReadByte();
5261  uint16 groupid = buf->ReadWord();
5262  if (!IsValidGroupID(groupid, "StationMapSpriteGroup")) continue;
5263 
5264  ctype = TranslateCargo(GSF_STATIONS, ctype);
5265  if (ctype == CT_INVALID) continue;
5266 
5267  for (uint i = 0; i < idcount; i++) {
5268  StationSpec *statspec = _cur.grffile->stations == NULL ? NULL : _cur.grffile->stations[stations[i]];
5269 
5270  if (statspec == NULL) {
5271  grfmsg(1, "StationMapSpriteGroup: Station with ID 0x%02X does not exist, skipping", stations[i]);
5272  continue;
5273  }
5274 
5275  statspec->grf_prop.spritegroup[ctype] = _cur.spritegroups[groupid];
5276  }
5277  }
5278 
5279  uint16 groupid = buf->ReadWord();
5280  if (!IsValidGroupID(groupid, "StationMapSpriteGroup")) return;
5281 
5282  for (uint i = 0; i < idcount; i++) {
5283  StationSpec *statspec = _cur.grffile->stations == NULL ? NULL : _cur.grffile->stations[stations[i]];
5284 
5285  if (statspec == NULL) {
5286  grfmsg(1, "StationMapSpriteGroup: Station with ID 0x%02X does not exist, skipping", stations[i]);
5287  continue;
5288  }
5289 
5290  if (statspec->grf_prop.grffile != NULL) {
5291  grfmsg(1, "StationMapSpriteGroup: Station with ID 0x%02X mapped multiple times, skipping", stations[i]);
5292  continue;
5293  }
5294 
5295  statspec->grf_prop.spritegroup[CT_DEFAULT] = _cur.spritegroups[groupid];
5296  statspec->grf_prop.grffile = _cur.grffile;
5297  statspec->grf_prop.local_id = stations[i];
5298  StationClass::Assign(statspec);
5299  }
5300 }
5301 
5302 
5303 static void TownHouseMapSpriteGroup(ByteReader *buf, uint8 idcount)
5304 {
5305  uint8 *houses = AllocaM(uint8, idcount);
5306  for (uint i = 0; i < idcount; i++) {
5307  houses[i] = buf->ReadByte();
5308  }
5309 
5310  /* Skip the cargo type section, we only care about the default group */
5311  uint8 cidcount = buf->ReadByte();
5312  buf->Skip(cidcount * 3);
5313 
5314  uint16 groupid = buf->ReadWord();
5315  if (!IsValidGroupID(groupid, "TownHouseMapSpriteGroup")) return;
5316 
5317  if (_cur.grffile->housespec == NULL) {
5318  grfmsg(1, "TownHouseMapSpriteGroup: No houses defined, skipping");
5319  return;
5320  }
5321 
5322  for (uint i = 0; i < idcount; i++) {
5323  HouseSpec *hs = _cur.grffile->housespec[houses[i]];
5324 
5325  if (hs == NULL) {
5326  grfmsg(1, "TownHouseMapSpriteGroup: House %d undefined, skipping.", houses[i]);
5327  continue;
5328  }
5329 
5330  hs->grf_prop.spritegroup[0] = _cur.spritegroups[groupid];
5331  }
5332 }
5333 
5334 static void IndustryMapSpriteGroup(ByteReader *buf, uint8 idcount)
5335 {
5336  uint8 *industries = AllocaM(uint8, idcount);
5337  for (uint i = 0; i < idcount; i++) {
5338  industries[i] = buf->ReadByte();
5339  }
5340 
5341  /* Skip the cargo type section, we only care about the default group */
5342  uint8 cidcount = buf->ReadByte();
5343  buf->Skip(cidcount * 3);
5344 
5345  uint16 groupid = buf->ReadWord();
5346  if (!IsValidGroupID(groupid, "IndustryMapSpriteGroup")) return;
5347 
5348  if (_cur.grffile->industryspec == NULL) {
5349  grfmsg(1, "IndustryMapSpriteGroup: No industries defined, skipping");
5350  return;
5351  }
5352 
5353  for (uint i = 0; i < idcount; i++) {
5354  IndustrySpec *indsp = _cur.grffile->industryspec[industries[i]];
5355 
5356  if (indsp == NULL) {
5357  grfmsg(1, "IndustryMapSpriteGroup: Industry %d undefined, skipping", industries[i]);
5358  continue;
5359  }
5360 
5361  indsp->grf_prop.spritegroup[0] = _cur.spritegroups[groupid];
5362  }
5363 }
5364 
5365 static void IndustrytileMapSpriteGroup(ByteReader *buf, uint8 idcount)
5366 {
5367  uint8 *indtiles = AllocaM(uint8, idcount);
5368  for (uint i = 0; i < idcount; i++) {
5369  indtiles[i] = buf->ReadByte();
5370  }
5371 
5372  /* Skip the cargo type section, we only care about the default group */
5373  uint8 cidcount = buf->ReadByte();
5374  buf->Skip(cidcount * 3);
5375 
5376  uint16 groupid = buf->ReadWord();
5377  if (!IsValidGroupID(groupid, "IndustrytileMapSpriteGroup")) return;
5378 
5379  if (_cur.grffile->indtspec == NULL) {
5380  grfmsg(1, "IndustrytileMapSpriteGroup: No industry tiles defined, skipping");
5381  return;
5382  }
5383 
5384  for (uint i = 0; i < idcount; i++) {
5385  IndustryTileSpec *indtsp = _cur.grffile->indtspec[indtiles[i]];
5386 
5387  if (indtsp == NULL) {
5388  grfmsg(1, "IndustrytileMapSpriteGroup: Industry tile %d undefined, skipping", indtiles[i]);
5389  continue;
5390  }
5391 
5392  indtsp->grf_prop.spritegroup[0] = _cur.spritegroups[groupid];
5393  }
5394 }
5395 
5396 static void CargoMapSpriteGroup(ByteReader *buf, uint8 idcount)
5397 {
5398  CargoID *cargoes = AllocaM(CargoID, idcount);
5399  for (uint i = 0; i < idcount; i++) {
5400  cargoes[i] = buf->ReadByte();
5401  }
5402 
5403  /* Skip the cargo type section, we only care about the default group */
5404  uint8 cidcount = buf->ReadByte();
5405  buf->Skip(cidcount * 3);
5406 
5407  uint16 groupid = buf->ReadWord();
5408  if (!IsValidGroupID(groupid, "CargoMapSpriteGroup")) return;
5409 
5410  for (uint i = 0; i < idcount; i++) {
5411  CargoID cid = cargoes[i];
5412 
5413  if (cid >= NUM_CARGO) {
5414  grfmsg(1, "CargoMapSpriteGroup: Cargo ID %d out of range, skipping", cid);
5415  continue;
5416  }
5417 
5418  CargoSpec *cs = CargoSpec::Get(cid);
5419  cs->grffile = _cur.grffile;
5420  cs->group = _cur.spritegroups[groupid];
5421  }
5422 }
5423 
5424 static void ObjectMapSpriteGroup(ByteReader *buf, uint8 idcount)
5425 {
5426  if (_cur.grffile->objectspec == NULL) {
5427  grfmsg(1, "ObjectMapSpriteGroup: No object tiles defined, skipping");
5428  return;
5429  }
5430 
5431  uint8 *objects = AllocaM(uint8, idcount);
5432  for (uint i = 0; i < idcount; i++) {
5433  objects[i] = buf->ReadByte();
5434  }
5435 
5436  uint8 cidcount = buf->ReadByte();
5437  for (uint c = 0; c < cidcount; c++) {
5438  uint8 ctype = buf->ReadByte();
5439  uint16 groupid = buf->ReadWord();
5440  if (!IsValidGroupID(groupid, "ObjectMapSpriteGroup")) continue;
5441 
5442  ctype = TranslateCargo(GSF_OBJECTS, ctype);
5443  if (ctype == CT_INVALID) continue;
5444 
5445  for (uint i = 0; i < idcount; i++) {
5446  ObjectSpec *spec = _cur.grffile->objectspec[objects[i]];
5447 
5448  if (spec == NULL) {
5449  grfmsg(1, "ObjectMapSpriteGroup: Object with ID 0x%02X undefined, skipping", objects[i]);
5450  continue;
5451  }
5452 
5453  spec->grf_prop.spritegroup[ctype] = _cur.spritegroups[groupid];
5454  }
5455  }
5456 
5457  uint16 groupid = buf->ReadWord();
5458  if (!IsValidGroupID(groupid, "ObjectMapSpriteGroup")) return;
5459 
5460  for (uint i = 0; i < idcount; i++) {
5461  ObjectSpec *spec = _cur.grffile->objectspec[objects[i]];
5462 
5463  if (spec == NULL) {
5464  grfmsg(1, "ObjectMapSpriteGroup: Object with ID 0x%02X undefined, skipping", objects[i]);
5465  continue;
5466  }
5467 
5468  if (spec->grf_prop.grffile != NULL) {
5469  grfmsg(1, "ObjectMapSpriteGroup: Object with ID 0x%02X mapped multiple times, skipping", objects[i]);
5470  continue;
5471  }
5472 
5473  spec->grf_prop.spritegroup[0] = _cur.spritegroups[groupid];
5474  spec->grf_prop.grffile = _cur.grffile;
5475  spec->grf_prop.local_id = objects[i];
5476  }
5477 }
5478 
5479 static void RailTypeMapSpriteGroup(ByteReader *buf, uint8 idcount)
5480 {
5481  uint8 *railtypes = AllocaM(uint8, idcount);
5482  for (uint i = 0; i < idcount; i++) {
5483  uint8 id = buf->ReadByte();
5484  railtypes[i] = id < RAILTYPE_END ? _cur.grffile->railtype_map[id] : INVALID_RAILTYPE;
5485  }
5486 
5487  uint8 cidcount = buf->ReadByte();
5488  for (uint c = 0; c < cidcount; c++) {
5489  uint8 ctype = buf->ReadByte();
5490  uint16 groupid = buf->ReadWord();
5491  if (!IsValidGroupID(groupid, "RailTypeMapSpriteGroup")) continue;
5492 
5493  if (ctype >= RTSG_END) continue;
5494 
5495  extern RailtypeInfo _railtypes[RAILTYPE_END];
5496  for (uint i = 0; i < idcount; i++) {
5497  if (railtypes[i] != INVALID_RAILTYPE) {
5498  RailtypeInfo *rti = &_railtypes[railtypes[i]];
5499 
5500  rti->grffile[ctype] = _cur.grffile;
5501  rti->group[ctype] = _cur.spritegroups[groupid];
5502  }
5503  }
5504  }
5505 
5506  /* Railtypes do not use the default group. */
5507  buf->ReadWord();
5508 }
5509 
5510 static void AirportMapSpriteGroup(ByteReader *buf, uint8 idcount)
5511 {
5512  uint8 *airports = AllocaM(uint8, idcount);
5513  for (uint i = 0; i < idcount; i++) {
5514  airports[i] = buf->ReadByte();
5515  }
5516 
5517  /* Skip the cargo type section, we only care about the default group */
5518  uint8 cidcount = buf->ReadByte();
5519  buf->Skip(cidcount * 3);
5520 
5521  uint16 groupid = buf->ReadWord();
5522  if (!IsValidGroupID(groupid, "AirportMapSpriteGroup")) return;
5523 
5524  if (_cur.grffile->airportspec == NULL) {
5525  grfmsg(1, "AirportMapSpriteGroup: No airports defined, skipping");
5526  return;
5527  }
5528 
5529  for (uint i = 0; i < idcount; i++) {
5530  AirportSpec *as = _cur.grffile->airportspec[airports[i]];
5531 
5532  if (as == NULL) {
5533  grfmsg(1, "AirportMapSpriteGroup: Airport %d undefined, skipping", airports[i]);
5534  continue;
5535  }
5536 
5537  as->grf_prop.spritegroup[0] = _cur.spritegroups[groupid];
5538  }
5539 }
5540 
5541 static void AirportTileMapSpriteGroup(ByteReader *buf, uint8 idcount)
5542 {
5543  uint8 *airptiles = AllocaM(uint8, idcount);
5544  for (uint i = 0; i < idcount; i++) {
5545  airptiles[i] = buf->ReadByte();
5546  }
5547 
5548  /* Skip the cargo type section, we only care about the default group */
5549  uint8 cidcount = buf->ReadByte();
5550  buf->Skip(cidcount * 3);
5551 
5552  uint16 groupid = buf->ReadWord();
5553  if (!IsValidGroupID(groupid, "AirportTileMapSpriteGroup")) return;
5554 
5555  if (_cur.grffile->airtspec == NULL) {
5556  grfmsg(1, "AirportTileMapSpriteGroup: No airport tiles defined, skipping");
5557  return;
5558  }
5559 
5560  for (uint i = 0; i < idcount; i++) {
5561  AirportTileSpec *airtsp = _cur.grffile->airtspec[airptiles[i]];
5562 
5563  if (airtsp == NULL) {
5564  grfmsg(1, "AirportTileMapSpriteGroup: Airport tile %d undefined, skipping", airptiles[i]);
5565  continue;
5566  }
5567 
5568  airtsp->grf_prop.spritegroup[0] = _cur.spritegroups[groupid];
5569  }
5570 }
5571 
5572 
5573 /* Action 0x03 */
5574 static void FeatureMapSpriteGroup(ByteReader *buf)
5575 {
5576  /* <03> <feature> <n-id> <ids>... <num-cid> [<cargo-type> <cid>]... <def-cid>
5577  * id-list := [<id>] [id-list]
5578  * cargo-list := <cargo-type> <cid> [cargo-list]
5579  *
5580  * B feature see action 0
5581  * B n-id bits 0-6: how many IDs this definition applies to
5582  * bit 7: if set, this is a wagon override definition (see below)
5583  * B ids the IDs for which this definition applies
5584  * B num-cid number of cargo IDs (sprite group IDs) in this definition
5585  * can be zero, in that case the def-cid is used always
5586  * B cargo-type type of this cargo type (e.g. mail=2, wood=7, see below)
5587  * W cid cargo ID (sprite group ID) for this type of cargo
5588  * W def-cid default cargo ID (sprite group ID) */
5589 
5590  uint8 feature = buf->ReadByte();
5591  uint8 idcount = buf->ReadByte();
5592 
5593  if (feature >= GSF_END) {
5594  grfmsg(1, "FeatureMapSpriteGroup: Unsupported feature 0x%02X, skipping", feature);
5595  return;
5596  }
5597 
5598  /* If idcount is zero, this is a feature callback */
5599  if (idcount == 0) {
5600  /* Skip number of cargo ids? */
5601  buf->ReadByte();
5602  uint16 groupid = buf->ReadWord();
5603  if (!IsValidGroupID(groupid, "FeatureMapSpriteGroup")) return;
5604 
5605  grfmsg(6, "FeatureMapSpriteGroup: Adding generic feature callback for feature 0x%02X", feature);
5606 
5607  AddGenericCallback(feature, _cur.grffile, _cur.spritegroups[groupid]);
5608  return;
5609  }
5610 
5611  /* Mark the feature as used by the grf (generic callbacks do not count) */
5612  SetBit(_cur.grffile->grf_features, feature);
5613 
5614  grfmsg(6, "FeatureMapSpriteGroup: Feature 0x%02X, %d ids", feature, idcount);
5615 
5616  switch (feature) {
5617  case GSF_TRAINS:
5618  case GSF_ROADVEHICLES:
5619  case GSF_SHIPS:
5620  case GSF_AIRCRAFT:
5621  VehicleMapSpriteGroup(buf, feature, idcount);
5622  return;
5623 
5624  case GSF_CANALS:
5625  CanalMapSpriteGroup(buf, idcount);
5626  return;
5627 
5628  case GSF_STATIONS:
5629  StationMapSpriteGroup(buf, idcount);
5630  return;
5631 
5632  case GSF_HOUSES:
5633  TownHouseMapSpriteGroup(buf, idcount);
5634  return;
5635 
5636  case GSF_INDUSTRIES:
5637  IndustryMapSpriteGroup(buf, idcount);
5638  return;
5639 
5640  case GSF_INDUSTRYTILES:
5641  IndustrytileMapSpriteGroup(buf, idcount);
5642  return;
5643 
5644  case GSF_CARGOES:
5645  CargoMapSpriteGroup(buf, idcount);
5646  return;
5647 
5648  case GSF_AIRPORTS:
5649  AirportMapSpriteGroup(buf, idcount);
5650  return;
5651 
5652  case GSF_OBJECTS:
5653  ObjectMapSpriteGroup(buf, idcount);
5654  break;
5655 
5656  case GSF_RAILTYPES:
5657  RailTypeMapSpriteGroup(buf, idcount);
5658  break;
5659 
5660  case GSF_AIRPORTTILES:
5661  AirportTileMapSpriteGroup(buf, idcount);
5662  return;
5663 
5664  default:
5665  grfmsg(1, "FeatureMapSpriteGroup: Unsupported feature 0x%02X, skipping", feature);
5666  return;
5667  }
5668 }
5669 
5670 /* Action 0x04 */
5671 static void FeatureNewName(ByteReader *buf)
5672 {
5673  /* <04> <veh-type> <language-id> <num-veh> <offset> <data...>
5674  *
5675  * B veh-type see action 0 (as 00..07, + 0A
5676  * But IF veh-type = 48, then generic text
5677  * B language-id If bit 6 is set, This is the extended language scheme,
5678  * with up to 64 language.
5679  * Otherwise, it is a mapping where set bits have meaning
5680  * 0 = american, 1 = english, 2 = german, 3 = french, 4 = spanish
5681  * Bit 7 set means this is a generic text, not a vehicle one (or else)
5682  * B num-veh number of vehicles which are getting a new name
5683  * B/W offset number of the first vehicle that gets a new name
5684  * Byte : ID of vehicle to change
5685  * Word : ID of string to change/add
5686  * S data new texts, each of them zero-terminated, after
5687  * which the next name begins. */
5688 
5689  bool new_scheme = _cur.grffile->grf_version >= 7;
5690 
5691  uint8 feature = buf->ReadByte();
5692  if (feature >= GSF_END && feature != 0x48) {
5693  grfmsg(1, "FeatureNewName: Unsupported feature 0x%02X, skipping", feature);
5694  return;
5695  }
5696 
5697  uint8 lang = buf->ReadByte();
5698  uint8 num = buf->ReadByte();
5699  bool generic = HasBit(lang, 7);
5700  uint16 id;
5701  if (generic) {
5702  id = buf->ReadWord();
5703  } else if (feature <= GSF_AIRCRAFT) {
5704  id = buf->ReadExtendedByte();
5705  } else {
5706  id = buf->ReadByte();
5707  }
5708 
5709  ClrBit(lang, 7);
5710 
5711  uint16 endid = id + num;
5712 
5713  grfmsg(6, "FeatureNewName: About to rename engines %d..%d (feature 0x%02X) in language 0x%02X",
5714  id, endid, feature, lang);
5715 
5716  for (; id < endid && buf->HasData(); id++) {
5717  const char *name = buf->ReadString();
5718  grfmsg(8, "FeatureNewName: 0x%04X <- %s", id, name);
5719 
5720  switch (feature) {
5721  case GSF_TRAINS:
5722  case GSF_ROADVEHICLES:
5723  case GSF_SHIPS:
5724  case GSF_AIRCRAFT:
5725  if (!generic) {
5726  Engine *e = GetNewEngine(_cur.grffile, (VehicleType)feature, id, HasBit(_cur.grfconfig->flags, GCF_STATIC));
5727  if (e == NULL) break;
5728  StringID string = AddGRFString(_cur.grffile->grfid, e->index, lang, new_scheme, false, name, e->info.string_id);
5729  e->info.string_id = string;
5730  } else {
5731  AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, true, name, STR_UNDEFINED);
5732  }
5733  break;
5734 
5735  default:
5736  if (IsInsideMM(id, 0xD000, 0xD400) || IsInsideMM(id, 0xD800, 0xE000)) {
5737  AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, true, name, STR_UNDEFINED);
5738  break;
5739  }
5740 
5741  switch (GB(id, 8, 8)) {
5742  case 0xC4: // Station class name
5743  if (_cur.grffile->stations == NULL || _cur.grffile->stations[GB(id, 0, 8)] == NULL) {
5744  grfmsg(1, "FeatureNewName: Attempt to name undefined station 0x%X, ignoring", GB(id, 0, 8));
5745  } else {
5746  StationClassID cls_id = _cur.grffile->stations[GB(id, 0, 8)]->cls_id;
5747  StationClass::Get(cls_id)->name = AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
5748  }
5749  break;
5750 
5751  case 0xC5: // Station name
5752  if (_cur.grffile->stations == NULL || _cur.grffile->stations[GB(id, 0, 8)] == NULL) {
5753  grfmsg(1, "FeatureNewName: Attempt to name undefined station 0x%X, ignoring", GB(id, 0, 8));
5754  } else {
5755  _cur.grffile->stations[GB(id, 0, 8)]->name = AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
5756  }
5757  break;
5758 
5759  case 0xC7: // Airporttile name
5760  if (_cur.grffile->airtspec == NULL || _cur.grffile->airtspec[GB(id, 0, 8)] == NULL) {
5761  grfmsg(1, "FeatureNewName: Attempt to name undefined airport tile 0x%X, ignoring", GB(id, 0, 8));
5762  } else {
5763  _cur.grffile->airtspec[GB(id, 0, 8)]->name = AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
5764  }
5765  break;
5766 
5767  case 0xC9: // House name
5768  if (_cur.grffile->housespec == NULL || _cur.grffile->housespec[GB(id, 0, 8)] == NULL) {
5769  grfmsg(1, "FeatureNewName: Attempt to name undefined house 0x%X, ignoring.", GB(id, 0, 8));
5770  } else {
5771  _cur.grffile->housespec[GB(id, 0, 8)]->building_name = AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
5772  }
5773  break;
5774 
5775  default:
5776  grfmsg(7, "FeatureNewName: Unsupported ID (0x%04X)", id);
5777  break;
5778  }
5779  break;
5780  }
5781  }
5782 }
5783 
5792 static uint16 SanitizeSpriteOffset(uint16& num, uint16 offset, int max_sprites, const char *name)
5793 {
5794 
5795  if (offset >= max_sprites) {
5796  grfmsg(1, "GraphicsNew: %s sprite offset must be less than %i, skipping", name, max_sprites);
5797  uint orig_num = num;
5798  num = 0;
5799  return orig_num;
5800  }
5801 
5802  if (offset + num > max_sprites) {
5803  grfmsg(4, "GraphicsNew: %s sprite overflow, truncating...", name);
5804  uint orig_num = num;
5805  num = max(max_sprites - offset, 0);
5806  return orig_num - num;
5807  }
5808 
5809  return 0;
5810 }
5811 
5812 
5818 };
5820 struct Action5Type {
5823  uint16 min_sprites;
5824  uint16 max_sprites;
5825  const char *name;
5826 };
5827 
5829 static const Action5Type _action5_types[] = {
5830  /* Note: min_sprites should not be changed. Therefore these constants are directly here and not in sprites.h */
5831  /* 0x00 */ { A5BLOCK_INVALID, 0, 0, 0, "Type 0x00" },
5832  /* 0x01 */ { A5BLOCK_INVALID, 0, 0, 0, "Type 0x01" },
5833  /* 0x02 */ { A5BLOCK_INVALID, 0, 0, 0, "Type 0x02" },
5834  /* 0x03 */ { A5BLOCK_INVALID, 0, 0, 0, "Type 0x03" },
5835  /* 0x04 */ { A5BLOCK_ALLOW_OFFSET, SPR_SIGNALS_BASE, 1, PRESIGNAL_SEMAPHORE_AND_PBS_SPRITE_COUNT, "Signal graphics" },
5836  /* 0x05 */ { A5BLOCK_ALLOW_OFFSET, SPR_ELRAIL_BASE, 1, ELRAIL_SPRITE_COUNT, "Rail catenary graphics" },
5837  /* 0x06 */ { A5BLOCK_ALLOW_OFFSET, SPR_SLOPES_BASE, 1, NORMAL_AND_HALFTILE_FOUNDATION_SPRITE_COUNT, "Foundation graphics" },
5838  /* 0x07 */ { A5BLOCK_INVALID, 0, 75, 0, "TTDP GUI graphics" }, // Not used by OTTD.
5839  /* 0x08 */ { A5BLOCK_ALLOW_OFFSET, SPR_CANALS_BASE, 1, CANALS_SPRITE_COUNT, "Canal graphics" },
5840  /* 0x09 */ { A5BLOCK_ALLOW_OFFSET, SPR_ONEWAY_BASE, 1, ONEWAY_SPRITE_COUNT, "One way road graphics" },
5841  /* 0x0A */ { A5BLOCK_ALLOW_OFFSET, SPR_2CCMAP_BASE, 1, TWOCCMAP_SPRITE_COUNT, "2CC colour maps" },
5842  /* 0x0B */ { A5BLOCK_ALLOW_OFFSET, SPR_TRAMWAY_BASE, 1, TRAMWAY_SPRITE_COUNT, "Tramway graphics" },
5843  /* 0x0C */ { A5BLOCK_INVALID, 0, 133, 0, "Snowy temperate tree" }, // Not yet used by OTTD.
5844  /* 0x0D */ { A5BLOCK_FIXED, SPR_SHORE_BASE, 16, SPR_SHORE_SPRITE_COUNT, "Shore graphics" },
5845  /* 0x0E */ { A5BLOCK_INVALID, 0, 0, 0, "New Signals graphics" }, // Not yet used by OTTD.
5846  /* 0x0F */ { A5BLOCK_ALLOW_OFFSET, SPR_TRACKS_FOR_SLOPES_BASE, 1, TRACKS_FOR_SLOPES_SPRITE_COUNT, "Sloped rail track" },
5847  /* 0x10 */ { A5BLOCK_ALLOW_OFFSET, SPR_AIRPORTX_BASE, 1, AIRPORTX_SPRITE_COUNT, "Airport graphics" },
5848  /* 0x11 */ { A5BLOCK_ALLOW_OFFSET, SPR_ROADSTOP_BASE, 1, ROADSTOP_SPRITE_COUNT, "Road stop graphics" },
5849  /* 0x12 */ { A5BLOCK_ALLOW_OFFSET, SPR_AQUEDUCT_BASE, 1, AQUEDUCT_SPRITE_COUNT, "Aqueduct graphics" },
5850  /* 0x13 */ { A5BLOCK_ALLOW_OFFSET, SPR_AUTORAIL_BASE, 1, AUTORAIL_SPRITE_COUNT, "Autorail graphics" },
5851  /* 0x14 */ { A5BLOCK_ALLOW_OFFSET, SPR_FLAGS_BASE, 1, FLAGS_SPRITE_COUNT, "Flag graphics" },
5852  /* 0x15 */ { A5BLOCK_ALLOW_OFFSET, SPR_OPENTTD_BASE, 1, OPENTTD_SPRITE_COUNT, "OpenTTD GUI graphics" },
5853  /* 0x16 */ { A5BLOCK_ALLOW_OFFSET, SPR_AIRPORT_PREVIEW_BASE, 1, SPR_AIRPORT_PREVIEW_COUNT, "Airport preview graphics" },
5854  /* 0x17 */ { A5BLOCK_ALLOW_OFFSET, SPR_RAILTYPE_TUNNEL_BASE, 1, RAILTYPE_TUNNEL_BASE_COUNT, "Railtype tunnel base" },
5855  /* 0x18 */ { A5BLOCK_ALLOW_OFFSET, SPR_PALETTE_BASE, 1, PALETTE_SPRITE_COUNT, "Palette" },
5856 };
5857 
5858 /* Action 0x05 */
5859 static void GraphicsNew(ByteReader *buf)
5860 {
5861  /* <05> <graphics-type> <num-sprites> <other data...>
5862  *
5863  * B graphics-type What set of graphics the sprites define.
5864  * E num-sprites How many sprites are in this set?
5865  * V other data Graphics type specific data. Currently unused. */
5866 
5867  uint8 type = buf->ReadByte();
5868  uint16 num = buf->ReadExtendedByte();
5869  uint16 offset = HasBit(type, 7) ? buf->ReadExtendedByte() : 0;
5870  ClrBit(type, 7); // Clear the high bit as that only indicates whether there is an offset.
5871 
5872  if ((type == 0x0D) && (num == 10) && HasBit(_cur.grfconfig->flags, GCF_SYSTEM)) {
5873  /* Special not-TTDP-compatible case used in openttd.grf
5874  * Missing shore sprites and initialisation of SPR_SHORE_BASE */
5875  grfmsg(2, "GraphicsNew: Loading 10 missing shore sprites from extra grf.");
5876  LoadNextSprite(SPR_SHORE_BASE + 0, _cur.file_index, _cur.nfo_line++, _cur.grf_container_ver); // SLOPE_STEEP_S
5877  LoadNextSprite(SPR_SHORE_BASE + 5, _cur.file_index, _cur.nfo_line++, _cur.grf_container_ver); // SLOPE_STEEP_W
5878  LoadNextSprite(SPR_SHORE_BASE + 7, _cur.file_index, _cur.nfo_line++, _cur.grf_container_ver); // SLOPE_WSE
5879  LoadNextSprite(SPR_SHORE_BASE + 10, _cur.file_index, _cur.nfo_line++, _cur.grf_container_ver); // SLOPE_STEEP_N
5880  LoadNextSprite(SPR_SHORE_BASE + 11, _cur.file_index, _cur.nfo_line++, _cur.grf_container_ver); // SLOPE_NWS
5881  LoadNextSprite(SPR_SHORE_BASE + 13, _cur.file_index, _cur.nfo_line++, _cur.grf_container_ver); // SLOPE_ENW
5882  LoadNextSprite(SPR_SHORE_BASE + 14, _cur.file_index, _cur.nfo_line++, _cur.grf_container_ver); // SLOPE_SEN
5883  LoadNextSprite(SPR_SHORE_BASE + 15, _cur.file_index, _cur.nfo_line++, _cur.grf_container_ver); // SLOPE_STEEP_E
5884  LoadNextSprite(SPR_SHORE_BASE + 16, _cur.file_index, _cur.nfo_line++, _cur.grf_container_ver); // SLOPE_EW
5885  LoadNextSprite(SPR_SHORE_BASE + 17, _cur.file_index, _cur.nfo_line++, _cur.grf_container_ver); // SLOPE_NS
5886  if (_loaded_newgrf_features.shore == SHORE_REPLACE_NONE) _loaded_newgrf_features.shore = SHORE_REPLACE_ONLY_NEW;
5887  return;
5888  }
5889 
5890  /* Supported type? */
5891  if ((type >= lengthof(_action5_types)) || (_action5_types[type].block_type == A5BLOCK_INVALID)) {
5892  grfmsg(2, "GraphicsNew: Custom graphics (type 0x%02X) sprite block of length %u (unimplemented, ignoring)", type, num);
5893  _cur.skip_sprites = num;
5894  return;
5895  }
5896 
5897  const Action5Type *action5_type = &_action5_types[type];
5898 
5899  /* Contrary to TTDP we allow always to specify too few sprites as we allow always an offset,
5900  * except for the long version of the shore type:
5901  * Ignore offset if not allowed */
5902  if ((action5_type->block_type != A5BLOCK_ALLOW_OFFSET) && (offset != 0)) {
5903  grfmsg(1, "GraphicsNew: %s (type 0x%02X) do not allow an <offset> field. Ignoring offset.", action5_type->name, type);
5904  offset = 0;
5905  }
5906 
5907  /* Ignore action5 if too few sprites are specified. (for TTDP compatibility)
5908  * This does not make sense, if <offset> is allowed */
5909  if ((action5_type->block_type == A5BLOCK_FIXED) && (num < action5_type->min_sprites)) {
5910  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);
5911  _cur.skip_sprites = num;
5912  return;
5913  }
5914 
5915  /* Load at most max_sprites sprites. Skip remaining sprites. (for compatibility with TTDP and future extentions) */
5916  uint16 skip_num = SanitizeSpriteOffset(num, offset, action5_type->max_sprites, action5_type->name);
5917  SpriteID replace = action5_type->sprite_base + offset;
5918 
5919  /* Load <num> sprites starting from <replace>, then skip <skip_num> sprites. */
5920  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);
5921 
5922  for (; num > 0; num--) {
5923  _cur.nfo_line++;
5924  LoadNextSprite(replace == 0 ? _cur.spriteid++ : replace++, _cur.file_index, _cur.nfo_line, _cur.grf_container_ver);
5925  }
5926 
5927  if (type == 0x0D) _loaded_newgrf_features.shore = SHORE_REPLACE_ACTION_5;
5928 
5929  _cur.skip_sprites = skip_num;
5930 }
5931 
5932 /* Action 0x05 (SKIP) */
5933 static void SkipAct5(ByteReader *buf)
5934 {
5935  /* Ignore type byte */
5936  buf->ReadByte();
5937 
5938  /* Skip the sprites of this action */
5939  _cur.skip_sprites = buf->ReadExtendedByte();
5940 
5941  grfmsg(3, "SkipAct5: Skipping %d sprites", _cur.skip_sprites);
5942 }
5943 
5955 bool GetGlobalVariable(byte param, uint32 *value, const GRFFile *grffile)
5956 {
5957  switch (param) {
5958  case 0x00: // current date
5959  *value = max(_date - DAYS_TILL_ORIGINAL_BASE_YEAR, 0);
5960  return true;
5961 
5962  case 0x01: // current year
5964  return true;
5965 
5966  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)
5967  YearMonthDay ymd;
5968  ConvertDateToYMD(_date, &ymd);
5969  Date start_of_year = ConvertYMDToDate(ymd.year, 0, 1);
5970  *value = ymd.month | (ymd.day - 1) << 8 | (IsLeapYear(ymd.year) ? 1 << 15 : 0) | (_date - start_of_year) << 16;
5971  return true;
5972  }
5973 
5974  case 0x03: // current climate, 0=temp, 1=arctic, 2=trop, 3=toyland
5976  return true;
5977 
5978  case 0x06: // road traffic side, bit 4 clear=left, set=right
5979  *value = _settings_game.vehicle.road_side << 4;
5980  return true;
5981 
5982  case 0x09: // date fraction
5983  *value = _date_fract * 885;
5984  return true;
5985 
5986  case 0x0A: // animation counter
5987  *value = _tick_counter;
5988  return true;
5989 
5990  case 0x0B: { // TTDPatch version
5991  uint major = 2;
5992  uint minor = 6;
5993  uint revision = 1; // special case: 2.0.1 is 2.0.10
5994  uint build = 1382;
5995  *value = (major << 24) | (minor << 20) | (revision << 16) | build;
5996  return true;
5997  }
5998 
5999  case 0x0D: // TTD Version, 00=DOS, 01=Windows
6000  *value = _cur.grfconfig->palette & GRFP_USE_MASK;
6001  return true;
6002 
6003  case 0x0E: // Y-offset for train sprites
6004  *value = _cur.grffile->traininfo_vehicle_pitch;
6005  return true;
6006 
6007  case 0x0F: // Rail track type cost factors
6008  *value = 0;
6009  SB(*value, 0, 8, GetRailTypeInfo(RAILTYPE_RAIL)->cost_multiplier); // normal rail
6011  /* skip elrail multiplier - disabled */
6012  SB(*value, 8, 8, GetRailTypeInfo(RAILTYPE_MONO)->cost_multiplier); // monorail
6013  } else {
6014  SB(*value, 8, 8, GetRailTypeInfo(RAILTYPE_ELECTRIC)->cost_multiplier); // electified railway
6015  /* Skip monorail multiplier - no space in result */
6016  }
6017  SB(*value, 16, 8, GetRailTypeInfo(RAILTYPE_MAGLEV)->cost_multiplier); // maglev
6018  return true;
6019 
6020  case 0x11: // current rail tool type
6021  *value = 0; // constant fake value to avoid desync
6022  return true;
6023 
6024  case 0x12: // Game mode
6025  *value = _game_mode;
6026  return true;
6027 
6028  /* case 0x13: // Tile refresh offset to left not implemented */
6029  /* case 0x14: // Tile refresh offset to right not implemented */
6030  /* case 0x15: // Tile refresh offset upwards not implemented */
6031  /* case 0x16: // Tile refresh offset downwards not implemented */
6032  /* case 0x17: // temperate snow line not implemented */
6033 
6034  case 0x1A: // Always -1
6035  *value = UINT_MAX;
6036  return true;
6037 
6038  case 0x1B: // Display options
6039  *value = 0x3F; // constant fake value to avoid desync
6040  return true;
6041 
6042  case 0x1D: // TTD Platform, 00=TTDPatch, 01=OpenTTD
6043  *value = 1;
6044  return true;
6045 
6046  case 0x1E: // Miscellaneous GRF features
6047  *value = _misc_grf_features;
6048 
6049  /* Add the local flags */
6050  assert(!HasBit(*value, GMB_TRAIN_WIDTH_32_PIXELS));
6051  if (_cur.grffile->traininfo_vehicle_width == VEHICLEINFO_FULL_VEHICLE_WIDTH) SetBit(*value, GMB_TRAIN_WIDTH_32_PIXELS);
6052  return true;
6053 
6054  /* case 0x1F: // locale dependent settings not implemented to avoid desync */
6055 
6056  case 0x20: { // snow line height
6057  byte snowline = GetSnowLine();
6059  *value = Clamp(snowline * (grffile->grf_version >= 8 ? 1 : TILE_HEIGHT), 0, 0xFE);
6060  } else {
6061  /* No snow */
6062  *value = 0xFF;
6063  }
6064  return true;
6065  }
6066 
6067  case 0x21: // OpenTTD version
6068  *value = _openttd_newgrf_version;
6069  return true;
6070 
6071  case 0x22: // difficulty level
6072  *value = SP_CUSTOM;
6073  return true;
6074 
6075  case 0x23: // long format date
6076  *value = _date;
6077  return true;
6078 
6079  case 0x24: // long format year
6080  *value = _cur_year;
6081  return true;
6082 
6083  default: return false;
6084  }
6085 }
6086 
6087 static uint32 GetParamVal(byte param, uint32 *cond_val)
6088 {
6089  /* First handle variable common with VarAction2 */
6090  uint32 value;
6091  if (GetGlobalVariable(param - 0x80, &value, _cur.grffile)) return value;
6092 
6093  /* Non-common variable */
6094  switch (param) {
6095  case 0x84: { // GRF loading stage
6096  uint32 res = 0;
6097 
6098  if (_cur.stage > GLS_INIT) SetBit(res, 0);
6099  if (_cur.stage == GLS_RESERVE) SetBit(res, 8);
6100  if (_cur.stage == GLS_ACTIVATION) SetBit(res, 9);
6101  return res;
6102  }
6103 
6104  case 0x85: // TTDPatch flags, only for bit tests
6105  if (cond_val == NULL) {
6106  /* Supported in Action 0x07 and 0x09, not 0x0D */
6107  return 0;
6108  } else {
6109  uint32 index = *cond_val / 0x20;
6110  uint32 param_val = index < lengthof(_ttdpatch_flags) ? _ttdpatch_flags[index] : 0;
6111  *cond_val %= 0x20;
6112  return param_val;
6113  }
6114 
6115  case 0x88: // GRF ID check
6116  return 0;
6117 
6118  /* case 0x99: Global ID offset not implemented */
6119 
6120  default:
6121  /* GRF Parameter */
6122  if (param < 0x80) return _cur.grffile->GetParam(param);
6123 
6124  /* In-game variable. */
6125  grfmsg(1, "Unsupported in-game variable 0x%02X", param);
6126  return UINT_MAX;
6127  }
6128 }
6129 
6130 /* Action 0x06 */
6131 static void CfgApply(ByteReader *buf)
6132 {
6133  /* <06> <param-num> <param-size> <offset> ... <FF>
6134  *
6135  * B param-num Number of parameter to substitute (First = "zero")
6136  * Ignored if that parameter was not specified in newgrf.cfg
6137  * B param-size How many bytes to replace. If larger than 4, the
6138  * bytes of the following parameter are used. In that
6139  * case, nothing is applied unless *all* parameters
6140  * were specified.
6141  * B offset Offset into data from beginning of next sprite
6142  * to place where parameter is to be stored. */
6143 
6144  /* Preload the next sprite */
6145  size_t pos = FioGetPos();
6146  uint32 num = _cur.grf_container_ver >= 2 ? FioReadDword() : FioReadWord();
6147  uint8 type = FioReadByte();
6148  byte *preload_sprite = NULL;
6149 
6150  /* Check if the sprite is a pseudo sprite. We can't operate on real sprites. */
6151  if (type == 0xFF) {
6152  preload_sprite = MallocT<byte>(num);
6153  FioReadBlock(preload_sprite, num);
6154  }
6155 
6156  /* Reset the file position to the start of the next sprite */
6157  FioSeekTo(pos, SEEK_SET);
6158 
6159  if (type != 0xFF) {
6160  grfmsg(2, "CfgApply: Ignoring (next sprite is real, unsupported)");
6161  free(preload_sprite);
6162  return;
6163  }
6164 
6165  GRFLocation location(_cur.grfconfig->ident.grfid, _cur.nfo_line + 1);
6166  GRFLineToSpriteOverride::iterator it = _grf_line_to_action6_sprite_override.find(location);
6167  if (it != _grf_line_to_action6_sprite_override.end()) {
6168  free(preload_sprite);
6169  preload_sprite = _grf_line_to_action6_sprite_override[location];
6170  } else {
6171  _grf_line_to_action6_sprite_override[location] = preload_sprite;
6172  }
6173 
6174  /* Now perform the Action 0x06 on our data. */
6175 
6176  for (;;) {
6177  uint i;
6178  uint param_num;
6179  uint param_size;
6180  uint offset;
6181  bool add_value;
6182 
6183  /* Read the parameter to apply. 0xFF indicates no more data to change. */
6184  param_num = buf->ReadByte();
6185  if (param_num == 0xFF) break;
6186 
6187  /* Get the size of the parameter to use. If the size covers multiple
6188  * double words, sequential parameter values are used. */
6189  param_size = buf->ReadByte();
6190 
6191  /* Bit 7 of param_size indicates we should add to the original value
6192  * instead of replacing it. */
6193  add_value = HasBit(param_size, 7);
6194  param_size = GB(param_size, 0, 7);
6195 
6196  /* Where to apply the data to within the pseudo sprite data. */
6197  offset = buf->ReadExtendedByte();
6198 
6199  /* If the parameter is a GRF parameter (not an internal variable) check
6200  * if it (and all further sequential parameters) has been defined. */
6201  if (param_num < 0x80 && (param_num + (param_size - 1) / 4) >= _cur.grffile->param_end) {
6202  grfmsg(2, "CfgApply: Ignoring (param %d not set)", (param_num + (param_size - 1) / 4));
6203  break;
6204  }
6205 
6206  grfmsg(8, "CfgApply: Applying %u bytes from parameter 0x%02X at offset 0x%04X", param_size, param_num, offset);
6207 
6208  bool carry = false;
6209  for (i = 0; i < param_size && offset + i < num; i++) {
6210  uint32 value = GetParamVal(param_num + i / 4, NULL);
6211  /* Reset carry flag for each iteration of the variable (only really
6212  * matters if param_size is greater than 4) */
6213  if (i % 4 == 0) carry = false;
6214 
6215  if (add_value) {
6216  uint new_value = preload_sprite[offset + i] + GB(value, (i % 4) * 8, 8) + (carry ? 1 : 0);
6217  preload_sprite[offset + i] = GB(new_value, 0, 8);
6218  /* Check if the addition overflowed */
6219  carry = new_value >= 256;
6220  } else {
6221  preload_sprite[offset + i] = GB(value, (i % 4) * 8, 8);
6222  }
6223  }
6224  }
6225 }
6226 
6237 {
6238  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_STATIC_GRF_CAUSES_DESYNC, c);
6239  error->data = stredup(_cur.grfconfig->GetName());
6240 }
6241 
6242 /* Action 0x07
6243  * Action 0x09 */
6244 static void SkipIf(ByteReader *buf)
6245 {
6246  /* <07/09> <param-num> <param-size> <condition-type> <value> <num-sprites>
6247  *
6248  * B param-num
6249  * B param-size
6250  * B condition-type
6251  * V value
6252  * B num-sprites */
6253  uint32 cond_val = 0;
6254  uint32 mask = 0;
6255  bool result;
6256 
6257  uint8 param = buf->ReadByte();
6258  uint8 paramsize = buf->ReadByte();
6259  uint8 condtype = buf->ReadByte();
6260 
6261  if (condtype < 2) {
6262  /* Always 1 for bit tests, the given value should be ignored. */
6263  paramsize = 1;
6264  }
6265 
6266  switch (paramsize) {
6267  case 8: cond_val = buf->ReadDWord(); mask = buf->ReadDWord(); break;
6268  case 4: cond_val = buf->ReadDWord(); mask = 0xFFFFFFFF; break;
6269  case 2: cond_val = buf->ReadWord(); mask = 0x0000FFFF; break;
6270  case 1: cond_val = buf->ReadByte(); mask = 0x000000FF; break;
6271  default: break;
6272  }
6273 
6274  if (param < 0x80 && _cur.grffile->param_end <= param) {
6275  grfmsg(7, "SkipIf: Param %d undefined, skipping test", param);
6276  return;
6277  }
6278 
6279  uint32 param_val = GetParamVal(param, &cond_val);
6280 
6281  grfmsg(7, "SkipIf: Test condtype %d, param 0x%08X, condval 0x%08X", condtype, param_val, cond_val);
6282 
6283  /*
6284  * Parameter (variable in specs) 0x88 can only have GRF ID checking
6285  * conditions, except conditions 0x0B, 0x0C (cargo availability) and
6286  * 0x0D, 0x0E (Rail type availability) as those ignore the parameter.
6287  * So, when the condition type is one of those, the specific variable
6288  * 0x88 code is skipped, so the "general" code for the cargo
6289  * availability conditions kicks in.
6290  */
6291  if (param == 0x88 && (condtype < 0x0B || condtype > 0x0E)) {
6292  /* GRF ID checks */
6293 
6294  GRFConfig *c = GetGRFConfig(cond_val, mask);
6295 
6296  if (c != NULL && HasBit(c->flags, GCF_STATIC) && !HasBit(_cur.grfconfig->flags, GCF_STATIC) && _networking) {
6298  c = NULL;
6299  }
6300 
6301  if (condtype != 10 && c == NULL) {
6302  grfmsg(7, "SkipIf: GRFID 0x%08X unknown, skipping test", BSWAP32(cond_val));
6303  return;
6304  }
6305 
6306  switch (condtype) {
6307  /* Tests 0x06 to 0x0A are only for param 0x88, GRFID checks */
6308  case 0x06: // Is GRFID active?
6309  result = c->status == GCS_ACTIVATED;
6310  break;
6311 
6312  case 0x07: // Is GRFID non-active?
6313  result = c->status != GCS_ACTIVATED;
6314  break;
6315 
6316  case 0x08: // GRFID is not but will be active?
6317  result = c->status == GCS_INITIALISED;
6318  break;
6319 
6320  case 0x09: // GRFID is or will be active?
6321  result = c->status == GCS_ACTIVATED || c->status == GCS_INITIALISED;
6322  break;
6323 
6324  case 0x0A: // GRFID is not nor will be active
6325  /* This is the only condtype that doesn't get ignored if the GRFID is not found */
6326  result = c == NULL || c->status == GCS_DISABLED || c->status == GCS_NOT_FOUND;
6327  break;
6328 
6329  default: grfmsg(1, "SkipIf: Unsupported GRF condition type %02X. Ignoring", condtype); return;
6330  }
6331  } else {
6332  /* Parameter or variable tests */
6333  switch (condtype) {
6334  case 0x00: result = !!(param_val & (1 << cond_val));
6335  break;
6336  case 0x01: result = !(param_val & (1 << cond_val));
6337  break;
6338  case 0x02: result = (param_val & mask) == cond_val;
6339  break;
6340  case 0x03: result = (param_val & mask) != cond_val;
6341  break;
6342  case 0x04: result = (param_val & mask) < cond_val;
6343  break;
6344  case 0x05: result = (param_val & mask) > cond_val;
6345  break;
6346  case 0x0B: result = GetCargoIDByLabel(BSWAP32(cond_val)) == CT_INVALID;
6347  break;
6348  case 0x0C: result = GetCargoIDByLabel(BSWAP32(cond_val)) != CT_INVALID;
6349  break;
6350  case 0x0D: result = GetRailTypeByLabel(BSWAP32(cond_val)) == INVALID_RAILTYPE;
6351  break;
6352  case 0x0E: result = GetRailTypeByLabel(BSWAP32(cond_val)) != INVALID_RAILTYPE;
6353  break;
6354 
6355  default: grfmsg(1, "SkipIf: Unsupported condition type %02X. Ignoring", condtype); return;
6356  }
6357  }
6358 
6359  if (!result) {
6360  grfmsg(2, "SkipIf: Not skipping sprites, test was false");
6361  return;
6362  }
6363 
6364  uint8 numsprites = buf->ReadByte();
6365 
6366  /* numsprites can be a GOTO label if it has been defined in the GRF
6367  * file. The jump will always be the first matching label that follows
6368  * the current nfo_line. If no matching label is found, the first matching
6369  * label in the file is used. */
6370  GRFLabel *choice = NULL;
6371  for (GRFLabel *label = _cur.grffile->label; label != NULL; label = label->next) {
6372  if (label->label != numsprites) continue;
6373 
6374  /* Remember a goto before the current line */
6375  if (choice == NULL) choice = label;
6376  /* If we find a label here, this is definitely good */
6377  if (label->nfo_line > _cur.nfo_line) {
6378  choice = label;
6379  break;
6380  }
6381  }
6382 
6383  if (choice != NULL) {
6384  grfmsg(2, "SkipIf: Jumping to label 0x%0X at line %d, test was true", choice->label, choice->nfo_line);
6385  FioSeekTo(choice->pos, SEEK_SET);
6386  _cur.nfo_line = choice->nfo_line;
6387  return;
6388  }
6389 
6390  grfmsg(2, "SkipIf: Skipping %d sprites, test was true", numsprites);
6391  _cur.skip_sprites = numsprites;
6392  if (_cur.skip_sprites == 0) {
6393  /* Zero means there are no sprites to skip, so
6394  * we use -1 to indicate that all further
6395  * sprites should be skipped. */
6396  _cur.skip_sprites = -1;
6397 
6398  /* If an action 8 hasn't been encountered yet, disable the grf. */
6399  if (_cur.grfconfig->status != (_cur.stage < GLS_RESERVE ? GCS_INITIALISED : GCS_ACTIVATED)) {
6400  DisableGrf();
6401  }
6402  }
6403 }
6404 
6405 
6406 /* Action 0x08 (GLS_FILESCAN) */
6407 static void ScanInfo(ByteReader *buf)
6408 {
6409  uint8 grf_version = buf->ReadByte();
6410  uint32 grfid = buf->ReadDWord();
6411  const char *name = buf->ReadString();
6412 
6413  _cur.grfconfig->ident.grfid = grfid;
6414 
6415  if (grf_version < 2 || grf_version > 8) {
6417  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);
6418  }
6419 
6420  /* GRF IDs starting with 0xFF are reserved for internal TTDPatch use */
6421  if (GB(grfid, 0, 8) == 0xFF) SetBit(_cur.grfconfig->flags, GCF_SYSTEM);
6422 
6423  AddGRFTextToList(&_cur.grfconfig->name->text, 0x7F, grfid, false, name);
6424 
6425  if (buf->HasData()) {
6426  const char *info = buf->ReadString();
6427  AddGRFTextToList(&_cur.grfconfig->info->text, 0x7F, grfid, true, info);
6428  }
6429 
6430  /* GLS_INFOSCAN only looks for the action 8, so we can skip the rest of the file */
6431  _cur.skip_sprites = -1;
6432 }
6433 
6434 /* Action 0x08 */
6435 static void GRFInfo(ByteReader *buf)
6436 {
6437  /* <08> <version> <grf-id> <name> <info>
6438  *
6439  * B version newgrf version, currently 06
6440  * 4*B grf-id globally unique ID of this .grf file
6441  * S name name of this .grf set
6442  * S info string describing the set, and e.g. author and copyright */
6443 
6444  uint8 version = buf->ReadByte();
6445  uint32 grfid = buf->ReadDWord();
6446  const char *name = buf->ReadString();
6447 
6448  if (_cur.stage < GLS_RESERVE && _cur.grfconfig->status != GCS_UNKNOWN) {
6449  DisableGrf(STR_NEWGRF_ERROR_MULTIPLE_ACTION_8);
6450  return;
6451  }
6452 
6453  if (_cur.grffile->grfid != grfid) {
6454  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));
6455  _cur.grffile->grfid = grfid;
6456  }
6457 
6458  _cur.grffile->grf_version = version;
6459  _cur.grfconfig->status = _cur.stage < GLS_RESERVE ? GCS_INITIALISED : GCS_ACTIVATED;
6460 
6461  /* Do swap the GRFID for displaying purposes since people expect that */
6462  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);
6463 }
6464 
6465 /* Action 0x0A */
6466 static void SpriteReplace(ByteReader *buf)
6467 {
6468  /* <0A> <num-sets> <set1> [<set2> ...]
6469  * <set>: <num-sprites> <first-sprite>
6470  *
6471  * B num-sets How many sets of sprites to replace.
6472  * Each set:
6473  * B num-sprites How many sprites are in this set
6474  * W first-sprite First sprite number to replace */
6475 
6476  uint8 num_sets = buf->ReadByte();
6477 
6478  for (uint i = 0; i < num_sets; i++) {
6479  uint8 num_sprites = buf->ReadByte();
6480  uint16 first_sprite = buf->ReadWord();
6481 
6482  grfmsg(2, "SpriteReplace: [Set %d] Changing %d sprites, beginning with %d",
6483  i, num_sprites, first_sprite
6484  );
6485 
6486  for (uint j = 0; j < num_sprites; j++) {
6487  int load_index = first_sprite + j;
6488  _cur.nfo_line++;
6489  LoadNextSprite(load_index, _cur.file_index, _cur.nfo_line, _cur.grf_container_ver); // XXX
6490 
6491  /* Shore sprites now located at different addresses.
6492  * So detect when the old ones get replaced. */
6493  if (IsInsideMM(load_index, SPR_ORIGINALSHORE_START, SPR_ORIGINALSHORE_END + 1)) {
6494  if (_loaded_newgrf_features.shore != SHORE_REPLACE_ACTION_5) _loaded_newgrf_features.shore = SHORE_REPLACE_ACTION_A;
6495  }
6496  }
6497  }
6498 }
6499 
6500 /* Action 0x0A (SKIP) */
6501 static void SkipActA(ByteReader *buf)
6502 {
6503  uint8 num_sets = buf->ReadByte();
6504 
6505  for (uint i = 0; i < num_sets; i++) {
6506  /* Skip the sprites this replaces */
6507  _cur.skip_sprites += buf->ReadByte();
6508  /* But ignore where they go */
6509  buf->ReadWord();
6510  }
6511 
6512  grfmsg(3, "SkipActA: Skipping %d sprites", _cur.skip_sprites);
6513 }
6514 
6515 /* Action 0x0B */
6516 static void GRFLoadError(ByteReader *buf)
6517 {
6518  /* <0B> <severity> <language-id> <message-id> [<message...> 00] [<data...>] 00 [<parnum>]
6519  *
6520  * B severity 00: notice, contine loading grf file
6521  * 01: warning, continue loading grf file
6522  * 02: error, but continue loading grf file, and attempt
6523  * loading grf again when loading or starting next game
6524  * 03: error, abort loading and prevent loading again in
6525  * the future (only when restarting the patch)
6526  * B language-id see action 4, use 1F for built-in error messages
6527  * B message-id message to show, see below
6528  * S message for custom messages (message-id FF), text of the message
6529  * not present for built-in messages.
6530  * V data additional data for built-in (or custom) messages
6531  * B parnum parameter numbers to be shown in the message (maximum of 2) */
6532 
6533  static const StringID msgstr[] = {
6534  STR_NEWGRF_ERROR_VERSION_NUMBER,
6535  STR_NEWGRF_ERROR_DOS_OR_WINDOWS,
6536  STR_NEWGRF_ERROR_UNSET_SWITCH,
6537  STR_NEWGRF_ERROR_INVALID_PARAMETER,
6538  STR_NEWGRF_ERROR_LOAD_BEFORE,
6539  STR_NEWGRF_ERROR_LOAD_AFTER,
6540  STR_NEWGRF_ERROR_OTTD_VERSION_NUMBER,
6541  };
6542 
6543  static const StringID sevstr[] = {
6544  STR_NEWGRF_ERROR_MSG_INFO,
6545  STR_NEWGRF_ERROR_MSG_WARNING,
6546  STR_NEWGRF_ERROR_MSG_ERROR,
6547  STR_NEWGRF_ERROR_MSG_FATAL
6548  };
6549 
6550  byte severity = buf->ReadByte();
6551  byte lang = buf->ReadByte();
6552  byte message_id = buf->ReadByte();
6553 
6554  /* Skip the error if it isn't valid for the current language. */
6555  if (!CheckGrfLangID(lang, _cur.grffile->grf_version)) return;
6556 
6557  /* Skip the error until the activation stage unless bit 7 of the severity
6558  * is set. */
6559  if (!HasBit(severity, 7) && _cur.stage == GLS_INIT) {
6560  grfmsg(7, "GRFLoadError: Skipping non-fatal GRFLoadError in stage %d", _cur.stage);
6561  return;
6562  }
6563  ClrBit(severity, 7);
6564 
6565  if (severity >= lengthof(sevstr)) {
6566  grfmsg(7, "GRFLoadError: Invalid severity id %d. Setting to 2 (non-fatal error).", severity);
6567  severity = 2;
6568  } else if (severity == 3) {
6569  /* This is a fatal error, so make sure the GRF is deactivated and no
6570  * more of it gets loaded. */
6571  DisableGrf();
6572 
6573  /* Make sure we show fatal errors, instead of silly infos from before */
6574  delete _cur.grfconfig->error;
6575  _cur.grfconfig->error = NULL;
6576  }
6577 
6578  if (message_id >= lengthof(msgstr) && message_id != 0xFF) {
6579  grfmsg(7, "GRFLoadError: Invalid message id.");
6580  return;
6581  }
6582 
6583  if (buf->Remaining() <= 1) {
6584  grfmsg(7, "GRFLoadError: No message data supplied.");
6585  return;
6586  }
6587 
6588  /* For now we can only show one message per newgrf file. */
6589  if (_cur.grfconfig->error != NULL) return;
6590 
6591  GRFError *error = new GRFError(sevstr[severity]);
6592 
6593  if (message_id == 0xFF) {
6594  /* This is a custom error message. */
6595  if (buf->HasData()) {
6596  const char *message = buf->ReadString();
6597 
6598  error->custom_message = TranslateTTDPatchCodes(_cur.grffile->grfid, lang, true, message, NULL, SCC_RAW_STRING_POINTER);
6599  } else {
6600  grfmsg(7, "GRFLoadError: No custom message supplied.");
6601  error->custom_message = stredup("");
6602  }
6603  } else {
6604  error->message = msgstr[message_id];
6605  }
6606 
6607  if (buf->HasData()) {
6608  const char *data = buf->ReadString();
6609 
6610  error->data = TranslateTTDPatchCodes(_cur.grffile->grfid, lang, true, data);
6611  } else {
6612  grfmsg(7, "GRFLoadError: No message data supplied.");
6613  error->data = stredup("");
6614  }
6615 
6616  /* Only two parameter numbers can be used in the string. */
6617  for (uint i = 0; i < lengthof(error->param_value) && buf->HasData(); i++) {
6618  uint param_number = buf->ReadByte();
6619  error->param_value[i] = _cur.grffile->GetParam(param_number);
6620  }
6621 
6622  _cur.grfconfig->error = error;
6623 }
6624 
6625 /* Action 0x0C */
6626 static void GRFComment(ByteReader *buf)
6627 {
6628  /* <0C> [<ignored...>]
6629  *
6630  * V ignored Anything following the 0C is ignored */
6631 
6632  if (!buf->HasData()) return;
6633 
6634  const char *text = buf->ReadString();
6635  grfmsg(2, "GRFComment: %s", text);
6636 }
6637 
6638 /* Action 0x0D (GLS_SAFETYSCAN) */
6639 static void SafeParamSet(ByteReader *buf)
6640 {
6641  uint8 target = buf->ReadByte();
6642 
6643  /* Writing GRF parameters and some bits of 'misc GRF features' are safe. */
6644  if (target < 0x80 || target == 0x9E) return;
6645 
6646  /* GRM could be unsafe, but as here it can only happen after other GRFs
6647  * are loaded, it should be okay. If the GRF tried to use the slots it
6648  * reserved, it would be marked unsafe anyway. GRM for (e.g. bridge)
6649  * sprites is considered safe. */
6650 
6651  SetBit(_cur.grfconfig->flags, GCF_UNSAFE);
6652 
6653  /* Skip remainder of GRF */
6654  _cur.skip_sprites = -1;
6655 }
6656 
6657 
6658 static uint32 GetPatchVariable(uint8 param)
6659 {
6660  switch (param) {
6661  /* start year - 1920 */
6663 
6664  /* freight trains weight factor */
6665  case 0x0E: return _settings_game.vehicle.freight_trains;
6666 
6667  /* empty wagon speed increase */
6668  case 0x0F: return 0;
6669 
6670  /* plane speed factor; our patch option is reversed from TTDPatch's,
6671  * the following is good for 1x, 2x and 4x (most common?) and...
6672  * well not really for 3x. */
6673  case 0x10:
6675  default:
6676  case 4: return 1;
6677  case 3: return 2;
6678  case 2: return 2;
6679  case 1: return 4;
6680  }
6681 
6682 
6683  /* 2CC colourmap base sprite */
6684  case 0x11: return SPR_2CCMAP_BASE;
6685 
6686  /* map size: format = -MABXYSS
6687  * M : the type of map
6688  * bit 0 : set : squared map. Bit 1 is now not relevant
6689  * clear : rectangle map. Bit 1 will indicate the bigger edge of the map
6690  * bit 1 : set : Y is the bigger edge. Bit 0 is clear
6691  * clear : X is the bigger edge.
6692  * A : minimum edge(log2) of the map
6693  * B : maximum edge(log2) of the map
6694  * XY : edges(log2) of each side of the map.
6695  * SS : combination of both X and Y, thus giving the size(log2) of the map
6696  */
6697  case 0x13: {
6698  byte map_bits = 0;
6699  byte log_X = MapLogX() - 6; // substraction is required to make the minimal size (64) zero based
6700  byte log_Y = MapLogY() - 6;
6701  byte max_edge = max(log_X, log_Y);
6702 
6703  if (log_X == log_Y) { // we have a squared map, since both edges are identical
6704  SetBit(map_bits, 0);
6705  } else {
6706  if (max_edge == log_Y) SetBit(map_bits, 1); // edge Y been the biggest, mark it
6707  }
6708 
6709  return (map_bits << 24) | (min(log_X, log_Y) << 20) | (max_edge << 16) |
6710  (log_X << 12) | (log_Y << 8) | (log_X + log_Y);
6711  }
6712 
6713  /* The maximum height of the map. */
6714  case 0x14:
6716 
6717  /* Extra foundations base sprite */
6718  case 0x15:
6719  return SPR_SLOPES_BASE;
6720 
6721  /* Shore base sprite */
6722  case 0x16:
6723  return SPR_SHORE_BASE;
6724 
6725  default:
6726  grfmsg(2, "ParamSet: Unknown Patch variable 0x%02X.", param);
6727  return 0;
6728  }
6729 }
6730 
6731 
6732 static uint32 PerformGRM(uint32 *grm, uint16 num_ids, uint16 count, uint8 op, uint8 target, const char *type)
6733 {
6734  uint start = 0;
6735  uint size = 0;
6736 
6737  if (op == 6) {
6738  /* Return GRFID of set that reserved ID */
6739  return grm[_cur.grffile->GetParam(target)];
6740  }
6741 
6742  /* With an operation of 2 or 3, we want to reserve a specific block of IDs */
6743  if (op == 2 || op == 3) start = _cur.grffile->GetParam(target);
6744 
6745  for (uint i = start; i < num_ids; i++) {
6746  if (grm[i] == 0) {
6747  size++;
6748  } else {
6749  if (op == 2 || op == 3) break;
6750  start = i + 1;
6751  size = 0;
6752  }
6753 
6754  if (size == count) break;
6755  }
6756 
6757  if (size == count) {
6758  /* Got the slot... */
6759  if (op == 0 || op == 3) {
6760  grfmsg(2, "ParamSet: GRM: Reserving %d %s at %d", count, type, start);
6761  for (uint i = 0; i < count; i++) grm[start + i] = _cur.grffile->grfid;
6762  }
6763  return start;
6764  }
6765 
6766  /* Unable to allocate */
6767  if (op != 4 && op != 5) {
6768  /* Deactivate GRF */
6769  grfmsg(0, "ParamSet: GRM: Unable to allocate %d %s, deactivating", count, type);
6770  DisableGrf(STR_NEWGRF_ERROR_GRM_FAILED);
6771  return UINT_MAX;
6772  }
6773 
6774  grfmsg(1, "ParamSet: GRM: Unable to allocate %d %s", count, type);
6775  return UINT_MAX;
6776 }
6777 
6778 
6780 static void ParamSet(ByteReader *buf)
6781 {
6782  /* <0D> <target> <operation> <source1> <source2> [<data>]
6783  *
6784  * B target parameter number where result is stored
6785  * B operation operation to perform, see below
6786  * B source1 first source operand
6787  * B source2 second source operand
6788  * D data data to use in the calculation, not necessary
6789  * if both source1 and source2 refer to actual parameters
6790  *
6791  * Operations
6792  * 00 Set parameter equal to source1
6793  * 01 Addition, source1 + source2
6794  * 02 Subtraction, source1 - source2
6795  * 03 Unsigned multiplication, source1 * source2 (both unsigned)
6796  * 04 Signed multiplication, source1 * source2 (both signed)
6797  * 05 Unsigned bit shift, source1 by source2 (source2 taken to be a
6798  * signed quantity; left shift if positive and right shift if
6799  * negative, source1 is unsigned)
6800  * 06 Signed bit shift, source1 by source2
6801  * (source2 like in 05, and source1 as well)
6802  */
6803 
6804  uint8 target = buf->ReadByte();
6805  uint8 oper = buf->ReadByte();
6806  uint32 src1 = buf->ReadByte();
6807  uint32 src2 = buf->ReadByte();
6808 
6809  uint32 data = 0;
6810  if (buf->Remaining() >= 4) data = buf->ReadDWord();
6811 
6812  /* You can add 80 to the operation to make it apply only if the target
6813  * is not defined yet. In this respect, a parameter is taken to be
6814  * defined if any of the following applies:
6815  * - it has been set to any value in the newgrf(w).cfg parameter list
6816  * - it OR A PARAMETER WITH HIGHER NUMBER has been set to any value by
6817  * an earlier action D */
6818  if (HasBit(oper, 7)) {
6819  if (target < 0x80 && target < _cur.grffile->param_end) {
6820  grfmsg(7, "ParamSet: Param %u already defined, skipping", target);
6821  return;
6822  }
6823 
6824  oper = GB(oper, 0, 7);
6825  }
6826 
6827  if (src2 == 0xFE) {
6828  if (GB(data, 0, 8) == 0xFF) {
6829  if (data == 0x0000FFFF) {
6830  /* Patch variables */
6831  src1 = GetPatchVariable(src1);
6832  } else {
6833  /* GRF Resource Management */
6834  uint8 op = src1;
6835  uint8 feature = GB(data, 8, 8);
6836  uint16 count = GB(data, 16, 16);
6837 
6838  if (_cur.stage == GLS_RESERVE) {
6839  if (feature == 0x08) {
6840  /* General sprites */
6841  if (op == 0) {
6842  /* Check if the allocated sprites will fit below the original sprite limit */
6843  if (_cur.spriteid + count >= 16384) {
6844  grfmsg(0, "ParamSet: GRM: Unable to allocate %d sprites; try changing NewGRF order", count);
6845  DisableGrf(STR_NEWGRF_ERROR_GRM_FAILED);
6846  return;
6847  }
6848 
6849  /* Reserve space at the current sprite ID */
6850  grfmsg(4, "ParamSet: GRM: Allocated %d sprites at %d", count, _cur.spriteid);
6851  _grm_sprites[GRFLocation(_cur.grffile->grfid, _cur.nfo_line)] = _cur.spriteid;
6852  _cur.spriteid += count;
6853  }
6854  }
6855  /* Ignore GRM result during reservation */
6856  src1 = 0;
6857  } else if (_cur.stage == GLS_ACTIVATION) {
6858  switch (feature) {
6859  case 0x00: // Trains
6860  case 0x01: // Road Vehicles
6861  case 0x02: // Ships
6862  case 0x03: // Aircraft
6864  src1 = PerformGRM(&_grm_engines[_engine_offsets[feature]], _engine_counts[feature], count, op, target, "vehicles");
6865  if (_cur.skip_sprites == -1) return;
6866  } else {
6867  /* GRM does not apply for dynamic engine allocation. */
6868  switch (op) {
6869  case 2:
6870  case 3:
6871  src1 = _cur.grffile->GetParam(target);
6872  break;
6873 
6874  default:
6875  src1 = 0;
6876  break;
6877  }
6878  }
6879  break;
6880 
6881  case 0x08: // General sprites
6882  switch (op) {
6883  case 0:
6884  /* Return space reserved during reservation stage */
6885  src1 = _grm_sprites[GRFLocation(_cur.grffile->grfid, _cur.nfo_line)];
6886  grfmsg(4, "ParamSet: GRM: Using pre-allocated sprites at %d", src1);
6887  break;
6888 
6889  case 1:
6890  src1 = _cur.spriteid;
6891  break;
6892 
6893  default:
6894  grfmsg(1, "ParamSet: GRM: Unsupported operation %d for general sprites", op);
6895  return;
6896  }
6897  break;
6898 
6899  case 0x0B: // Cargo
6900  /* There are two ranges: one for cargo IDs and one for cargo bitmasks */
6901  src1 = PerformGRM(_grm_cargoes, NUM_CARGO * 2, count, op, target, "cargoes");
6902  if (_cur.skip_sprites == -1) return;
6903  break;
6904 
6905  default: grfmsg(1, "ParamSet: GRM: Unsupported feature 0x%X", feature); return;
6906  }
6907  } else {
6908  /* Ignore GRM during initialization */
6909  src1 = 0;
6910  }
6911  }
6912  } else {
6913  /* Read another GRF File's parameter */
6914  const GRFFile *file = GetFileByGRFID(data);
6915  GRFConfig *c = GetGRFConfig(data);
6916  if (c != NULL && HasBit(c->flags, GCF_STATIC) && !HasBit(_cur.grfconfig->flags, GCF_STATIC) && _networking) {
6917  /* Disable the read GRF if it is a static NewGRF. */
6919  src1 = 0;
6920  } else if (file == NULL || c == NULL || c->status == GCS_DISABLED) {
6921  src1 = 0;
6922  } else if (src1 == 0xFE) {
6923  src1 = c->version;
6924  } else {
6925  src1 = file->GetParam(src1);
6926  }
6927  }
6928  } else {
6929  /* The source1 and source2 operands refer to the grf parameter number
6930  * like in action 6 and 7. In addition, they can refer to the special
6931  * variables available in action 7, or they can be FF to use the value
6932  * of <data>. If referring to parameters that are undefined, a value
6933  * of 0 is used instead. */
6934  src1 = (src1 == 0xFF) ? data : GetParamVal(src1, NULL);
6935  src2 = (src2 == 0xFF) ? data : GetParamVal(src2, NULL);
6936  }
6937 
6938  uint32 res;
6939  switch (oper) {
6940  case 0x00:
6941  res = src1;
6942  break;
6943 
6944  case 0x01:
6945  res = src1 + src2;
6946  break;
6947 
6948  case 0x02:
6949  res = src1 - src2;
6950  break;
6951 
6952  case 0x03:
6953  res = src1 * src2;
6954  break;
6955 
6956  case 0x04:
6957  res = (int32)src1 * (int32)src2;
6958  break;
6959 
6960  case 0x05:
6961  if ((int32)src2 < 0) {
6962  res = src1 >> -(int32)src2;
6963  } else {
6964  res = src1 << (src2 & 0x1F); // Same behaviour as in EvalAdjustT, mask 'value' to 5 bits, which should behave the same on all architectures.
6965  }
6966  break;
6967 
6968  case 0x06:
6969  if ((int32)src2 < 0) {
6970  res = (int32)src1 >> -(int32)src2;
6971  } else {
6972  res = (int32)src1 << (src2 & 0x1F); // Same behaviour as in EvalAdjustT, mask 'value' to 5 bits, which should behave the same on all architectures.
6973  }
6974  break;
6975 
6976  case 0x07: // Bitwise AND
6977  res = src1 & src2;
6978  break;
6979 
6980  case 0x08: // Bitwise OR
6981  res = src1 | src2;
6982  break;
6983 
6984  case 0x09: // Unsigned division
6985  if (src2 == 0) {
6986  res = src1;
6987  } else {
6988  res = src1 / src2;
6989  }
6990  break;
6991 
6992  case 0x0A: // Signed divison
6993  if (src2 == 0) {
6994  res = src1;
6995  } else {
6996  res = (int32)src1 / (int32)src2;
6997  }
6998  break;
6999 
7000  case 0x0B: // Unsigned modulo
7001  if (src2 == 0) {
7002  res = src1;
7003  } else {
7004  res = src1 % src2;
7005  }
7006  break;
7007 
7008  case 0x0C: // Signed modulo
7009  if (src2 == 0) {
7010  res = src1;
7011  } else {
7012  res = (int32)src1 % (int32)src2;
7013  }
7014  break;
7015 
7016  default: grfmsg(0, "ParamSet: Unknown operation %d, skipping", oper); return;
7017  }
7018 
7019  switch (target) {
7020  case 0x8E: // Y-Offset for train sprites
7021  _cur.grffile->traininfo_vehicle_pitch = res;
7022  break;
7023 
7024  case 0x8F: { // Rail track type cost factors
7025  extern RailtypeInfo _railtypes[RAILTYPE_END];
7026  _railtypes[RAILTYPE_RAIL].cost_multiplier = GB(res, 0, 8);
7028  _railtypes[RAILTYPE_ELECTRIC].cost_multiplier = GB(res, 0, 8);
7029  _railtypes[RAILTYPE_MONO].cost_multiplier = GB(res, 8, 8);
7030  } else {
7031  _railtypes[RAILTYPE_ELECTRIC].cost_multiplier = GB(res, 8, 8);
7032  _railtypes[RAILTYPE_MONO].cost_multiplier = GB(res, 16, 8);
7033  }
7034  _railtypes[RAILTYPE_MAGLEV].cost_multiplier = GB(res, 16, 8);
7035  break;
7036  }
7037 
7038  /* not implemented */
7039  case 0x93: // Tile refresh offset to left -- Intended to allow support for larger sprites, not necessary for OTTD
7040  case 0x94: // Tile refresh offset to right
7041  case 0x95: // Tile refresh offset upwards
7042  case 0x96: // Tile refresh offset downwards
7043  case 0x97: // Snow line height -- Better supported by feature 8 property 10h (snow line table) TODO: implement by filling the entire snow line table with the given value
7044  case 0x99: // Global ID offset -- Not necessary since IDs are remapped automatically
7045  grfmsg(7, "ParamSet: Skipping unimplemented target 0x%02X", target);
7046  break;
7047 
7048  case 0x9E: // Miscellaneous GRF features
7049  /* Set train list engine width */
7050  _cur.grffile->traininfo_vehicle_width = HasBit(res, GMB_TRAIN_WIDTH_32_PIXELS) ? VEHICLEINFO_FULL_VEHICLE_WIDTH : TRAININFO_DEFAULT_VEHICLE_WIDTH;
7051  /* Remove the local flags from the global flags */
7053 
7054  /* Only copy safe bits for static grfs */
7055  if (HasBit(_cur.grfconfig->flags, GCF_STATIC)) {
7056  uint32 safe_bits = 0;
7057  SetBit(safe_bits, GMB_SECOND_ROCKY_TILE_SET);
7058 
7059  _misc_grf_features = (_misc_grf_features & ~safe_bits) | (res & safe_bits);
7060  } else {
7061  _misc_grf_features = res;
7062  }
7063  break;
7064 
7065  case 0x9F: // locale-dependent settings
7066  grfmsg(7, "ParamSet: Skipping unimplemented target 0x%02X", target);
7067  break;
7068 
7069  default:
7070  if (target < 0x80) {
7071  _cur.grffile->param[target] = res;
7072  /* param is zeroed by default */
7073  if (target + 1U > _cur.grffile->param_end) _cur.grffile->param_end = target + 1;
7074  } else {
7075  grfmsg(7, "ParamSet: Skipping unknown target 0x%02X", target);
7076  }
7077  break;
7078  }
7079 }
7080 
7081 /* Action 0x0E (GLS_SAFETYSCAN) */
7082 static void SafeGRFInhibit(ByteReader *buf)
7083 {
7084  /* <0E> <num> <grfids...>
7085  *
7086  * B num Number of GRFIDs that follow
7087  * D grfids GRFIDs of the files to deactivate */
7088 
7089  uint8 num = buf->ReadByte();
7090 
7091  for (uint i = 0; i < num; i++) {
7092  uint32 grfid = buf->ReadDWord();
7093 
7094  /* GRF is unsafe it if tries to deactivate other GRFs */
7095  if (grfid != _cur.grfconfig->ident.grfid) {
7096  SetBit(_cur.grfconfig->flags, GCF_UNSAFE);
7097 
7098  /* Skip remainder of GRF */
7099  _cur.skip_sprites = -1;
7100 
7101  return;
7102  }
7103  }
7104 }
7105 
7106 /* Action 0x0E */
7107 static void GRFInhibit(ByteReader *buf)
7108 {
7109  /* <0E> <num> <grfids...>
7110  *
7111  * B num Number of GRFIDs that follow
7112  * D grfids GRFIDs of the files to deactivate */
7113 
7114  uint8 num = buf->ReadByte();
7115 
7116  for (uint i = 0; i < num; i++) {
7117  uint32 grfid = buf->ReadDWord();
7118  GRFConfig *file = GetGRFConfig(grfid);
7119 
7120  /* Unset activation flag */
7121  if (file != NULL && file != _cur.grfconfig) {
7122  grfmsg(2, "GRFInhibit: Deactivating file '%s'", file->filename);
7123  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_FORCEFULLY_DISABLED, file);
7124  error->data = stredup(_cur.grfconfig->GetName());
7125  }
7126  }
7127 }
7128 
7130 static void FeatureTownName(ByteReader *buf)
7131 {
7132  /* <0F> <id> <style-name> <num-parts> <parts>
7133  *
7134  * B id ID of this definition in bottom 7 bits (final definition if bit 7 set)
7135  * V style-name Name of the style (only for final definition)
7136  * B num-parts Number of parts in this definition
7137  * V parts The parts */
7138 
7139  uint32 grfid = _cur.grffile->grfid;
7140 
7141  GRFTownName *townname = AddGRFTownName(grfid);
7142 
7143  byte id = buf->ReadByte();
7144  grfmsg(6, "FeatureTownName: definition 0x%02X", id & 0x7F);
7145 
7146  if (HasBit(id, 7)) {
7147  /* Final definition */
7148  ClrBit(id, 7);
7149  bool new_scheme = _cur.grffile->grf_version >= 7;
7150 
7151  byte lang = buf->ReadByte();
7152 
7153  byte nb_gen = townname->nb_gen;
7154  do {
7155  ClrBit(lang, 7);
7156 
7157  const char *name = buf->ReadString();
7158 
7159  char *lang_name = TranslateTTDPatchCodes(grfid, lang, false, name);
7160  grfmsg(6, "FeatureTownName: lang 0x%X -> '%s'", lang, lang_name);
7161  free(lang_name);
7162 
7163  townname->name[nb_gen] = AddGRFString(grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
7164 
7165  lang = buf->ReadByte();
7166  } while (lang != 0);
7167  townname->id[nb_gen] = id;
7168  townname->nb_gen++;
7169  }
7170 
7171  byte nb = buf->ReadByte();
7172  grfmsg(6, "FeatureTownName: %u parts", nb);
7173 
7174  townname->nbparts[id] = nb;
7175  townname->partlist[id] = CallocT<NamePartList>(nb);
7176 
7177  for (int i = 0; i < nb; i++) {
7178  byte nbtext = buf->ReadByte();
7179  townname->partlist[id][i].bitstart = buf->ReadByte();
7180  townname->partlist[id][i].bitcount = buf->ReadByte();
7181  townname->partlist[id][i].maxprob = 0;
7182  townname->partlist[id][i].partcount = nbtext;
7183  townname->partlist[id][i].parts = CallocT<NamePart>(nbtext);
7184  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);
7185 
7186  for (int j = 0; j < nbtext; j++) {
7187  byte prob = buf->ReadByte();
7188 
7189  if (HasBit(prob, 7)) {
7190  byte ref_id = buf->ReadByte();
7191 
7192  if (townname->nbparts[ref_id] == 0) {
7193  grfmsg(0, "FeatureTownName: definition 0x%02X doesn't exist, deactivating", ref_id);
7194  DelGRFTownName(grfid);
7195  DisableGrf(STR_NEWGRF_ERROR_INVALID_ID);
7196  return;
7197  }
7198 
7199  grfmsg(6, "FeatureTownName: part %d, text %d, uses intermediate definition 0x%02X (with probability %d)", i, j, ref_id, prob & 0x7F);
7200  townname->partlist[id][i].parts[j].data.id = ref_id;
7201  } else {
7202  const char *text = buf->ReadString();
7203  townname->partlist[id][i].parts[j].data.text = TranslateTTDPatchCodes(grfid, 0, false, text);
7204  grfmsg(6, "FeatureTownName: part %d, text %d, '%s' (with probability %d)", i, j, townname->partlist[id][i].parts[j].data.text, prob);
7205  }
7206  townname->partlist[id][i].parts[j].prob = prob;
7207  townname->partlist[id][i].maxprob += GB(prob, 0, 7);
7208  }
7209  grfmsg(6, "FeatureTownName: part %d, total probability %d", i, townname->partlist[id][i].maxprob);
7210  }
7211 }
7212 
7214 static void DefineGotoLabel(ByteReader *buf)
7215 {
7216  /* <10> <label> [<comment>]
7217  *
7218  * B label The label to define
7219  * V comment Optional comment - ignored */
7220 
7221  byte nfo_label = buf->ReadByte();
7222 
7223  GRFLabel *label = MallocT<GRFLabel>(1);
7224  label->label = nfo_label;
7225  label->nfo_line = _cur.nfo_line;
7226  label->pos = FioGetPos();
7227  label->next = NULL;
7228 
7229  /* Set up a linked list of goto targets which we will search in an Action 0x7/0x9 */
7230  if (_cur.grffile->label == NULL) {
7231  _cur.grffile->label = label;
7232  } else {
7233  /* Attach the label to the end of the list */
7234  GRFLabel *l;
7235  for (l = _cur.grffile->label; l->next != NULL; l = l->next) {}
7236  l->next = label;
7237  }
7238 
7239  grfmsg(2, "DefineGotoLabel: GOTO target with label 0x%02X", label->label);
7240 }
7241 
7246 static void ImportGRFSound(SoundEntry *sound)
7247 {
7248  const GRFFile *file;
7249  uint32 grfid = FioReadDword();
7250  SoundID sound_id = FioReadWord();
7251 
7252  file = GetFileByGRFID(grfid);
7253  if (file == NULL || file->sound_offset == 0) {
7254  grfmsg(1, "ImportGRFSound: Source file not available");
7255  return;
7256  }
7257 
7258  if (sound_id >= file->num_sounds) {
7259  grfmsg(1, "ImportGRFSound: Sound effect %d is invalid", sound_id);
7260  return;
7261  }
7262 
7263  grfmsg(2, "ImportGRFSound: Copying sound %d (%d) from file %X", sound_id, file->sound_offset + sound_id, grfid);
7264 
7265  *sound = *GetSound(file->sound_offset + sound_id);
7266 
7267  /* Reset volume and priority, which TTDPatch doesn't copy */
7268  sound->volume = 128;
7269  sound->priority = 0;
7270 }
7271 
7277 static void LoadGRFSound(size_t offs, SoundEntry *sound)
7278 {
7279  /* Set default volume and priority */
7280  sound->volume = 0x80;
7281  sound->priority = 0;
7282 
7283  if (offs != SIZE_MAX) {
7284  /* Sound is present in the NewGRF. */
7285  sound->file_slot = _cur.file_index;
7286  sound->file_offset = offs;
7287  sound->grf_container_ver = _cur.grf_container_ver;
7288  }
7289 }
7290 
7291 /* Action 0x11 */
7292 static void GRFSound(ByteReader *buf)
7293 {
7294  /* <11> <num>
7295  *
7296  * W num Number of sound files that follow */
7297 
7298  uint16 num = buf->ReadWord();
7299  if (num == 0) return;
7300 
7301  SoundEntry *sound;
7302  if (_cur.grffile->sound_offset == 0) {
7303  _cur.grffile->sound_offset = GetNumSounds();
7304  _cur.grffile->num_sounds = num;
7305  sound = AllocateSound(num);
7306  } else {
7307  sound = GetSound(_cur.grffile->sound_offset);
7308  }
7309 
7310  for (int i = 0; i < num; i++) {
7311  _cur.nfo_line++;
7312 
7313  /* Check whether the index is in range. This might happen if multiple action 11 are present.
7314  * While this is invalid, we do not check for this. But we should prevent it from causing bigger trouble */
7315  bool invalid = i >= _cur.grffile->num_sounds;
7316 
7317  size_t offs = FioGetPos();
7318 
7319  uint32 len = _cur.grf_container_ver >= 2 ? FioReadDword() : FioReadWord();
7320  byte type = FioReadByte();
7321 
7322  if (_cur.grf_container_ver >= 2 && type == 0xFD) {
7323  /* Reference to sprite section. */
7324  if (invalid) {
7325  grfmsg(1, "GRFSound: Sound index out of range (multiple Action 11?)");
7326  FioSkipBytes(len);
7327  } else if (len != 4) {
7328  grfmsg(1, "GRFSound: Invalid sprite section import");
7329  FioSkipBytes(len);
7330  } else {
7331  uint32 id = FioReadDword();
7332  if (_cur.stage == GLS_INIT) LoadGRFSound(GetGRFSpriteOffset(id), sound + i);
7333  }
7334  continue;
7335  }
7336 
7337  if (type != 0xFF) {
7338  grfmsg(1, "GRFSound: Unexpected RealSprite found, skipping");
7339  FioSkipBytes(7);
7340  SkipSpriteData(type, len - 8);
7341  continue;
7342  }
7343 
7344  if (invalid) {
7345  grfmsg(1, "GRFSound: Sound index out of range (multiple Action 11?)");
7346  FioSkipBytes(len);
7347  }
7348 
7349  byte action = FioReadByte();
7350  switch (action) {
7351  case 0xFF:
7352  /* Allocate sound only in init stage. */
7353  if (_cur.stage == GLS_INIT) {
7354  if (_cur.grf_container_ver >= 2) {
7355  grfmsg(1, "GRFSound: Inline sounds are not supported for container version >= 2");
7356  } else {
7357  LoadGRFSound(offs, sound + i);
7358  }
7359  }
7360  FioSkipBytes(len - 1); // already read <action>
7361  break;
7362 
7363  case 0xFE:
7364  if (_cur.stage == GLS_ACTIVATION) {
7365  /* XXX 'Action 0xFE' isn't really specified. It is only mentioned for
7366  * importing sounds, so this is probably all wrong... */
7367  if (FioReadByte() != 0) grfmsg(1, "GRFSound: Import type mismatch");
7368  ImportGRFSound(sound + i);
7369  } else {
7370  FioSkipBytes(len - 1); // already read <action>
7371  }
7372  break;
7373 
7374  default:
7375  grfmsg(1, "GRFSound: Unexpected Action %x found, skipping", action);
7376  FioSkipBytes(len - 1); // already read <action>
7377  break;
7378  }
7379  }
7380 }
7381 
7382 /* Action 0x11 (SKIP) */
7383 static void SkipAct11(ByteReader *buf)
7384 {
7385  /* <11> <num>
7386  *
7387  * W num Number of sound files that follow */
7388 
7389  _cur.skip_sprites = buf->ReadWord();
7390 
7391  grfmsg(3, "SkipAct11: Skipping %d sprites", _cur.skip_sprites);
7392 }
7393 
7395 static void LoadFontGlyph(ByteReader *buf)
7396 {
7397  /* <12> <num_def> <font_size> <num_char> <base_char>
7398  *
7399  * B num_def Number of definitions
7400  * B font_size Size of font (0 = normal, 1 = small, 2 = large, 3 = mono)
7401  * B num_char Number of consecutive glyphs
7402  * W base_char First character index */
7403 
7404  uint8 num_def = buf->ReadByte();
7405 
7406  for (uint i = 0; i < num_def; i++) {
7407  FontSize size = (FontSize)buf->ReadByte();
7408  uint8 num_char = buf->ReadByte();
7409  uint16 base_char = buf->ReadWord();
7410 
7411  if (size >= FS_END) {
7412  grfmsg(1, "LoadFontGlyph: Size %u is not supported, ignoring", size);
7413  }
7414 
7415  grfmsg(7, "LoadFontGlyph: Loading %u glyph(s) at 0x%04X for size %u", num_char, base_char, size);
7416 
7417  for (uint c = 0; c < num_char; c++) {
7418  if (size < FS_END) SetUnicodeGlyph(size, base_char + c, _cur.spriteid);
7419  _cur.nfo_line++;
7420  LoadNextSprite(_cur.spriteid++, _cur.file_index, _cur.nfo_line, _cur.grf_container_ver);
7421  }
7422  }
7423 }
7424 
7426 static void SkipAct12(ByteReader *buf)
7427 {
7428  /* <12> <num_def> <font_size> <num_char> <base_char>
7429  *
7430  * B num_def Number of definitions
7431  * B font_size Size of font (0 = normal, 1 = small, 2 = large)
7432  * B num_char Number of consecutive glyphs
7433  * W base_char First character index */
7434 
7435  uint8 num_def = buf->ReadByte();
7436 
7437  for (uint i = 0; i < num_def; i++) {
7438  /* Ignore 'size' byte */
7439  buf->ReadByte();
7440 
7441  /* Sum up number of characters */
7442  _cur.skip_sprites += buf->ReadByte();
7443 
7444  /* Ignore 'base_char' word */
7445  buf->ReadWord();
7446  }
7447 
7448  grfmsg(3, "SkipAct12: Skipping %d sprites", _cur.skip_sprites);
7449 }
7450 
7453 {
7454  /* <13> <grfid> <num-ent> <offset> <text...>
7455  *
7456  * 4*B grfid The GRFID of the file whose texts are to be translated
7457  * B num-ent Number of strings
7458  * W offset First text ID
7459  * S text... Zero-terminated strings */
7460 
7461  uint32 grfid = buf->ReadDWord();
7462  const GRFConfig *c = GetGRFConfig(grfid);
7463  if (c == NULL || (c->status != GCS_INITIALISED && c->status != GCS_ACTIVATED)) {
7464  grfmsg(7, "TranslateGRFStrings: GRFID 0x%08x unknown, skipping action 13", BSWAP32(grfid));
7465  return;
7466  }
7467 
7468  if (c->status == GCS_INITIALISED) {
7469  /* If the file is not active but will be activated later, give an error
7470  * and disable this file. */
7471  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LOAD_AFTER);
7472 
7473  char tmp[256];
7474  GetString(tmp, STR_NEWGRF_ERROR_AFTER_TRANSLATED_FILE, lastof(tmp));
7475  error->data = stredup(tmp);
7476 
7477  return;
7478  }
7479 
7480  /* Since no language id is supplied for with version 7 and lower NewGRFs, this string has
7481  * to be added as a generic string, thus the language id of 0x7F. For this to work
7482  * new_scheme has to be true as well, which will also be implicitly the case for version 8
7483  * and higher. A language id of 0x7F will be overridden by a non-generic id, so this will
7484  * not change anything if a string has been provided specifically for this language. */
7485  byte language = _cur.grffile->grf_version >= 8 ? buf->ReadByte() : 0x7F;
7486  byte num_strings = buf->ReadByte();
7487  uint16 first_id = buf->ReadWord();
7488 
7489  if (!((first_id >= 0xD000 && first_id + num_strings <= 0xD400) || (first_id >= 0xD800 && first_id + num_strings <= 0xE000))) {
7490  grfmsg(7, "TranslateGRFStrings: Attempting to set out-of-range string IDs in action 13 (first: 0x%4X, number: 0x%2X)", first_id, num_strings);
7491  return;
7492  }
7493 
7494  for (uint i = 0; i < num_strings && buf->HasData(); i++) {
7495  const char *string = buf->ReadString();
7496 
7497  if (StrEmpty(string)) {
7498  grfmsg(7, "TranslateGRFString: Ignoring empty string.");
7499  continue;
7500  }
7501 
7502  AddGRFString(grfid, first_id + i, language, true, true, string, STR_UNDEFINED);
7503  }
7504 }
7505 
7507 static bool ChangeGRFName(byte langid, const char *str)
7508 {
7509  AddGRFTextToList(&_cur.grfconfig->name->text, langid, _cur.grfconfig->ident.grfid, false, str);
7510  return true;
7511 }
7512 
7514 static bool ChangeGRFDescription(byte langid, const char *str)
7515 {
7516  AddGRFTextToList(&_cur.grfconfig->info->text, langid, _cur.grfconfig->ident.grfid, true, str);
7517  return true;
7518 }
7519 
7521 static bool ChangeGRFURL(byte langid, const char *str)
7522 {
7523  AddGRFTextToList(&_cur.grfconfig->url->text, langid, _cur.grfconfig->ident.grfid, false, str);
7524  return true;
7525 }
7526 
7528 static bool ChangeGRFNumUsedParams(size_t len, ByteReader *buf)
7529 {
7530  if (len != 1) {
7531  grfmsg(2, "StaticGRFInfo: expected only 1 byte for 'INFO'->'NPAR' but got " PRINTF_SIZE ", ignoring this field", len);
7532  buf->Skip(len);
7533  } else {
7534  _cur.grfconfig->num_valid_params = min(buf->ReadByte(), lengthof(_cur.grfconfig->param));
7535  }
7536  return true;
7537 }
7538 
7540 static bool ChangeGRFPalette(size_t len, ByteReader *buf)
7541 {
7542  if (len != 1) {
7543  grfmsg(2, "StaticGRFInfo: expected only 1 byte for 'INFO'->'PALS' but got " PRINTF_SIZE ", ignoring this field", len);
7544  buf->Skip(len);
7545  } else {
7546  char data = buf->ReadByte();
7547  GRFPalette pal = GRFP_GRF_UNSET;
7548  switch (data) {
7549  case '*':
7550  case 'A': pal = GRFP_GRF_ANY; break;
7551  case 'W': pal = GRFP_GRF_WINDOWS; break;
7552  case 'D': pal = GRFP_GRF_DOS; break;
7553  default:
7554  grfmsg(2, "StaticGRFInfo: unexpected value '%02x' for 'INFO'->'PALS', ignoring this field", data);
7555  break;
7556  }
7557  if (pal != GRFP_GRF_UNSET) {
7558  _cur.grfconfig->palette &= ~GRFP_GRF_MASK;
7559  _cur.grfconfig->palette |= pal;
7560  }
7561  }
7562  return true;
7563 }
7564 
7566 static bool ChangeGRFBlitter(size_t len, ByteReader *buf)
7567 {
7568  if (len != 1) {
7569  grfmsg(2, "StaticGRFInfo: expected only 1 byte for 'INFO'->'BLTR' but got " PRINTF_SIZE ", ignoring this field", len);
7570  buf->Skip(len);
7571  } else {
7572  char data = buf->ReadByte();
7573  GRFPalette pal = GRFP_BLT_UNSET;
7574  switch (data) {
7575  case '8': pal = GRFP_BLT_UNSET; break;
7576  case '3': pal = GRFP_BLT_32BPP; break;
7577  default:
7578  grfmsg(2, "StaticGRFInfo: unexpected value '%02x' for 'INFO'->'BLTR', ignoring this field", data);
7579  return true;
7580  }
7581  _cur.grfconfig->palette &= ~GRFP_BLT_MASK;
7582  _cur.grfconfig->palette |= pal;
7583  }
7584  return true;
7585 }
7586 
7588 static bool ChangeGRFVersion(size_t len, ByteReader *buf)
7589 {
7590  if (len != 4) {
7591  grfmsg(2, "StaticGRFInfo: expected 4 bytes for 'INFO'->'VRSN' but got " PRINTF_SIZE ", ignoring this field", len);
7592  buf->Skip(len);
7593  } else {
7594  /* Set min_loadable_version as well (default to minimal compatibility) */
7595  _cur.grfconfig->version = _cur.grfconfig->min_loadable_version = buf->ReadDWord();
7596  }
7597  return true;
7598 }
7599 
7601 static bool ChangeGRFMinVersion(size_t len, ByteReader *buf)
7602 {
7603  if (len != 4) {
7604  grfmsg(2, "StaticGRFInfo: expected 4 bytes for 'INFO'->'MINV' but got " PRINTF_SIZE ", ignoring this field", len);
7605  buf->Skip(len);
7606  } else {
7607  _cur.grfconfig->min_loadable_version = buf->ReadDWord();
7608  if (_cur.grfconfig->version == 0) {
7609  grfmsg(2, "StaticGRFInfo: 'MINV' defined before 'VRSN' or 'VRSN' set to 0, ignoring this field");
7610  _cur.grfconfig->min_loadable_version = 0;
7611  }
7612  if (_cur.grfconfig->version < _cur.grfconfig->min_loadable_version) {
7613  grfmsg(2, "StaticGRFInfo: 'MINV' defined as %d, limiting it to 'VRSN'", _cur.grfconfig->min_loadable_version);
7615  }
7616  }
7617  return true;
7618 }
7619 
7621 
7623 static bool ChangeGRFParamName(byte langid, const char *str)
7624 {
7625  AddGRFTextToList(&_cur_parameter->name, langid, _cur.grfconfig->ident.grfid, false, str);
7626  return true;
7627 }
7628 
7630 static bool ChangeGRFParamDescription(byte langid, const char *str)
7631 {
7632  AddGRFTextToList(&_cur_parameter->desc, langid, _cur.grfconfig->ident.grfid, true, str);
7633  return true;
7634 }
7635 
7637 static bool ChangeGRFParamType(size_t len, ByteReader *buf)
7638 {
7639  if (len != 1) {
7640  grfmsg(2, "StaticGRFInfo: expected 1 byte for 'INFO'->'PARA'->'TYPE' but got " PRINTF_SIZE ", ignoring this field", len);
7641  buf->Skip(len);
7642  } else {
7643  GRFParameterType type = (GRFParameterType)buf->ReadByte();
7644  if (type < PTYPE_END) {
7645  _cur_parameter->type = type;
7646  } else {
7647  grfmsg(3, "StaticGRFInfo: unknown parameter type %d, ignoring this field", type);
7648  }
7649  }
7650  return true;
7651 }
7652 
7654 static bool ChangeGRFParamLimits(size_t len, ByteReader *buf)
7655 {
7656  if (_cur_parameter->type != PTYPE_UINT_ENUM) {
7657  grfmsg(2, "StaticGRFInfo: 'INFO'->'PARA'->'LIMI' is only valid for parameters with type uint/enum, ignoring this field");
7658  buf->Skip(len);
7659  } else if (len != 8) {
7660  grfmsg(2, "StaticGRFInfo: expected 8 bytes for 'INFO'->'PARA'->'LIMI' but got " PRINTF_SIZE ", ignoring this field", len);
7661  buf->Skip(len);
7662  } else {
7663  _cur_parameter->min_value = buf->ReadDWord();
7664  _cur_parameter->max_value = buf->ReadDWord();
7665  }
7666  return true;
7667 }
7668 
7670 static bool ChangeGRFParamMask(size_t len, ByteReader *buf)
7671 {
7672  if (len < 1 || len > 3) {
7673  grfmsg(2, "StaticGRFInfo: expected 1 to 3 bytes for 'INFO'->'PARA'->'MASK' but got " PRINTF_SIZE ", ignoring this field", len);
7674  buf->Skip(len);
7675  } else {
7676  byte param_nr = buf->ReadByte();
7677  if (param_nr >= lengthof(_cur.grfconfig->param)) {
7678  grfmsg(2, "StaticGRFInfo: invalid parameter number in 'INFO'->'PARA'->'MASK', param %d, ignoring this field", param_nr);
7679  buf->Skip(len - 1);
7680  } else {
7681  _cur_parameter->param_nr = param_nr;
7682  if (len >= 2) _cur_parameter->first_bit = min(buf->ReadByte(), 31);
7683  if (len >= 3) _cur_parameter->num_bit = min(buf->ReadByte(), 32 - _cur_parameter->first_bit);
7684  }
7685  }
7686 
7687  return true;
7688 }
7689 
7691 static bool ChangeGRFParamDefault(size_t len, ByteReader *buf)
7692 {
7693  if (len != 4) {
7694  grfmsg(2, "StaticGRFInfo: expected 4 bytes for 'INFO'->'PARA'->'DEFA' but got " PRINTF_SIZE ", ignoring this field", len);
7695  buf->Skip(len);
7696  } else {
7697  _cur_parameter->def_value = buf->ReadDWord();
7698  }
7699  _cur.grfconfig->has_param_defaults = true;
7700  return true;
7701 }
7702 
7703 typedef bool (*DataHandler)(size_t, ByteReader *);
7704 typedef bool (*TextHandler)(byte, const char *str);
7705 typedef bool (*BranchHandler)(ByteReader *);
7706 
7717  id(0),
7718  type(0)
7719  {}
7720 
7726  AllowedSubtags(uint32 id, DataHandler handler) :
7727  id(id),
7728  type('B')
7729  {
7730  this->handler.data = handler;
7731  }
7732 
7738  AllowedSubtags(uint32 id, TextHandler handler) :
7739  id(id),
7740  type('T')
7741  {
7742  this->handler.text = handler;
7743  }
7744 
7750  AllowedSubtags(uint32 id, BranchHandler handler) :
7751  id(id),
7752  type('C')
7753  {
7754  this->handler.call_handler = true;
7755  this->handler.u.branch = handler;
7756  }
7757 
7763  AllowedSubtags(uint32 id, AllowedSubtags *subtags) :
7764  id(id),
7765  type('C')
7766  {
7767  this->handler.call_handler = false;
7768  this->handler.u.subtags = subtags;
7769  }
7770 
7771  uint32 id;
7772  byte type;
7773  union {
7776  struct {
7777  union {
7780  } u;
7782  };
7783  } handler;
7784 };
7785 
7786 static bool SkipUnknownInfo(ByteReader *buf, byte type);
7787 static bool HandleNodes(ByteReader *buf, AllowedSubtags *tags);
7788 
7796 {
7797  byte type = buf->ReadByte();
7798  while (type != 0) {
7799  uint32 id = buf->ReadDWord();
7800  if (type != 'T' || id > _cur_parameter->max_value) {
7801  grfmsg(2, "StaticGRFInfo: all child nodes of 'INFO'->'PARA'->param_num->'VALU' should have type 't' and the value/bit number as id");
7802  if (!SkipUnknownInfo(buf, type)) return false;
7803  type = buf->ReadByte();
7804  continue;
7805  }
7806 
7807  byte langid = buf->ReadByte();
7808  const char *name_string = buf->ReadString();
7809 
7810  SmallPair<uint32, GRFText *> *val_name = _cur_parameter->value_names.Find(id);
7811  if (val_name != _cur_parameter->value_names.End()) {
7812  AddGRFTextToList(&val_name->second, langid, _cur.grfconfig->ident.grfid, false, name_string);
7813  } else {
7814  GRFText *list = NULL;
7815  AddGRFTextToList(&list, langid, _cur.grfconfig->ident.grfid, false, name_string);
7816  _cur_parameter->value_names.Insert(id, list);
7817  }
7818 
7819  type = buf->ReadByte();
7820  }
7821  return true;
7822 }
7823 
7833  AllowedSubtags()
7834 };
7835 
7843 {
7844  byte type = buf->ReadByte();
7845  while (type != 0) {
7846  uint32 id = buf->ReadDWord();
7847  if (type != 'C' || id >= _cur.grfconfig->num_valid_params) {
7848  grfmsg(2, "StaticGRFInfo: all child nodes of 'INFO'->'PARA' should have type 'C' and their parameter number as id");
7849  if (!SkipUnknownInfo(buf, type)) return false;
7850  type = buf->ReadByte();
7851  continue;
7852  }
7853 
7854  if (id >= _cur.grfconfig->param_info.Length()) {
7855  uint num_to_add = id - _cur.grfconfig->param_info.Length() + 1;
7856  GRFParameterInfo **newdata = _cur.grfconfig->param_info.Append(num_to_add);
7857  MemSetT<GRFParameterInfo *>(newdata, 0, num_to_add);
7858  }
7859  if (_cur.grfconfig->param_info[id] == NULL) {
7860  _cur.grfconfig->param_info[id] = new GRFParameterInfo(id);
7861  }
7862  _cur_parameter = _cur.grfconfig->param_info[id];
7863  /* Read all parameter-data and process each node. */
7864  if (!HandleNodes(buf, _tags_parameters)) return false;
7865  type = buf->ReadByte();
7866  }
7867  return true;
7868 }
7869 
7872  AllowedSubtags('NAME', ChangeGRFName),
7874  AllowedSubtags('URL_', ChangeGRFURL),
7881  AllowedSubtags()
7882 };
7883 
7886  AllowedSubtags('INFO', _tags_info),
7887  AllowedSubtags()
7888 };
7889 
7890 
7897 static bool SkipUnknownInfo(ByteReader *buf, byte type)
7898 {
7899  /* type and id are already read */
7900  switch (type) {
7901  case 'C': {
7902  byte new_type = buf->ReadByte();
7903  while (new_type != 0) {
7904  buf->ReadDWord(); // skip the id
7905  if (!SkipUnknownInfo(buf, new_type)) return false;
7906  new_type = buf->ReadByte();
7907  }
7908  break;
7909  }
7910 
7911  case 'T':
7912  buf->ReadByte(); // lang
7913  buf->ReadString(); // actual text
7914  break;
7915 
7916  case 'B': {
7917  uint16 size = buf->ReadWord();
7918  buf->Skip(size);
7919  break;
7920  }
7921 
7922  default:
7923  return false;
7924  }
7925 
7926  return true;
7927 }
7928 
7937 static bool HandleNode(byte type, uint32 id, ByteReader *buf, AllowedSubtags subtags[])
7938 {
7939  uint i = 0;
7940  AllowedSubtags *tag;
7941  while ((tag = &subtags[i++])->type != 0) {
7942  if (tag->id != BSWAP32(id) || tag->type != type) continue;
7943  switch (type) {
7944  default: NOT_REACHED();
7945 
7946  case 'T': {
7947  byte langid = buf->ReadByte();
7948  return tag->handler.text(langid, buf->ReadString());
7949  }
7950 
7951  case 'B': {
7952  size_t len = buf->ReadWord();
7953  if (buf->Remaining() < len) return false;
7954  return tag->handler.data(len, buf);
7955  }
7956 
7957  case 'C': {
7958  if (tag->handler.call_handler) {
7959  return tag->handler.u.branch(buf);
7960  }
7961  return HandleNodes(buf, tag->handler.u.subtags);
7962  }
7963  }
7964  }
7965  grfmsg(2, "StaticGRFInfo: unknown type/id combination found, type=%c, id=%x", type, id);
7966  return SkipUnknownInfo(buf, type);
7967 }
7968 
7975 static bool HandleNodes(ByteReader *buf, AllowedSubtags subtags[])
7976 {
7977  byte type = buf->ReadByte();
7978  while (type != 0) {
7979  uint32 id = buf->ReadDWord();
7980  if (!HandleNode(type, id, buf, subtags)) return false;
7981  type = buf->ReadByte();
7982  }
7983  return true;
7984 }
7985 
7990 static void StaticGRFInfo(ByteReader *buf)
7991 {
7992  /* <14> <type> <id> <text/data...> */
7993  HandleNodes(buf, _tags_root);
7994 }
7995 
8001 static void GRFUnsafe(ByteReader *buf)
8002 {
8003  SetBit(_cur.grfconfig->flags, GCF_UNSAFE);
8004 
8005  /* Skip remainder of GRF */
8006  _cur.skip_sprites = -1;
8007 }
8008 
8009 
8012 {
8013  _ttdpatch_flags[0] = ((_settings_game.station.never_expire_airports ? 1 : 0) << 0x0C) // keepsmallairport
8014  | (1 << 0x0D) // newairports
8015  | (1 << 0x0E) // largestations
8016  | ((_settings_game.construction.max_bridge_length > 16 ? 1 : 0) << 0x0F) // longbridges
8017  | (0 << 0x10) // loadtime
8018  | (1 << 0x12) // presignals
8019  | (1 << 0x13) // extpresignals
8020  | ((_settings_game.vehicle.never_expire_vehicles ? 1 : 0) << 0x16) // enginespersist
8021  | (1 << 0x1B) // multihead
8022  | (1 << 0x1D) // lowmemory
8023  | (1 << 0x1E); // generalfixes
8024 
8025  _ttdpatch_flags[1] = ((_settings_game.economy.station_noise_level ? 1 : 0) << 0x07) // moreairports - based on units of noise
8026  | (1 << 0x08) // mammothtrains
8027  | (1 << 0x09) // trainrefit
8028  | (0 << 0x0B) // subsidiaries
8029  | ((_settings_game.order.gradual_loading ? 1 : 0) << 0x0C) // gradualloading
8030  | (1 << 0x12) // unifiedmaglevmode - set bit 0 mode. Not revelant to OTTD
8031  | (1 << 0x13) // unifiedmaglevmode - set bit 1 mode
8032  | (1 << 0x14) // bridgespeedlimits
8033  | (1 << 0x16) // eternalgame
8034  | (1 << 0x17) // newtrains
8035  | (1 << 0x18) // newrvs
8036  | (1 << 0x19) // newships
8037  | (1 << 0x1A) // newplanes
8038  | ((_settings_game.construction.train_signal_side == 1 ? 1 : 0) << 0x1B) // signalsontrafficside
8039  | ((_settings_game.vehicle.disable_elrails ? 0 : 1) << 0x1C); // electrifiedrailway
8040 
8041  _ttdpatch_flags[2] = (1 << 0x01) // loadallgraphics - obsolote
8042  | (1 << 0x03) // semaphores
8043  | (1 << 0x0A) // newobjects
8044  | (0 << 0x0B) // enhancedgui
8045  | (0 << 0x0C) // newagerating
8046  | ((_settings_game.construction.build_on_slopes ? 1 : 0) << 0x0D) // buildonslopes
8047  | (1 << 0x0E) // fullloadany
8048  | (1 << 0x0F) // planespeed
8049  | (0 << 0x10) // moreindustriesperclimate - obsolete
8050  | (0 << 0x11) // moretoylandfeatures
8051  | (1 << 0x12) // newstations
8052  | (1 << 0x13) // tracktypecostdiff
8053  | (1 << 0x14) // manualconvert
8054  | ((_settings_game.construction.build_on_slopes ? 1 : 0) << 0x15) // buildoncoasts
8055  | (1 << 0x16) // canals
8056  | (1 << 0x17) // newstartyear
8057  | ((_settings_game.vehicle.freight_trains > 1 ? 1 : 0) << 0x18) // freighttrains
8058  | (1 << 0x19) // newhouses
8059  | (1 << 0x1A) // newbridges
8060  | (1 << 0x1B) // newtownnames
8061  | (1 << 0x1C) // moreanimation
8062  | ((_settings_game.vehicle.wagon_speed_limits ? 1 : 0) << 0x1D) // wagonspeedlimits
8063  | (1 << 0x1E) // newshistory
8064  | (0 << 0x1F); // custombridgeheads
8065 
8066  _ttdpatch_flags[3] = (0 << 0x00) // newcargodistribution
8067  | (1 << 0x01) // windowsnap
8068  | ((_settings_game.economy.allow_town_roads || _generating_world ? 0 : 1) << 0x02) // townbuildnoroad
8069  | (1 << 0x03) // pathbasedsignalling
8070  | (0 << 0x04) // aichoosechance
8071  | (1 << 0x05) // resolutionwidth
8072  | (1 << 0x06) // resolutionheight
8073  | (1 << 0x07) // newindustries
8074  | ((_settings_game.order.improved_load ? 1 : 0) << 0x08) // fifoloading
8075  | (0 << 0x09) // townroadbranchprob
8076  | (0 << 0x0A) // tempsnowline
8077  | (1 << 0x0B) // newcargo
8078  | (1 << 0x0C) // enhancemultiplayer
8079  | (1 << 0x0D) // onewayroads
8080  | (1 << 0x0E) // irregularstations
8081  | (1 << 0x0F) // statistics
8082  | (1 << 0x10) // newsounds
8083  | (1 << 0x11) // autoreplace
8084  | (1 << 0x12) // autoslope
8085  | (0 << 0x13) // followvehicle
8086  | (1 << 0x14) // trams
8087  | (0 << 0x15) // enhancetunnels
8088  | (1 << 0x16) // shortrvs
8089  | (1 << 0x17) // articulatedrvs
8090  | ((_settings_game.vehicle.dynamic_engines ? 1 : 0) << 0x18) // dynamic engines
8091  | (1 << 0x1E) // variablerunningcosts
8092  | (1 << 0x1F); // any switch is on
8093 
8094  _ttdpatch_flags[4] = (1 << 0x00); // larger persistent storage
8095 }
8096 
8098 static void ResetCustomStations()
8099 {
8100  const GRFFile * const *end = _grf_files.End();
8101  for (GRFFile **file = _grf_files.Begin(); file != end; file++) {
8102  StationSpec **&stations = (*file)->stations;
8103  if (stations == NULL) continue;
8104  for (uint i = 0; i < NUM_STATIONS_PER_GRF; i++) {
8105  if (stations[i] == NULL) continue;
8106  StationSpec *statspec = stations[i];
8107 
8108  delete[] statspec->renderdata;
8109 
8110  /* Release platforms and layouts */
8111  if (!statspec->copied_layouts) {
8112  for (uint l = 0; l < statspec->lengths; l++) {
8113  for (uint p = 0; p < statspec->platforms[l]; p++) {
8114  free(statspec->layouts[l][p]);
8115  }
8116  free(statspec->layouts[l]);
8117  }
8118  free(statspec->layouts);
8119  free(statspec->platforms);
8120  }
8121 
8122  /* Release this station */
8123  free(statspec);
8124  }
8125 
8126  /* Free and reset the station data */
8127  free(stations);
8128  stations = NULL;
8129  }
8130 }
8131 
8133 static void ResetCustomHouses()
8134 {
8135  const GRFFile * const *end = _grf_files.End();
8136  for (GRFFile **file = _grf_files.Begin(); file != end; file++) {
8137  HouseSpec **&housespec = (*file)->housespec;
8138  if (housespec == NULL) continue;
8139  for (uint i = 0; i < NUM_HOUSES_PER_GRF; i++) {
8140  free(housespec[i]);
8141  }
8142 
8143  free(housespec);
8144  housespec = NULL;
8145  }
8146 }
8147 
8149 static void ResetCustomAirports()
8150 {
8151  const GRFFile * const *end = _grf_files.End();
8152  for (GRFFile **file = _grf_files.Begin(); file != end; file++) {
8153  AirportSpec **aslist = (*file)->airportspec;
8154  if (aslist != NULL) {
8155  for (uint i = 0; i < NUM_AIRPORTS_PER_GRF; i++) {
8156  AirportSpec *as = aslist[i];
8157 
8158  if (as != NULL) {
8159  /* We need to remove the tiles layouts */
8160  for (int j = 0; j < as->num_table; j++) {
8161  /* remove the individual layouts */
8162  free(as->table[j]);
8163  }
8164  free(as->table);
8165  free(as->depot_table);
8166  free(as->rotation);
8167 
8168  free(as);
8169  }
8170  }
8171  free(aslist);
8172  (*file)->airportspec = NULL;
8173  }
8174 
8175  AirportTileSpec **&airporttilespec = (*file)->airtspec;
8176  if (airporttilespec != NULL) {
8177  for (uint i = 0; i < NUM_AIRPORTTILES_PER_GRF; i++) {
8178  free(airporttilespec[i]);
8179  }
8180  free(airporttilespec);
8181  airporttilespec = NULL;
8182  }
8183  }
8184 }
8185 
8188 {
8189  const GRFFile * const *end = _grf_files.End();
8190  for (GRFFile **file = _grf_files.Begin(); file != end; file++) {
8191  IndustrySpec **&industryspec = (*file)->industryspec;
8192  IndustryTileSpec **&indtspec = (*file)->indtspec;
8193 
8194  /* We are verifiying both tiles and industries specs loaded from the grf file
8195  * First, let's deal with industryspec */
8196  if (industryspec != NULL) {
8197  for (uint i = 0; i < NUM_INDUSTRYTYPES_PER_GRF; i++) {
8198  IndustrySpec *ind = industryspec[i];
8199  if (ind == NULL) continue;
8200 
8201  /* We need to remove the sounds array */
8202  if (HasBit(ind->cleanup_flag, CLEAN_RANDOMSOUNDS)) {
8203  free(ind->random_sounds);
8204  }
8205 
8206  /* We need to remove the tiles layouts */
8208 
8209  free(ind);
8210  }
8211 
8212  free(industryspec);
8213  industryspec = NULL;
8214  }
8215 
8216  if (indtspec == NULL) continue;
8217  for (uint i = 0; i < NUM_INDUSTRYTILES_PER_GRF; i++) {
8218  free(indtspec[i]);
8219  }
8220 
8221  free(indtspec);
8222  indtspec = NULL;
8223  }
8224 }
8225 
8227 static void ResetCustomObjects()
8228 {
8229  const GRFFile * const *end = _grf_files.End();
8230  for (GRFFile **file = _grf_files.Begin(); file != end; file++) {
8231  ObjectSpec **&objectspec = (*file)->objectspec;
8232  if (objectspec == NULL) continue;
8233  for (uint i = 0; i < NUM_OBJECTS_PER_GRF; i++) {
8234  free(objectspec[i]);
8235  }
8236 
8237  free(objectspec);
8238  objectspec = NULL;
8239  }
8240 }
8241 
8243 static void ResetNewGRF()
8244 {
8245  const GRFFile * const *end = _grf_files.End();
8246  for (GRFFile **file = _grf_files.Begin(); file != end; file++) {
8247  delete *file;
8248  }
8249 
8250  _grf_files.Clear();
8251  _cur.grffile = NULL;
8252 }
8253 
8255 static void ResetNewGRFErrors()
8256 {
8257  for (GRFConfig *c = _grfconfig; c != NULL; c = c->next) {
8258  if (!HasBit(c->flags, GCF_COPY) && c->error != NULL) {
8259  delete c->error;
8260  c->error = NULL;
8261  }
8262  }
8263 }
8264 
8269 {
8270  CleanUpStrings();
8271  CleanUpGRFTownNames();
8272 
8273  /* Copy/reset original engine info data */
8274  SetupEngines();
8275 
8276  /* Copy/reset original bridge info data */
8277  ResetBridges();
8278 
8279  /* Reset rail type information */
8280  ResetRailTypes();
8281 
8282  /* Allocate temporary refit/cargo class data */
8283  _gted = CallocT<GRFTempEngineData>(Engine::GetPoolSize());
8284 
8285  /* Fill rail type label temporary data for default trains */
8286  Engine *e;
8287  FOR_ALL_ENGINES_OF_TYPE(e, VEH_TRAIN) {
8288  _gted[e->index].railtypelabel = GetRailTypeInfo(e->u.rail.railtype)->label;
8289  }
8290 
8291  /* Reset GRM reservations */
8292  memset(&_grm_engines, 0, sizeof(_grm_engines));
8293  memset(&_grm_cargoes, 0, sizeof(_grm_cargoes));
8294 
8295  /* Reset generic feature callback lists */
8297 
8298  /* Reset price base data */
8300 
8301  /* Reset the curencies array */
8302  ResetCurrencies();
8303 
8304  /* Reset the house array */
8306  ResetHouses();
8307 
8308  /* Reset the industries structures*/
8310  ResetIndustries();
8311 
8312  /* Reset the objects. */
8313  ObjectClass::Reset();
8315  ResetObjects();
8316 
8317  /* Reset station classes */
8318  StationClass::Reset();
8320 
8321  /* Reset airport-related structures */
8322  AirportClass::Reset();
8326 
8327  /* Reset canal sprite groups and flags */
8328  memset(_water_feature, 0, sizeof(_water_feature));
8329 
8330  /* Reset the snowline table. */
8331  ClearSnowLine();
8332 
8333  /* Reset NewGRF files */
8334  ResetNewGRF();
8335 
8336  /* Reset NewGRF errors. */
8338 
8339  /* Set up the default cargo types */
8341 
8342  /* Reset misc GRF features and train list display variables */
8343  _misc_grf_features = 0;
8344 
8345  _loaded_newgrf_features.has_2CC = false;
8346  _loaded_newgrf_features.used_liveries = 1 << LS_DEFAULT;
8347  _loaded_newgrf_features.has_newhouses = false;
8348  _loaded_newgrf_features.has_newindustries = false;
8349  _loaded_newgrf_features.shore = SHORE_REPLACE_NONE;
8350 
8351  /* Clear all GRF overrides */
8352  _grf_id_overrides.clear();
8353 
8354  InitializeSoundPool();
8355  _spritegroup_pool.CleanPool();
8356 }
8357 
8362 {
8363  /* Reset override managers */
8364  _engine_mngr.ResetToDefaultMapping();
8365  _house_mngr.ResetMapping();
8366  _industry_mngr.ResetMapping();
8367  _industile_mngr.ResetMapping();
8368  _airport_mngr.ResetMapping();
8369  _airporttile_mngr.ResetMapping();
8370 }
8371 
8377 {
8378  memset(_cur.grffile->cargo_map, 0xFF, sizeof(_cur.grffile->cargo_map));
8379 
8380  for (CargoID c = 0; c < NUM_CARGO; c++) {
8381  const CargoSpec *cs = CargoSpec::Get(c);
8382  if (!cs->IsValid()) continue;
8383 
8384  if (_cur.grffile->cargo_list.Length() == 0) {
8385  /* Default translation table, so just a straight mapping to bitnum */
8386  _cur.grffile->cargo_map[c] = cs->bitnum;
8387  } else {
8388  /* Check the translation table for this cargo's label */
8389  int index = _cur.grffile->cargo_list.FindIndex(cs->label);
8390  if (index >= 0) _cur.grffile->cargo_map[c] = index;
8391  }
8392  }
8393 }
8394 
8399 static void InitNewGRFFile(const GRFConfig *config)
8400 {
8401  GRFFile *newfile = GetFileByFilename(config->filename);
8402  if (newfile != NULL) {
8403  /* We already loaded it once. */
8404  _cur.grffile = newfile;
8405  return;
8406  }
8407 
8408  newfile = new GRFFile(config);
8409  *_grf_files.Append() = _cur.grffile = newfile;
8410 }
8411 
8417 {
8418  this->filename = stredup(config->filename);
8419  this->grfid = config->ident.grfid;
8420 
8421  /* Initialise local settings to defaults */
8422  this->traininfo_vehicle_pitch = 0;
8423  this->traininfo_vehicle_width = TRAININFO_DEFAULT_VEHICLE_WIDTH;
8424 
8425  /* Mark price_base_multipliers as 'not set' */
8426  for (Price i = PR_BEGIN; i < PR_END; i++) {
8427  this->price_base_multipliers[i] = INVALID_PRICE_MODIFIER;
8428  }
8429 
8430  /* Initialise rail type map with default rail types */
8431  memset(this->railtype_map, INVALID_RAILTYPE, sizeof(this->railtype_map));
8432  this->railtype_map[0] = RAILTYPE_RAIL;
8433  this->railtype_map[1] = RAILTYPE_ELECTRIC;
8434  this->railtype_map[2] = RAILTYPE_MONO;
8435  this->railtype_map[3] = RAILTYPE_MAGLEV;
8436 
8437  /* Copy the initial parameter list
8438  * 'Uninitialised' parameters are zeroed as that is their default value when dynamically creating them. */
8439  assert_compile(lengthof(this->param) == lengthof(config->param) && lengthof(this->param) == 0x80);
8440 
8441  assert(config->num_params <= lengthof(config->param));
8442  this->param_end = config->num_params;
8443  if (this->param_end > 0) {
8444  MemCpyT(this->param, config->param, this->param_end);
8445  }
8446 }
8447 
8448 GRFFile::~GRFFile()
8449 {
8450  free(this->filename);
8451  delete[] this->language_map;
8452 }
8453 
8454 
8460  'PASS', 'COAL', 'MAIL', 'LVST', 'GOOD', 'GRAI', 'WHEA', 'MAIZ', 'WOOD',
8461  'IORE', 'STEL', 'VALU', 'GOLD', 'DIAM', 'PAPR', 'FOOD', 'FRUT', 'CORE',
8462  'WATR', 'SUGR', 'TOYS', 'BATT', 'SWET', 'TOFF', 'COLA', 'CTCD', 'BUBL',
8463  'PLST', 'FZDR',
8464  0 };
8465 
8466 static const CargoLabel _default_refitmasks_road[] = {
8467  0 };
8468 
8469 static const CargoLabel _default_refitmasks_ships[] = {
8470  'COAL', 'MAIL', 'LVST', 'GOOD', 'GRAI', 'WHEA', 'MAIZ', 'WOOD', 'IORE',
8471  'STEL', 'VALU', 'GOLD', 'DIAM', 'PAPR', 'FOOD', 'FRUT', 'CORE', 'WATR',
8472  'RUBR', 'SUGR', 'TOYS', 'BATT', 'SWET', 'TOFF', 'COLA', 'CTCD', 'BUBL',
8473  'PLST', 'FZDR',
8474  0 };
8475 
8476 static const CargoLabel _default_refitmasks_aircraft[] = {
8477  'PASS', 'MAIL', 'GOOD', 'VALU', 'GOLD', 'DIAM', 'FOOD', 'FRUT', 'SUGR',
8478  'TOYS', 'BATT', 'SWET', 'TOFF', 'COLA', 'CTCD', 'BUBL', 'PLST', 'FZDR',
8479  0 };
8480 
8481 static const CargoLabel * const _default_refitmasks[] = {
8483  _default_refitmasks_road,
8484  _default_refitmasks_ships,
8485  _default_refitmasks_aircraft,
8486 };
8487 
8488 
8492 static void CalculateRefitMasks()
8493 {
8494  Engine *e;
8495 
8496  FOR_ALL_ENGINES(e) {
8497  EngineID engine = e->index;
8498  EngineInfo *ei = &e->info;
8499  bool only_defaultcargo;
8500 
8501  /* Did the newgrf specify any refitting? If not, use defaults. */
8502  if (_gted[engine].refittability != GRFTempEngineData::UNSET) {
8503  CargoTypes mask = 0;
8504  CargoTypes not_mask = 0;
8505  CargoTypes xor_mask = ei->refit_mask;
8506 
8507  /* If the original masks set by the grf are zero, the vehicle shall only carry the default cargo.
8508  * Note: After applying the translations, the vehicle may end up carrying no defined cargo. It becomes unavailable in that case. */
8509  only_defaultcargo = _gted[engine].refittability == GRFTempEngineData::EMPTY;
8510 
8511  if (_gted[engine].cargo_allowed != 0) {
8512  /* Build up the list of cargo types from the set cargo classes. */
8513  const CargoSpec *cs;
8514  FOR_ALL_CARGOSPECS(cs) {
8515  if (_gted[engine].cargo_allowed & cs->classes) SetBit(mask, cs->Index());
8516  if (_gted[engine].cargo_disallowed & cs->classes) SetBit(not_mask, cs->Index());
8517  }
8518  }
8519 
8520  ei->refit_mask = ((mask & ~not_mask) ^ xor_mask) & _cargo_mask;
8521 
8522  /* Apply explicit refit includes/excludes. */
8523  ei->refit_mask |= _gted[engine].ctt_include_mask;
8524  ei->refit_mask &= ~_gted[engine].ctt_exclude_mask;
8525  } else {
8526  CargoTypes xor_mask = 0;
8527 
8528  /* Don't apply default refit mask to wagons nor engines with no capacity */
8529  if (e->type != VEH_TRAIN || (e->u.rail.capacity != 0 && e->u.rail.railveh_type != RAILVEH_WAGON)) {
8530  const CargoLabel *cl = _default_refitmasks[e->type];
8531  for (uint i = 0;; i++) {
8532  if (cl[i] == 0) break;
8533 
8534  CargoID cargo = GetCargoIDByLabel(cl[i]);
8535  if (cargo == CT_INVALID) continue;
8536 
8537  SetBit(xor_mask, cargo);
8538  }
8539  }
8540 
8541  ei->refit_mask = xor_mask & _cargo_mask;
8542 
8543  /* If the mask is zero, the vehicle shall only carry the default cargo */
8544  only_defaultcargo = (ei->refit_mask == 0);
8545  }
8546 
8547  /* Clear invalid cargoslots (from default vehicles or pre-NewCargo GRFs) */
8548  if (!HasBit(_cargo_mask, ei->cargo_type)) ei->cargo_type = CT_INVALID;
8549 
8550  /* Ensure that the vehicle is either not refittable, or that the default cargo is one of the refittable cargoes.
8551  * Note: Vehicles refittable to no cargo are handle differently to vehicle refittable to a single cargo. The latter might have subtypes. */
8552  if (!only_defaultcargo && (e->type != VEH_SHIP || e->u.ship.old_refittable) && ei->cargo_type != CT_INVALID && !HasBit(ei->refit_mask, ei->cargo_type)) {
8553  ei->cargo_type = CT_INVALID;
8554  }
8555 
8556  /* Check if this engine's cargo type is valid. If not, set to the first refittable
8557  * cargo type. Finally disable the vehicle, if there is still no cargo. */
8558  if (ei->cargo_type == CT_INVALID && ei->refit_mask != 0) {
8559  /* Figure out which CTT to use for the default cargo, if it is 'first refittable'. */
8560  const uint8 *cargo_map_for_first_refittable = NULL;
8561  {
8562  const GRFFile *file = _gted[engine].defaultcargo_grf;
8563  if (file == NULL) file = e->GetGRF();
8564  if (file != NULL && file->grf_version >= 8 && file->cargo_list.Length() != 0) {
8565  cargo_map_for_first_refittable = file->cargo_map;
8566  }
8567  }
8568 
8569  if (cargo_map_for_first_refittable != NULL) {
8570  /* Use first refittable cargo from cargo translation table */
8571  byte best_local_slot = 0xFF;
8572  CargoID cargo_type;
8573  FOR_EACH_SET_CARGO_ID(cargo_type, ei->refit_mask) {
8574  byte local_slot = cargo_map_for_first_refittable[cargo_type];
8575  if (local_slot < best_local_slot) {
8576  best_local_slot = local_slot;
8577  ei->cargo_type = cargo_type;
8578  }
8579  }
8580  }
8581 
8582  if (ei->cargo_type == CT_INVALID) {
8583  /* Use first refittable cargo slot */
8584  ei->cargo_type = (CargoID)FindFirstBit(ei->refit_mask);
8585  }
8586  }
8587  if (ei->cargo_type == CT_INVALID) ei->climates = 0;
8588 
8589  /* Clear refit_mask for not refittable ships */
8590  if (e->type == VEH_SHIP && !e->u.ship.old_refittable) {
8591  ei->refit_mask = 0;
8592  }
8593  }
8594 }
8595 
8597 static void FinaliseCanals()
8598 {
8599  for (uint i = 0; i < CF_END; i++) {
8600  if (_water_feature[i].grffile != NULL) {
8603  }
8604  }
8605 }
8606 
8608 static void FinaliseEngineArray()
8609 {
8610  Engine *e;
8611 
8612  FOR_ALL_ENGINES(e) {
8613  if (e->GetGRF() == NULL) {
8614  const EngineIDMapping &eid = _engine_mngr[e->index];
8615  if (eid.grfid != INVALID_GRFID || eid.internal_id != eid.substitute_id) {
8616  e->info.string_id = STR_NEWGRF_INVALID_ENGINE;
8617  }
8618  }
8619 
8620  if (!HasBit(e->info.climates, _settings_game.game_creation.landscape)) continue;
8621 
8622  /* When the train does not set property 27 (misc flags), but it
8623  * is overridden by a NewGRF graphically we want to disable the
8624  * flipping possibility. */
8625  if (e->type == VEH_TRAIN && !_gted[e->index].prop27_set && e->GetGRF() != NULL && is_custom_sprite(e->u.rail.image_index)) {
8626  ClrBit(e->info.misc_flags, EF_RAIL_FLIPS);
8627  }
8628 
8629  /* Skip wagons, there livery is defined via the engine */
8630  if (e->type != VEH_TRAIN || e->u.rail.railveh_type != RAILVEH_WAGON) {
8632  SetBit(_loaded_newgrf_features.used_liveries, ls);
8633  /* Note: For ships and roadvehicles we assume that they cannot be refitted between passenger and freight */
8634 
8635  if (e->type == VEH_TRAIN) {
8636  SetBit(_loaded_newgrf_features.used_liveries, LS_FREIGHT_WAGON);
8637  switch (ls) {
8638  case LS_STEAM:
8639  case LS_DIESEL:
8640  case LS_ELECTRIC:
8641  case LS_MONORAIL:
8642  case LS_MAGLEV:
8643  SetBit(_loaded_newgrf_features.used_liveries, LS_PASSENGER_WAGON_STEAM + ls - LS_STEAM);
8644  break;
8645 
8646  case LS_DMU:
8647  case LS_EMU:
8648  SetBit(_loaded_newgrf_features.used_liveries, LS_PASSENGER_WAGON_DIESEL + ls - LS_DMU);
8649  break;
8650 
8651  default: NOT_REACHED();
8652  }
8653  }
8654  }
8655  }
8656 }
8657 
8659 static void FinaliseCargoArray()
8660 {
8661  for (CargoID c = 0; c < NUM_CARGO; c++) {
8662  CargoSpec *cs = CargoSpec::Get(c);
8663  if (!cs->IsValid()) {
8664  cs->name = cs->name_single = cs->units_volume = STR_NEWGRF_INVALID_CARGO;
8665  cs->quantifier = STR_NEWGRF_INVALID_CARGO_QUANTITY;
8666  cs->abbrev = STR_NEWGRF_INVALID_CARGO_ABBREV;
8667  }
8668  }
8669 }
8670 
8682 static bool IsHouseSpecValid(HouseSpec *hs, const HouseSpec *next1, const HouseSpec *next2, const HouseSpec *next3, const char *filename)
8683 {
8684  if (((hs->building_flags & BUILDING_HAS_2_TILES) != 0 &&
8685  (next1 == NULL || !next1->enabled || (next1->building_flags & BUILDING_HAS_1_TILE) != 0)) ||
8686  ((hs->building_flags & BUILDING_HAS_4_TILES) != 0 &&
8687  (next2 == NULL || !next2->enabled || (next2->building_flags & BUILDING_HAS_1_TILE) != 0 ||
8688  next3 == NULL || !next3->enabled || (next3->building_flags & BUILDING_HAS_1_TILE) != 0))) {
8689  hs->enabled = false;
8690  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);
8691  return false;
8692  }
8693 
8694  /* Some places sum population by only counting north tiles. Other places use all tiles causing desyncs.
8695  * As the newgrf specs define population to be zero for non-north tiles, we just disable the offending house.
8696  * If you want to allow non-zero populations somewhen, make sure to sum the population of all tiles in all places. */
8697  if (((hs->building_flags & BUILDING_HAS_2_TILES) != 0 && next1->population != 0) ||
8698  ((hs->building_flags & BUILDING_HAS_4_TILES) != 0 && (next2->population != 0 || next3->population != 0))) {
8699  hs->enabled = false;
8700  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);
8701  return false;
8702  }
8703 
8704  /* Substitute type is also used for override, and having an override with a different size causes crashes.
8705  * This check should only be done for NewGRF houses because grf_prop.subst_id is not set for original houses.*/
8706  if (filename != NULL && (hs->building_flags & BUILDING_HAS_1_TILE) != (HouseSpec::Get(hs->grf_prop.subst_id)->building_flags & BUILDING_HAS_1_TILE)) {
8707  hs->enabled = false;
8708  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);
8709  return false;
8710  }
8711 
8712  /* Make sure that additional parts of multitile houses are not available. */
8713  if ((hs->building_flags & BUILDING_HAS_1_TILE) == 0 && (hs->building_availability & HZ_ZONALL) != 0 && (hs->building_availability & HZ_CLIMALL) != 0) {
8714  hs->enabled = false;
8715  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);
8716  return false;
8717  }
8718 
8719  return true;
8720 }
8721 
8728 static void EnsureEarlyHouse(HouseZones bitmask)
8729 {
8730  Year min_year = MAX_YEAR;
8731 
8732  for (int i = 0; i < NUM_HOUSES; i++) {
8733  HouseSpec *hs = HouseSpec::Get(i);
8734  if (hs == NULL || !hs->enabled) continue;
8735  if ((hs->building_availability & bitmask) != bitmask) continue;
8736  if (hs->min_year < min_year) min_year = hs->min_year;
8737  }
8738 
8739  if (min_year == 0) return;
8740 
8741  for (int i = 0; i < NUM_HOUSES; i++) {
8742  HouseSpec *hs = HouseSpec::Get(i);
8743  if (hs == NULL || !hs->enabled) continue;
8744  if ((hs->building_availability & bitmask) != bitmask) continue;
8745  if (hs->min_year == min_year) hs->min_year = 0;
8746  }
8747 }
8748 
8755 static void FinaliseHouseArray()
8756 {
8757  /* If there are no houses with start dates before 1930, then all houses
8758  * with start dates of 1930 have them reset to 0. This is in order to be
8759  * compatible with TTDPatch, where if no houses have start dates before
8760  * 1930 and the date is before 1930, the game pretends that this is 1930.
8761  * If there have been any houses defined with start dates before 1930 then
8762  * the dates are left alone.
8763  * On the other hand, why 1930? Just 'fix' the houses with the lowest
8764  * minimum introduction date to 0.
8765  */
8766  const GRFFile * const *end = _grf_files.End();
8767  for (GRFFile **file = _grf_files.Begin(); file != end; file++) {
8768  HouseSpec **&housespec = (*file)->housespec;
8769  if (housespec == NULL) continue;
8770 
8771  for (int i = 0; i < NUM_HOUSES_PER_GRF; i++) {
8772  HouseSpec *hs = housespec[i];
8773 
8774  if (hs == NULL) continue;
8775 
8776  const HouseSpec *next1 = (i + 1 < NUM_HOUSES_PER_GRF ? housespec[i + 1] : NULL);
8777  const HouseSpec *next2 = (i + 2 < NUM_HOUSES_PER_GRF ? housespec[i + 2] : NULL);
8778  const HouseSpec *next3 = (i + 3 < NUM_HOUSES_PER_GRF ? housespec[i + 3] : NULL);
8779 
8780  if (!IsHouseSpecValid(hs, next1, next2, next3, (*file)->filename)) continue;
8781 
8782  _house_mngr.SetEntitySpec(hs);
8783  }
8784  }
8785 
8786  for (int i = 0; i < NUM_HOUSES; i++) {
8787  HouseSpec *hs = HouseSpec::Get(i);
8788  const HouseSpec *next1 = (i + 1 < NUM_HOUSES ? HouseSpec::Get(i + 1) : NULL);
8789  const HouseSpec *next2 = (i + 2 < NUM_HOUSES ? HouseSpec::Get(i + 2) : NULL);
8790  const HouseSpec *next3 = (i + 3 < NUM_HOUSES ? HouseSpec::Get(i + 3) : NULL);
8791 
8792  /* We need to check all houses again to we are sure that multitile houses
8793  * did get consecutive IDs and none of the parts are missing. */
8794  if (!IsHouseSpecValid(hs, next1, next2, next3, NULL)) {
8795  /* GetHouseNorthPart checks 3 houses that are directly before
8796  * it in the house pool. If any of those houses have multi-tile
8797  * flags set it assumes it's part of a multitile house. Since
8798  * we can have invalid houses in the pool marked as disabled, we
8799  * don't want to have them influencing valid tiles. As such set
8800  * building_flags to zero here to make sure any house following
8801  * this one in the pool is properly handled as 1x1 house. */
8802  hs->building_flags = TILE_NO_FLAG;
8803  }
8804  }
8805 
8806  HouseZones climate_mask = (HouseZones)(1 << (_settings_game.game_creation.landscape + 12));
8807  EnsureEarlyHouse(HZ_ZON1 | climate_mask);
8808  EnsureEarlyHouse(HZ_ZON2 | climate_mask);
8809  EnsureEarlyHouse(HZ_ZON3 | climate_mask);
8810  EnsureEarlyHouse(HZ_ZON4 | climate_mask);
8811  EnsureEarlyHouse(HZ_ZON5 | climate_mask);
8812 
8813  if (_settings_game.game_creation.landscape == LT_ARCTIC) {
8819  }
8820 }
8821 
8828 {
8829  const GRFFile * const *end = _grf_files.End();
8830  for (GRFFile **file = _grf_files.Begin(); file != end; file++) {
8831  IndustrySpec **&industryspec = (*file)->industryspec;
8832  IndustryTileSpec **&indtspec = (*file)->indtspec;
8833  if (industryspec != NULL) {
8834  for (int i = 0; i < NUM_INDUSTRYTYPES_PER_GRF; i++) {
8835  IndustrySpec *indsp = industryspec[i];
8836 
8837  if (indsp != NULL && indsp->enabled) {
8838  StringID strid;
8839  /* process the conversion of text at the end, so to be sure everything will be fine
8840  * and available. Check if it does not return undefind marker, which is a very good sign of a
8841  * substitute industry who has not changed the string been examined, thus using it as such */
8842  strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->name);
8843  if (strid != STR_UNDEFINED) indsp->name = strid;
8844 
8845  strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->closure_text);
8846  if (strid != STR_UNDEFINED) indsp->closure_text = strid;
8847 
8848  strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->production_up_text);
8849  if (strid != STR_UNDEFINED) indsp->production_up_text = strid;
8850 
8851  strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->production_down_text);
8852  if (strid != STR_UNDEFINED) indsp->production_down_text = strid;
8853 
8854  strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->new_industry_text);
8855  if (strid != STR_UNDEFINED) indsp->new_industry_text = strid;
8856 
8857  if (indsp->station_name != STR_NULL) {
8858  /* STR_NULL (0) can be set by grf. It has a meaning regarding assignation of the
8859  * station's name. Don't want to lose the value, therefore, do not process. */
8860  strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->station_name);
8861  if (strid != STR_UNDEFINED) indsp->station_name = strid;
8862  }
8863 
8864  _industry_mngr.SetEntitySpec(indsp);
8865  _loaded_newgrf_features.has_newindustries = true;
8866  }
8867  }
8868  }
8869 
8870  if (indtspec != NULL) {
8871  for (int i = 0; i < NUM_INDUSTRYTILES_PER_GRF; i++) {
8872  IndustryTileSpec *indtsp = indtspec[i];
8873  if (indtsp != NULL) {
8874  _industile_mngr.SetEntitySpec(indtsp);
8875  }
8876  }
8877  }
8878  }
8879 
8880  for (uint j = 0; j < NUM_INDUSTRYTYPES; j++) {
8881  IndustrySpec *indsp = &_industry_specs[j];
8882  if (indsp->enabled && indsp->grf_prop.grffile != NULL) {
8883  for (uint i = 0; i < 3; i++) {
8884  indsp->conflicting[i] = MapNewGRFIndustryType(indsp->conflicting[i], indsp->grf_prop.grffile->grfid);
8885  }
8886  }
8887  if (!indsp->enabled) {
8888  indsp->name = STR_NEWGRF_INVALID_INDUSTRYTYPE;
8889  }
8890  }
8891 }
8892 
8899 {
8900  const GRFFile * const *end = _grf_files.End();
8901  for (GRFFile **file = _grf_files.Begin(); file != end; file++) {
8902  ObjectSpec **&objectspec = (*file)->objectspec;
8903  if (objectspec != NULL) {
8904  for (int i = 0; i < NUM_OBJECTS_PER_GRF; i++) {
8905  if (objectspec[i] != NULL && objectspec[i]->grf_prop.grffile != NULL && objectspec[i]->enabled) {
8906  _object_mngr.SetEntitySpec(objectspec[i]);
8907  }
8908  }
8909  }
8910  }
8911 }
8912 
8919 {
8920  const GRFFile * const *end = _grf_files.End();
8921  for (GRFFile **file = _grf_files.Begin(); file != end; file++) {
8922  AirportSpec **&airportspec = (*file)->airportspec;
8923  if (airportspec != NULL) {
8924  for (int i = 0; i < NUM_AIRPORTS_PER_GRF; i++) {
8925  if (airportspec[i] != NULL && airportspec[i]->enabled) {
8926  _airport_mngr.SetEntitySpec(airportspec[i]);
8927  }
8928  }
8929  }
8930 
8931  AirportTileSpec **&airporttilespec = (*file)->airtspec;
8932  if (airporttilespec != NULL) {
8933  for (uint i = 0; i < NUM_AIRPORTTILES_PER_GRF; i++) {
8934  if (airporttilespec[i] != NULL && airporttilespec[i]->enabled) {
8935  _airporttile_mngr.SetEntitySpec(airporttilespec[i]);
8936  }
8937  }
8938  }
8939  }
8940 }
8941 
8942 /* Here we perform initial decoding of some special sprites (as are they
8943  * described at http://www.ttdpatch.net/src/newgrf.txt, but this is only a very
8944  * partial implementation yet).
8945  * XXX: We consider GRF files trusted. It would be trivial to exploit OTTD by
8946  * a crafted invalid GRF file. We should tell that to the user somehow, or
8947  * better make this more robust in the future. */
8948 static void DecodeSpecialSprite(byte *buf, uint num, GrfLoadingStage stage)
8949 {
8950  /* XXX: There is a difference between staged loading in TTDPatch and
8951  * here. In TTDPatch, for some reason actions 1 and 2 are carried out
8952  * during stage 1, whilst action 3 is carried out during stage 2 (to
8953  * "resolve" cargo IDs... wtf). This is a little problem, because cargo
8954  * IDs are valid only within a given set (action 1) block, and may be
8955  * overwritten after action 3 associates them. But overwriting happens
8956  * in an earlier stage than associating, so... We just process actions
8957  * 1 and 2 in stage 2 now, let's hope that won't get us into problems.
8958  * --pasky
8959  * We need a pre-stage to set up GOTO labels of Action 0x10 because the grf
8960  * is not in memory and scanning the file every time would be too expensive.
8961  * In other stages we skip action 0x10 since it's already dealt with. */
8962  static const SpecialSpriteHandler handlers[][GLS_END] = {
8963  /* 0x00 */ { NULL, SafeChangeInfo, NULL, NULL, ReserveChangeInfo, FeatureChangeInfo, },
8964  /* 0x01 */ { SkipAct1, SkipAct1, SkipAct1, SkipAct1, SkipAct1, NewSpriteSet, },
8965  /* 0x02 */ { NULL, NULL, NULL, NULL, NULL, NewSpriteGroup, },
8966  /* 0x03 */ { NULL, GRFUnsafe, NULL, NULL, NULL, FeatureMapSpriteGroup, },
8967  /* 0x04 */ { NULL, NULL, NULL, NULL, NULL, FeatureNewName, },
8968  /* 0x05 */ { SkipAct5, SkipAct5, SkipAct5, SkipAct5, SkipAct5, GraphicsNew, },
8969  /* 0x06 */ { NULL, NULL, NULL, CfgApply, CfgApply, CfgApply, },
8970  /* 0x07 */ { NULL, NULL, NULL, NULL, SkipIf, SkipIf, },
8971  /* 0x08 */ { ScanInfo, NULL, NULL, GRFInfo, GRFInfo, GRFInfo, },
8972  /* 0x09 */ { NULL, NULL, NULL, SkipIf, SkipIf, SkipIf, },
8973  /* 0x0A */ { SkipActA, SkipActA, SkipActA, SkipActA, SkipActA, SpriteReplace, },
8974  /* 0x0B */ { NULL, NULL, NULL, GRFLoadError, GRFLoadError, GRFLoadError, },
8975  /* 0x0C */ { NULL, NULL, NULL, GRFComment, NULL, GRFComment, },
8976  /* 0x0D */ { NULL, SafeParamSet, NULL, ParamSet, ParamSet, ParamSet, },
8977  /* 0x0E */ { NULL, SafeGRFInhibit, NULL, GRFInhibit, GRFInhibit, GRFInhibit, },
8978  /* 0x0F */ { NULL, GRFUnsafe, NULL, FeatureTownName, NULL, NULL, },
8979  /* 0x10 */ { NULL, NULL, DefineGotoLabel, NULL, NULL, NULL, },
8980  /* 0x11 */ { SkipAct11,GRFUnsafe, SkipAct11, GRFSound, SkipAct11, GRFSound, },
8982  /* 0x13 */ { NULL, NULL, NULL, NULL, NULL, TranslateGRFStrings, },
8983  /* 0x14 */ { StaticGRFInfo, NULL, NULL, NULL, NULL, NULL, },
8984  };
8985 
8986  GRFLocation location(_cur.grfconfig->ident.grfid, _cur.nfo_line);
8987 
8988  GRFLineToSpriteOverride::iterator it = _grf_line_to_action6_sprite_override.find(location);
8989  if (it == _grf_line_to_action6_sprite_override.end()) {
8990  /* No preloaded sprite to work with; read the
8991  * pseudo sprite content. */
8992  FioReadBlock(buf, num);
8993  } else {
8994  /* Use the preloaded sprite data. */
8995  buf = _grf_line_to_action6_sprite_override[location];
8996  grfmsg(7, "DecodeSpecialSprite: Using preloaded pseudo sprite data");
8997 
8998  /* Skip the real (original) content of this action. */
8999  FioSeekTo(num, SEEK_CUR);
9000  }
9001 
9002  ByteReader br(buf, buf + num);
9003  ByteReader *bufp = &br;
9004 
9005  try {
9006  byte action = bufp->ReadByte();
9007 
9008  if (action == 0xFF) {
9009  grfmsg(2, "DecodeSpecialSprite: Unexpected data block, skipping");
9010  } else if (action == 0xFE) {
9011  grfmsg(2, "DecodeSpecialSprite: Unexpected import block, skipping");
9012  } else if (action >= lengthof(handlers)) {
9013  grfmsg(7, "DecodeSpecialSprite: Skipping unknown action 0x%02X", action);
9014  } else if (handlers[action][stage] == NULL) {
9015  grfmsg(7, "DecodeSpecialSprite: Skipping action 0x%02X in stage %d", action, stage);
9016  } else {
9017  grfmsg(7, "DecodeSpecialSprite: Handling action 0x%02X in stage %d", action, stage);
9018  handlers[action][stage](bufp);
9019  }
9020  } catch (...) {
9021  grfmsg(1, "DecodeSpecialSprite: Tried to read past end of pseudo-sprite data");
9022  DisableGrf(STR_NEWGRF_ERROR_READ_BOUNDS);
9023  }
9024 }
9025 
9026 
9028 extern const byte _grf_cont_v2_sig[8] = {'G', 'R', 'F', 0x82, 0x0D, 0x0A, 0x1A, 0x0A};
9029 
9035 {
9036  size_t pos = FioGetPos();
9037 
9038  if (FioReadWord() == 0) {
9039  /* Check for GRF container version 2, which is identified by the bytes
9040  * '47 52 46 82 0D 0A 1A 0A' at the start of the file. */
9041  for (uint i = 0; i < lengthof(_grf_cont_v2_sig); i++) {
9042  if (FioReadByte() != _grf_cont_v2_sig[i]) return 0; // Invalid format
9043  }
9044 
9045  return 2;
9046  }
9047 
9048  /* Container version 1 has no header, rewind to start. */
9049  FioSeekTo(pos, SEEK_SET);
9050  return 1;
9051 }
9052 
9060 void LoadNewGRFFile(GRFConfig *config, uint file_index, GrfLoadingStage stage, Subdirectory subdir)
9061 {
9062  const char *filename = config->filename;
9063 
9064  /* A .grf file is activated only if it was active when the game was
9065  * started. If a game is loaded, only its active .grfs will be
9066  * reactivated, unless "loadallgraphics on" is used. A .grf file is
9067  * considered active if its action 8 has been processed, i.e. its
9068  * action 8 hasn't been skipped using an action 7.
9069  *
9070  * During activation, only actions 0, 1, 2, 3, 4, 5, 7, 8, 9, 0A and 0B are
9071  * carried out. All others are ignored, because they only need to be
9072  * processed once at initialization. */
9073  if (stage != GLS_FILESCAN && stage != GLS_SAFETYSCAN && stage != GLS_LABELSCAN) {
9074  _cur.grffile = GetFileByFilename(filename);
9075  if (_cur.grffile == NULL) usererror("File '%s' lost in cache.\n", filename);
9076  if (stage == GLS_RESERVE && config->status != GCS_INITIALISED) return;
9077  if (stage == GLS_ACTIVATION && !HasBit(config->flags, GCF_RESERVED)) return;
9078  }
9079 
9080  if (file_index >= MAX_FILE_SLOTS) {
9081  DEBUG(grf, 0, "'%s' is not loaded as the maximum number of file slots has been reached", filename);
9082  config->status = GCS_DISABLED;
9083  config->error = new GRFError(STR_NEWGRF_ERROR_MSG_FATAL, STR_NEWGRF_ERROR_TOO_MANY_NEWGRFS_LOADED);
9084  return;
9085  }
9086 
9087  FioOpenFile(file_index, filename, subdir);
9088  _cur.file_index = file_index; // XXX
9089  _palette_remap_grf[_cur.file_index] = (config->palette & GRFP_USE_MASK);
9090 
9091  _cur.grfconfig = config;
9092 
9093  DEBUG(grf, 2, "LoadNewGRFFile: Reading NewGRF-file '%s'", filename);
9094 
9096  if (_cur.grf_container_ver == 0) {
9097  DEBUG(grf, 7, "LoadNewGRFFile: Custom .grf has invalid format");
9098  return;
9099  }
9100 
9101  if (stage == GLS_INIT || stage == GLS_ACTIVATION) {
9102  /* We need the sprite offsets in the init stage for NewGRF sounds
9103  * and in the activation stage for real sprites. */
9105  } else {
9106  /* Skip sprite section offset if present. */
9107  if (_cur.grf_container_ver >= 2) FioReadDword();
9108  }
9109 
9110  if (_cur.grf_container_ver >= 2) {
9111  /* Read compression value. */
9112  byte compression = FioReadByte();
9113  if (compression != 0) {
9114  DEBUG(grf, 7, "LoadNewGRFFile: Unsupported compression format");
9115  return;
9116  }
9117  }
9118 
9119  /* Skip the first sprite; we don't care about how many sprites this
9120  * does contain; newest TTDPatches and George's longvehicles don't
9121  * neither, apparently. */
9122  uint32 num = _cur.grf_container_ver >= 2 ? FioReadDword() : FioReadWord();
9123  if (num == 4 && FioReadByte() == 0xFF) {
9124  FioReadDword();
9125  } else {
9126  DEBUG(grf, 7, "LoadNewGRFFile: Custom .grf has invalid format");
9127  return;
9128  }
9129 
9130  _cur.ClearDataForNextFile();
9131 
9133 
9134  while ((num = (_cur.grf_container_ver >= 2 ? FioReadDword() : FioReadWord())) != 0) {
9135  byte type = FioReadByte();
9136  _cur.nfo_line++;
9137 
9138  if (type == 0xFF) {
9139  if (_cur.skip_sprites == 0) {
9140  DecodeSpecialSprite(buf.Allocate(num), num, stage);
9141 
9142  /* Stop all processing if we are to skip the remaining sprites */
9143  if (_cur.skip_sprites == -1) break;
9144 
9145  continue;
9146  } else {
9147  FioSkipBytes(num);
9148  }
9149  } else {
9150  if (_cur.skip_sprites == 0) {
9151  grfmsg(0, "LoadNewGRFFile: Unexpected sprite, disabling");
9152  DisableGrf(STR_NEWGRF_ERROR_UNEXPECTED_SPRITE);
9153  break;
9154  }
9155 
9156  if (_cur.grf_container_ver >= 2 && type == 0xFD) {
9157  /* Reference to data section. Container version >= 2 only. */
9158  FioSkipBytes(num);
9159  } else {
9160  FioSkipBytes(7);
9161  SkipSpriteData(type, num - 8);
9162  }
9163  }
9164 
9165  if (_cur.skip_sprites > 0) _cur.skip_sprites--;
9166  }
9167 }
9168 
9176 static void ActivateOldShore()
9177 {
9178  /* Use default graphics, if no shore sprites were loaded.
9179  * Should not happen, as the base set's extra grf should include some. */
9180  if (_loaded_newgrf_features.shore == SHORE_REPLACE_NONE) _loaded_newgrf_features.shore = SHORE_REPLACE_ACTION_A;
9181 
9182  if (_loaded_newgrf_features.shore != SHORE_REPLACE_ACTION_5) {
9183  DupSprite(SPR_ORIGINALSHORE_START + 1, SPR_SHORE_BASE + 1); // SLOPE_W
9184  DupSprite(SPR_ORIGINALSHORE_START + 2, SPR_SHORE_BASE + 2); // SLOPE_S
9185  DupSprite(SPR_ORIGINALSHORE_START + 6, SPR_SHORE_BASE + 3); // SLOPE_SW
9186  DupSprite(SPR_ORIGINALSHORE_START + 0, SPR_SHORE_BASE + 4); // SLOPE_E
9187  DupSprite(SPR_ORIGINALSHORE_START + 4, SPR_SHORE_BASE + 6); // SLOPE_SE
9188  DupSprite(SPR_ORIGINALSHORE_START + 3, SPR_SHORE_BASE + 8); // SLOPE_N
9189  DupSprite(SPR_ORIGINALSHORE_START + 7, SPR_SHORE_BASE + 9); // SLOPE_NW
9190  DupSprite(SPR_ORIGINALSHORE_START + 5, SPR_SHORE_BASE + 12); // SLOPE_NE
9191  }
9192 
9193  if (_loaded_newgrf_features.shore == SHORE_REPLACE_ACTION_A) {
9194  DupSprite(SPR_FLAT_GRASS_TILE + 16, SPR_SHORE_BASE + 0); // SLOPE_STEEP_S
9195  DupSprite(SPR_FLAT_GRASS_TILE + 17, SPR_SHORE_BASE + 5); // SLOPE_STEEP_W
9196  DupSprite(SPR_FLAT_GRASS_TILE + 7, SPR_SHORE_BASE + 7); // SLOPE_WSE
9197  DupSprite(SPR_FLAT_GRASS_TILE + 15, SPR_SHORE_BASE + 10); // SLOPE_STEEP_N
9198  DupSprite(SPR_FLAT_GRASS_TILE + 11, SPR_SHORE_BASE + 11); // SLOPE_NWS
9199  DupSprite(SPR_FLAT_GRASS_TILE + 13, SPR_SHORE_BASE + 13); // SLOPE_ENW
9200  DupSprite(SPR_FLAT_GRASS_TILE + 14, SPR_SHORE_BASE + 14); // SLOPE_SEN
9201  DupSprite(SPR_FLAT_GRASS_TILE + 18, SPR_SHORE_BASE + 15); // SLOPE_STEEP_E
9202 
9203  /* XXX - SLOPE_EW, SLOPE_NS are currently not used.
9204  * If they would be used somewhen, then these grass tiles will most like not look as needed */
9205  DupSprite(SPR_FLAT_GRASS_TILE + 5, SPR_SHORE_BASE + 16); // SLOPE_EW
9206  DupSprite(SPR_FLAT_GRASS_TILE + 10, SPR_SHORE_BASE + 17); // SLOPE_NS
9207  }
9208 }
9209 
9214 {
9215  extern const PriceBaseSpec _price_base_specs[];
9217  static const uint32 override_features = (1 << GSF_TRAINS) | (1 << GSF_ROADVEHICLES) | (1 << GSF_SHIPS) | (1 << GSF_AIRCRAFT);
9218 
9219  /* Evaluate grf overrides */
9220  int num_grfs = _grf_files.Length();
9221  int *grf_overrides = AllocaM(int, num_grfs);
9222  for (int i = 0; i < num_grfs; i++) {
9223  grf_overrides[i] = -1;
9224 
9225  GRFFile *source = _grf_files[i];
9226  uint32 override = _grf_id_overrides[source->grfid];
9227  if (override == 0) continue;
9228 
9229  GRFFile *dest = GetFileByGRFID(override);
9230  if (dest == NULL) continue;
9231 
9232  grf_overrides[i] = _grf_files.FindIndex(dest);
9233  assert(grf_overrides[i] >= 0);
9234  }
9235 
9236  /* Override features and price base multipliers of earlier loaded grfs */
9237  for (int i = 0; i < num_grfs; i++) {
9238  if (grf_overrides[i] < 0 || grf_overrides[i] >= i) continue;
9239  GRFFile *source = _grf_files[i];
9240  GRFFile *dest = _grf_files[grf_overrides[i]];
9241 
9242  uint32 features = (source->grf_features | dest->grf_features) & override_features;
9243  source->grf_features |= features;
9244  dest->grf_features |= features;
9245 
9246  for (Price p = PR_BEGIN; p < PR_END; p++) {
9247  /* No price defined -> nothing to do */
9248  if (!HasBit(features, _price_base_specs[p].grf_feature) || source->price_base_multipliers[p] == INVALID_PRICE_MODIFIER) continue;
9249  DEBUG(grf, 3, "'%s' overrides price base multiplier %d of '%s'", source->filename, p, dest->filename);
9250  dest->price_base_multipliers[p] = source->price_base_multipliers[p];
9251  }
9252  }
9253 
9254  /* Propagate features and price base multipliers of afterwards loaded grfs, if none is present yet */
9255  for (int i = num_grfs - 1; i >= 0; i--) {
9256  if (grf_overrides[i] < 0 || grf_overrides[i] <= i) continue;
9257  GRFFile *source = _grf_files[i];
9258  GRFFile *dest = _grf_files[grf_overrides[i]];
9259 
9260  uint32 features = (source->grf_features | dest->grf_features) & override_features;
9261  source->grf_features |= features;
9262  dest->grf_features |= features;
9263 
9264  for (Price p = PR_BEGIN; p < PR_END; p++) {
9265  /* Already a price defined -> nothing to do */
9266  if (!HasBit(features, _price_base_specs[p].grf_feature) || dest->price_base_multipliers[p] != INVALID_PRICE_MODIFIER) continue;
9267  DEBUG(grf, 3, "Price base multiplier %d from '%s' propagated to '%s'", p, source->filename, dest->filename);
9268  dest->price_base_multipliers[p] = source->price_base_multipliers[p];
9269  }
9270  }
9271 
9272  /* The 'master grf' now have the correct multipliers. Assign them to the 'addon grfs' to make everything consistent. */
9273  for (int i = 0; i < num_grfs; i++) {
9274  if (grf_overrides[i] < 0) continue;
9275  GRFFile *source = _grf_files[i];
9276  GRFFile *dest = _grf_files[grf_overrides[i]];
9277 
9278  uint32 features = (source->grf_features | dest->grf_features) & override_features;
9279  source->grf_features |= features;
9280  dest->grf_features |= features;
9281 
9282  for (Price p = PR_BEGIN; p < PR_END; p++) {
9283  if (!HasBit(features, _price_base_specs[p].grf_feature)) continue;
9284  if (source->price_base_multipliers[p] != dest->price_base_multipliers[p]) {
9285  DEBUG(grf, 3, "Price base multiplier %d from '%s' propagated to '%s'", p, dest->filename, source->filename);
9286  }
9287  source->price_base_multipliers[p] = dest->price_base_multipliers[p];
9288  }
9289  }
9290 
9291  /* Apply fallback prices for grf version < 8 */
9292  const GRFFile * const *end = _grf_files.End();
9293  for (GRFFile **file = _grf_files.Begin(); file != end; file++) {
9294  if ((*file)->grf_version >= 8) continue;
9295  PriceMultipliers &price_base_multipliers = (*file)->price_base_multipliers;
9296  for (Price p = PR_BEGIN; p < PR_END; p++) {
9297  Price fallback_price = _price_base_specs[p].fallback_price;
9298  if (fallback_price != INVALID_PRICE && price_base_multipliers[p] == INVALID_PRICE_MODIFIER) {
9299  /* No price multiplier has been set.
9300  * So copy the multiplier from the fallback price, maybe a multiplier was set there. */
9301  price_base_multipliers[p] = price_base_multipliers[fallback_price];
9302  }
9303  }
9304  }
9305 
9306  /* Decide local/global scope of price base multipliers */
9307  for (GRFFile **file = _grf_files.Begin(); file != end; file++) {
9308  PriceMultipliers &price_base_multipliers = (*file)->price_base_multipliers;
9309  for (Price p = PR_BEGIN; p < PR_END; p++) {
9310  if (price_base_multipliers[p] == INVALID_PRICE_MODIFIER) {
9311  /* No multiplier was set; set it to a neutral value */
9312  price_base_multipliers[p] = 0;
9313  } else {
9314  if (!HasBit((*file)->grf_features, _price_base_specs[p].grf_feature)) {
9315  /* The grf does not define any objects of the feature,
9316  * so it must be a difficulty setting. Apply it globally */
9317  DEBUG(grf, 3, "'%s' sets global price base multiplier %d", (*file)->filename, p);
9318  SetPriceBaseMultiplier(p, price_base_multipliers[p]);
9319  price_base_multipliers[p] = 0;
9320  } else {
9321  DEBUG(grf, 3, "'%s' sets local price base multiplier %d", (*file)->filename, p);
9322  }
9323  }
9324  }
9325  }
9326 }
9327 
9328 extern void InitGRFTownGeneratorNames();
9329 
9331 static void AfterLoadGRFs()
9332 {
9333  for (StringIDMapping *it = _string_to_grf_mapping.Begin(); it != _string_to_grf_mapping.End(); it++) {
9334  *it->target = MapGRFStringID(it->grfid, it->source);
9335  }
9336  _string_to_grf_mapping.Clear();
9337 
9338  /* Free the action 6 override sprites. */
9339  for (GRFLineToSpriteOverride::iterator it = _grf_line_to_action6_sprite_override.begin(); it != _grf_line_to_action6_sprite_override.end(); it++) {
9340  free((*it).second);
9341  }
9342  _grf_line_to_action6_sprite_override.clear();
9343 
9344  /* Polish cargoes */
9346 
9347  /* Pre-calculate all refit masks after loading GRF files. */
9349 
9350  /* Polish engines */
9352 
9353  /* Set the actually used Canal properties */
9354  FinaliseCanals();
9355 
9356  /* Add all new houses to the house array. */
9358 
9359  /* Add all new industries to the industry array. */
9361 
9362  /* Add all new objects to the object array. */
9364 
9366 
9367  /* Sort the list of industry types. */
9369 
9370  /* Create dynamic list of industry legends for smallmap_gui.cpp */
9372 
9373  /* Build the routemap legend, based on the available cargos */
9375 
9376  /* Add all new airports to the airports array. */
9378  BindAirportSpecs();
9379 
9380  /* Update the townname generators list */
9382 
9383  /* Run all queued vehicle list order changes */
9385 
9386  /* Load old shore sprites in new position, if they were replaced by ActionA */
9387  ActivateOldShore();
9388 
9389  /* Set up custom rail types */
9390  InitRailTypes();
9391 
9392  Engine *e;
9393  FOR_ALL_ENGINES_OF_TYPE(e, VEH_ROAD) {
9394  if (_gted[e->index].rv_max_speed != 0) {
9395  /* Set RV maximum speed from the mph/0.8 unit value */
9396  e->u.road.max_speed = _gted[e->index].rv_max_speed * 4;
9397  }
9398  }
9399 
9400  FOR_ALL_ENGINES_OF_TYPE(e, VEH_TRAIN) {
9401  RailType railtype = GetRailTypeByLabel(_gted[e->index].railtypelabel);
9402  if (railtype == INVALID_RAILTYPE) {
9403  /* Rail type is not available, so disable this engine */
9404  e->info.climates = 0;
9405  } else {
9406  e->u.rail.railtype = railtype;
9407  }
9408  }
9409 
9411 
9413 
9414  /* Deallocate temporary loading data */
9415  free(_gted);
9416  _grm_sprites.clear();
9417 }
9418 
9425 void LoadNewGRF(uint load_index, uint file_index, uint num_baseset)
9426 {
9427  /* In case of networking we need to "sync" the start values
9428  * so all NewGRFs are loaded equally. For this we use the
9429  * start date of the game and we set the counters, etc. to
9430  * 0 so they're the same too. */
9431  Date date = _date;
9432  Year year = _cur_year;
9433  DateFract date_fract = _date_fract;
9434  uint16 tick_counter = _tick_counter;
9435  byte display_opt = _display_opt;
9436 
9437  if (_networking) {
9439  _date = ConvertYMDToDate(_cur_year, 0, 1);
9440  _date_fract = 0;
9441  _tick_counter = 0;
9442  _display_opt = 0;
9443  }
9444 
9446 
9447  ResetNewGRFData();
9448 
9449  /*
9450  * Reset the status of all files, so we can 'retry' to load them.
9451  * This is needed when one for example rearranges the NewGRFs in-game
9452  * and a previously disabled NewGRF becomes useable. If it would not
9453  * be reset, the NewGRF would remain disabled even though it should
9454  * have been enabled.
9455  */
9456  for (GRFConfig *c = _grfconfig; c != NULL; c = c->next) {
9457  if (c->status != GCS_NOT_FOUND) c->status = GCS_UNKNOWN;
9458  }
9459 
9460  _cur.spriteid = load_index;
9461 
9462  /* Load newgrf sprites
9463  * in each loading stage, (try to) open each file specified in the config
9464  * and load information from it. */
9465  for (GrfLoadingStage stage = GLS_LABELSCAN; stage <= GLS_ACTIVATION; stage++) {
9466  /* Set activated grfs back to will-be-activated between reservation- and activation-stage.
9467  * This ensures that action7/9 conditions 0x06 - 0x0A work correctly. */
9468  for (GRFConfig *c = _grfconfig; c != NULL; c = c->next) {
9469  if (c->status == GCS_ACTIVATED) c->status = GCS_INITIALISED;
9470  }
9471 
9472  if (stage == GLS_RESERVE) {
9473  static const uint32 overrides[][2] = {
9474  { 0x44442202, 0x44440111 }, // UKRS addons modifies UKRS
9475  { 0x6D620402, 0x6D620401 }, // DBSetXL ECS extension modifies DBSetXL
9476  { 0x4D656f20, 0x4D656F17 }, // LV4cut modifies LV4
9477  };
9478  for (size_t i = 0; i < lengthof(overrides); i++) {
9479  SetNewGRFOverride(BSWAP32(overrides[i][0]), BSWAP32(overrides[i][1]));
9480  }
9481  }
9482 
9483  uint slot = file_index;
9484  uint num_non_static = 0;
9485 
9486  _cur.stage = stage;
9487  for (GRFConfig *c = _grfconfig; c != NULL; c = c->next) {
9488  if (c->status == GCS_DISABLED || c->status == GCS_NOT_FOUND) continue;
9489  if (stage > GLS_INIT && HasBit(c->flags, GCF_INIT_ONLY)) continue;
9490 
9491  Subdirectory subdir = slot < file_index + num_baseset ? BASESET_DIR : NEWGRF_DIR;
9492  if (!FioCheckFileExists(c->filename, subdir)) {
9493  DEBUG(grf, 0, "NewGRF file is missing '%s'; disabling", c->filename);
9494  c->status = GCS_NOT_FOUND;
9495  continue;
9496  }
9497 
9498  if (stage == GLS_LABELSCAN) InitNewGRFFile(c);
9499 
9500  if (!HasBit(c->flags, GCF_STATIC) && !HasBit(c->flags, GCF_SYSTEM)) {
9501  if (num_non_static == NETWORK_MAX_GRF_COUNT) {
9502  DEBUG(grf, 0, "'%s' is not loaded as the maximum number of non-static GRFs has been reached", c->filename);
9503  c->status = GCS_DISABLED;
9504  c->error = new GRFError(STR_NEWGRF_ERROR_MSG_FATAL, STR_NEWGRF_ERROR_TOO_MANY_NEWGRFS_LOADED);
9505  continue;
9506  }
9507  num_non_static++;
9508  }
9509  LoadNewGRFFile(c, slot++, stage, subdir);
9510  if (stage == GLS_RESERVE) {
9511  SetBit(c->flags, GCF_RESERVED);
9512  } else if (stage == GLS_ACTIVATION) {
9513  ClrBit(c->flags, GCF_RESERVED);
9514  assert(GetFileByGRFID(c->ident.grfid) == _cur.grffile);
9517  DEBUG(sprite, 2, "LoadNewGRF: Currently %i sprites are loaded", _cur.spriteid);
9518  } else if (stage == GLS_INIT && HasBit(c->flags, GCF_INIT_ONLY)) {
9519  /* We're not going to activate this, so free whatever data we allocated */
9521  }
9522  }
9523  }
9524 
9525  /* Pseudo sprite processing is finished; free temporary stuff */
9526  _cur.ClearDataForNextFile();
9527 
9528  /* Call any functions that should be run after GRFs have been loaded. */
9529  AfterLoadGRFs();
9530 
9531  /* Now revert back to the original situation */
9532  _cur_year = year;
9533  _date = date;
9534  _date_fract = date_fract;
9535  _tick_counter = tick_counter;
9536  _display_opt = display_opt;
9537 }
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:7775
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:8608
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:8227
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:8827
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:9331
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:8149
AllowedSubtags(uint32 id, DataHandler handler)
Create a binary leaf node.
Definition: newgrf.cpp:7726
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:8243
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:5821
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:5824
static void FinaliseObjectsArray()
Add all new objects to the object array.
Definition: newgrf.cpp:8898
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:7763
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:7670
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:7246
static void FinaliseCanals()
Set to use the correct action0 properties for each canal feature.
Definition: newgrf.cpp:8597
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:8416
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:7654
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:8001
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:8376
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:5816
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:7871
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:8659
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:8361
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:9176
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:7623
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:9425
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:5792
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:7540
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:7514
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:7214
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:7277
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:5822
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:1889
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:8918
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:907
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
In 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:8755
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:8492
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:7705
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:7771
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:7521
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:7990
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:8187
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:92
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:7130
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:9060
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:5829
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:7795
static void LoadFontGlyph(ByteReader *buf)
Action 0x12.
Definition: newgrf.cpp:7395
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:7691
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:7738
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:1517
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:7937
bool call_handler
True if there is a callback function for this node, false if there is a list of subnodes.
Definition: newgrf.cpp:7781
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:7588
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:5817
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:7601
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:7716
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:1505
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:7566
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:4719
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:7825
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:9213
#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:8133
static void ParamSet(ByteReader *buf)
Action 0x0D: Set parameter.
Definition: newgrf.cpp:6780
AllowedSubtags * subtags
Pointer to a list of subtags, only valid if type == &#39;C&#39; && !call_handler.
Definition: newgrf.cpp:7779
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:8682
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:7528
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:1520
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:7750
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:5955
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:7704
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.
Definition: newgrf.cpp:8268
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:6236
static void ResetNewGRFErrors()
Clear all NewGRF errors.
Definition: newgrf.cpp:8255
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:8399
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:1519
void CDECL error(const char *s,...)
Error handling for fatal non-user errors.
Definition: openttd.cpp:112
Action5BlockType
The type of action 5 type.
Definition: newgrf.cpp:5814
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:7975
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:7703
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:895
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:8459
uint32 CargoLabel
Globally unique label of a cargo type.
Definition: cargotype.h:22
uint8 version
Production callback version used, or 0xFF if marked invalid.
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:7772
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:7714
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:8011
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:8728
byte GetGRFContainerVersion()
Get the container version of the currently opened GRF file.
Definition: newgrf.cpp:9034
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:7897
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:7774
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:7885
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:7778
static GRFParameterInfo * _cur_parameter
The parameter which info is currently changed by the newgrf.
Definition: newgrf.cpp:7620
static void ResetCustomStations()
Reset and clear all NewGRF stations.
Definition: newgrf.cpp:8098
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:7637
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:7426
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:7452
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:7630
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:1518
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:5825
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:7507
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:5815
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:5823
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:5820
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:7842
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.