12 #include "3rdparty/md5/md5.h"
38 filename(filename), num_valid_params(
ClampTo<uint8_t>(
GRFConfig::param.size()))
49 original_md5sum(config.original_md5sum),
50 filename(config.filename),
55 version(config.version),
56 min_loadable_version(config.min_loadable_version),
57 flags(config.flags & ~(1 <<
GCF_COPY)),
58 status(config.status),
59 grf_bugs(config.grf_bugs),
61 num_params(config.num_params),
62 num_valid_params(config.num_valid_params),
63 palette(config.palette),
64 param_info(config.param_info),
65 has_param_defaults(config.has_param_defaults)
69 void GRFConfig::SetParams(
const std::vector<uint32_t> &pars)
71 this->
num_params =
static_cast<uint8_t
>(std::min(this->
param.size(), pars.size()));
72 std::copy(pars.begin(), pars.begin() + this->num_params, this->param.begin());
130 for (uint i = 0; i < this->
param_info.size(); i++) {
158 if (!
info.has_value())
continue;
187 max_value(UINT32_MAX),
193 complete_labels(false)
205 return GB(config->
param[this->param_nr], this->first_bit, this->num_bit);
219 SB(config->
param[this->param_nr], this->first_bit, this->num_bit, value);
258 static const uint header_len = 14;
260 uint8_t data[header_len];
261 if (fread(data, 1, header_len, f) == header_len) {
264 size_t offset = (
static_cast<size_t>(data[13]) << 24) | (
static_cast<size_t>(data[12]) << 16) | (
static_cast<size_t>(data[11]) << 8) |
static_cast<size_t>(data[10]);
265 if (offset >= 1 * 1024 * 1024 * 1024) {
266 Debug(grf, 0,
"Unexpectedly large offset for NewGRF");
272 return header_len + offset;
288 uint8_t buffer[1024];
293 if (!f.has_value())
return false;
295 long start = ftell(*f);
298 if (start < 0 || fseek(*f, start, SEEK_SET) < 0) {
303 while ((len = fread(buffer, 1, (size >
sizeof(buffer)) ?
sizeof(buffer) : size, *f)) != 0 && size != 0) {
305 checksum.Append(buffer, len);
355 for (c = *config; c !=
nullptr; c = next) {
374 for (; src !=
nullptr; src = src->
next) {
405 if (list ==
nullptr)
return;
407 for (prev = list, cur = list->
next; cur !=
nullptr; prev = cur, cur = cur->
next) {
425 while (*tail !=
nullptr) tail = &(*tail)->
next;
439 while (*tail !=
nullptr) tail = &(*tail)->
next;
476 Debug(grf, 1,
"NewGRF {:08X} ({}) not found; checksum {}. Compatibility mode on",
BSWAP32(c->ident.grfid), c->filename,
FormatArrayAsHex(c->ident.md5sum));
480 c->original_md5sum = c->ident.md5sum;
531 this->next_update = std::chrono::steady_clock::now();
534 bool AddFile(
const std::string &filename,
size_t basepath_length,
const std::string &tar_filename)
override;
556 if (_exit_game)
return false;
591 const char *name =
nullptr;
593 if (name ==
nullptr) name = c->
filename.c_str();
626 Debug(grf, 1,
"Scanning for NewGRFs");
629 Debug(grf, 1,
"Scan complete, found {} files", num);
634 std::vector<GRFConfig *> to_sort;
638 to_sort.push_back(p);
643 std::sort(to_sort.begin(), to_sort.end(),
GRFSorter);
645 for (i = 1; i < num; i++) {
646 to_sort[i - 1]->next = to_sort[i];
648 to_sort[num - 1]->next =
nullptr;
688 assert((mode ==
FGCM_EXACT) != (md5sum ==
nullptr));
692 if (!c->ident.HasGrfIdentifier(grfid, md5sum))
continue;
694 if (md5sum !=
nullptr || mode ==
FGCM_ANY)
return c;
698 if (mode ==
FGCM_COMPATIBLE && !c->IsCompatible(desired_version))
continue;
717 if ((c->
ident.
grfid & mask) == (grfid & mask))
return c;
729 if (!result.empty()) result +=
' ';
730 result += std::to_string(c->
param[i]);
constexpr debug_inline bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
constexpr T SB(T &x, const uint8_t s, const uint8_t n, const U d)
Set n bits in x starting at bit s to d.
constexpr T SetBit(T &x, const uint8_t y)
Set a bit in a variable.
static uint32_t BSWAP32(uint32_t x)
Perform a 32 bits endianness bitswap on x.
constexpr static debug_inline uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
constexpr T ClrBit(T &x, const uint8_t y)
Clears a bit in a variable.
Helper for scanning for files with a given name.
uint Scan(std::string_view extension, Subdirectory sd, bool tars=true, bool recursive=true)
Scan for files with the given extension in the given search path.
Helper for scanning for files with GRF as extension.
static uint DoScan()
Do the scan for GRFs.
std::chrono::steady_clock::time_point next_update
The next moment we do update the screen.
bool AddFile(const std::string &filename, size_t basepath_length, const std::string &tar_filename) override
Add a file with the given filename.
uint num_scanned
The number of GRFs we have scanned.
uint DoScan(Subdirectory sd)
Perform the scanning of a particular subdirectory.
@ NEWGRF
Scan for non-base sets.
void GameLoopPause()
Pause the game-loop for a bit, releasing the game-state lock.
static VideoDriver * GetInstance()
Get the currently active instance of the video driver.
Base class that provides memory initialization on dynamically created objects.
Functions related to debugging.
#define Debug(category, level, format_string,...)
Ouptut a line of debugging information.
bool FioCheckFileExists(const std::string &filename, Subdirectory subdir)
Check whether the given file exists.
std::optional< FileHandle > FioFOpenFile(const std::string &filename, const char *mode, Subdirectory subdir, size_t *filesize)
Opens a OpenTTD file somewhere in a personal or global directory.
Functions for Standard In/Out file operations.
Subdirectory
The different kinds of subdirectories OpenTTD uses.
@ NEWGRF_DIR
Subdirectory for all NewGRFs.
Declarations for savegames operations.
Functions related to the gfx engine.
PaletteType
Palettes OpenTTD supports.
@ PAL_DOS
Use the DOS palette.
@ PAL_WINDOWS
Use the Windows palette.
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
constexpr To ClampTo(From value)
Clamp the given value down to lie within the requested type.
int MemCmpT(const T *ptr1, const T *ptr2, size_t num=1)
Type-safe version of memcmp().
Network functions used by other parts of OpenTTD.
void NetworkAfterNewGRFScan()
Rebuild the GRFConfig's of the servers in the game list as we did a rescan and might have found new N...
void LoadNewGRFFile(GRFConfig *config, GrfLoadingStage stage, Subdirectory subdir, bool temporary)
Load a particular NewGRF.
Base for the NewGRF implementation.
GRFConfig * GetGRFConfig(uint32_t grfid, uint32_t mask)
Retrieve a NewGRF from the current config by its grfid.
void UpdateNewGRFConfigPalette(int32_t)
Update the palettes of the graphics from the config file.
GRFConfig * _all_grfs
First item in list of all scanned NewGRFs.
std::string GRFBuildParamList(const GRFConfig *c)
Build a string containing space separated parameter values, and terminate.
void ClearGRFConfigList(GRFConfig **config)
Clear a GRF Config list, freeing all nodes.
uint _missing_extra_graphics
Number of sprites provided by the fallback extra GRF, i.e. missing in the baseset.
void AppendToGRFConfigList(GRFConfig **dst, GRFConfig *el)
Appends an element to a list of GRFs.
bool FillGRFDetails(GRFConfig *config, bool is_static, Subdirectory subdir)
Find the GRFID of a given grf, and calculate its md5sum.
GRFConfig * _grfconfig
First item in list of current GRF set up.
static bool GRFSorter(GRFConfig *const &c1, GRFConfig *const &c2)
Simple sorter for GRFS.
void ResetGRFConfig(bool defaults)
Reset the current GRF Config to either blank or newgame settings.
static bool CalcGRFMD5Sum(GRFConfig *config, Subdirectory subdir)
Calculate the MD5 sum for a GRF, and store it in the config.
GRFConfig * _grfconfig_static
First item in list of static GRF set up.
static void RemoveDuplicatesFromGRFConfigList(GRFConfig *list)
Removes duplicates from lists of GRFConfigs.
GRFListCompatibility IsGoodGRFConfigList(GRFConfig *grfconfig)
Check if all GRFs in the GRF config from a savegame can be loaded.
const GRFConfig * FindGRFConfig(uint32_t grfid, FindGRFConfigMode mode, const MD5Hash *md5sum, uint32_t desired_version)
Find a NewGRF in the scanned list.
void ScanNewGRFFiles(NewGRFScanCallback *callback)
Scan for all NewGRFs.
GRFConfig ** CopyGRFConfigList(GRFConfig **dst, const GRFConfig *src, bool init_only)
Copy a GRF Config list.
void AppendStaticGRFConfigs(GRFConfig **dst)
Appends the static GRFs to a list of GRFs.
size_t GRFGetSizeOfDataSection(FileHandle &f)
Get the data section size of a GRF.
void DoScanNewGRFFiles(NewGRFScanCallback *callback)
Really perform the scan for all NewGRFs.
GRFConfig * _grfconfig_newgame
First item in list of default GRF set up.
int _skip_all_newgrf_scanning
Set this flag to prevent any NewGRF scanning from being done.
Functions to find and configure NewGRFs.
GRFListCompatibility
Status of post-gameload GRF compatibility check.
@ GLC_COMPATIBLE
Compatible (eg. the same ID, but different checksum) GRF found in at least one case.
@ GLC_ALL_GOOD
All GRF needed by game are present.
@ GLC_NOT_FOUND
At least one GRF couldn't be found (higher priority than GLC_COMPATIBLE)
@ GRFP_USE_DOS
The palette state is set to use the DOS palette.
@ GRFP_GRF_WINDOWS
The NewGRF says the Windows palette can be used.
@ GRFP_USE_WINDOWS
The palette state is set to use the Windows palette.
@ GRFP_GRF_DOS
The NewGRF says the DOS palette can be used.
@ GRFP_USE_BIT
The bit used for storing the palette to use.
@ GRFP_GRF_MASK
Bitmask to get only the NewGRF supplied information.
void UpdateNewGRFScanStatus(uint num, const char *name)
Update the NewGRF scan status.
@ GCF_INIT_ONLY
GRF file is processed up to GLS_INIT.
@ GCF_INVALID
GRF is unusable with this version of OpenTTD.
@ GCF_UNSAFE
GRF file is unsafe for static usage.
@ GCF_COMPATIBLE
GRF file does not exactly match the requested GRF (different MD5SUM), but grfid matches)
@ GCF_COPY
The data is copied from a grf in _all_grfs.
@ GCF_SYSTEM
GRF file is an openttd-internal system grf.
@ PTYPE_UINT_ENUM
The parameter allows a range of numbers, each of which can have a special name.
@ GCS_NOT_FOUND
GRF file was not found in the local cache.
FindGRFConfigMode
Method to find GRFs using FindGRFConfig.
@ FGCM_NEWEST
Find newest Grf.
@ FGCM_ANY
Use first found.
@ FGCM_EXACT
Only find Grfs matching md5sum.
@ FGCM_COMPATIBLE
Find best compatible Grf wrt. desired_version.
const char * GetGRFStringFromGRFText(const GRFTextList &text_list)
Get a C-string from a GRFText-list.
Header of Action 04 "universal holder" structure and functions.
void SetModalProgress(bool state)
Set the modal progress state.
Functions related to modal progress.
A number of safeguards to prevent using unsafe methods.
ClientSettings _settings_client
The current settings for this game.
const uint8_t _grf_cont_v2_sig[8]
Signature of a container version 2 GRF.
Definition of base types and functions in a cross-platform compatible way.
std::string FormatArrayAsHex(std::span< const uint8_t > data)
Format a byte array into a continuous hex string.
int StrNaturalCompare(std::string_view s1, std::string_view s2, bool ignore_garbage_at_front)
Compares two strings using case insensitive natural sort.
int StrCompareIgnoreCase(const std::string_view str1, const std::string_view str2)
Compares two string( view)s, while ignoring the case of the characters.
Functions related to low-level strings.
bool StrEmpty(const char *s)
Check if a string buffer is empty.
Functions related to OTTD's strings.
uint32_t StringID
Numeric value that represents a string, independent of the selected language.
GUISettings gui
settings related to the GUI
Information about GRF, used in the game and (part of it) in savegames.
void SetParameterDefaults()
Set the default value for all parameters as specified by action14.
const char * GetURL() const
Get the grf url.
GRFConfig(const std::string &filename=std::string{})
Create a new GRFConfig.
GRFTextWrapper url
NOSAVE: URL belonging to this GRF.
uint8_t palette
GRFPalette, bitset.
uint8_t flags
NOSAVE: GCF_Flags, bitset.
const char * GetDescription() const
Get the grf info.
GRFTextWrapper info
NOSAVE: GRF info (author, copyright, ...) (Action 0x08)
std::vector< std::optional< GRFParameterInfo > > param_info
NOSAVE: extra information about the parameters.
uint32_t version
NOSAVE: Version a NewGRF can set so only the newest NewGRF is shown.
void FinalizeParameterInfo()
Finalize Action 14 info after file scan is finished.
bool has_param_defaults
NOSAVE: did this newgrf specify any defaults for it's parameters.
GRFTextWrapper name
NOSAVE: GRF name (Action 0x08)
uint8_t num_params
Number of used parameters.
struct GRFConfig * next
NOSAVE: Next item in the linked list.
GRFStatus status
NOSAVE: GRFStatus, enum.
bool IsCompatible(uint32_t old_version) const
Return whether this NewGRF can replace an older version of the same NewGRF.
void CopyParams(const GRFConfig &src)
Copy the parameter information from the src config.
std::optional< std::string > GetTextfile(TextfileType type) const
Search a textfile file next to this NewGRF.
uint8_t num_valid_params
NOSAVE: Number of valid parameters (action 0x14)
std::string filename
Filename - either with or without full path.
GRFIdentifier ident
grfid and md5sum to uniquely identify newgrfs
const char * GetName() const
Get the name of this grf.
void SetSuitablePalette()
Set the palette of this GRFConfig to something suitable.
uint32_t min_loadable_version
NOSAVE: Minimum compatible version a NewGRF can define.
std::array< uint32_t, 0x80 > param
GRF parameters.
GRFError(StringID severity, StringID message=0)
Construct a new GRFError.
uint32_t grfid
GRF ID (defined by Action 0x08)
MD5Hash md5sum
MD5 checksum of file to distinguish files with the same GRF ID (eg. newer version of GRF)
bool complete_labels
True if all values have a label.
std::map< uint32_t, GRFTextList > value_names
Names for each value.
uint8_t param_nr
GRF parameter to store content in.
uint32_t min_value
The minimal value this parameter can have.
uint8_t num_bit
Number of bits to use for this parameter.
uint32_t max_value
The maximal value of this parameter.
uint32_t GetValue(struct GRFConfig *config) const
Get the value of this user-changeable parameter from the given config.
void Finalize()
Finalize Action 14 info after file scan is finished.
GRFParameterInfo(uint nr)
Create a new empty GRFParameterInfo object.
void SetValue(struct GRFConfig *config, uint32_t value)
Set the value of this user-changeable parameter in the given config.
uint32_t last_newgrf_count
the numbers of NewGRFs we found during the last scan
uint8_t newgrf_default_palette
default palette to use for NewGRFs without action 14 palette information
Callback for NewGRF scanning.
virtual void OnNewGRFsScanned()=0
Called whenever the NewGRF scan completed.
std::optional< std::string > GetTextfile(TextfileType type, Subdirectory dir, const std::string &filename)
Search a textfile file next to the given content.
GUI functions related to textfiles.
TextfileType
Additional text files accompanying Tar archives.
Base of all video drivers.
void CloseWindowByClass(WindowClass cls, int data)
Close all windows of a given class.
void InvalidateWindowData(WindowClass cls, WindowNumber number, int data, bool gui_scope)
Mark window data of the window of a given class and specific window number as invalid (in need of re-...
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
void InvalidateWindowClassesData(WindowClass cls, int data, bool gui_scope)
Mark window data of all windows of a given class as invalid (in need of re-computing) Note that by de...
Window functions not directly related to making/drawing windows.
@ WN_GAME_OPTIONS_NEWGRF_STATE
NewGRF settings.
@ WC_GAME_OPTIONS
Game options window; Window numbers:
@ WC_SAVELOAD
Saveload window; Window numbers:
@ WC_MODAL_PROGRESS
Progress report of landscape generation; Window numbers:
@ GOID_NEWGRF_RESCANNED
NewGRFs were just rescanned.