2 * This file is part of OpenTTD.
3 * 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.
4 * 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.
5 * 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 /** @file newgrf_config.cpp Finding NewGRFs and configuring them. */
12 #include "3rdparty/md5/md5.h"
14 #include "network/network_func.h"
16 #include "newgrf_text.h"
17 #include "window_func.h"
19 #include "video/video_driver.hpp"
20 #include "strings_func.h"
21 #include "textfile_gui.h"
23 #include "newgrf_config.h"
24 #include "newgrf_text.h"
26 #include "fileio_func.h"
29 #include "safeguards.h"
33 * Create a new GRFConfig.
34 * @param filename Set the filename of this GRFConfig to filename. The argument
35 * is copied so the original string isn't needed after the constructor.
37 GRFConfig::GRFConfig(const char *filename
) :
38 num_valid_params(lengthof(param
))
40 if (filename
!= nullptr) this->filename
= stredup(filename
);
44 * Create a new GRFConfig that is a deep copy of an existing config.
45 * @param config The GRFConfig object to make a copy of.
47 GRFConfig::GRFConfig(const GRFConfig
&config
) :
48 ZeroedMemoryAllocator(),
53 version(config
.version
),
54 min_loadable_version(config
.min_loadable_version
),
55 flags(config
.flags
& ~(1 << GCF_COPY
)),
56 status(config
.status
),
57 grf_bugs(config
.grf_bugs
),
58 num_params(config
.num_params
),
59 num_valid_params(config
.num_valid_params
),
60 palette(config
.palette
),
61 has_param_defaults(config
.has_param_defaults
)
63 MemCpyT
<uint8
>(this->original_md5sum
, config
.original_md5sum
, lengthof(this->original_md5sum
));
64 MemCpyT
<uint32
>(this->param
, config
.param
, lengthof(this->param
));
65 if (config
.filename
!= nullptr) this->filename
= stredup(config
.filename
);
66 if (config
.error
!= nullptr) this->error
= new GRFError(*config
.error
);
67 for (uint i
= 0; i
< config
.param_info
.size(); i
++) {
68 if (config
.param_info
[i
] == nullptr) {
69 this->param_info
.push_back(nullptr);
71 this->param_info
.push_back(new GRFParameterInfo(*config
.param_info
[i
]));
76 /** Cleanup a GRFConfig object. */
77 GRFConfig::~GRFConfig()
79 /* GCF_COPY as in NOT stredupped/alloced the filename */
80 if (!HasBit(this->flags
, GCF_COPY
)) {
85 for (uint i
= 0; i
< this->param_info
.size(); i
++) delete this->param_info
[i
];
89 * Copy the parameter information from the \a src config.
90 * @param src Source config.
92 void GRFConfig::CopyParams(const GRFConfig
&src
)
94 this->num_params
= src
.num_params
;
95 this->num_valid_params
= src
.num_valid_params
;
96 MemCpyT
<uint32
>(this->param
, src
.param
, lengthof(this->param
));
100 * Get the name of this grf. In case the name isn't known
101 * the filename is returned.
102 * @return The name of filename of this grf.
104 const char *GRFConfig::GetName() const
106 const char *name
= GetGRFStringFromGRFText(this->name
);
107 return StrEmpty(name
) ? this->filename
: name
;
112 * @return A string with a description of this grf.
114 const char *GRFConfig::GetDescription() const
116 return GetGRFStringFromGRFText(this->info
);
121 * @return A string with an url of this grf.
123 const char *GRFConfig::GetURL() const
125 return GetGRFStringFromGRFText(this->url
);
128 /** Set the default value for all parameters as specified by action14. */
129 void GRFConfig::SetParameterDefaults()
131 this->num_params
= 0;
132 MemSetT
<uint32
>(this->param
, 0, lengthof(this->param
));
134 if (!this->has_param_defaults
) return;
136 for (uint i
= 0; i
< this->param_info
.size(); i
++) {
137 if (this->param_info
[i
] == nullptr) continue;
138 this->param_info
[i
]->SetValue(this, this->param_info
[i
]->def_value
);
143 * Set the palette of this GRFConfig to something suitable.
144 * That is either the setting coming from the NewGRF or
145 * the globally used palette.
147 void GRFConfig::SetSuitablePalette()
150 switch (this->palette
& GRFP_GRF_MASK
) {
151 case GRFP_GRF_DOS
: pal
= PAL_DOS
; break;
152 case GRFP_GRF_WINDOWS
: pal
= PAL_WINDOWS
; break;
153 default: pal
= _settings_client
.gui
.newgrf_default_palette
== 1 ? PAL_WINDOWS
: PAL_DOS
; break;
155 SB(this->palette
, GRFP_USE_BIT
, 1, pal
== PAL_WINDOWS
? GRFP_USE_WINDOWS
: GRFP_USE_DOS
);
159 * Finalize Action 14 info after file scan is finished.
161 void GRFConfig::FinalizeParameterInfo()
163 for (GRFParameterInfo
*info
: this->param_info
) {
164 if (info
== nullptr) continue;
169 GRFConfig
*_all_grfs
;
170 GRFConfig
*_grfconfig
;
171 GRFConfig
*_grfconfig_newgame
;
172 GRFConfig
*_grfconfig_static
;
173 uint _missing_extra_graphics
= 0;
176 * Construct a new GRFError.
177 * @param severity The severity of this error.
178 * @param message The actual error-string.
180 GRFError::GRFError(StringID severity
, StringID message
) :
188 * Create a new GRFError that is a deep copy of an existing error message.
189 * @param error The GRFError object to make a copy of.
191 GRFError::GRFError(const GRFError
&error
) :
192 custom_message(error
.custom_message
),
194 message(error
.message
),
195 severity(error
.severity
)
197 memcpy(this->param_value
, error
.param_value
, sizeof(this->param_value
));
201 * Create a new empty GRFParameterInfo object.
202 * @param nr The newgrf parameter that is changed.
204 GRFParameterInfo::GRFParameterInfo(uint nr
) :
207 type(PTYPE_UINT_ENUM
),
209 max_value(UINT32_MAX
),
215 complete_labels(false)
219 * Create a new GRFParameterInfo object that is a deep copy of an existing
220 * parameter info object.
221 * @param info The GRFParameterInfo object to make a copy of.
223 GRFParameterInfo::GRFParameterInfo(GRFParameterInfo
&info
) :
227 min_value(info
.min_value
),
228 max_value(info
.max_value
),
229 def_value(info
.def_value
),
230 param_nr(info
.param_nr
),
231 first_bit(info
.first_bit
),
232 num_bit(info
.num_bit
),
233 value_names(info
.value_names
),
234 complete_labels(info
.complete_labels
)
239 * Get the value of this user-changeable parameter from the given config.
240 * @param config The GRFConfig to get the value from.
241 * @return The value of this parameter.
243 uint32
GRFParameterInfo::GetValue(struct GRFConfig
*config
) const
245 /* GB doesn't work correctly with nbits == 32, so handle that case here. */
246 if (this->num_bit
== 32) return config
->param
[this->param_nr
];
247 return GB(config
->param
[this->param_nr
], this->first_bit
, this->num_bit
);
251 * Set the value of this user-changeable parameter in the given config.
252 * @param config The GRFConfig to set the value in.
253 * @param value The new value.
255 void GRFParameterInfo::SetValue(struct GRFConfig
*config
, uint32 value
)
257 /* SB doesn't work correctly with nbits == 32, so handle that case here. */
258 if (this->num_bit
== 32) {
259 config
->param
[this->param_nr
] = value
;
261 SB(config
->param
[this->param_nr
], this->first_bit
, this->num_bit
, value
);
263 config
->num_params
= std::max
<uint
>(config
->num_params
, this->param_nr
+ 1);
264 SetWindowDirty(WC_GAME_OPTIONS
, WN_GAME_OPTIONS_NEWGRF_STATE
);
268 * Finalize Action 14 info after file scan is finished.
270 void GRFParameterInfo::Finalize()
272 this->complete_labels
= true;
273 for (uint32 value
= this->min_value
; value
<= this->max_value
; value
++) {
274 if (!this->value_names
.Contains(value
)) {
275 this->complete_labels
= false;
282 * Update the palettes of the graphics from the config file.
283 * Called when changing the default palette in advanced settings.
285 * @return Always true.
287 bool UpdateNewGRFConfigPalette(int32 p1
)
289 for (GRFConfig
*c
= _grfconfig_newgame
; c
!= nullptr; c
= c
->next
) c
->SetSuitablePalette();
290 for (GRFConfig
*c
= _grfconfig_static
; c
!= nullptr; c
= c
->next
) c
->SetSuitablePalette();
291 for (GRFConfig
*c
= _all_grfs
; c
!= nullptr; c
= c
->next
) c
->SetSuitablePalette();
296 * Get the data section size of a GRF.
298 * @return Size of the data section or SIZE_MAX if the file has no separate data section.
300 size_t GRFGetSizeOfDataSection(FILE *f
)
302 extern const byte _grf_cont_v2_sig
[];
303 static const uint header_len
= 14;
305 byte data
[header_len
];
306 if (fread(data
, 1, header_len
, f
) == header_len
) {
307 if (data
[0] == 0 && data
[1] == 0 && MemCmpT(data
+ 2, _grf_cont_v2_sig
, 8) == 0) {
308 /* Valid container version 2, get data section size. */
309 size_t offset
= ((size_t)data
[13] << 24) | ((size_t)data
[12] << 16) | ((size_t)data
[11] << 8) | (size_t)data
[10];
310 if (offset
>= 1 * 1024 * 1024 * 1024) {
311 DEBUG(grf
, 0, "Unexpectedly large offset for NewGRF");
312 /* Having more than 1 GiB of data is very implausible. Mostly because then
313 * all pools in OpenTTD are flooded already. Or it's just Action C all over.
314 * In any case, the offsets to graphics will likely not work either. */
317 return header_len
+ offset
;
325 * Calculate the MD5 sum for a GRF, and store it in the config.
326 * @param config GRF to compute.
327 * @param subdir The subdirectory to look in.
328 * @return MD5 sum was successfully computed
330 static bool CalcGRFMD5Sum(GRFConfig
*config
, Subdirectory subdir
)
338 f
= FioFOpenFile(config
->filename
, "rb", subdir
, &size
);
339 if (f
== nullptr) return false;
341 long start
= ftell(f
);
342 size
= std::min(size
, GRFGetSizeOfDataSection(f
));
344 if (start
< 0 || fseek(f
, start
, SEEK_SET
) < 0) {
349 /* calculate md5sum */
350 while ((len
= fread(buffer
, 1, (size
> sizeof(buffer
)) ? sizeof(buffer
) : size
, f
)) != 0 && size
!= 0) {
352 checksum
.Append(buffer
, len
);
354 checksum
.Finish(config
->ident
.md5sum
);
363 * Find the GRFID of a given grf, and calculate its md5sum.
364 * @param config grf to fill.
365 * @param is_static grf is static.
366 * @param subdir the subdirectory to search in.
367 * @return Operation was successfully completed.
369 bool FillGRFDetails(GRFConfig
*config
, bool is_static
, Subdirectory subdir
)
371 if (!FioCheckFileExists(config
->filename
, subdir
)) {
372 config
->status
= GCS_NOT_FOUND
;
376 /* Find and load the Action 8 information */
377 LoadNewGRFFile(config
, CONFIG_SLOT
, GLS_FILESCAN
, subdir
);
378 config
->SetSuitablePalette();
379 config
->FinalizeParameterInfo();
381 /* Skip if the grfid is 0 (not read) or if it is an internal GRF */
382 if (config
->ident
.grfid
== 0 || HasBit(config
->flags
, GCF_SYSTEM
)) return false;
385 /* Perform a 'safety scan' for static GRFs */
386 LoadNewGRFFile(config
, CONFIG_SLOT
, GLS_SAFETYSCAN
, subdir
);
388 /* GCF_UNSAFE is set if GLS_SAFETYSCAN finds unsafe actions */
389 if (HasBit(config
->flags
, GCF_UNSAFE
)) return false;
392 return CalcGRFMD5Sum(config
, subdir
);
397 * Clear a GRF Config list, freeing all nodes.
398 * @param config Start of the list.
399 * @post \a config is set to \c nullptr.
401 void ClearGRFConfigList(GRFConfig
**config
)
404 for (c
= *config
; c
!= nullptr; c
= next
) {
413 * Copy a GRF Config list
414 * @param dst pointer to destination list
415 * @param src pointer to source list values
416 * @param init_only the copied GRF will be processed up to GLS_INIT
417 * @return pointer to the last value added to the destination list
419 GRFConfig
**CopyGRFConfigList(GRFConfig
**dst
, const GRFConfig
*src
, bool init_only
)
421 /* Clear destination as it will be overwritten */
422 ClearGRFConfigList(dst
);
423 for (; src
!= nullptr; src
= src
->next
) {
424 GRFConfig
*c
= new GRFConfig(*src
);
426 ClrBit(c
->flags
, GCF_INIT_ONLY
);
427 if (init_only
) SetBit(c
->flags
, GCF_INIT_ONLY
);
437 * Removes duplicates from lists of GRFConfigs. These duplicates
438 * are introduced when the _grfconfig_static GRFs are appended
439 * to the _grfconfig on a newgame or savegame. As the parameters
440 * of the static GRFs could be different that the parameters of
441 * the ones used non-statically. This can result in desyncs in
442 * multiplayers, so the duplicate static GRFs have to be removed.
444 * This function _assumes_ that all static GRFs are placed after
445 * the non-static GRFs.
447 * @param list the list to remove the duplicates from
449 static void RemoveDuplicatesFromGRFConfigList(GRFConfig
*list
)
454 if (list
== nullptr) return;
456 for (prev
= list
, cur
= list
->next
; cur
!= nullptr; prev
= cur
, cur
= cur
->next
) {
457 if (cur
->ident
.grfid
!= list
->ident
.grfid
) continue;
459 prev
->next
= cur
->next
;
461 cur
= prev
; // Just go back one so it continues as normal later on
464 RemoveDuplicatesFromGRFConfigList(list
->next
);
468 * Appends the static GRFs to a list of GRFs
469 * @param dst the head of the list to add to
471 void AppendStaticGRFConfigs(GRFConfig
**dst
)
473 GRFConfig
**tail
= dst
;
474 while (*tail
!= nullptr) tail
= &(*tail
)->next
;
476 CopyGRFConfigList(tail
, _grfconfig_static
, false);
477 RemoveDuplicatesFromGRFConfigList(*dst
);
481 * Appends an element to a list of GRFs
482 * @param dst the head of the list to add to
483 * @param el the new tail to be
485 void AppendToGRFConfigList(GRFConfig
**dst
, GRFConfig
*el
)
487 GRFConfig
**tail
= dst
;
488 while (*tail
!= nullptr) tail
= &(*tail
)->next
;
491 RemoveDuplicatesFromGRFConfigList(*dst
);
495 /** Reset the current GRF Config to either blank or newgame settings. */
496 void ResetGRFConfig(bool defaults
)
498 CopyGRFConfigList(&_grfconfig
, _grfconfig_newgame
, !defaults
);
499 AppendStaticGRFConfigs(&_grfconfig
);
504 * Check if all GRFs in the GRF config from a savegame can be loaded.
505 * @param grfconfig GrfConfig to check
506 * @return will return any of the following 3 values:<br>
508 * <li> GLC_ALL_GOOD: No problems occurred, all GRF files were found and loaded
509 * <li> GLC_COMPATIBLE: For one or more GRF's no exact match was found, but a
510 * compatible GRF with the same grfid was found and used instead
511 * <li> GLC_NOT_FOUND: For one or more GRF's no match was found at all
514 GRFListCompatibility
IsGoodGRFConfigList(GRFConfig
*grfconfig
)
516 GRFListCompatibility res
= GLC_ALL_GOOD
;
518 for (GRFConfig
*c
= grfconfig
; c
!= nullptr; c
= c
->next
) {
519 const GRFConfig
*f
= FindGRFConfig(c
->ident
.grfid
, FGCM_EXACT
, c
->ident
.md5sum
);
520 if (f
== nullptr || HasBit(f
->flags
, GCF_INVALID
)) {
523 /* If we have not found the exactly matching GRF try to find one with the
524 * same grfid, as it most likely is compatible */
525 f
= FindGRFConfig(c
->ident
.grfid
, FGCM_COMPATIBLE
, nullptr, c
->version
);
527 md5sumToString(buf
, lastof(buf
), c
->ident
.md5sum
);
528 DEBUG(grf
, 1, "NewGRF %08X (%s) not found; checksum %s. Compatibility mode on", BSWAP32(c
->ident
.grfid
), c
->filename
, buf
);
529 if (!HasBit(c
->flags
, GCF_COMPATIBLE
)) {
530 /* Preserve original_md5sum after it has been assigned */
531 SetBit(c
->flags
, GCF_COMPATIBLE
);
532 memcpy(c
->original_md5sum
, c
->ident
.md5sum
, sizeof(c
->original_md5sum
));
535 /* Non-found has precedence over compatibility load */
536 if (res
!= GLC_NOT_FOUND
) res
= GLC_COMPATIBLE
;
540 /* No compatible grf was found, mark it as disabled */
541 md5sumToString(buf
, lastof(buf
), c
->ident
.md5sum
);
542 DEBUG(grf
, 0, "NewGRF %08X (%s) not found; checksum %s", BSWAP32(c
->ident
.grfid
), c
->filename
, buf
);
544 c
->status
= GCS_NOT_FOUND
;
548 DEBUG(grf
, 1, "Loading GRF %08X from %s", BSWAP32(f
->ident
.grfid
), f
->filename
);
549 /* The filename could be the filename as in the savegame. As we need
550 * to load the GRF here, we need the correct filename, so overwrite that
551 * in any case and set the name and info when it is not set already.
552 * When the GCF_COPY flag is set, it is certain that the filename is
553 * already a local one, so there is no need to replace it. */
554 if (!HasBit(c
->flags
, GCF_COPY
)) {
556 c
->filename
= stredup(f
->filename
);
557 memcpy(c
->ident
.md5sum
, f
->ident
.md5sum
, sizeof(c
->ident
.md5sum
));
561 c
->version
= f
->version
;
562 c
->min_loadable_version
= f
->min_loadable_version
;
563 c
->num_valid_params
= f
->num_valid_params
;
564 c
->has_param_defaults
= f
->has_param_defaults
;
565 for (uint i
= 0; i
< f
->param_info
.size(); i
++) {
566 if (f
->param_info
[i
] == nullptr) {
567 c
->param_info
.push_back(nullptr);
569 c
->param_info
.push_back(new GRFParameterInfo(*f
->param_info
[i
]));
579 /** Helper for scanning for files with GRF as extension */
580 class GRFFileScanner
: FileScanner
{
581 std::chrono::steady_clock::time_point next_update
; ///< The next moment we do update the screen.
582 uint num_scanned
; ///< The number of GRFs we have scanned.
585 GRFFileScanner() : num_scanned(0)
587 this->next_update
= std::chrono::steady_clock::now();
590 bool AddFile(const std::string
&filename
, size_t basepath_length
, const std::string
&tar_filename
) override
;
592 /** Do the scan for GRFs. */
596 int ret
= fs
.Scan(".grf", NEWGRF_DIR
);
597 /* The number scanned and the number returned may not be the same;
598 * duplicate NewGRFs and base sets are ignored in the return value. */
599 _settings_client
.gui
.last_newgrf_count
= fs
.num_scanned
;
604 bool GRFFileScanner::AddFile(const std::string
&filename
, size_t basepath_length
, const std::string
&tar_filename
)
606 GRFConfig
*c
= new GRFConfig(filename
.c_str() + basepath_length
);
609 if (FillGRFDetails(c
, false)) {
610 if (_all_grfs
== nullptr) {
613 /* Insert file into list at a position determined by its
614 * name, so the list is sorted as we go along */
617 for (pd
= &_all_grfs
; (d
= *pd
) != nullptr; pd
= &d
->next
) {
618 if (c
->ident
.grfid
== d
->ident
.grfid
&& memcmp(c
->ident
.md5sum
, d
->ident
.md5sum
, sizeof(c
->ident
.md5sum
)) == 0) added
= false;
619 /* Because there can be multiple grfs with the same name, make sure we checked all grfs with the same name,
620 * before inserting the entry. So insert a new grf at the end of all grfs with the same name, instead of
621 * just after the first with the same name. Avoids doubles in the list. */
622 if (strcasecmp(c
->GetName(), d
->GetName()) <= 0) {
638 if (std::chrono::steady_clock::now() >= this->next_update
) {
639 this->next_update
= std::chrono::steady_clock::now() + std::chrono::milliseconds(MODAL_PROGRESS_REDRAW_TIMEOUT
);
641 _modal_progress_work_mutex
.unlock();
642 _modal_progress_paint_mutex
.lock();
644 const char *name
= nullptr;
645 if (c
->name
!= nullptr) name
= GetGRFStringFromGRFText(c
->name
);
646 if (name
== nullptr) name
= c
->filename
;
647 UpdateNewGRFScanStatus(this->num_scanned
, name
);
649 _modal_progress_work_mutex
.lock();
650 _modal_progress_paint_mutex
.unlock();
654 /* File couldn't be opened, or is either not a NewGRF or is a
655 * 'system' NewGRF or it's already known, so forget about it. */
663 * Simple sorter for GRFS
664 * @param c1 the first GRFConfig *
665 * @param c2 the second GRFConfig *
666 * @return true if the name of first NewGRF is before the name of the second.
668 static bool GRFSorter(GRFConfig
* const &c1
, GRFConfig
* const &c2
)
670 return strnatcmp(c1
->GetName(), c2
->GetName()) < 0;
674 * Really perform the scan for all NewGRFs.
675 * @param callback The callback to call after the scanning is complete.
677 void DoScanNewGRFFiles(NewGRFScanCallback
*callback
)
679 std::unique_lock
<std::mutex
> lock_work(_modal_progress_work_mutex
);
681 ClearGRFConfigList(&_all_grfs
);
682 TarScanner::DoScan(TarScanner::NEWGRF
);
684 DEBUG(grf
, 1, "Scanning for NewGRFs");
685 uint num
= GRFFileScanner::DoScan();
687 DEBUG(grf
, 1, "Scan complete, found %d files", num
);
688 if (num
!= 0 && _all_grfs
!= nullptr) {
689 /* Sort the linked list using quicksort.
690 * For that we first have to make an array, then sort and
691 * then remake the linked list. */
692 std::vector
<GRFConfig
*> to_sort
;
695 for (GRFConfig
*p
= _all_grfs
; p
!= nullptr; p
= p
->next
, i
++) {
696 to_sort
.push_back(p
);
698 /* Number of files is not necessarily right */
701 std::sort(to_sort
.begin(), to_sort
.end(), GRFSorter
);
703 for (i
= 1; i
< num
; i
++) {
704 to_sort
[i
- 1]->next
= to_sort
[i
];
706 to_sort
[num
- 1]->next
= nullptr;
707 _all_grfs
= to_sort
[0];
709 NetworkAfterNewGRFScan();
713 std::lock_guard
<std::mutex
> lock_paint(_modal_progress_paint_mutex
);
715 /* Yes... these are the NewGRF windows */
716 InvalidateWindowClassesData(WC_SAVELOAD
, 0, true);
717 InvalidateWindowData(WC_GAME_OPTIONS
, WN_GAME_OPTIONS_NEWGRF_STATE
, GOID_NEWGRF_RESCANNED
, true);
718 if (callback
!= nullptr) callback
->OnNewGRFsScanned();
720 DeleteWindowByClass(WC_MODAL_PROGRESS
);
721 SetModalProgress(false);
722 MarkWholeScreenDirty();
726 * Scan for all NewGRFs.
727 * @param callback The callback to call after the scanning is complete.
729 void ScanNewGRFFiles(NewGRFScanCallback
*callback
)
731 /* First set the modal progress. This ensures that it will eventually let go of the paint mutex. */
732 SetModalProgress(true);
733 /* Only then can we really start, especially by marking the whole screen dirty. Get those other windows hidden!. */
734 MarkWholeScreenDirty();
736 if (!UseThreadedModelProgress() || !VideoDriver::GetInstance()->HasGUI() || !StartNewThread(nullptr, "ottd:newgrf-scan", &DoScanNewGRFFiles
, (NewGRFScanCallback
*)callback
)) { // Without the seemingly superfluous cast, strange compiler errors ensue.
737 _modal_progress_work_mutex
.unlock();
738 _modal_progress_paint_mutex
.unlock();
739 DoScanNewGRFFiles(callback
);
740 _modal_progress_paint_mutex
.lock();
741 _modal_progress_work_mutex
.lock();
743 UpdateNewGRFScanStatus(0, nullptr);
748 * Find a NewGRF in the scanned list.
749 * @param grfid GRFID to look for,
750 * @param mode Restrictions for matching grfs
751 * @param md5sum Expected MD5 sum
752 * @param desired_version Requested version
753 * @return The matching grf, if it exists in #_all_grfs, else \c nullptr.
755 const GRFConfig
*FindGRFConfig(uint32 grfid
, FindGRFConfigMode mode
, const uint8
*md5sum
, uint32 desired_version
)
757 assert((mode
== FGCM_EXACT
) != (md5sum
== nullptr));
758 const GRFConfig
*best
= nullptr;
759 for (const GRFConfig
*c
= _all_grfs
; c
!= nullptr; c
= c
->next
) {
760 /* if md5sum is set, we look for an exact match and continue if not found */
761 if (!c
->ident
.HasGrfIdentifier(grfid
, md5sum
)) continue;
762 /* return it, if the exact same newgrf is found, or if we do not care about finding "the best" */
763 if (md5sum
!= nullptr || mode
== FGCM_ANY
) return c
;
764 /* Skip incompatible stuff, unless explicitly allowed */
765 if (mode
!= FGCM_NEWEST
&& HasBit(c
->flags
, GCF_INVALID
)) continue;
766 /* check version compatibility */
767 if (mode
== FGCM_COMPATIBLE
&& (c
->version
< desired_version
|| c
->min_loadable_version
> desired_version
)) continue;
768 /* remember the newest one as "the best" */
769 if (best
== nullptr || c
->version
> best
->version
) best
= c
;
775 /** Structure for UnknownGRFs; this is a lightweight variant of GRFConfig */
776 struct UnknownGRF
: public GRFIdentifier
{
777 GRFTextWrapper name
; ///< Name of the GRF.
779 UnknownGRF() = default;
780 UnknownGRF(const UnknownGRF
&other
) = default;
781 UnknownGRF(UnknownGRF
&&other
) = default;
782 UnknownGRF(uint32 grfid
, const uint8
*_md5sum
) : GRFIdentifier(grfid
, _md5sum
), name(new GRFTextList
) {}
786 * Finds the name of a NewGRF in the list of names for unknown GRFs. An
787 * unknown GRF is a GRF where the .grf is not found during scanning.
789 * The names are resolved via UDP calls to servers that should know the name,
790 * though the replies may not come. This leaves "<Unknown>" as name, though
791 * that shouldn't matter _very_ much as they need GRF crawler or so to look
792 * up the GRF anyway and that works better with the GRF ID.
794 * @param grfid the GRF ID part of the 'unique' GRF identifier
795 * @param md5sum the MD5 checksum part of the 'unique' GRF identifier
796 * @param create whether to create a new GRFConfig if the GRFConfig did not
797 * exist in the fake list of GRFConfigs.
798 * @return The GRFTextWrapper of the name of the GRFConfig with the given GRF ID
799 * and MD5 checksum or nullptr when it does not exist and create is false.
800 * This value must NEVER be freed by the caller.
802 GRFTextWrapper
FindUnknownGRFName(uint32 grfid
, uint8
*md5sum
, bool create
)
804 static std::vector
<UnknownGRF
> unknown_grfs
;
806 for (const auto &grf
: unknown_grfs
) {
807 if (grf
.grfid
== grfid
) {
808 if (memcmp(md5sum
, grf
.md5sum
, sizeof(grf
.md5sum
)) == 0) return grf
.name
;
812 if (!create
) return nullptr;
814 unknown_grfs
.emplace_back(grfid
, md5sum
);
815 UnknownGRF
&grf
= unknown_grfs
.back();
817 AddGRFTextToList(grf
.name
, UNKNOWN_GRF_NAME_PLACEHOLDER
);
823 * Retrieve a NewGRF from the current config by its grfid.
824 * @param grfid grf to look for.
825 * @param mask GRFID mask to allow for partial matching.
826 * @return The grf config, if it exists, else \c nullptr.
828 GRFConfig
*GetGRFConfig(uint32 grfid
, uint32 mask
)
832 for (c
= _grfconfig
; c
!= nullptr; c
= c
->next
) {
833 if ((c
->ident
.grfid
& mask
) == (grfid
& mask
)) return c
;
840 /** Build a string containing space separated parameter values, and terminate */
841 char *GRFBuildParamList(char *dst
, const GRFConfig
*c
, const char *last
)
845 /* Return an empty string if there are no parameters */
846 if (c
->num_params
== 0) return strecpy(dst
, "", last
);
848 for (i
= 0; i
< c
->num_params
; i
++) {
849 if (i
> 0) dst
= strecpy(dst
, " ", last
);
850 dst
+= seprintf(dst
, last
, "%d", c
->param
[i
]);
855 /** Base GRF ID for OpenTTD's base graphics GRFs. */
856 static const uint32 OPENTTD_GRAPHICS_BASE_GRF_ID
= BSWAP32(0xFF4F5400);
859 * Search a textfile file next to this NewGRF.
860 * @param type The type of the textfile to search for.
861 * @return The filename for the textfile, \c nullptr otherwise.
863 const char *GRFConfig::GetTextfile(TextfileType type
) const
865 return ::GetTextfile(type
, NEWGRF_DIR
, this->filename
);