# newgrf.cpp File Reference

Base of all NewGRF support. More...

`#include "stdafx.h"`
`#include <stdarg.h>`
`#include "openttd.h"`
`#include "debug.h"`
`#include "fileio_func.h"`
`#include "engine_func.h"`
`#include "engine_base.h"`
`#include "spritecache.h"`
`#include "variables.h"`
`#include "bridge.h"`
`#include "town.h"`
`#include "newgrf_engine.h"`
`#include "newgrf_text.h"`
`#include "fontcache.h"`
`#include "currency.h"`
`#include "landscape.h"`
`#include "newgrf_house.h"`
`#include "newgrf_sound.h"`
`#include "newgrf_station.h"`
`#include "industry.h"`
`#include "newgrf_canal.h"`
`#include "newgrf_commons.h"`
`#include "newgrf_townname.h"`
`#include "newgrf_industries.h"`
`#include "rev.h"`
`#include "fios.h"`
`#include "rail.h"`
`#include "strings_func.h"`
`#include "gfx_func.h"`
`#include "date_func.h"`
`#include "vehicle_func.h"`
`#include "sound_func.h"`
`#include "string_func.h"`
`#include "network/network.h"`
`#include "map_func.h"`
`#include <map>`
`#include "table/strings.h"`
`#include "table/build_industry.h"`

Go to the source code of this file.

## Data Structures
struct | GRFTempEngineData
struct | GRFLocation
## Defines
#define | TEXID_TO_STRINGID(begin, end, stringid) if (str >= begin && str <= end) return str + (stringid - begin)
## Typedefs
typedef void(* | SpecialSpriteHandler )(byte *buf, size_t len)
typedef std::map< GRFLocation, byte * > | GRFLineToSpriteOverride
typedef std::map< StringID *, uint32 > | StringIDToGRFIDMapping
typedef ChangeInfoResult(* | VCI_Handler )(uint engine, int numinfo, int prop, byte **buf, int len)
## Enumerations
enum | GrfDataType { GDT_SOUND }
enum | { MAX_STATIONS = 256 }
enum | ChangeInfoResult { CIR_SUCCESS, CIR_UNHANDLED, CIR_UNKNOWN, CIR_INVALID_ID }
## Functions
void CDECL | grfmsg (int severity, const char *str,...)
| DEBUG() function dedicated to newGRF debugging messages Function is essentialy the same as DEBUG(grf, severity, .
static bool | check_length (size_t real, size_t wanted, const char *str)
static byte | grf_load_byte (byte **buf)
static uint16 | grf_load_word (byte **buf)
static uint16 | grf_load_extended (byte **buf)
static uint32 | grf_load_dword (byte **buf)
static uint32 | grf_load_var (byte size, byte **buf)
static const char * | grf_load_string (byte **buf, size_t max_len)
static GRFFile * | GetFileByGRFID (uint32 grfid)
static GRFFile * | GetFileByFilename (const char *filename)
static void | ClearTemporaryNewGRFData (GRFFile *gf)
| Reset all NewGRFData that was used only while processing data.
StringID | MapGRFStringID (uint32 grfid, StringID str)
| Used when setting an object's property to map to the GRF's strings while taking in consideration the "drift" between TTDPatch string system and OpenTTD's one.
static uint8 | MapDOSColour (uint8 colour)
static void | SetNewGRFOverride (uint32 source_grfid, uint32 target_grfid)
static Engine * | GetNewEngine (const GRFFile *file, VehicleType type, uint16 internal_id)
EngineID | GetNewEngineID (const GRFFile *file, VehicleType type, uint16 internal_id)
static void | MapSpriteMappingRecolour (PalSpriteID *grf_sprite)
| Map the colour modifiers of TTDPatch to those that Open is using.
static ChangeInfoResult | CommonVehicleChangeInfo (EngineInfo *ei, int prop, byte **buf)
static ChangeInfoResult | RailVehicleChangeInfo (uint engine, int numinfo, int prop, byte **bufp, int len)
static ChangeInfoResult | RoadVehicleChangeInfo (uint engine, int numinfo, int prop, byte **bufp, int len)
static ChangeInfoResult | ShipVehicleChangeInfo (uint engine, int numinfo, int prop, byte **bufp, int len)
static ChangeInfoResult | AircraftVehicleChangeInfo (uint engine, int numinfo, int prop, byte **bufp, int len)
static ChangeInfoResult | StationChangeInfo (uint stid, int numinfo, int prop, byte **bufp, int len)
static ChangeInfoResult | CanalChangeInfo (uint id, int numinfo, int prop, byte **bufp, int len)
static ChangeInfoResult | BridgeChangeInfo (uint brid, int numinfo, int prop, byte **bufp, int len)
static ChangeInfoResult | TownHouseChangeInfo (uint hid, int numinfo, int prop, byte **bufp, int len)
static ChangeInfoResult | GlobalVarChangeInfo (uint gvid, int numinfo, int prop, byte **bufp, int len)
static ChangeInfoResult | GlobalVarReserveInfo (uint gvid, int numinfo, int prop, byte **bufp, int len)
static ChangeInfoResult | CargoChangeInfo (uint cid, int numinfo, int prop, byte **bufp, int len)
static ChangeInfoResult | SoundEffectChangeInfo (uint sid, int numinfo, int prop, byte **bufp, int len)
static ChangeInfoResult | IndustrytilesChangeInfo (uint indtid, int numinfo, int prop, byte **bufp, int len)
static ChangeInfoResult | IndustriesChangeInfo (uint indid, int numinfo, int prop, byte **bufp, int len)
static bool | HandleChangeInfoResult (const char *caller, ChangeInfoResult cir, uint8 feature, uint8 property)
static void | FeatureChangeInfo (byte *buf, size_t len)
static void | SafeChangeInfo (byte *buf, size_t len)
static void | ReserveChangeInfo (byte *buf, size_t len)
static const SpriteGroup * | NewCallBackResultSpriteGroup (uint16 value)
| Creates a spritegroup representing a callback result.
static const SpriteGroup * | NewResultSpriteGroup (SpriteID sprite, byte num_sprites)
| Creates a spritegroup representing a sprite number result.
static void | NewSpriteSet (byte *buf, size_t len)
static void | SkipAct1 (byte *buf, size_t len)
static const SpriteGroup * | GetGroupFromGroupID (byte setid, byte type, uint16 groupid)
static const SpriteGroup * | CreateGroupFromGroupID (byte feature, byte setid, byte type, uint16 spriteid, uint16 num_sprites)
static void | NewSpriteGroup (byte *buf, size_t len)
static CargoID | TranslateCargo (uint8 feature, uint8 ctype)
static bool | IsValidGroupID (uint16 groupid, const char *function)
static void | VehicleMapSpriteGroup (byte *buf, byte feature, uint8 idcount)
static void | CanalMapSpriteGroup (byte *buf, uint8 idcount)
static void | StationMapSpriteGroup (byte *buf, uint8 idcount)
static void | TownHouseMapSpriteGroup (byte *buf, uint8 idcount)
static void | IndustryMapSpriteGroup (byte *buf, uint8 idcount)
static void | IndustrytileMapSpriteGroup (byte *buf, uint8 idcount)
static void | CargoMapSpriteGroup (byte *buf, uint8 idcount)
static void | FeatureMapSpriteGroup (byte *buf, size_t len)
static void | FeatureNewName (byte *buf, size_t len)
static uint16 | SanitizeSpriteOffset (uint16 &num, uint16 offset, int max_sprites, const char *name)
| Sanitize incoming sprite offsets for Action 5 graphics replacements.
static void | GraphicsNew (byte *buf, size_t len)
static void | SkipAct5 (byte *buf, size_t len)
bool | GetGlobalVariable (byte param, uint32 *value)
| Reads a variable common to VarAction2 and Action7/9/D.
static uint32 | GetParamVal (byte param, uint32 *cond_val)
static void | CfgApply (byte *buf, size_t len)
static void | DisableStaticNewGRFInfluencingNonStaticNewGRFs (GRFConfig *c)
| Disable a static NewGRF when it is influencing another (non-static) NewGRF as this could cause desyncs.
static void | SkipIf (byte *buf, size_t len)
static void | ScanInfo (byte *buf, size_t len)
static void | GRFInfo (byte *buf, size_t len)
static void | SpriteReplace (byte *buf, size_t len)
static void | SkipActA (byte *buf, size_t len)
static void | GRFLoadError (byte *buf, size_t len)
static void | GRFComment (byte *buf, size_t len)
static void | SafeParamSet (byte *buf, size_t len)
static uint32 | GetPatchVariable (uint8 param)
static uint32 | PerformGRM (uint32 *grm, uint16 num_ids, uint16 count, uint8 op, uint8 target, const char *type)
static void | ParamSet (byte *buf, size_t len)
static void | SafeGRFInhibit (byte *buf, size_t len)
static void | GRFInhibit (byte *buf, size_t len)
static void | FeatureTownName (byte *buf, size_t len)
static void | DefineGotoLabel (byte *buf, size_t len)
static void | GRFSound (byte *buf, size_t len)
static void | SkipAct11 (byte *buf, size_t len)
static void | ImportGRFSound (byte *buf, int len)
static void | GRFImportBlock (byte *buf, int len)
static void | LoadGRFSound (byte *buf, int len)
static void | LoadFontGlyph (byte *buf, size_t len)
static void | SkipAct12 (byte *buf, size_t len)
static void | TranslateGRFStrings (byte *buf, size_t len)
static void | GRFDataBlock (byte *buf, int len)
static void | GRFUnsafe (byte *buf, size_t len)
static void | InitializeGRFSpecial ()
static void | ResetCustomStations ()
static void | ResetCustomHouses ()
static void | ResetCustomIndustries ()
static void | ResetNewGRF ()
static void | ResetNewGRFErrors ()
static void | ResetNewGRFData ()
| Reset all NewGRF loaded data TODO.
static void | BuildCargoTranslationMap ()
static void | InitNewGRFFile (const GRFConfig *config, int sprite_offset)
static void | CalculateRefitMasks ()
| Precalculate refit masks from cargo classes for all vehicles.
static void | FinaliseHouseArray ()
| Add all new houses to the house array.
static void | FinaliseIndustriesArray ()
| Add all new industries to the industry array.
static void | DecodeSpecialSprite (uint num, GrfLoadingStage stage)
void | LoadNewGRFFile (GRFConfig *config, uint file_index, GrfLoadingStage stage)
static void | ActivateOldShore ()
| Relocates the old shore sprites at new positions.
void | InitDepotWindowBlockSizes ()
void | InitGRFTownGeneratorNames ()
static void | AfterLoadGRFs ()
void | LoadNewGRF (uint load_index, uint file_index)
bool | HasGrfMiscBit (GrfMiscBit bit)
## Variables
static int | _skip_sprites
static uint | _file_index
static GRFFile * | _cur_grffile
GRFFile * | _first_grffile
static SpriteID | _cur_spriteid
static GrfLoadingStage | _cur_stage
static uint32 | _nfo_line
static GRFConfig * | _cur_grfconfig
static byte | _misc_grf_features = 0
static uint32 | _ttdpatch_flags [8]
GRFLoadedFeatures | _loaded_newgrf_features
static byte | _grf_data_blocks
static GrfDataType | _grf_data_type
static GRFTempEngineData * | _gted
static uint32 | _grm_engines [256]
static uint32 | _grm_cargos [NUM_CARGO *2]
static std::map< GRFLocation, SpriteID > | _grm_sprites
GRFLineToSpriteOverride | _grf_line_to_action6_sprite_override
StringIDToGRFIDMapping | _string_to_grf_mapping
static std::map< uint32, uint32 > | _grf_id_overrides
static const CargoLabel | _default_refitmasks_rail []
| List of what cargo labels are refittable for the given the vehicle-type.
static const CargoLabel | _default_refitmasks_road []
static const CargoLabel | _default_refitmasks_ships []
static const CargoLabel | _default_refitmasks_aircraft []
static const CargoLabel * | _default_refitmasks []

## Detailed Description

Base of all NewGRF support.

Definition in file newgrf.cpp.

## Enumeration Type Documentation

enum ChangeInfoResult

Enumerator:

  CIR_SUCCESS | Variable was parsed and read.
  CIR_UNHANDLED | Variable was parsed but unread.
  CIR_UNKNOWN | Variable is unknown.
  CIR_INVALID_ID | Attempt to modify an invalid ID.

Definition at line 421 of file newgrf.cpp.

## Function Documentation

static void ActivateOldShore | ( |  | ) | `[static]`

Relocates the old shore sprites at new positions.

1. If shore sprites are neither loaded by Action5 nor ActionA, the extra sprites from openttd(w/d).grf are used. (SHORE_REPLACE_ONLY_NEW) 2. If a newgrf replaces some shore sprites by ActionA. The (maybe also replaced) grass tiles are used for corner shores. (SHORE_REPLACE_ACTION_A) 3. If a newgrf replaces shore sprites by Action5 any shore replacement by ActionA has no effect. (SHORE_REPLACE_ACTION_5)

Definition at line 6048 of file newgrf.cpp.

References SHORE_REPLACE_ACTION_5, SHORE_REPLACE_ACTION_A, and SHORE_REPLACE_NONE.

static void DisableStaticNewGRFInfluencingNonStaticNewGRFs | ( | GRFConfig * | c | ) | `[static]`

Disable a static NewGRF when it is influencing another (non-static) NewGRF as this could cause desyncs.

We could just tell the NewGRF querying that the file doesn't exist, but that might give unwanted results. Disabling the NewGRF gives the best result as no NewGRF author can complain about that.

Parameters:

  | c | the NewGRF to disable.

Definition at line 3949 of file newgrf.cpp.

References ClearTemporaryNewGRFData(), GRFError::custom_message, GRFError::data, GRFConfig::error, GCS_DISABLED, GRFIdentifier::grfid, GRFError::message, GRFConfig::name, GRFError::severity, and GRFConfig::status.

static void FinaliseHouseArray | ( |  | ) | `[static]`

Add all new houses to the house array.

House properties can be set at any time in the GRF file, so we can only add a house spec to the house array after the file has finished loading. We also need to check the dates, due to the TTDPatch behaviour described below that we need to emulate.

Definition at line 5776 of file newgrf.cpp.

static void FinaliseIndustriesArray | ( |  | ) | `[static]`

Add all new industries to the industry array.

Industry properties can be set at any time in the GRF file, so we can only add a industry spec to the industry array after the file has finished loading.

Definition at line 5813 of file newgrf.cpp.

References IndustrySpec::closure_text, IndustrySpec::conflicting, IndustrySpec::enabled, GetGRFStringID(), IndustrySpec::grf_prop, GRFFileProps::grffile, IndustrySpec::name, IndustrySpec::new_industry_text, NUM_INDUSTRYTILES, IndustrySpec::production_down_text, IndustrySpec::production_up_text, and IndustrySpec::station_name.

bool GetGlobalVariable | ( | byte | param,
|  | uint32 * | value |
| ) |  |  |

Reads a variable common to VarAction2 and Action7/9/D.

Returns VarAction2 variable 'param' resp. Action7/9/D variable '0x80 + param'. If a variable is not accessible from all four actions, it is handled in the action specific functions.

Parameters:

  | param | variable number (as for VarAction2, for Action7/9/D you have to subtract 0x80 first).
  | value | returns the value of the variable.

Returns:
  true iff the variable is known and the value is returned in 'value'.

Definition at line 3679 of file newgrf.cpp.

References _cur_year, _date, _settings_game, Clamp(), ConvertDateToYMD(), ConvertYMDToDate(), YearMonthDay::day, DAYS_TILL_ORIGINAL_BASE_YEAR, DifficultySettings::diff_level, GameSettings::difficulty, VehicleSettings::disable_elrails, GameSettings::game_creation, GB(), GetRailTypeInfo(), GetSnowLine(), GameCreationSettings::landscape, max(), YearMonthDay::month, ORIGINAL_BASE_YEAR, ORIGINAL_MAX_YEAR, RAILTYPE_ELECTRIC, RAILTYPE_MAGLEV, RAILTYPE_MONO, RAILTYPE_RAIL, VehicleSettings::road_side, SB(), GameSettings::vehicle, GRFConfig::windows_paletted, and YearMonthDay::year.

static void GraphicsNew | ( | byte * | buf,
|  | size_t | len |
| ) |  |  | `[static]`

< Only allow replacing a whole block of sprites. (TTDP compatible)

< Allow replacing any subset by specifiing an offset.

< unknown/not-implemented type

< How is this Action5 type processed?

< Load the sprites starting from this sprite.

< If the Action5 contains less sprites, the whole block will be ignored.

< If the Action5 contains more sprites, only the first max_sprites sprites will be used.

< Name for error messages.

Definition at line 3541 of file newgrf.cpp.

References ClrBit(), grfmsg(), HasBit(), lengthof, SanitizeSpriteOffset(), SHORE_REPLACE_ACTION_5, SHORE_REPLACE_NONE, and SHORE_REPLACE_ONLY_NEW.

void CDECL grfmsg | ( | int | severity,
|  | const char * | str,
|  |  | ... |
| ) |  |  |

DEBUG() function dedicated to newGRF debugging messages Function is essentialy the same as DEBUG(grf, severity, .

..) with the addition of file:line information when parsing grf files. NOTE: for the above reason(s) grfmsg() should ONLY be used for loading/parsing grf files, not for runtime debug messages as there is no file information available during that time.

Parameters:

  | severity | debugging severity level, see debug.h
  | str | message in printf() format

Definition at line 137 of file newgrf.cpp.

References buf, and GRFConfig::filename.

Referenced by AddGenericCallback(), AddGRFString(), AllocateStationClass(), GraphicsNew(), RailVehicleChangeInfo(), SanitizeSpriteOffset(), ShipVehicleChangeInfo(), and TownHouseChangeInfo().

StringID MapGRFStringID | ( | uint32 | grfid,
|  | StringID | str |
| ) |  |  |

Used when setting an object's property to map to the GRF's strings while taking in consideration the "drift" between TTDPatch string system and OpenTTD's one.

Parameters:

  | grfid | Id of the grf file
  | str | StringID that we want to have the equivalent in OoenTTD

Returns:
  the properly adjusted StringID

Definition at line 258 of file newgrf.cpp.

References GB(), and GetGRFStringID().

Referenced by ChangeIndustryProduction().

static void MapSpriteMappingRecolour | ( | PalSpriteID * | grf_sprite | ) | `[static]`

Map the colour modifiers of TTDPatch to those that Open is using.

Parameters:

  | grf_sprite | pointer to the structure been modified

Definition at line 403 of file newgrf.cpp.

References ClrBit(), HasBit(), PalSpriteID::pal, PALETTE_MODIFIER_COLOUR, PALETTE_MODIFIER_TRANSPARENT, SetBit(), PalSpriteID::sprite, and SPRITE_MODIFIER_OPAQUE.

static const SpriteGroup* NewCallBackResultSpriteGroup | ( | uint16 | value | ) | `[static]`

Creates a spritegroup representing a callback result.

Parameters:

  | value | The value that was used to represent this callback result

Returns:
  A spritegroup representing that callback result

Definition at line 2557 of file newgrf.cpp.

static const SpriteGroup* NewResultSpriteGroup | ( | SpriteID | sprite,
|  | byte | num_sprites |
| ) |  |  | `[static]`

Creates a spritegroup representing a sprite number result.

Parameters:

  | sprite | The sprite number.
  | num_sprites | The number of sprites per set.

Returns:
  A spritegroup representing the sprite number result.

Definition at line 2582 of file newgrf.cpp.

static ChangeInfoResult RailVehicleChangeInfo | ( | uint | engine,
|  | int | numinfo,
|  | int | prop,
|  | byte ** | bufp,
|  | int | len |
| ) |  |  | `[static]`

Todo:
  Air drag for trains.

See also:
  note in engine.h about rvi->visual_effect

Definition at line 468 of file newgrf.cpp.

References EngineInfo::base_intro, EngineInfo::callbackmask, CIR_SUCCESS, CIR_UNHANDLED, EngineInfo::climates, EF_USES_2CC, GetRailTypeByLabel(), grfmsg(), HasBit(), INVALID_RAILTYPE, EngineInfo::misc_flags, RAILTYPE_ELECTRIC, RAILTYPE_MAGLEV, RAILTYPE_MONO, RAILTYPE_RAIL, RAILVEH_MULTIHEAD, RAILVEH_SINGLEHEAD, RAILVEH_WAGON, EngineInfo::refit_cost, EngineInfo::refit_mask, EngineInfo::retire_early, and SB().

static uint16 SanitizeSpriteOffset | ( | uint16 & | num,
|  | uint16 | offset,
|  | int | max_sprites,
|  | const char * | name |
| ) |  |  | `[static]`

Sanitize incoming sprite offsets for Action 5 graphics replacements.

Parameters:

  | num | the number of sprites to load.
  | offset | offset from the base.
  | max_sprites | the maximum number of sprites that can be loaded in this action 5.
  | name | used for error warnings.

Returns:
  the number of sprites that is going to be skipped

Definition at line 3520 of file newgrf.cpp.

References grfmsg(), and max().

Referenced by GraphicsNew().

static ChangeInfoResult ShipVehicleChangeInfo | ( | uint | engine,
|  | int | numinfo,
|  | int | prop,
|  | byte ** | bufp,
|  | int | len |
| ) |  |  | `[static]`

Todo:
  Speed fractions for ships on oceans and canals

Definition at line 863 of file newgrf.cpp.

References EngineInfo::base_intro, EngineInfo::callbackmask, CIR_SUCCESS, CIR_UNHANDLED, EF_USES_2CC, grfmsg(), HasBit(), EngineInfo::misc_flags, EngineInfo::refit_cost, EngineInfo::refit_mask, and EngineInfo::retire_early.

static ChangeInfoResult TownHouseChangeInfo | ( | uint | hid,
|  | int | numinfo,
|  | int | prop,
|  | byte ** | bufp,
|  | int | len |
| ) |  |  | `[static]`

New houses do not (currently) expect to have a default start date before 1930, as this breaks the build date stuff.

See also:
  FinaliseHouseArray() for more details.

Definition at line 1425 of file newgrf.cpp.

References _settings_game, abs(), CIR_INVALID_ID, CIR_SUCCESS, CIR_UNHANDLED, CIR_UNKNOWN, Clamp(), GameSettings::game_creation, GB(), grfmsg(), GameCreationSettings::landscape, and ORIGINAL_BASE_YEAR.

## Variable Documentation

const CargoLabel* _default_refitmasks[]`[static]`

Initial value:

     {
      _default_refitmasks_rail,
      _default_refitmasks_road,
      _default_refitmasks_ships,
      _default_refitmasks_aircraft,
    }

Definition at line 5675 of file newgrf.cpp.

const CargoLabel _default_refitmasks_aircraft[]`[static]`

Initial value:

     {
      'PASS', 'MAIL', 'GOOD', 'VALU', 'GOLD', 'DIAM', 'FOOD', 'FRUT', 'SUGR',
      'TOYS', 'BATT', 'SWET', 'TOFF', 'COLA', 'CTCD', 'BUBL', 'PLST', 'FZDR',
      0 }

Definition at line 5670 of file newgrf.cpp.

const CargoLabel _default_refitmasks_rail[]`[static]`

Initial value:

     {
      'PASS', 'COAL', 'MAIL', 'LVST', 'GOOD', 'GRAI', 'WHEA', 'MAIZ', 'WOOD',
      'IORE', 'STEL', 'VALU', 'GOLD', 'DIAM', 'PAPR', 'FOOD', 'FRUT', 'CORE',
      'WATR', 'SUGR', 'TOYS', 'BATT', 'SWET', 'TOFF', 'COLA', 'CTCD', 'BUBL',
      'PLST', 'FZDR',
      0 }

List of what cargo labels are refittable for the given the vehicle-type.

Only currently active labels are applied.

Definition at line 5653 of file newgrf.cpp.

const CargoLabel _default_refitmasks_road[]`[static]`

Initial value:

     {
      0 }

Definition at line 5660 of file newgrf.cpp.

const CargoLabel _default_refitmasks_ships[]`[static]`

Initial value:

     {
      'COAL', 'MAIL', 'LVST', 'GOOD', 'GRAI', 'WHEA', 'MAIZ', 'WOOD', 'IORE',
      'STEL', 'VALU', 'GOLD', 'DIAM', 'PAPR', 'FOOD', 'FRUT', 'CORE', 'WATR',
      'RUBR', 'SUGR', 'TOYS', 'BATT', 'SWET', 'TOFF', 'COLA', 'CTCD', 'BUBL',
      'PLST', 'FZDR',
      0 }

Definition at line 5663 of file newgrf.cpp.