# newgrf_config.cpp

Go to the documentation of this file.

    00001 /* $Id: newgrf_config.cpp 26070 2013-11-23 18:11:01Z rubidium $ */
    00002
    00003 /*
    00004  * This file is part of OpenTTD.
    00005  * 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.
    00006  * 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.
    00007  * 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/>.
    00008  */
    00009
    00012 #include "stdafx.h"
    00013 #include "debug.h"
    00014 #include "3rdparty/md5/md5.h"
    00015 #include "newgrf.h"
    00016 #include "network/network_func.h"
    00017 #include "gfx_func.h"
    00018 #include "newgrf_text.h"
    00019 #include "window_func.h"
    00020 #include "progress.h"
    00021 #include "video/video_driver.hpp"
    00022 #include "strings_func.h"
    00023 #include "textfile_gui.h"
    00024
    00025 #include "fileio_func.h"
    00026 #include "fios.h"
    00027
    00029 GRFTextWrapper::GRFTextWrapper() :
    00030   text(NULL)
    00031 {
    00032 }
    00033
    00035 GRFTextWrapper::~GRFTextWrapper()
    00036 {
    00037   CleanUpGRFText(this->text);
    00038 }
    00039
    00045 GRFConfig::GRFConfig(const char *filename) :
    00046   name(new GRFTextWrapper()),
    00047   info(new GRFTextWrapper()),
    00048   url(new GRFTextWrapper()),
    00049   num_valid_params(lengthof(param))
    00050 {
    00051   if (filename != NULL) this->filename = strdup(filename);
    00052   this->name->AddRef();
    00053   this->info->AddRef();
    00054   this->url->AddRef();
    00055 }
    00056
    00061 GRFConfig::GRFConfig(const GRFConfig &config) :
    00062   ZeroedMemoryAllocator(),
    00063   ident(config.ident),
    00064   name(config.name),
    00065   info(config.info),
    00066   url(config.url),
    00067   version(config.version),
    00068   min_loadable_version(config.min_loadable_version),
    00069   flags(config.flags & ~(1 << GCF_COPY)),
    00070   status(config.status),
    00071   grf_bugs(config.grf_bugs),
    00072   num_params(config.num_params),
    00073   num_valid_params(config.num_valid_params),
    00074   palette(config.palette),
    00075   has_param_defaults(config.has_param_defaults)
    00076 {
    00077   MemCpyT<uint8>(this->original_md5sum, config.original_md5sum, lengthof(this->original_md5sum));
    00078   MemCpyT<uint32>(this->param, config.param, lengthof(this->param));
    00079   if (config.filename != NULL) this->filename = strdup(config.filename);
    00080   this->name->AddRef();
    00081   this->info->AddRef();
    00082   this->url->AddRef();
    00083   if (config.error    != NULL) this->error    = new GRFError(*config.error);
    00084   for (uint i = 0; i < config.param_info.Length(); i++) {
    00085     if (config.param_info[i] == NULL) {
    00086       *this->param_info.Append() = NULL;
    00087     } else {
    00088       *this->param_info.Append() = new GRFParameterInfo(*config.param_info[i]);
    00089     }
    00090   }
    00091 }
    00092
    00094 GRFConfig::~GRFConfig()
    00095 {
    00096   /* GCF_COPY as in NOT strdupped/alloced the filename */
    00097   if (!HasBit(this->flags, GCF_COPY)) {
    00098     free(this->filename);
    00099     delete this->error;
    00100   }
    00101   this->name->Release();
    00102   this->info->Release();
    00103   this->url->Release();
    00104
    00105   for (uint i = 0; i < this->param_info.Length(); i++) delete this->param_info[i];
    00106 }
    00107
    00113 const char *GRFConfig::GetName() const
    00114 {
    00115   const char *name = GetGRFStringFromGRFText(this->name->text);
    00116   return StrEmpty(name) ? this->filename : name;
    00117 }
    00118
    00123 const char *GRFConfig::GetDescription() const
    00124 {
    00125   return GetGRFStringFromGRFText(this->info->text);
    00126 }
    00127
    00132 const char *GRFConfig::GetURL() const
    00133 {
    00134   return GetGRFStringFromGRFText(this->url->text);
    00135 }
    00136
    00138 void GRFConfig::SetParameterDefaults()
    00139 {
    00140   this->num_params = 0;
    00141   MemSetT<uint32>(this->param, 0, lengthof(this->param));
    00142
    00143   if (!this->has_param_defaults) return;
    00144
    00145   for (uint i = 0; i < this->param_info.Length(); i++) {
    00146     if (this->param_info[i] == NULL) continue;
    00147     this->param_info[i]->SetValue(this, this->param_info[i]->def_value);
    00148   }
    00149 }
    00150
    00156 void GRFConfig::SetSuitablePalette()
    00157 {
    00158   PaletteType pal;
    00159   switch (this->palette & GRFP_GRF_MASK) {
    00160     case GRFP_GRF_DOS:     pal = PAL_DOS;      break;
    00161     case GRFP_GRF_WINDOWS: pal = PAL_WINDOWS;  break;
    00162     default:               pal = _settings_client.gui.newgrf_default_palette == 1 ? PAL_WINDOWS : PAL_DOS; break;
    00163   }
    00164   SB(this->palette, GRFP_USE_BIT, 1, pal == PAL_WINDOWS ? GRFP_USE_WINDOWS : GRFP_USE_DOS);
    00165 }
    00166
    00170 void GRFConfig::FinalizeParameterInfo()
    00171 {
    00172   for (GRFParameterInfo **info = this->param_info.Begin(); info != this->param_info.End(); ++info) {
    00173     if (*info == NULL) continue;
    00174     (*info)->Finalize();
    00175   }
    00176 }
    00177
    00178 GRFConfig *_all_grfs;
    00179 GRFConfig *_grfconfig;
    00180 GRFConfig *_grfconfig_newgame;
    00181 GRFConfig *_grfconfig_static;
    00182
    00188 GRFError::GRFError(StringID severity, StringID message) :
    00189   message(message),
    00190   severity(severity)
    00191 {
    00192 }
    00193
    00198 GRFError::GRFError(const GRFError &error) :
    00199   ZeroedMemoryAllocator(),
    00200   custom_message(error.custom_message),
    00201   data(error.data),
    00202   message(error.message),
    00203   severity(error.severity)
    00204 {
    00205   if (error.custom_message != NULL) this->custom_message = strdup(error.custom_message);
    00206   if (error.data           != NULL) this->data           = strdup(error.data);
    00207   memcpy(this->param_value, error.param_value, sizeof(this->param_value));
    00208 }
    00209
    00210 GRFError::~GRFError()
    00211 {
    00212   free(this->custom_message);
    00213   free(this->data);
    00214 }
    00215
    00220 GRFParameterInfo::GRFParameterInfo(uint nr) :
    00221   name(NULL),
    00222   desc(NULL),
    00223   type(PTYPE_UINT_ENUM),
    00224   min_value(0),
    00225   max_value(UINT32_MAX),
    00226   def_value(0),
    00227   param_nr(nr),
    00228   first_bit(0),
    00229   num_bit(32),
    00230   complete_labels(false)
    00231 {}
    00232
    00238 GRFParameterInfo::GRFParameterInfo(GRFParameterInfo &info) :
    00239   name(DuplicateGRFText(info.name)),
    00240   desc(DuplicateGRFText(info.desc)),
    00241   type(info.type),
    00242   min_value(info.min_value),
    00243   max_value(info.max_value),
    00244   def_value(info.def_value),
    00245   param_nr(info.param_nr),
    00246   first_bit(info.first_bit),
    00247   num_bit(info.num_bit),
    00248   complete_labels(info.complete_labels)
    00249 {
    00250   for (uint i = 0; i < info.value_names.Length(); i++) {
    00251     SmallPair<uint32, GRFText *> *data = info.value_names.Get(i);
    00252     this->value_names.Insert(data->first, DuplicateGRFText(data->second));
    00253   }
    00254 }
    00255
    00257 GRFParameterInfo::~GRFParameterInfo()
    00258 {
    00259   CleanUpGRFText(this->name);
    00260   CleanUpGRFText(this->desc);
    00261   for (uint i = 0; i < this->value_names.Length(); i++) {
    00262     SmallPair<uint32, GRFText *> *data = this->value_names.Get(i);
    00263     CleanUpGRFText(data->second);
    00264   }
    00265 }
    00266
    00272 uint32 GRFParameterInfo::GetValue(struct GRFConfig *config) const
    00273 {
    00274   /* GB doesn't work correctly with nbits == 32, so handle that case here. */
    00275   if (this->num_bit == 32) return config->param[this->param_nr];
    00276   return GB(config->param[this->param_nr], this->first_bit, this->num_bit);
    00277 }
    00278
    00284 void GRFParameterInfo::SetValue(struct GRFConfig *config, uint32 value)
    00285 {
    00286   /* SB doesn't work correctly with nbits == 32, so handle that case here. */
    00287   if (this->num_bit == 32) {
    00288     config->param[this->param_nr] = value;
    00289   } else {
    00290     SB(config->param[this->param_nr], this->first_bit, this->num_bit, value);
    00291   }
    00292   config->num_params = max<uint>(config->num_params, this->param_nr + 1);
    00293   SetWindowDirty(WC_GAME_OPTIONS, WN_GAME_OPTIONS_NEWGRF_STATE);
    00294 }
    00295
    00299 void GRFParameterInfo::Finalize()
    00300 {
    00301   this->complete_labels = true;
    00302   for (uint32 value = this->min_value; value <= this->max_value; value++) {
    00303     if (!this->value_names.Contains(value)) {
    00304       this->complete_labels = false;
    00305       break;
    00306     }
    00307   }
    00308 }
    00309
    00316 bool UpdateNewGRFConfigPalette(int32 p1)
    00317 {
    00318   for (GRFConfig *c = _grfconfig_newgame; c != NULL; c = c->next) c->SetSuitablePalette();
    00319   for (GRFConfig *c = _grfconfig_static;  c != NULL; c = c->next) c->SetSuitablePalette();
    00320   for (GRFConfig *c = _all_grfs;          c != NULL; c = c->next) c->SetSuitablePalette();
    00321   return true;
    00322 }
    00323
    00329 size_t GRFGetSizeOfDataSection(FILE *f)
    00330 {
    00331   extern const byte _grf_cont_v2_sig[];
    00332   static const uint header_len = 14;
    00333
    00334   byte data[header_len];
    00335   if (fread(data, 1, header_len, f) == header_len) {
    00336     if (data[0] == 0 && data[1] == 0 && MemCmpT(data + 2, _grf_cont_v2_sig, 8) == 0) {
    00337       /* Valid container version 2, get data section size. */
    00338       size_t offset = ((size_t)data[13] << 24) | ((size_t)data[12] << 16) | ((size_t)data[11] << 8) | (size_t)data[10];
    00339       if (offset >= 1 * 1024 * 1024 * 1024) {
    00340         DEBUG(grf, 0, "Unexpectedly large offset for NewGRF");
    00341         /* Having more than 1 GiB of data is very implausible. Mostly because then
    00342          * all pools in OpenTTD are flooded already. Or it's just Action C all over.
    00343          * In any case, the offsets to graphics will likely not work either. */
    00344         return SIZE_MAX;
    00345       }
    00346       return header_len + offset;
    00347     }
    00348   }
    00349
    00350   return SIZE_MAX;
    00351 }
    00352
    00359 static bool CalcGRFMD5Sum(GRFConfig *config, Subdirectory subdir)
    00360 {
    00361   FILE *f;
    00362   Md5 checksum;
    00363   uint8 buffer[1024];
    00364   size_t len, size;
    00365
    00366   /* open the file */
    00367   f = FioFOpenFile(config->filename, "rb", subdir, &size);
    00368   if (f == NULL) return false;
    00369
    00370   long start = ftell(f);
    00371   size = min(size, GRFGetSizeOfDataSection(f));
    00372
    00373   if (start < 0 || fseek(f, start, SEEK_SET) < 0) {
    00374     FioFCloseFile(f);
    00375     return false;
    00376   }
    00377
    00378   /* calculate md5sum */
    00379   while ((len = fread(buffer, 1, (size > sizeof(buffer)) ? sizeof(buffer) : size, f)) != 0 && size != 0) {
    00380     size -= len;
    00381     checksum.Append(buffer, len);
    00382   }
    00383   checksum.Finish(config->ident.md5sum);
    00384
    00385   FioFCloseFile(f);
    00386
    00387   return true;
    00388 }
    00389
    00390
    00398 bool FillGRFDetails(GRFConfig *config, bool is_static, Subdirectory subdir)
    00399 {
    00400   if (!FioCheckFileExists(config->filename, subdir)) {
    00401     config->status = GCS_NOT_FOUND;
    00402     return false;
    00403   }
    00404
    00405   /* Find and load the Action 8 information */
    00406   LoadNewGRFFile(config, CONFIG_SLOT, GLS_FILESCAN, subdir);
    00407   config->SetSuitablePalette();
    00408   config->FinalizeParameterInfo();
    00409
    00410   /* Skip if the grfid is 0 (not read) or 0xFFFFFFFF (ttdp system grf) */
    00411   if (config->ident.grfid == 0 || config->ident.grfid == 0xFFFFFFFF || config->IsOpenTTDBaseGRF()) return false;
    00412
    00413   if (is_static) {
    00414     /* Perform a 'safety scan' for static GRFs */
    00415     LoadNewGRFFile(config, 62, GLS_SAFETYSCAN, subdir);
    00416
    00417     /* GCF_UNSAFE is set if GLS_SAFETYSCAN finds unsafe actions */
    00418     if (HasBit(config->flags, GCF_UNSAFE)) return false;
    00419   }
    00420
    00421   return CalcGRFMD5Sum(config, subdir);
    00422 }
    00423
    00424
    00430 void ClearGRFConfigList(GRFConfig **config)
    00431 {
    00432   GRFConfig *c, *next;
    00433   for (c = *config; c != NULL; c = next) {
    00434     next = c->next;
    00435     delete c;
    00436   }
    00437   *config = NULL;
    00438 }
    00439
    00440
    00448 GRFConfig **CopyGRFConfigList(GRFConfig **dst, const GRFConfig *src, bool init_only)
    00449 {
    00450   /* Clear destination as it will be overwritten */
    00451   ClearGRFConfigList(dst);
    00452   for (; src != NULL; src = src->next) {
    00453     GRFConfig *c = new GRFConfig(*src);
    00454
    00455     ClrBit(c->flags, GCF_INIT_ONLY);
    00456     if (init_only) SetBit(c->flags, GCF_INIT_ONLY);
    00457
    00458     *dst = c;
    00459     dst = &c->next;
    00460   }
    00461
    00462   return dst;
    00463 }
    00464
    00478 static void RemoveDuplicatesFromGRFConfigList(GRFConfig *list)
    00479 {
    00480   GRFConfig *prev;
    00481   GRFConfig *cur;
    00482
    00483   if (list == NULL) return;
    00484
    00485   for (prev = list, cur = list->next; cur != NULL; prev = cur, cur = cur->next) {
    00486     if (cur->ident.grfid != list->ident.grfid) continue;
    00487
    00488     prev->next = cur->next;
    00489     delete cur;
    00490     cur = prev; // Just go back one so it continues as normal later on
    00491   }
    00492
    00493   RemoveDuplicatesFromGRFConfigList(list->next);
    00494 }
    00495
    00500 void AppendStaticGRFConfigs(GRFConfig **dst)
    00501 {
    00502   GRFConfig **tail = dst;
    00503   while (*tail != NULL) tail = &(*tail)->next;
    00504
    00505   CopyGRFConfigList(tail, _grfconfig_static, false);
    00506   RemoveDuplicatesFromGRFConfigList(*dst);
    00507 }
    00508
    00514 void AppendToGRFConfigList(GRFConfig **dst, GRFConfig *el)
    00515 {
    00516   GRFConfig **tail = dst;
    00517   while (*tail != NULL) tail = &(*tail)->next;
    00518   *tail = el;
    00519
    00520   RemoveDuplicatesFromGRFConfigList(*dst);
    00521 }
    00522
    00523
    00525 void ResetGRFConfig(bool defaults)
    00526 {
    00527   CopyGRFConfigList(&_grfconfig, _grfconfig_newgame, !defaults);
    00528   AppendStaticGRFConfigs(&_grfconfig);
    00529 }
    00530
    00531
    00543 GRFListCompatibility IsGoodGRFConfigList(GRFConfig *grfconfig)
    00544 {
    00545   GRFListCompatibility res = GLC_ALL_GOOD;
    00546
    00547   for (GRFConfig *c = grfconfig; c != NULL; c = c->next) {
    00548     const GRFConfig *f = FindGRFConfig(c->ident.grfid, FGCM_EXACT, c->ident.md5sum);
    00549     if (f == NULL || HasBit(f->flags, GCF_INVALID)) {
    00550       char buf[256];
    00551
    00552       /* If we have not found the exactly matching GRF try to find one with the
    00553        * same grfid, as it most likely is compatible */
    00554       f = FindGRFConfig(c->ident.grfid, FGCM_COMPATIBLE, NULL, c->version);
    00555       if (f != NULL) {
    00556         md5sumToString(buf, lastof(buf), c->ident.md5sum);
    00557         DEBUG(grf, 1, "NewGRF %08X (%s) not found; checksum %s. Compatibility mode on", BSWAP32(c->ident.grfid), c->filename, buf);
    00558         if (!HasBit(c->flags, GCF_COMPATIBLE)) {
    00559           /* Preserve original_md5sum after it has been assigned */
    00560           SetBit(c->flags, GCF_COMPATIBLE);
    00561           memcpy(c->original_md5sum, c->ident.md5sum, sizeof(c->original_md5sum));
    00562         }
    00563
    00564         /* Non-found has precedence over compatibility load */
    00565         if (res != GLC_NOT_FOUND) res = GLC_COMPATIBLE;
    00566         goto compatible_grf;
    00567       }
    00568
    00569       /* No compatible grf was found, mark it as disabled */
    00570       md5sumToString(buf, lastof(buf), c->ident.md5sum);
    00571       DEBUG(grf, 0, "NewGRF %08X (%s) not found; checksum %s", BSWAP32(c->ident.grfid), c->filename, buf);
    00572
    00573       c->status = GCS_NOT_FOUND;
    00574       res = GLC_NOT_FOUND;
    00575     } else {
    00576 compatible_grf:
    00577       DEBUG(grf, 1, "Loading GRF %08X from %s", BSWAP32(f->ident.grfid), f->filename);
    00578       /* The filename could be the filename as in the savegame. As we need
    00579        * to load the GRF here, we need the correct filename, so overwrite that
    00580        * in any case and set the name and info when it is not set already.
    00581        * When the GCF_COPY flag is set, it is certain that the filename is
    00582        * already a local one, so there is no need to replace it. */
    00583       if (!HasBit(c->flags, GCF_COPY)) {
    00584         free(c->filename);
    00585         c->filename = strdup(f->filename);
    00586         memcpy(c->ident.md5sum, f->ident.md5sum, sizeof(c->ident.md5sum));
    00587         c->name->Release();
    00588         c->name = f->name;
    00589         c->name->AddRef();
    00590         c->info->Release();
    00591         c->info = f->name;
    00592         c->info->AddRef();
    00593         c->error = NULL;
    00594         c->version = f->version;
    00595         c->min_loadable_version = f->min_loadable_version;
    00596         c->num_valid_params = f->num_valid_params;
    00597         c->has_param_defaults = f->has_param_defaults;
    00598         for (uint i = 0; i < f->param_info.Length(); i++) {
    00599           if (f->param_info[i] == NULL) {
    00600             *c->param_info.Append() = NULL;
    00601           } else {
    00602             *c->param_info.Append() = new GRFParameterInfo(*f->param_info[i]);
    00603           }
    00604         }
    00605       }
    00606     }
    00607   }
    00608
    00609   return res;
    00610 }
    00611
    00613 class GRFFileScanner : FileScanner {
    00614   uint next_update;
    00615   uint num_scanned;
    00616
    00617 public:
    00618   GRFFileScanner() : next_update(_realtime_tick), num_scanned(0)
    00619   {
    00620   }
    00621
    00622   /* virtual */ bool AddFile(const char *filename, size_t basepath_length, const char *tar_filename);
    00623
    00625   static uint DoScan()
    00626   {
    00627     GRFFileScanner fs;
    00628     int ret = fs.Scan(".grf", NEWGRF_DIR);
    00629     /* The number scanned and the number returned may not be the same;
    00630      * duplicate NewGRFs and base sets are ignored in the return value. */
    00631     _settings_client.gui.last_newgrf_count = fs.num_scanned;
    00632     return ret;
    00633   }
    00634 };
    00635
    00636 bool GRFFileScanner::AddFile(const char *filename, size_t basepath_length, const char *tar_filename)
    00637 {
    00638   GRFConfig *c = new GRFConfig(filename + basepath_length);
    00639
    00640   bool added = true;
    00641   if (FillGRFDetails(c, false)) {
    00642     if (_all_grfs == NULL) {
    00643       _all_grfs = c;
    00644     } else {
    00645       /* Insert file into list at a position determined by its
    00646        * name, so the list is sorted as we go along */
    00647       GRFConfig **pd, *d;
    00648       bool stop = false;
    00649       for (pd = &_all_grfs; (d = *pd) != NULL; pd = &d->next) {
    00650         if (c->ident.grfid == d->ident.grfid && memcmp(c->ident.md5sum, d->ident.md5sum, sizeof(c->ident.md5sum)) == 0) added = false;
    00651         /* Because there can be multiple grfs with the same name, make sure we checked all grfs with the same name,
    00652          *  before inserting the entry. So insert a new grf at the end of all grfs with the same name, instead of
    00653          *  just after the first with the same name. Avoids doubles in the list. */
    00654         if (strcasecmp(c->GetName(), d->GetName()) <= 0) {
    00655           stop = true;
    00656         } else if (stop) {
    00657           break;
    00658         }
    00659       }
    00660       if (added) {
    00661         c->next = d;
    00662         *pd = c;
    00663       }
    00664     }
    00665   } else {
    00666     added = false;
    00667   }
    00668
    00669   this->num_scanned++;
    00670   if (this->next_update <= _realtime_tick) {
    00671     _modal_progress_work_mutex->EndCritical();
    00672     _modal_progress_paint_mutex->BeginCritical();
    00673
    00674     const char *name = NULL;
    00675     if (c->name != NULL) name = GetGRFStringFromGRFText(c->name->text);
    00676     if (name == NULL) name = c->filename;
    00677     UpdateNewGRFScanStatus(this->num_scanned, name);
    00678
    00679     _modal_progress_work_mutex->BeginCritical();
    00680     _modal_progress_paint_mutex->EndCritical();
    00681
    00682     this->next_update = _realtime_tick + 200;
    00683   }
    00684
    00685   if (!added) {
    00686     /* File couldn't be opened, or is either not a NewGRF or is a
    00687      * 'system' NewGRF or it's already known, so forget about it. */
    00688     delete c;
    00689   }
    00690
    00691   return added;
    00692 }
    00693
    00700 static int CDECL GRFSorter(GRFConfig * const *p1, GRFConfig * const *p2)
    00701 {
    00702   const GRFConfig *c1 = *p1;
    00703   const GRFConfig *c2 = *p2;
    00704
    00705   return strcasecmp(c1->GetName(), c2->GetName());
    00706 }
    00707
    00712 void DoScanNewGRFFiles(void *callback)
    00713 {
    00714   _modal_progress_work_mutex->BeginCritical();
    00715
    00716   ClearGRFConfigList(&_all_grfs);
    00717   TarScanner::DoScan(TarScanner::NEWGRF);
    00718
    00719   DEBUG(grf, 1, "Scanning for NewGRFs");
    00720   uint num = GRFFileScanner::DoScan();
    00721
    00722   DEBUG(grf, 1, "Scan complete, found %d files", num);
    00723   if (num != 0 && _all_grfs != NULL) {
    00724     /* Sort the linked list using quicksort.
    00725     * For that we first have to make an array, then sort and
    00726     * then remake the linked list. */
    00727     GRFConfig **to_sort = MallocT<GRFConfig*>(num);
    00728
    00729     uint i = 0;
    00730     for (GRFConfig *p = _all_grfs; p != NULL; p = p->next, i++) {
    00731       to_sort[i] = p;
    00732     }
    00733     /* Number of files is not necessarily right */
    00734     num = i;
    00735
    00736     QSortT(to_sort, num, &GRFSorter);
    00737
    00738     for (i = 1; i < num; i++) {
    00739       to_sort[i - 1]->next = to_sort[i];
    00740     }
    00741     to_sort[num - 1]->next = NULL;
    00742     _all_grfs = to_sort[0];
    00743
    00744     free(to_sort);
    00745
    00746 #ifdef ENABLE_NETWORK
    00747     NetworkAfterNewGRFScan();
    00748 #endif
    00749   }
    00750
    00751   _modal_progress_work_mutex->EndCritical();
    00752   _modal_progress_paint_mutex->BeginCritical();
    00753
    00754   /* Yes... these are the NewGRF windows */
    00755   InvalidateWindowClassesData(WC_SAVELOAD, 0, true);
    00756   InvalidateWindowData(WC_GAME_OPTIONS, WN_GAME_OPTIONS_NEWGRF_STATE, GOID_NEWGRF_RESCANNED, true);
    00757   if (callback != NULL) ((NewGRFScanCallback*)callback)->OnNewGRFsScanned();
    00758
    00759   DeleteWindowByClass(WC_MODAL_PROGRESS);
    00760   SetModalProgress(false);
    00761   MarkWholeScreenDirty();
    00762   _modal_progress_paint_mutex->EndCritical();
    00763 }
    00764
    00769 void ScanNewGRFFiles(NewGRFScanCallback *callback)
    00770 {
    00771   /* First set the modal progress. This ensures that it will eventually let go of the paint mutex. */
    00772   SetModalProgress(true);
    00773   /* Only then can we really start, especially by marking the whole screen dirty. Get those other windows hidden!. */
    00774   MarkWholeScreenDirty();
    00775
    00776   if (!_video_driver->HasGUI() || !ThreadObject::New(&DoScanNewGRFFiles, callback, NULL)) {
    00777     _modal_progress_work_mutex->EndCritical();
    00778     _modal_progress_paint_mutex->EndCritical();
    00779     DoScanNewGRFFiles(callback);
    00780     _modal_progress_paint_mutex->BeginCritical();
    00781     _modal_progress_work_mutex->BeginCritical();
    00782   } else {
    00783     UpdateNewGRFScanStatus(0, NULL);
    00784   }
    00785 }
    00786
    00795 const GRFConfig *FindGRFConfig(uint32 grfid, FindGRFConfigMode mode, const uint8 *md5sum, uint32 desired_version)
    00796 {
    00797   assert((mode == FGCM_EXACT) != (md5sum == NULL));
    00798   const GRFConfig *best = NULL;
    00799   for (const GRFConfig *c = _all_grfs; c != NULL; c = c->next) {
    00800     /* if md5sum is set, we look for an exact match and continue if not found */
    00801     if (!c->ident.HasGrfIdentifier(grfid, md5sum)) continue;
    00802     /* return it, if the exact same newgrf is found, or if we do not care about finding "the best" */
    00803     if (md5sum != NULL || mode == FGCM_ANY) return c;
    00804     /* Skip incompatible stuff, unless explicitly allowed */
    00805     if (mode != FGCM_NEWEST && HasBit(c->flags, GCF_INVALID)) continue;
    00806     /* check version compatibility */
    00807     if (mode == FGCM_COMPATIBLE && (c->version < desired_version || c->min_loadable_version > desired_version)) continue;
    00808     /* remember the newest one as "the best" */
    00809     if (best == NULL || c->version > best->version) best = c;
    00810   }
    00811
    00812   return best;
    00813 }
    00814
    00815 #ifdef ENABLE_NETWORK
    00816
    00818 struct UnknownGRF : public GRFIdentifier {
    00819   UnknownGRF *next;
    00820   GRFTextWrapper *name;
    00821 };
    00822
    00840 GRFTextWrapper *FindUnknownGRFName(uint32 grfid, uint8 *md5sum, bool create)
    00841 {
    00842   UnknownGRF *grf;
    00843   static UnknownGRF *unknown_grfs = NULL;
    00844
    00845   for (grf = unknown_grfs; grf != NULL; grf = grf->next) {
    00846     if (grf->grfid == grfid) {
    00847       if (memcmp(md5sum, grf->md5sum, sizeof(grf->md5sum)) == 0) return grf->name;
    00848     }
    00849   }
    00850
    00851   if (!create) return NULL;
    00852
    00853   grf = CallocT<UnknownGRF>(1);
    00854   grf->grfid = grfid;
    00855   grf->next  = unknown_grfs;
    00856   grf->name = new GRFTextWrapper();
    00857   grf->name->AddRef();
    00858
    00859   AddGRFTextToList(&grf->name->text, UNKNOWN_GRF_NAME_PLACEHOLDER);
    00860   memcpy(grf->md5sum, md5sum, sizeof(grf->md5sum));
    00861
    00862   unknown_grfs = grf;
    00863   return grf->name;
    00864 }
    00865
    00866 #endif /* ENABLE_NETWORK */
    00867
    00868
    00875 GRFConfig *GetGRFConfig(uint32 grfid, uint32 mask)
    00876 {
    00877   GRFConfig *c;
    00878
    00879   for (c = _grfconfig; c != NULL; c = c->next) {
    00880     if ((c->ident.grfid & mask) == (grfid & mask)) return c;
    00881   }
    00882
    00883   return NULL;
    00884 }
    00885
    00886
    00888 char *GRFBuildParamList(char *dst, const GRFConfig *c, const char *last)
    00889 {
    00890   uint i;
    00891
    00892   /* Return an empty string if there are no parameters */
    00893   if (c->num_params == 0) return strecpy(dst, "", last);
    00894
    00895   for (i = 0; i < c->num_params; i++) {
    00896     if (i > 0) dst = strecpy(dst, " ", last);
    00897     dst += seprintf(dst, last, "%d", c->param[i]);
    00898   }
    00899   return dst;
    00900 }
    00901
    00903 static const uint32 OPENTTD_GRAPHICS_BASE_GRF_ID = BSWAP32(0xFF4F5400);
    00904
    00909 bool GRFConfig::IsOpenTTDBaseGRF() const
    00910 {
    00911   return (this->ident.grfid & 0x00FFFFFF) == OPENTTD_GRAPHICS_BASE_GRF_ID;
    00912 }
    00913
    00919 const char *GRFConfig::GetTextfile(TextfileType type) const
    00920 {
    00921   return ::GetTextfile(type, NEWGRF_DIR, this->filename);
    00922 }