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