Silence uninitialised variable warnings in SSE blitters
[openttd/fttd.git] / src / newgrf_config.cpp
blob337b3edd11c010705f9ea241514b59f741c0c24a
1 /* $Id$ */
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 */
10 /** @file newgrf_config.cpp Finding NewGRFs and configuring them. */
12 #include "stdafx.h"
13 #include "debug.h"
14 #include "3rdparty/md5/md5.h"
15 #include "newgrf.h"
16 #include "network/network_func.h"
17 #include "gfx_func.h"
18 #include "newgrf_text.h"
19 #include "window_func.h"
20 #include "progress.h"
21 #include "video/video_driver.hpp"
22 #include "strings_func.h"
23 #include "textfile_gui.h"
25 #include "fileio_func.h"
26 #include "fios.h"
28 /** Create a new GRFTextWrapper. */
29 GRFTextWrapper::GRFTextWrapper() :
30 text(NULL)
34 /** Cleanup a GRFTextWrapper object. */
35 GRFTextWrapper::~GRFTextWrapper()
37 CleanUpGRFText(this->text);
40 /**
41 * Create a new GRFConfig.
42 * @param filename Set the filename of this GRFConfig to filename. The argument
43 * is copied so the original string isn't needed after the constructor.
45 GRFConfig::GRFConfig(const char *filename) :
46 name(new GRFTextWrapper()),
47 info(new GRFTextWrapper()),
48 url(new GRFTextWrapper()),
49 num_valid_params(lengthof(param))
51 if (filename != NULL) this->filename = strdup(filename);
52 this->name->AddRef();
53 this->info->AddRef();
54 this->url->AddRef();
57 /**
58 * Create a new GRFConfig that is a deep copy of an existing config.
59 * @param config The GRFConfig object to make a copy of.
61 GRFConfig::GRFConfig(const GRFConfig &config) :
62 ZeroedMemoryAllocator(),
63 ident(config.ident),
64 name(config.name),
65 info(config.info),
66 url(config.url),
67 version(config.version),
68 min_loadable_version(config.min_loadable_version),
69 flags(config.flags & ~(1 << GCF_COPY)),
70 status(config.status),
71 grf_bugs(config.grf_bugs),
72 num_params(config.num_params),
73 num_valid_params(config.num_valid_params),
74 palette(config.palette),
75 has_param_defaults(config.has_param_defaults)
77 MemCpyT<uint8>(this->original_md5sum, config.original_md5sum, lengthof(this->original_md5sum));
78 MemCpyT<uint32>(this->param, config.param, lengthof(this->param));
79 if (config.filename != NULL) this->filename = strdup(config.filename);
80 this->name->AddRef();
81 this->info->AddRef();
82 this->url->AddRef();
83 if (config.error != NULL) this->error = new GRFError(*config.error);
84 for (uint i = 0; i < config.param_info.Length(); i++) {
85 if (config.param_info[i] == NULL) {
86 *this->param_info.Append() = NULL;
87 } else {
88 *this->param_info.Append() = new GRFParameterInfo(*config.param_info[i]);
93 /** Cleanup a GRFConfig object. */
94 GRFConfig::~GRFConfig()
96 /* GCF_COPY as in NOT strdupped/alloced the filename */
97 if (!HasBit(this->flags, GCF_COPY)) {
98 free(this->filename);
99 delete this->error;
101 this->name->Release();
102 this->info->Release();
103 this->url->Release();
105 for (uint i = 0; i < this->param_info.Length(); i++) delete this->param_info[i];
109 * Get the name of this grf. In case the name isn't known
110 * the filename is returned.
111 * @return The name of filename of this grf.
113 const char *GRFConfig::GetName() const
115 const char *name = GetGRFStringFromGRFText(this->name->text);
116 return StrEmpty(name) ? this->filename : name;
120 * Get the grf info.
121 * @return A string with a description of this grf.
123 const char *GRFConfig::GetDescription() const
125 return GetGRFStringFromGRFText(this->info->text);
129 * Get the grf url.
130 * @return A string with an url of this grf.
132 const char *GRFConfig::GetURL() const
134 return GetGRFStringFromGRFText(this->url->text);
137 /** Set the default value for all parameters as specified by action14. */
138 void GRFConfig::SetParameterDefaults()
140 this->num_params = 0;
141 MemSetT<uint32>(this->param, 0, lengthof(this->param));
143 if (!this->has_param_defaults) return;
145 for (uint i = 0; i < this->param_info.Length(); i++) {
146 if (this->param_info[i] == NULL) continue;
147 this->param_info[i]->SetValue(this, this->param_info[i]->def_value);
152 * Set the palette of this GRFConfig to something suitable.
153 * That is either the setting coming from the NewGRF or
154 * the globally used palette.
156 void GRFConfig::SetSuitablePalette()
158 PaletteType pal;
159 switch (this->palette & GRFP_GRF_MASK) {
160 case GRFP_GRF_DOS: pal = PAL_DOS; break;
161 case GRFP_GRF_WINDOWS: pal = PAL_WINDOWS; break;
162 default: pal = _settings_client.gui.newgrf_default_palette == 1 ? PAL_WINDOWS : PAL_DOS; break;
164 SB(this->palette, GRFP_USE_BIT, 1, pal == PAL_WINDOWS ? GRFP_USE_WINDOWS : GRFP_USE_DOS);
168 * Finalize Action 14 info after file scan is finished.
170 void GRFConfig::FinalizeParameterInfo()
172 for (GRFParameterInfo **info = this->param_info.Begin(); info != this->param_info.End(); ++info) {
173 if (*info == NULL) continue;
174 (*info)->Finalize();
178 GRFConfig *_all_grfs;
179 GRFConfig *_grfconfig;
180 GRFConfig *_grfconfig_newgame;
181 GRFConfig *_grfconfig_static;
184 * Construct a new GRFError.
185 * @param severity The severity of this error.
186 * @param message The actual error-string.
188 GRFError::GRFError(StringID severity, StringID message) :
189 message(message),
190 severity(severity)
195 * Create a new GRFError that is a deep copy of an existing error message.
196 * @param error The GRFError object to make a copy of.
198 GRFError::GRFError(const GRFError &error) :
199 ZeroedMemoryAllocator(),
200 custom_message(error.custom_message),
201 data(error.data),
202 message(error.message),
203 severity(error.severity)
205 if (error.custom_message != NULL) this->custom_message = strdup(error.custom_message);
206 if (error.data != NULL) this->data = strdup(error.data);
207 memcpy(this->param_value, error.param_value, sizeof(this->param_value));
210 GRFError::~GRFError()
212 free(this->custom_message);
213 free(this->data);
217 * Create a new empty GRFParameterInfo object.
218 * @param nr The newgrf parameter that is changed.
220 GRFParameterInfo::GRFParameterInfo(uint nr) :
221 name(NULL),
222 desc(NULL),
223 type(PTYPE_UINT_ENUM),
224 min_value(0),
225 max_value(UINT32_MAX),
226 def_value(0),
227 param_nr(nr),
228 first_bit(0),
229 num_bit(32),
230 complete_labels(false)
234 * Create a new GRFParameterInfo object that is a deep copy of an existing
235 * parameter info object.
236 * @param info The GRFParameterInfo object to make a copy of.
238 GRFParameterInfo::GRFParameterInfo(GRFParameterInfo &info) :
239 name(DuplicateGRFText(info.name)),
240 desc(DuplicateGRFText(info.desc)),
241 type(info.type),
242 min_value(info.min_value),
243 max_value(info.max_value),
244 def_value(info.def_value),
245 param_nr(info.param_nr),
246 first_bit(info.first_bit),
247 num_bit(info.num_bit),
248 complete_labels(info.complete_labels)
250 for (uint i = 0; i < info.value_names.Length(); i++) {
251 SmallPair<uint32, GRFText *> *data = info.value_names.Get(i);
252 this->value_names.Insert(data->first, DuplicateGRFText(data->second));
256 /** Cleanup all parameter info. */
257 GRFParameterInfo::~GRFParameterInfo()
259 CleanUpGRFText(this->name);
260 CleanUpGRFText(this->desc);
261 for (uint i = 0; i < this->value_names.Length(); i++) {
262 SmallPair<uint32, GRFText *> *data = this->value_names.Get(i);
263 CleanUpGRFText(data->second);
268 * Get the value of this user-changeable parameter from the given config.
269 * @param config The GRFConfig to get the value from.
270 * @return The value of this parameter.
272 uint32 GRFParameterInfo::GetValue(struct GRFConfig *config) const
274 /* GB doesn't work correctly with nbits == 32, so handle that case here. */
275 if (this->num_bit == 32) return config->param[this->param_nr];
276 return GB(config->param[this->param_nr], this->first_bit, this->num_bit);
280 * Set the value of this user-changeable parameter in the given config.
281 * @param config The GRFConfig to set the value in.
282 * @param value The new value.
284 void GRFParameterInfo::SetValue(struct GRFConfig *config, uint32 value)
286 /* SB doesn't work correctly with nbits == 32, so handle that case here. */
287 if (this->num_bit == 32) {
288 config->param[this->param_nr] = value;
289 } else {
290 SB(config->param[this->param_nr], this->first_bit, this->num_bit, value);
292 config->num_params = max<uint>(config->num_params, this->param_nr + 1);
293 SetWindowDirty(WC_GAME_OPTIONS, WN_GAME_OPTIONS_NEWGRF_STATE);
297 * Finalize Action 14 info after file scan is finished.
299 void GRFParameterInfo::Finalize()
301 this->complete_labels = true;
302 for (uint32 value = this->min_value; value <= this->max_value; value++) {
303 if (!this->value_names.Contains(value)) {
304 this->complete_labels = false;
305 break;
311 * Update the palettes of the graphics from the config file.
312 * Called when changing the default palette in advanced settings.
313 * @param p1 Unused.
314 * @return Always true.
316 bool UpdateNewGRFConfigPalette(int32 p1)
318 for (GRFConfig *c = _grfconfig_newgame; c != NULL; c = c->next) c->SetSuitablePalette();
319 for (GRFConfig *c = _grfconfig_static; c != NULL; c = c->next) c->SetSuitablePalette();
320 for (GRFConfig *c = _all_grfs; c != NULL; c = c->next) c->SetSuitablePalette();
321 return true;
325 * Get the data section size of a GRF.
326 * @param f GRF.
327 * @return Size of the data section or SIZE_MAX if the file has no separate data section.
329 size_t GRFGetSizeOfDataSection(FILE *f)
331 extern const byte _grf_cont_v2_sig[];
332 static const uint header_len = 14;
334 byte data[header_len];
335 if (fread(data, 1, header_len, f) == header_len) {
336 if (data[0] == 0 && data[1] == 0 && MemCmpT(data + 2, _grf_cont_v2_sig, 8) == 0) {
337 /* Valid container version 2, get data section size. */
338 size_t offset = ((size_t)data[13] << 24) | ((size_t)data[12] << 16) | ((size_t)data[11] << 8) | (size_t)data[10];
339 if (offset >= 1 * 1024 * 1024 * 1024) {
340 DEBUG(grf, 0, "Unexpectedly large offset for NewGRF");
341 /* Having more than 1 GiB of data is very implausible. Mostly because then
342 * all pools in OpenTTD are flooded already. Or it's just Action C all over.
343 * In any case, the offsets to graphics will likely not work either. */
344 return SIZE_MAX;
346 return header_len + offset;
350 return SIZE_MAX;
354 * Calculate the MD5 sum for a GRF, and store it in the config.
355 * @param config GRF to compute.
356 * @param subdir The subdirectory to look in.
357 * @return MD5 sum was successfully computed
359 static bool CalcGRFMD5Sum(GRFConfig *config, Subdirectory subdir)
361 FILE *f;
362 Md5 checksum;
363 uint8 buffer[1024];
364 size_t len, size;
366 /* open the file */
367 f = FioFOpenFile(config->filename, "rb", subdir, &size);
368 if (f == NULL) return false;
370 long start = ftell(f);
371 size = min(size, GRFGetSizeOfDataSection(f));
373 if (start < 0 || fseek(f, start, SEEK_SET) < 0) {
374 FioFCloseFile(f);
375 return false;
378 /* calculate md5sum */
379 while ((len = fread(buffer, 1, (size > sizeof(buffer)) ? sizeof(buffer) : size, f)) != 0 && size != 0) {
380 size -= len;
381 checksum.Append(buffer, len);
383 checksum.Finish(config->ident.md5sum);
385 FioFCloseFile(f);
387 return true;
392 * Find the GRFID of a given grf, and calculate its md5sum.
393 * @param config grf to fill.
394 * @param is_static grf is static.
395 * @param subdir the subdirectory to search in.
396 * @return Operation was successfully completed.
398 bool FillGRFDetails(GRFConfig *config, bool is_static, Subdirectory subdir)
400 if (!FioCheckFileExists(config->filename, subdir)) {
401 config->status = GCS_NOT_FOUND;
402 return false;
405 /* Find and load the Action 8 information */
406 LoadNewGRFFile(config, CONFIG_SLOT, GLS_FILESCAN, subdir);
407 config->SetSuitablePalette();
408 config->FinalizeParameterInfo();
410 /* Skip if the grfid is 0 (not read) or 0xFFFFFFFF (ttdp system grf) */
411 if (config->ident.grfid == 0 || config->ident.grfid == 0xFFFFFFFF || config->IsOpenTTDBaseGRF()) return false;
413 if (is_static) {
414 /* Perform a 'safety scan' for static GRFs */
415 LoadNewGRFFile(config, 62, GLS_SAFETYSCAN, subdir);
417 /* GCF_UNSAFE is set if GLS_SAFETYSCAN finds unsafe actions */
418 if (HasBit(config->flags, GCF_UNSAFE)) return false;
421 return CalcGRFMD5Sum(config, subdir);
426 * Clear a GRF Config list, freeing all nodes.
427 * @param config Start of the list.
428 * @post \a config is set to \c NULL.
430 void ClearGRFConfigList(GRFConfig **config)
432 GRFConfig *c, *next;
433 for (c = *config; c != NULL; c = next) {
434 next = c->next;
435 delete c;
437 *config = NULL;
442 * Copy a GRF Config list
443 * @param dst pointer to destination list
444 * @param src pointer to source list values
445 * @param init_only the copied GRF will be processed up to GLS_INIT
446 * @return pointer to the last value added to the destination list
448 GRFConfig **CopyGRFConfigList(GRFConfig **dst, const GRFConfig *src, bool init_only)
450 /* Clear destination as it will be overwritten */
451 ClearGRFConfigList(dst);
452 for (; src != NULL; src = src->next) {
453 GRFConfig *c = new GRFConfig(*src);
455 ClrBit(c->flags, GCF_INIT_ONLY);
456 if (init_only) SetBit(c->flags, GCF_INIT_ONLY);
458 *dst = c;
459 dst = &c->next;
462 return dst;
466 * Removes duplicates from lists of GRFConfigs. These duplicates
467 * are introduced when the _grfconfig_static GRFs are appended
468 * to the _grfconfig on a newgame or savegame. As the parameters
469 * of the static GRFs could be different that the parameters of
470 * the ones used non-statically. This can result in desyncs in
471 * multiplayers, so the duplicate static GRFs have to be removed.
473 * This function _assumes_ that all static GRFs are placed after
474 * the non-static GRFs.
476 * @param list the list to remove the duplicates from
478 static void RemoveDuplicatesFromGRFConfigList(GRFConfig *list)
480 GRFConfig *prev;
481 GRFConfig *cur;
483 if (list == NULL) return;
485 for (prev = list, cur = list->next; cur != NULL; prev = cur, cur = cur->next) {
486 if (cur->ident.grfid != list->ident.grfid) continue;
488 prev->next = cur->next;
489 delete cur;
490 cur = prev; // Just go back one so it continues as normal later on
493 RemoveDuplicatesFromGRFConfigList(list->next);
497 * Appends the static GRFs to a list of GRFs
498 * @param dst the head of the list to add to
500 void AppendStaticGRFConfigs(GRFConfig **dst)
502 GRFConfig **tail = dst;
503 while (*tail != NULL) tail = &(*tail)->next;
505 CopyGRFConfigList(tail, _grfconfig_static, false);
506 RemoveDuplicatesFromGRFConfigList(*dst);
510 * Appends an element to a list of GRFs
511 * @param dst the head of the list to add to
512 * @param el the new tail to be
514 void AppendToGRFConfigList(GRFConfig **dst, GRFConfig *el)
516 GRFConfig **tail = dst;
517 while (*tail != NULL) tail = &(*tail)->next;
518 *tail = el;
520 RemoveDuplicatesFromGRFConfigList(*dst);
524 /** Reset the current GRF Config to either blank or newgame settings. */
525 void ResetGRFConfig(bool defaults)
527 CopyGRFConfigList(&_grfconfig, _grfconfig_newgame, !defaults);
528 AppendStaticGRFConfigs(&_grfconfig);
533 * Check if all GRFs in the GRF config from a savegame can be loaded.
534 * @param grfconfig GrfConfig to check
535 * @return will return any of the following 3 values:<br>
536 * <ul>
537 * <li> GLC_ALL_GOOD: No problems occurred, all GRF files were found and loaded
538 * <li> GLC_COMPATIBLE: For one or more GRF's no exact match was found, but a
539 * compatible GRF with the same grfid was found and used instead
540 * <li> GLC_NOT_FOUND: For one or more GRF's no match was found at all
541 * </ul>
543 GRFListCompatibility IsGoodGRFConfigList(GRFConfig *grfconfig)
545 GRFListCompatibility res = GLC_ALL_GOOD;
547 for (GRFConfig *c = grfconfig; c != NULL; c = c->next) {
548 const GRFConfig *f = FindGRFConfig(c->ident.grfid, FGCM_EXACT, c->ident.md5sum);
549 if (f == NULL || HasBit(f->flags, GCF_INVALID)) {
550 char buf[256];
552 /* If we have not found the exactly matching GRF try to find one with the
553 * same grfid, as it most likely is compatible */
554 f = FindGRFConfig(c->ident.grfid, FGCM_COMPATIBLE, NULL, c->version);
555 if (f != NULL) {
556 md5sumToString(buf, lastof(buf), c->ident.md5sum);
557 DEBUG(grf, 1, "NewGRF %08X (%s) not found; checksum %s. Compatibility mode on", BSWAP32(c->ident.grfid), c->filename, buf);
558 if (!HasBit(c->flags, GCF_COMPATIBLE)) {
559 /* Preserve original_md5sum after it has been assigned */
560 SetBit(c->flags, GCF_COMPATIBLE);
561 memcpy(c->original_md5sum, c->ident.md5sum, sizeof(c->original_md5sum));
564 /* Non-found has precedence over compatibility load */
565 if (res != GLC_NOT_FOUND) res = GLC_COMPATIBLE;
566 goto compatible_grf;
569 /* No compatible grf was found, mark it as disabled */
570 md5sumToString(buf, lastof(buf), c->ident.md5sum);
571 DEBUG(grf, 0, "NewGRF %08X (%s) not found; checksum %s", BSWAP32(c->ident.grfid), c->filename, buf);
573 c->status = GCS_NOT_FOUND;
574 res = GLC_NOT_FOUND;
575 } else {
576 compatible_grf:
577 DEBUG(grf, 1, "Loading GRF %08X from %s", BSWAP32(f->ident.grfid), f->filename);
578 /* The filename could be the filename as in the savegame. As we need
579 * to load the GRF here, we need the correct filename, so overwrite that
580 * in any case and set the name and info when it is not set already.
581 * When the GCF_COPY flag is set, it is certain that the filename is
582 * already a local one, so there is no need to replace it. */
583 if (!HasBit(c->flags, GCF_COPY)) {
584 free(c->filename);
585 c->filename = strdup(f->filename);
586 memcpy(c->ident.md5sum, f->ident.md5sum, sizeof(c->ident.md5sum));
587 c->name->Release();
588 c->name = f->name;
589 c->name->AddRef();
590 c->info->Release();
591 c->info = f->name;
592 c->info->AddRef();
593 c->error = NULL;
594 c->version = f->version;
595 c->min_loadable_version = f->min_loadable_version;
596 c->num_valid_params = f->num_valid_params;
597 c->has_param_defaults = f->has_param_defaults;
598 for (uint i = 0; i < f->param_info.Length(); i++) {
599 if (f->param_info[i] == NULL) {
600 *c->param_info.Append() = NULL;
601 } else {
602 *c->param_info.Append() = new GRFParameterInfo(*f->param_info[i]);
609 return res;
612 /** Helper for scanning for files with GRF as extension */
613 class GRFFileScanner : FileScanner {
614 uint next_update; ///< The next (realtime tick) we do update the screen.
615 uint num_scanned; ///< The number of GRFs we have scanned.
617 public:
618 GRFFileScanner() : next_update(_realtime_tick), num_scanned(0)
622 /* virtual */ bool AddFile(const char *filename, size_t basepath_length, const char *tar_filename);
624 /** Do the scan for GRFs. */
625 static uint DoScan()
627 GRFFileScanner fs;
628 int ret = fs.Scan(".grf", NEWGRF_DIR);
629 /* The number scanned and the number returned may not be the same;
630 * duplicate NewGRFs and base sets are ignored in the return value. */
631 _settings_client.gui.last_newgrf_count = fs.num_scanned;
632 return ret;
636 bool GRFFileScanner::AddFile(const char *filename, size_t basepath_length, const char *tar_filename)
638 GRFConfig *c = new GRFConfig(filename + basepath_length);
640 bool added = true;
641 if (FillGRFDetails(c, false)) {
642 if (_all_grfs == NULL) {
643 _all_grfs = c;
644 } else {
645 /* Insert file into list at a position determined by its
646 * name, so the list is sorted as we go along */
647 GRFConfig **pd, *d;
648 bool stop = false;
649 for (pd = &_all_grfs; (d = *pd) != NULL; pd = &d->next) {
650 if (c->ident.grfid == d->ident.grfid && memcmp(c->ident.md5sum, d->ident.md5sum, sizeof(c->ident.md5sum)) == 0) added = false;
651 /* Because there can be multiple grfs with the same name, make sure we checked all grfs with the same name,
652 * before inserting the entry. So insert a new grf at the end of all grfs with the same name, instead of
653 * just after the first with the same name. Avoids doubles in the list. */
654 if (strcasecmp(c->GetName(), d->GetName()) <= 0) {
655 stop = true;
656 } else if (stop) {
657 break;
660 if (added) {
661 c->next = d;
662 *pd = c;
665 } else {
666 added = false;
669 this->num_scanned++;
670 if (this->next_update <= _realtime_tick) {
671 _modal_progress_work_mutex->EndCritical();
672 _modal_progress_paint_mutex->BeginCritical();
674 const char *name = NULL;
675 if (c->name != NULL) name = GetGRFStringFromGRFText(c->name->text);
676 if (name == NULL) name = c->filename;
677 UpdateNewGRFScanStatus(this->num_scanned, name);
679 _modal_progress_work_mutex->BeginCritical();
680 _modal_progress_paint_mutex->EndCritical();
682 this->next_update = _realtime_tick + 200;
685 if (!added) {
686 /* File couldn't be opened, or is either not a NewGRF or is a
687 * 'system' NewGRF or it's already known, so forget about it. */
688 delete c;
691 return added;
695 * Simple sorter for GRFS
696 * @param p1 the first GRFConfig *
697 * @param p2 the second GRFConfig *
698 * @return the same strcmp would return for the name of the NewGRF.
700 static int CDECL GRFSorter(GRFConfig * const *p1, GRFConfig * const *p2)
702 const GRFConfig *c1 = *p1;
703 const GRFConfig *c2 = *p2;
705 return strcasecmp(c1->GetName(), c2->GetName());
709 * Really perform the scan for all NewGRFs.
710 * @param callback The callback to call after the scanning is complete.
712 void DoScanNewGRFFiles(void *callback)
714 _modal_progress_work_mutex->BeginCritical();
716 ClearGRFConfigList(&_all_grfs);
717 TarScanner::DoScan(TarScanner::NEWGRF);
719 DEBUG(grf, 1, "Scanning for NewGRFs");
720 uint num = GRFFileScanner::DoScan();
722 DEBUG(grf, 1, "Scan complete, found %d files", num);
723 if (num != 0 && _all_grfs != NULL) {
724 /* Sort the linked list using quicksort.
725 * For that we first have to make an array, then sort and
726 * then remake the linked list. */
727 GRFConfig **to_sort = MallocT<GRFConfig*>(num);
729 uint i = 0;
730 for (GRFConfig *p = _all_grfs; p != NULL; p = p->next, i++) {
731 to_sort[i] = p;
733 /* Number of files is not necessarily right */
734 num = i;
736 QSortT(to_sort, num, &GRFSorter);
738 for (i = 1; i < num; i++) {
739 to_sort[i - 1]->next = to_sort[i];
741 to_sort[num - 1]->next = NULL;
742 _all_grfs = to_sort[0];
744 free(to_sort);
746 #ifdef ENABLE_NETWORK
747 NetworkAfterNewGRFScan();
748 #endif
751 _modal_progress_work_mutex->EndCritical();
752 _modal_progress_paint_mutex->BeginCritical();
754 /* Yes... these are the NewGRF windows */
755 InvalidateWindowClassesData(WC_SAVELOAD, 0, true);
756 InvalidateWindowData(WC_GAME_OPTIONS, WN_GAME_OPTIONS_NEWGRF_STATE, GOID_NEWGRF_RESCANNED, true);
757 if (callback != NULL) ((NewGRFScanCallback*)callback)->OnNewGRFsScanned();
759 DeleteWindowByClass(WC_MODAL_PROGRESS);
760 SetModalProgress(false);
761 MarkWholeScreenDirty();
762 _modal_progress_paint_mutex->EndCritical();
766 * Scan for all NewGRFs.
767 * @param callback The callback to call after the scanning is complete.
769 void ScanNewGRFFiles(NewGRFScanCallback *callback)
771 /* First set the modal progress. This ensures that it will eventually let go of the paint mutex. */
772 SetModalProgress(true);
773 /* Only then can we really start, especially by marking the whole screen dirty. Get those other windows hidden!. */
774 MarkWholeScreenDirty();
776 if (!_video_driver->HasGUI() || !ThreadObject::New(&DoScanNewGRFFiles, callback, NULL)) {
777 _modal_progress_work_mutex->EndCritical();
778 _modal_progress_paint_mutex->EndCritical();
779 DoScanNewGRFFiles(callback);
780 _modal_progress_paint_mutex->BeginCritical();
781 _modal_progress_work_mutex->BeginCritical();
782 } else {
783 UpdateNewGRFScanStatus(0, NULL);
788 * Find a NewGRF in the scanned list.
789 * @param grfid GRFID to look for,
790 * @param mode Restrictions for matching grfs
791 * @param md5sum Expected MD5 sum
792 * @param desired_version Requested version
793 * @return The matching grf, if it exists in #_all_grfs, else \c NULL.
795 const GRFConfig *FindGRFConfig(uint32 grfid, FindGRFConfigMode mode, const uint8 *md5sum, uint32 desired_version)
797 assert((mode == FGCM_EXACT) != (md5sum == NULL));
798 const GRFConfig *best = NULL;
799 for (const GRFConfig *c = _all_grfs; c != NULL; c = c->next) {
800 /* if md5sum is set, we look for an exact match and continue if not found */
801 if (!c->ident.HasGrfIdentifier(grfid, md5sum)) continue;
802 /* return it, if the exact same newgrf is found, or if we do not care about finding "the best" */
803 if (md5sum != NULL || mode == FGCM_ANY) return c;
804 /* Skip incompatible stuff, unless explicitly allowed */
805 if (mode != FGCM_NEWEST && HasBit(c->flags, GCF_INVALID)) continue;
806 /* check version compatibility */
807 if (mode == FGCM_COMPATIBLE && (c->version < desired_version || c->min_loadable_version > desired_version)) continue;
808 /* remember the newest one as "the best" */
809 if (best == NULL || c->version > best->version) best = c;
812 return best;
815 #ifdef ENABLE_NETWORK
817 /** Structure for UnknownGRFs; this is a lightweight variant of GRFConfig */
818 struct UnknownGRF : public GRFIdentifier {
819 UnknownGRF *next; ///< The next unknown GRF.
820 GRFTextWrapper *name; ///< Name of the GRF.
824 * Finds the name of a NewGRF in the list of names for unknown GRFs. An
825 * unknown GRF is a GRF where the .grf is not found during scanning.
827 * The names are resolved via UDP calls to servers that should know the name,
828 * though the replies may not come. This leaves "<Unknown>" as name, though
829 * that shouldn't matter _very_ much as they need GRF crawler or so to look
830 * up the GRF anyway and that works better with the GRF ID.
832 * @param grfid the GRF ID part of the 'unique' GRF identifier
833 * @param md5sum the MD5 checksum part of the 'unique' GRF identifier
834 * @param create whether to create a new GRFConfig if the GRFConfig did not
835 * exist in the fake list of GRFConfigs.
836 * @return The GRFTextWrapper of the name of the GRFConfig with the given GRF ID
837 * and MD5 checksum or NULL when it does not exist and create is false.
838 * This value must NEVER be freed by the caller.
840 GRFTextWrapper *FindUnknownGRFName(uint32 grfid, uint8 *md5sum, bool create)
842 UnknownGRF *grf;
843 static UnknownGRF *unknown_grfs = NULL;
845 for (grf = unknown_grfs; grf != NULL; grf = grf->next) {
846 if (grf->grfid == grfid) {
847 if (memcmp(md5sum, grf->md5sum, sizeof(grf->md5sum)) == 0) return grf->name;
851 if (!create) return NULL;
853 grf = CallocT<UnknownGRF>(1);
854 grf->grfid = grfid;
855 grf->next = unknown_grfs;
856 grf->name = new GRFTextWrapper();
857 grf->name->AddRef();
859 AddGRFTextToList(&grf->name->text, UNKNOWN_GRF_NAME_PLACEHOLDER);
860 memcpy(grf->md5sum, md5sum, sizeof(grf->md5sum));
862 unknown_grfs = grf;
863 return grf->name;
866 #endif /* ENABLE_NETWORK */
870 * Retrieve a NewGRF from the current config by its grfid.
871 * @param grfid grf to look for.
872 * @param mask GRFID mask to allow for partial matching.
873 * @return The grf config, if it exists, else \c NULL.
875 GRFConfig *GetGRFConfig(uint32 grfid, uint32 mask)
877 GRFConfig *c;
879 for (c = _grfconfig; c != NULL; c = c->next) {
880 if ((c->ident.grfid & mask) == (grfid & mask)) return c;
883 return NULL;
887 /** Build a string containing space separated parameter values, and terminate */
888 char *GRFBuildParamList(char *dst, const GRFConfig *c, const char *last)
890 uint i;
892 /* Return an empty string if there are no parameters */
893 if (c->num_params == 0) return strecpy(dst, "", last);
895 for (i = 0; i < c->num_params; i++) {
896 if (i > 0) dst = strecpy(dst, " ", last);
897 dst += seprintf(dst, last, "%d", c->param[i]);
899 return dst;
902 /** Base GRF ID for OpenTTD's base graphics GRFs. */
903 static const uint32 OPENTTD_GRAPHICS_BASE_GRF_ID = BSWAP32(0xFF4F5400);
906 * Checks whether this GRF is a OpenTTD base graphic GRF.
907 * @return true if and only if it is a base GRF.
909 bool GRFConfig::IsOpenTTDBaseGRF() const
911 return (this->ident.grfid & 0x00FFFFFF) == OPENTTD_GRAPHICS_BASE_GRF_ID;
915 * Search a textfile file next to this NewGRF.
916 * @param type The type of the textfile to search for.
917 * @return The filename for the textfile, \c NULL otherwise.
919 const char *GRFConfig::GetTextfile(TextfileType type) const
921 return ::GetTextfile(type, NEWGRF_DIR, this->filename);