# newgrf_config.cpp

Go to the documentation of this file.

    00001 /* $Id$ */
    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
    00021 #include "fileio_func.h"
    00022 #include "fios.h"
    00023
    00025 GRFTextWrapper::GRFTextWrapper() :
    00026   text(NULL)
    00027 {
    00028 }
    00029
    00031 GRFTextWrapper::~GRFTextWrapper()
    00032 {
    00033   CleanUpGRFText(this->text);
    00034 }
    00035
    00041 GRFConfig::GRFConfig(const char *filename) :
    00042   name(new GRFTextWrapper()),
    00043   info(new GRFTextWrapper()),
    00044   num_valid_params(lengthof(param))
    00045 {
    00046   if (filename != NULL) this->filename = strdup(filename);
    00047   this->name->AddRef();
    00048   this->info->AddRef();
    00049 }
    00050
    00055 GRFConfig::GRFConfig(const GRFConfig &config) :
    00056   ZeroedMemoryAllocator(),
    00057   ident(config.ident),
    00058   name(config.name),
    00059   info(config.info),
    00060   version(config.version),
    00061   min_loadable_version(config.min_loadable_version),
    00062   flags(config.flags & ~(1 << GCF_COPY)),
    00063   status(config.status),
    00064   grf_bugs(config.grf_bugs),
    00065   num_params(config.num_params),
    00066   num_valid_params(config.num_valid_params),
    00067   palette(config.palette),
    00068   has_param_defaults(config.has_param_defaults)
    00069 {
    00070   MemCpyT<uint8>(this->original_md5sum, config.original_md5sum, lengthof(this->original_md5sum));
    00071   MemCpyT<uint32>(this->param, config.param, lengthof(this->param));
    00072   if (config.filename != NULL) this->filename = strdup(config.filename);
    00073   this->name->AddRef();
    00074   this->info->AddRef();
    00075   if (config.error    != NULL) this->error    = new GRFError(*config.error);
    00076   for (uint i = 0; i < config.param_info.Length(); i++) {
    00077     if (config.param_info[i] == NULL) {
    00078       *this->param_info.Append() = NULL;
    00079     } else {
    00080       *this->param_info.Append() = new GRFParameterInfo(*config.param_info[i]);
    00081     }
    00082   }
    00083 }
    00084
    00086 GRFConfig::~GRFConfig()
    00087 {
    00088   /* GCF_COPY as in NOT strdupped/alloced the filename */
    00089   if (!HasBit(this->flags, GCF_COPY)) {
    00090     free(this->filename);
    00091     delete this->error;
    00092   }
    00093   this->name->Release();
    00094   this->info->Release();
    00095
    00096   for (uint i = 0; i < this->param_info.Length(); i++) delete this->param_info[i];
    00097 }
    00098
    00104 const char *GRFConfig::GetName() const
    00105 {
    00106   const char *name = GetGRFStringFromGRFText(this->name->text);
    00107   return StrEmpty(name) ? this->filename : name;
    00108 }
    00109
    00114 const char *GRFConfig::GetDescription() const
    00115 {
    00116   return GetGRFStringFromGRFText(this->info->text);
    00117 }
    00118
    00120 void GRFConfig::SetParameterDefaults()
    00121 {
    00122   this->num_params = 0;
    00123   MemSetT<uint32>(this->param, 0, lengthof(this->param));
    00124
    00125   if (!this->has_param_defaults) return;
    00126
    00127   for (uint i = 0; i < this->param_info.Length(); i++) {
    00128     if (this->param_info[i] == NULL) continue;
    00129     this->param_info[i]->SetValue(this, this->param_info[i]->def_value);
    00130   }
    00131 }
    00132
    00138 void GRFConfig::SetSuitablePalette()
    00139 {
    00140   PaletteType pal;
    00141   switch (this->palette & GRFP_GRF_MASK) {
    00142     case GRFP_GRF_DOS:     pal = PAL_DOS;      break;
    00143     case GRFP_GRF_WINDOWS: pal = PAL_WINDOWS;  break;
    00144     default:               pal = _use_palette; break;
    00145   }
    00146   SB(this->palette, GRFP_USE_BIT, 1, pal == PAL_WINDOWS ? GRFP_USE_WINDOWS : GRFP_USE_DOS);
    00147 }
    00148
    00149 GRFConfig *_all_grfs;
    00150 GRFConfig *_grfconfig;
    00151 GRFConfig *_grfconfig_newgame;
    00152 GRFConfig *_grfconfig_static;
    00153
    00159 GRFError::GRFError(StringID severity, StringID message) :
    00160   message(message),
    00161   severity(severity)
    00162 {
    00163 }
    00164
    00169 GRFError::GRFError(const GRFError &error) :
    00170   ZeroedMemoryAllocator(),
    00171   custom_message(error.custom_message),
    00172   data(error.data),
    00173   message(error.message),
    00174   severity(error.severity),
    00175   num_params(error.num_params)
    00176 {
    00177   if (error.custom_message != NULL) this->custom_message = strdup(error.custom_message);
    00178   if (error.data           != NULL) this->data           = strdup(error.data);
    00179   memcpy(this->param_value, error.param_value, sizeof(this->param_value));
    00180 }
    00181
    00182 GRFError::~GRFError()
    00183 {
    00184   free(this->custom_message);
    00185   free(this->data);
    00186 }
    00187
    00192 GRFParameterInfo::GRFParameterInfo(uint nr) :
    00193   name(NULL),
    00194   desc(NULL),
    00195   type(PTYPE_UINT_ENUM),
    00196   min_value(0),
    00197   max_value(UINT32_MAX),
    00198   def_value(0),
    00199   param_nr(nr),
    00200   first_bit(0),
    00201   num_bit(32)
    00202 {}
    00203
    00209 GRFParameterInfo::GRFParameterInfo(GRFParameterInfo &info) :
    00210   name(DuplicateGRFText(info.name)),
    00211   desc(DuplicateGRFText(info.desc)),
    00212   type(info.type),
    00213   min_value(info.min_value),
    00214   max_value(info.max_value),
    00215   def_value(info.def_value),
    00216   param_nr(info.param_nr),
    00217   first_bit(info.first_bit),
    00218   num_bit(info.num_bit)
    00219 {
    00220   for (uint i = 0; i < info.value_names.Length(); i++) {
    00221     SmallPair<uint32, GRFText *> *data = info.value_names.Get(i);
    00222     this->value_names.Insert(data->first, DuplicateGRFText(data->second));
    00223   }
    00224 }
    00225
    00227 GRFParameterInfo::~GRFParameterInfo()
    00228 {
    00229   CleanUpGRFText(this->name);
    00230   CleanUpGRFText(this->desc);
    00231   for (uint i = 0; i < this->value_names.Length(); i++) {
    00232     SmallPair<uint32, GRFText *> *data = this->value_names.Get(i);
    00233     CleanUpGRFText(data->second);
    00234   }
    00235 }
    00236
    00242 uint32 GRFParameterInfo::GetValue(struct GRFConfig *config) const
    00243 {
    00244   /* GB doesn't work correctly with nbits == 32, so handle that case here. */
    00245   if (this->num_bit == 32) return config->param[this->param_nr];
    00246   return GB(config->param[this->param_nr], this->first_bit, this->num_bit);
    00247 }
    00248
    00254 void GRFParameterInfo::SetValue(struct GRFConfig *config, uint32 value)
    00255 {
    00256   /* SB doesn't work correctly with nbits == 32, so handle that case here. */
    00257   if (this->num_bit == 32) {
    00258     config->param[this->param_nr] = value;
    00259   } else {
    00260     SB(config->param[this->param_nr], this->first_bit, this->num_bit, value);
    00261   }
    00262   config->num_params = max<uint>(config->num_params, this->param_nr + 1);
    00263   SetWindowClassesDirty(WC_GAME_OPTIONS); // Is always the newgrf window
    00264 }
    00265
    00274 void UpdateNewGRFConfigPalette()
    00275 {
    00276   for (GRFConfig *c = _grfconfig_newgame; c != NULL; c = c->next) c->SetSuitablePalette();
    00277   for (GRFConfig *c = _grfconfig_static;  c != NULL; c = c->next) c->SetSuitablePalette();
    00278 }
    00279
    00285 static bool CalcGRFMD5Sum(GRFConfig *config)
    00286 {
    00287   FILE *f;
    00288   Md5 checksum;
    00289   uint8 buffer[1024];
    00290   size_t len, size;
    00291
    00292   /* open the file */
    00293   f = FioFOpenFile(config->filename, "rb", DATA_DIR, &size);
    00294   if (f == NULL) return false;
    00295
    00296   /* calculate md5sum */
    00297   while ((len = fread(buffer, 1, (size > sizeof(buffer)) ? sizeof(buffer) : size, f)) != 0 && size != 0) {
    00298     size -= len;
    00299     checksum.Append(buffer, len);
    00300   }
    00301   checksum.Finish(config->ident.md5sum);
    00302
    00303   FioFCloseFile(f);
    00304
    00305   return true;
    00306 }
    00307
    00308
    00315 bool FillGRFDetails(GRFConfig *config, bool is_static)
    00316 {
    00317   if (!FioCheckFileExists(config->filename)) {
    00318     config->status = GCS_NOT_FOUND;
    00319     return false;
    00320   }
    00321
    00322   /* Find and load the Action 8 information */
    00323   LoadNewGRFFile(config, CONFIG_SLOT, GLS_FILESCAN);
    00324   config->SetSuitablePalette();
    00325
    00326   /* Skip if the grfid is 0 (not read) or 0xFFFFFFFF (ttdp system grf) */
    00327   if (config->ident.grfid == 0 || config->ident.grfid == 0xFFFFFFFF || config->IsOpenTTDBaseGRF()) return false;
    00328
    00329   if (is_static) {
    00330     /* Perform a 'safety scan' for static GRFs */
    00331     LoadNewGRFFile(config, 62, GLS_SAFETYSCAN);
    00332
    00333     /* GCF_UNSAFE is set if GLS_SAFETYSCAN finds unsafe actions */
    00334     if (HasBit(config->flags, GCF_UNSAFE)) return false;
    00335   }
    00336
    00337   return CalcGRFMD5Sum(config);
    00338 }
    00339
    00340
    00346 void ClearGRFConfigList(GRFConfig **config)
    00347 {
    00348   GRFConfig *c, *next;
    00349   for (c = *config; c != NULL; c = next) {
    00350     next = c->next;
    00351     delete c;
    00352   }
    00353   *config = NULL;
    00354 }
    00355
    00356
    00364 GRFConfig **CopyGRFConfigList(GRFConfig **dst, const GRFConfig *src, bool init_only)
    00365 {
    00366   /* Clear destination as it will be overwritten */
    00367   ClearGRFConfigList(dst);
    00368   for (; src != NULL; src = src->next) {
    00369     GRFConfig *c = new GRFConfig(*src);
    00370
    00371     ClrBit(c->flags, GCF_INIT_ONLY);
    00372     if (init_only) SetBit(c->flags, GCF_INIT_ONLY);
    00373
    00374     *dst = c;
    00375     dst = &c->next;
    00376   }
    00377
    00378   return dst;
    00379 }
    00380
    00394 static void RemoveDuplicatesFromGRFConfigList(GRFConfig *list)
    00395 {
    00396   GRFConfig *prev;
    00397   GRFConfig *cur;
    00398
    00399   if (list == NULL) return;
    00400
    00401   for (prev = list, cur = list->next; cur != NULL; prev = cur, cur = cur->next) {
    00402     if (cur->ident.grfid != list->ident.grfid) continue;
    00403
    00404     prev->next = cur->next;
    00405     delete cur;
    00406     cur = prev; // Just go back one so it continues as normal later on
    00407   }
    00408
    00409   RemoveDuplicatesFromGRFConfigList(list->next);
    00410 }
    00411
    00416 void AppendStaticGRFConfigs(GRFConfig **dst)
    00417 {
    00418   GRFConfig **tail = dst;
    00419   while (*tail != NULL) tail = &(*tail)->next;
    00420
    00421   CopyGRFConfigList(tail, _grfconfig_static, false);
    00422   RemoveDuplicatesFromGRFConfigList(*dst);
    00423 }
    00424
    00430 void AppendToGRFConfigList(GRFConfig **dst, GRFConfig *el)
    00431 {
    00432   GRFConfig **tail = dst;
    00433   while (*tail != NULL) tail = &(*tail)->next;
    00434   *tail = el;
    00435
    00436   RemoveDuplicatesFromGRFConfigList(*dst);
    00437 }
    00438
    00439
    00441 void ResetGRFConfig(bool defaults)
    00442 {
    00443   CopyGRFConfigList(&_grfconfig, _grfconfig_newgame, !defaults);
    00444   AppendStaticGRFConfigs(&_grfconfig);
    00445 }
    00446
    00447
    00459 GRFListCompatibility IsGoodGRFConfigList(GRFConfig *grfconfig)
    00460 {
    00461   GRFListCompatibility res = GLC_ALL_GOOD;
    00462
    00463   for (GRFConfig *c = grfconfig; c != NULL; c = c->next) {
    00464     const GRFConfig *f = FindGRFConfig(c->ident.grfid, FGCM_EXACT, c->ident.md5sum);
    00465     if (f == NULL || HasBit(f->flags, GCF_INVALID)) {
    00466       char buf[256];
    00467
    00468       /* If we have not found the exactly matching GRF try to find one with the
    00469        * same grfid, as it most likely is compatible */
    00470       f = FindGRFConfig(c->ident.grfid, FGCM_COMPATIBLE, NULL, c->version);
    00471       if (f != NULL) {
    00472         md5sumToString(buf, lastof(buf), c->ident.md5sum);
    00473         DEBUG(grf, 1, "NewGRF %08X (%s) not found; checksum %s. Compatibility mode on", BSWAP32(c->ident.grfid), c->filename, buf);
    00474         if (!HasBit(c->flags, GCF_COMPATIBLE)) {
    00475           /* Preserve original_md5sum after it has been assigned */
    00476           SetBit(c->flags, GCF_COMPATIBLE);
    00477           memcpy(c->original_md5sum, c->ident.md5sum, sizeof(c->original_md5sum));
    00478         }
    00479
    00480         /* Non-found has precedence over compatibility load */
    00481         if (res != GLC_NOT_FOUND) res = GLC_COMPATIBLE;
    00482         goto compatible_grf;
    00483       }
    00484
    00485       /* No compatible grf was found, mark it as disabled */
    00486       md5sumToString(buf, lastof(buf), c->ident.md5sum);
    00487       DEBUG(grf, 0, "NewGRF %08X (%s) not found; checksum %s", BSWAP32(c->ident.grfid), c->filename, buf);
    00488
    00489       c->status = GCS_NOT_FOUND;
    00490       res = GLC_NOT_FOUND;
    00491     } else {
    00492 compatible_grf:
    00493       DEBUG(grf, 1, "Loading GRF %08X from %s", BSWAP32(f->ident.grfid), f->filename);
    00494       /* The filename could be the filename as in the savegame. As we need
    00495        * to load the GRF here, we need the correct filename, so overwrite that
    00496        * in any case and set the name and info when it is not set already.
    00497        * When the GCF_COPY flag is set, it is certain that the filename is
    00498        * already a local one, so there is no need to replace it. */
    00499       if (!HasBit(c->flags, GCF_COPY)) {
    00500         free(c->filename);
    00501         c->filename = strdup(f->filename);
    00502         memcpy(c->ident.md5sum, f->ident.md5sum, sizeof(c->ident.md5sum));
    00503         c->name->Release();
    00504         c->name = f->name;
    00505         c->name->AddRef();
    00506         c->info->Release();
    00507         c->info = f->name;
    00508         c->info->AddRef();
    00509         c->error = NULL;
    00510         c->version = f->version;
    00511         c->min_loadable_version = f->min_loadable_version;
    00512         c->num_valid_params = f->num_valid_params;
    00513         c->has_param_defaults = f->has_param_defaults;
    00514         for (uint i = 0; i < f->param_info.Length(); i++) {
    00515           if (f->param_info[i] == NULL) {
    00516             *c->param_info.Append() = NULL;
    00517           } else {
    00518             *c->param_info.Append() = new GRFParameterInfo(*f->param_info[i]);
    00519           }
    00520         }
    00521       }
    00522     }
    00523   }
    00524
    00525   return res;
    00526 }
    00527
    00529 class GRFFileScanner : FileScanner {
    00530 public:
    00531   /* virtual */ bool AddFile(const char *filename, size_t basepath_length);
    00532
    00534   static uint DoScan()
    00535   {
    00536     GRFFileScanner fs;
    00537     return fs.Scan(".grf", DATA_DIR);
    00538   }
    00539 };
    00540
    00541 bool GRFFileScanner::AddFile(const char *filename, size_t basepath_length)
    00542 {
    00543   GRFConfig *c = new GRFConfig(filename + basepath_length);
    00544
    00545   bool added = true;
    00546   if (FillGRFDetails(c, false)) {
    00547     if (_all_grfs == NULL) {
    00548       _all_grfs = c;
    00549     } else {
    00550       /* Insert file into list at a position determined by its
    00551        * name, so the list is sorted as we go along */
    00552       GRFConfig **pd, *d;
    00553       bool stop = false;
    00554       for (pd = &_all_grfs; (d = *pd) != NULL; pd = &d->next) {
    00555         if (c->ident.grfid == d->ident.grfid && memcmp(c->ident.md5sum, d->ident.md5sum, sizeof(c->ident.md5sum)) == 0) added = false;
    00556         /* Because there can be multiple grfs with the same name, make sure we checked all grfs with the same name,
    00557          *  before inserting the entry. So insert a new grf at the end of all grfs with the same name, instead of
    00558          *  just after the first with the same name. Avoids doubles in the list. */
    00559         if (strcasecmp(c->GetName(), d->GetName()) <= 0) {
    00560           stop = true;
    00561         } else if (stop) {
    00562           break;
    00563         }
    00564       }
    00565       if (added) {
    00566         c->next = d;
    00567         *pd = c;
    00568       }
    00569     }
    00570   } else {
    00571     added = false;
    00572   }
    00573
    00574   if (!added) {
    00575     /* File couldn't be opened, or is either not a NewGRF or is a
    00576      * 'system' NewGRF or it's already known, so forget about it. */
    00577     delete c;
    00578   }
    00579
    00580   return added;
    00581 }
    00582
    00589 static int CDECL GRFSorter(GRFConfig * const *p1, GRFConfig * const *p2)
    00590 {
    00591   const GRFConfig *c1 = *p1;
    00592   const GRFConfig *c2 = *p2;
    00593
    00594   return strcasecmp(c1->GetName(), c2->GetName());
    00595 }
    00596
    00598 void ScanNewGRFFiles()
    00599 {
    00600   ClearGRFConfigList(&_all_grfs);
    00601
    00602   TarScanner::DoScan();
    00603
    00604   DEBUG(grf, 1, "Scanning for NewGRFs");
    00605   uint num = GRFFileScanner::DoScan();
    00606
    00607   DEBUG(grf, 1, "Scan complete, found %d files", num);
    00608   if (num == 0 || _all_grfs == NULL) return;
    00609
    00610   /* Sort the linked list using quicksort.
    00611    * For that we first have to make an array, then sort and
    00612    * then remake the linked list. */
    00613   GRFConfig **to_sort = MallocT<GRFConfig*>(num);
    00614
    00615   uint i = 0;
    00616   for (GRFConfig *p = _all_grfs; p != NULL; p = p->next, i++) {
    00617     to_sort[i] = p;
    00618   }
    00619   /* Number of files is not necessarily right */
    00620   num = i;
    00621
    00622   QSortT(to_sort, num, &GRFSorter);
    00623
    00624   for (i = 1; i < num; i++) {
    00625     to_sort[i - 1]->next = to_sort[i];
    00626   }
    00627   to_sort[num - 1]->next = NULL;
    00628   _all_grfs = to_sort[0];
    00629
    00630   free(to_sort);
    00631
    00632 #ifdef ENABLE_NETWORK
    00633   NetworkAfterNewGRFScan();
    00634 #endif
    00635 }
    00636
    00637
    00646 const GRFConfig *FindGRFConfig(uint32 grfid, FindGRFConfigMode mode, const uint8 *md5sum, uint32 desired_version)
    00647 {
    00648   assert((mode == FGCM_EXACT) != (md5sum == NULL));
    00649   const GRFConfig *best = NULL;
    00650   for (const GRFConfig *c = _all_grfs; c != NULL; c = c->next) {
    00651     /* if md5sum is set, we look for an exact match and continue if not found */
    00652     if (!c->ident.HasGrfIdentifier(grfid, md5sum)) continue;
    00653     /* return it, if the exact same newgrf is found, or if we do not care about finding "the best" */
    00654     if (md5sum != NULL || mode == FGCM_ANY) return c;
    00655     /* Skip incompatible stuff, unless explicitly allowed */
    00656     if (mode != FGCM_NEWEST && HasBit(c->flags, GCF_INVALID)) continue;
    00657     /* check version compatibility */
    00658     if (mode == FGCM_COMPATIBLE && (c->version < desired_version || c->min_loadable_version > desired_version)) continue;
    00659     /* remember the newest one as "the best" */
    00660     if (best == NULL || c->version > best->version) best = c;
    00661   }
    00662
    00663   return best;
    00664 }
    00665
    00666 #ifdef ENABLE_NETWORK
    00667
    00669 struct UnknownGRF : public GRFIdentifier {
    00670   UnknownGRF *next;
    00671   GRFTextWrapper *name;
    00672 };
    00673
    00691 GRFTextWrapper *FindUnknownGRFName(uint32 grfid, uint8 *md5sum, bool create)
    00692 {
    00693   UnknownGRF *grf;
    00694   static UnknownGRF *unknown_grfs = NULL;
    00695
    00696   for (grf = unknown_grfs; grf != NULL; grf = grf->next) {
    00697     if (grf->grfid == grfid) {
    00698       if (memcmp(md5sum, grf->md5sum, sizeof(grf->md5sum)) == 0) return grf->name;
    00699     }
    00700   }
    00701
    00702   if (!create) return NULL;
    00703
    00704   grf = CallocT<UnknownGRF>(1);
    00705   grf->grfid = grfid;
    00706   grf->next  = unknown_grfs;
    00707   grf->name = new GRFTextWrapper();
    00708   grf->name->AddRef();
    00709
    00710   AddGRFTextToList(&grf->name->text, UNKNOWN_GRF_NAME_PLACEHOLDER);
    00711   memcpy(grf->md5sum, md5sum, sizeof(grf->md5sum));
    00712
    00713   unknown_grfs = grf;
    00714   return grf->name;
    00715 }
    00716
    00717 #endif /* ENABLE_NETWORK */
    00718
    00719
    00726 GRFConfig *GetGRFConfig(uint32 grfid, uint32 mask)
    00727 {
    00728   GRFConfig *c;
    00729
    00730   for (c = _grfconfig; c != NULL; c = c->next) {
    00731     if ((c->ident.grfid & mask) == (grfid & mask)) return c;
    00732   }
    00733
    00734   return NULL;
    00735 }
    00736
    00737
    00739 char *GRFBuildParamList(char *dst, const GRFConfig *c, const char *last)
    00740 {
    00741   uint i;
    00742
    00743   /* Return an empty string if there are no parameters */
    00744   if (c->num_params == 0) return strecpy(dst, "", last);
    00745
    00746   for (i = 0; i < c->num_params; i++) {
    00747     if (i > 0) dst = strecpy(dst, " ", last);
    00748     dst += seprintf(dst, last, "%d", c->param[i]);
    00749   }
    00750   return dst;
    00751 }
    00752
    00754 static const uint32 OPENTTD_GRAPHICS_BASE_GRF_ID = BSWAP32(0xFF4F5400);
    00755
    00760 bool GRFConfig::IsOpenTTDBaseGRF() const
    00761 {
    00762   return (this->ident.grfid & 0x00FFFFFF) == OPENTTD_GRAPHICS_BASE_GRF_ID;
    00763 }