newgrf_config.cpp

Go to the documentation of this file.
00001 /* $Id: newgrf_config.cpp 21814 2011-01-15 21:13:47Z frosch $ */
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 
00029 GRFConfig::GRFConfig(const char *filename) :
00030   num_valid_params(lengthof(param))
00031 {
00032   if (filename != NULL) this->filename = strdup(filename);
00033 }
00034 
00039 GRFConfig::GRFConfig(const GRFConfig &config) :
00040   ZeroedMemoryAllocator(),
00041   ident(config.ident),
00042   version(config.version),
00043   min_loadable_version(config.min_loadable_version),
00044   flags(config.flags & ~(1 << GCF_COPY)),
00045   status(config.status),
00046   grf_bugs(config.grf_bugs),
00047   num_params(config.num_params),
00048   num_valid_params(config.num_valid_params),
00049   palette(config.palette),
00050   has_param_defaults(config.has_param_defaults)
00051 {
00052   MemCpyT<uint8>(this->original_md5sum, config.original_md5sum, lengthof(this->original_md5sum));
00053   MemCpyT<uint32>(this->param, config.param, lengthof(this->param));
00054   if (config.filename != NULL) this->filename = strdup(config.filename);
00055   this->name = DuplicateGRFText(config.name);
00056   this->info = DuplicateGRFText(config.info);
00057   if (config.error    != NULL) this->error    = new GRFError(*config.error);
00058   for (uint i = 0; i < config.param_info.Length(); i++) {
00059     if (config.param_info[i] == NULL) {
00060       *this->param_info.Append() = NULL;
00061     } else {
00062       *this->param_info.Append() = new GRFParameterInfo(*config.param_info[i]);
00063     }
00064   }
00065 }
00066 
00068 GRFConfig::~GRFConfig()
00069 {
00070   /* GCF_COPY as in NOT strdupped/alloced the filename and info */
00071   if (!HasBit(this->flags, GCF_COPY)) {
00072     free(this->filename);
00073     CleanUpGRFText(this->info);
00074     delete this->error;
00075   }
00076   CleanUpGRFText(this->name);
00077 
00078   for (uint i = 0; i < this->param_info.Length(); i++) delete this->param_info[i];
00079 }
00080 
00086 const char *GRFConfig::GetName() const
00087 {
00088   const char *name = GetGRFStringFromGRFText(this->name);
00089   return StrEmpty(name) ? this->filename : name;
00090 }
00091 
00096 const char *GRFConfig::GetDescription() const
00097 {
00098   return GetGRFStringFromGRFText(this->info);
00099 }
00100 
00102 void GRFConfig::SetParameterDefaults()
00103 {
00104   this->num_params = 0;
00105   MemSetT<uint32>(this->param, 0, lengthof(this->param));
00106 
00107   if (!this->has_param_defaults) return;
00108 
00109   for (uint i = 0; i < this->param_info.Length(); i++) {
00110     if (this->param_info[i] == NULL) continue;
00111     this->param_info[i]->SetValue(this, this->param_info[i]->def_value);
00112   }
00113 }
00114 
00120 void GRFConfig::SetSuitablePalette()
00121 {
00122   PaletteType pal;
00123   switch (this->palette & GRFP_GRF_MASK) {
00124     case GRFP_GRF_DOS:     pal = PAL_DOS;      break;
00125     case GRFP_GRF_WINDOWS: pal = PAL_WINDOWS;  break;
00126     default:               pal = _use_palette; break;
00127   }
00128   SB(this->palette, GRFP_USE_BIT, 1, pal == PAL_WINDOWS ? GRFP_USE_WINDOWS : GRFP_USE_DOS);
00129 }
00130 
00131 GRFConfig *_all_grfs;
00132 GRFConfig *_grfconfig;
00133 GRFConfig *_grfconfig_newgame;
00134 GRFConfig *_grfconfig_static;
00135 
00141 GRFError::GRFError(StringID severity, StringID message) :
00142   message(message),
00143   severity(severity)
00144 {
00145 }
00146 
00151 GRFError::GRFError(const GRFError &error) :
00152   ZeroedMemoryAllocator(),
00153   custom_message(error.custom_message),
00154   data(error.data),
00155   message(error.message),
00156   severity(error.severity),
00157   num_params(error.num_params)
00158 {
00159   if (error.custom_message != NULL) this->custom_message = strdup(error.custom_message);
00160   if (error.data           != NULL) this->data           = strdup(error.data);
00161   memcpy(this->param_value, error.param_value, sizeof(this->param_value));
00162 }
00163 
00164 GRFError::~GRFError()
00165 {
00166   free(this->custom_message);
00167   free(this->data);
00168 }
00169 
00174 GRFParameterInfo::GRFParameterInfo(uint nr) :
00175   name(NULL),
00176   desc(NULL),
00177   type(PTYPE_UINT_ENUM),
00178   min_value(0),
00179   max_value(UINT32_MAX),
00180   def_value(0),
00181   param_nr(nr),
00182   first_bit(0),
00183   num_bit(32)
00184 {}
00185 
00191 GRFParameterInfo::GRFParameterInfo(GRFParameterInfo &info) :
00192   name(DuplicateGRFText(info.name)),
00193   desc(DuplicateGRFText(info.desc)),
00194   type(info.type),
00195   min_value(info.min_value),
00196   max_value(info.max_value),
00197   def_value(info.def_value),
00198   param_nr(info.param_nr),
00199   first_bit(info.first_bit),
00200   num_bit(info.num_bit)
00201 {
00202   for (uint i = 0; i < info.value_names.Length(); i++) {
00203     SmallPair<uint32, GRFText *> *data = info.value_names.Get(i);
00204     this->value_names.Insert(data->first, DuplicateGRFText(data->second));
00205   }
00206 }
00207 
00209 GRFParameterInfo::~GRFParameterInfo()
00210 {
00211   CleanUpGRFText(this->name);
00212   CleanUpGRFText(this->desc);
00213   for (uint i = 0; i < this->value_names.Length(); i++) {
00214     SmallPair<uint32, GRFText *> *data = this->value_names.Get(i);
00215     CleanUpGRFText(data->second);
00216   }
00217 }
00218 
00224 uint32 GRFParameterInfo::GetValue(struct GRFConfig *config) const
00225 {
00226   /* GB doesn't work correctly with nbits == 32, so handle that case here. */
00227   if (this->num_bit == 32) return config->param[this->param_nr];
00228   return GB(config->param[this->param_nr], this->first_bit, this->num_bit);
00229 }
00230 
00236 void GRFParameterInfo::SetValue(struct GRFConfig *config, uint32 value)
00237 {
00238   /* SB doesn't work correctly with nbits == 32, so handle that case here. */
00239   if (this->num_bit == 32) {
00240     config->param[this->param_nr] = value;
00241   } else {
00242     SB(config->param[this->param_nr], this->first_bit, this->num_bit, value);
00243   }
00244   config->num_params = max<uint>(config->num_params, this->param_nr + 1);
00245   SetWindowClassesDirty(WC_GAME_OPTIONS); // Is always the newgrf window
00246 }
00247 
00256 void UpdateNewGRFConfigPalette()
00257 {
00258   for (GRFConfig *c = _grfconfig_newgame; c != NULL; c = c->next) c->SetSuitablePalette();
00259   for (GRFConfig *c = _grfconfig_static;  c != NULL; c = c->next) c->SetSuitablePalette();
00260 }
00261 
00267 static bool CalcGRFMD5Sum(GRFConfig *config)
00268 {
00269   FILE *f;
00270   Md5 checksum;
00271   uint8 buffer[1024];
00272   size_t len, size;
00273 
00274   /* open the file */
00275   f = FioFOpenFile(config->filename, "rb", DATA_DIR, &size);
00276   if (f == NULL) return false;
00277 
00278   /* calculate md5sum */
00279   while ((len = fread(buffer, 1, (size > sizeof(buffer)) ? sizeof(buffer) : size, f)) != 0 && size != 0) {
00280     size -= len;
00281     checksum.Append(buffer, len);
00282   }
00283   checksum.Finish(config->ident.md5sum);
00284 
00285   FioFCloseFile(f);
00286 
00287   return true;
00288 }
00289 
00290 
00297 bool FillGRFDetails(GRFConfig *config, bool is_static)
00298 {
00299   if (!FioCheckFileExists(config->filename)) {
00300     config->status = GCS_NOT_FOUND;
00301     return false;
00302   }
00303 
00304   /* Find and load the Action 8 information */
00305   LoadNewGRFFile(config, CONFIG_SLOT, GLS_FILESCAN);
00306   config->SetSuitablePalette();
00307 
00308   /* Skip if the grfid is 0 (not read) or 0xFFFFFFFF (ttdp system grf) */
00309   if (config->ident.grfid == 0 || config->ident.grfid == 0xFFFFFFFF || config->IsOpenTTDBaseGRF()) return false;
00310 
00311   if (is_static) {
00312     /* Perform a 'safety scan' for static GRFs */
00313     LoadNewGRFFile(config, 62, GLS_SAFETYSCAN);
00314 
00315     /* GCF_UNSAFE is set if GLS_SAFETYSCAN finds unsafe actions */
00316     if (HasBit(config->flags, GCF_UNSAFE)) return false;
00317   }
00318 
00319   return CalcGRFMD5Sum(config);
00320 }
00321 
00322 
00328 void ClearGRFConfigList(GRFConfig **config)
00329 {
00330   GRFConfig *c, *next;
00331   for (c = *config; c != NULL; c = next) {
00332     next = c->next;
00333     delete c;
00334   }
00335   *config = NULL;
00336 }
00337 
00338 
00346 GRFConfig **CopyGRFConfigList(GRFConfig **dst, const GRFConfig *src, bool init_only)
00347 {
00348   /* Clear destination as it will be overwritten */
00349   ClearGRFConfigList(dst);
00350   for (; src != NULL; src = src->next) {
00351     GRFConfig *c = new GRFConfig(*src);
00352 
00353     ClrBit(c->flags, GCF_INIT_ONLY);
00354     if (init_only) SetBit(c->flags, GCF_INIT_ONLY);
00355 
00356     *dst = c;
00357     dst = &c->next;
00358   }
00359 
00360   return dst;
00361 }
00362 
00376 static void RemoveDuplicatesFromGRFConfigList(GRFConfig *list)
00377 {
00378   GRFConfig *prev;
00379   GRFConfig *cur;
00380 
00381   if (list == NULL) return;
00382 
00383   for (prev = list, cur = list->next; cur != NULL; prev = cur, cur = cur->next) {
00384     if (cur->ident.grfid != list->ident.grfid) continue;
00385 
00386     prev->next = cur->next;
00387     delete cur;
00388     cur = prev; // Just go back one so it continues as normal later on
00389   }
00390 
00391   RemoveDuplicatesFromGRFConfigList(list->next);
00392 }
00393 
00398 void AppendStaticGRFConfigs(GRFConfig **dst)
00399 {
00400   GRFConfig **tail = dst;
00401   while (*tail != NULL) tail = &(*tail)->next;
00402 
00403   CopyGRFConfigList(tail, _grfconfig_static, false);
00404   RemoveDuplicatesFromGRFConfigList(*dst);
00405 }
00406 
00412 void AppendToGRFConfigList(GRFConfig **dst, GRFConfig *el)
00413 {
00414   GRFConfig **tail = dst;
00415   while (*tail != NULL) tail = &(*tail)->next;
00416   *tail = el;
00417 
00418   RemoveDuplicatesFromGRFConfigList(*dst);
00419 }
00420 
00421 
00423 void ResetGRFConfig(bool defaults)
00424 {
00425   CopyGRFConfigList(&_grfconfig, _grfconfig_newgame, !defaults);
00426   AppendStaticGRFConfigs(&_grfconfig);
00427 }
00428 
00429 
00441 GRFListCompatibility IsGoodGRFConfigList(GRFConfig *grfconfig)
00442 {
00443   GRFListCompatibility res = GLC_ALL_GOOD;
00444 
00445   for (GRFConfig *c = grfconfig; c != NULL; c = c->next) {
00446     const GRFConfig *f = FindGRFConfig(c->ident.grfid, FGCM_EXACT, c->ident.md5sum);
00447     if (f == NULL || HasBit(f->flags, GCF_INVALID)) {
00448       char buf[256];
00449 
00450       /* If we have not found the exactly matching GRF try to find one with the
00451        * same grfid, as it most likely is compatible */
00452       f = FindGRFConfig(c->ident.grfid, FGCM_COMPATIBLE, NULL, c->version);
00453       if (f != NULL) {
00454         md5sumToString(buf, lastof(buf), c->ident.md5sum);
00455         DEBUG(grf, 1, "NewGRF %08X (%s) not found; checksum %s. Compatibility mode on", BSWAP32(c->ident.grfid), c->filename, buf);
00456         if (!HasBit(c->flags, GCF_COMPATIBLE)) {
00457           /* Preserve original_md5sum after it has been assigned */
00458           SetBit(c->flags, GCF_COMPATIBLE);
00459           memcpy(c->original_md5sum, c->ident.md5sum, sizeof(c->original_md5sum));
00460         }
00461 
00462         /* Non-found has precedence over compatibility load */
00463         if (res != GLC_NOT_FOUND) res = GLC_COMPATIBLE;
00464         goto compatible_grf;
00465       }
00466 
00467       /* No compatible grf was found, mark it as disabled */
00468       md5sumToString(buf, lastof(buf), c->ident.md5sum);
00469       DEBUG(grf, 0, "NewGRF %08X (%s) not found; checksum %s", BSWAP32(c->ident.grfid), c->filename, buf);
00470 
00471       c->status = GCS_NOT_FOUND;
00472       res = GLC_NOT_FOUND;
00473     } else {
00474 compatible_grf:
00475       DEBUG(grf, 1, "Loading GRF %08X from %s", BSWAP32(f->ident.grfid), f->filename);
00476       /* The filename could be the filename as in the savegame. As we need
00477        * to load the GRF here, we need the correct filename, so overwrite that
00478        * in any case and set the name and info when it is not set already.
00479        * When the GCF_COPY flag is set, it is certain that the filename is
00480        * already a local one, so there is no need to replace it. */
00481       if (!HasBit(c->flags, GCF_COPY)) {
00482         free(c->filename);
00483         c->filename = strdup(f->filename);
00484         memcpy(c->ident.md5sum, f->ident.md5sum, sizeof(c->ident.md5sum));
00485         if (c->name == NULL) c->name = DuplicateGRFText(f->name);
00486         if (c->info == NULL) c->info = DuplicateGRFText(f->info);
00487         c->error = NULL;
00488         c->version = f->version;
00489         c->min_loadable_version = f->min_loadable_version;
00490         c->num_valid_params = f->num_valid_params;
00491         c->has_param_defaults = f->has_param_defaults;
00492         for (uint i = 0; i < f->param_info.Length(); i++) {
00493           if (f->param_info[i] == NULL) {
00494             *c->param_info.Append() = NULL;
00495           } else {
00496             *c->param_info.Append() = new GRFParameterInfo(*f->param_info[i]);
00497           }
00498         }
00499       }
00500     }
00501   }
00502 
00503   return res;
00504 }
00505 
00507 class GRFFileScanner : FileScanner {
00508 public:
00509   /* virtual */ bool AddFile(const char *filename, size_t basepath_length);
00510 
00512   static uint DoScan()
00513   {
00514     GRFFileScanner fs;
00515     return fs.Scan(".grf", DATA_DIR);
00516   }
00517 };
00518 
00519 bool GRFFileScanner::AddFile(const char *filename, size_t basepath_length)
00520 {
00521   GRFConfig *c = new GRFConfig(filename + basepath_length);
00522 
00523   bool added = true;
00524   if (FillGRFDetails(c, false)) {
00525     if (_all_grfs == NULL) {
00526       _all_grfs = c;
00527     } else {
00528       /* Insert file into list at a position determined by its
00529        * name, so the list is sorted as we go along */
00530       GRFConfig **pd, *d;
00531       bool stop = false;
00532       for (pd = &_all_grfs; (d = *pd) != NULL; pd = &d->next) {
00533         if (c->ident.grfid == d->ident.grfid && memcmp(c->ident.md5sum, d->ident.md5sum, sizeof(c->ident.md5sum)) == 0) added = false;
00534         /* Because there can be multiple grfs with the same name, make sure we checked all grfs with the same name,
00535          *  before inserting the entry. So insert a new grf at the end of all grfs with the same name, instead of
00536          *  just after the first with the same name. Avoids doubles in the list. */
00537         if (strcasecmp(c->GetName(), d->GetName()) <= 0) {
00538           stop = true;
00539         } else if (stop) {
00540           break;
00541         }
00542       }
00543       if (added) {
00544         c->next = d;
00545         *pd = c;
00546       }
00547     }
00548   } else {
00549     added = false;
00550   }
00551 
00552   if (!added) {
00553     /* File couldn't be opened, or is either not a NewGRF or is a
00554      * 'system' NewGRF or it's already known, so forget about it. */
00555     delete c;
00556   }
00557 
00558   return added;
00559 }
00560 
00567 static int CDECL GRFSorter(GRFConfig * const *p1, GRFConfig * const *p2)
00568 {
00569   const GRFConfig *c1 = *p1;
00570   const GRFConfig *c2 = *p2;
00571 
00572   return strcasecmp(c1->GetName(), c2->GetName());
00573 }
00574 
00576 void ScanNewGRFFiles()
00577 {
00578   ClearGRFConfigList(&_all_grfs);
00579 
00580   TarScanner::DoScan();
00581 
00582   DEBUG(grf, 1, "Scanning for NewGRFs");
00583   uint num = GRFFileScanner::DoScan();
00584 
00585   DEBUG(grf, 1, "Scan complete, found %d files", num);
00586   if (num == 0 || _all_grfs == NULL) return;
00587 
00588   /* Sort the linked list using quicksort.
00589    * For that we first have to make an array, then sort and
00590    * then remake the linked list. */
00591   GRFConfig **to_sort = MallocT<GRFConfig*>(num);
00592 
00593   uint i = 0;
00594   for (GRFConfig *p = _all_grfs; p != NULL; p = p->next, i++) {
00595     to_sort[i] = p;
00596   }
00597   /* Number of files is not necessarily right */
00598   num = i;
00599 
00600   QSortT(to_sort, num, &GRFSorter);
00601 
00602   for (i = 1; i < num; i++) {
00603     to_sort[i - 1]->next = to_sort[i];
00604   }
00605   to_sort[num - 1]->next = NULL;
00606   _all_grfs = to_sort[0];
00607 
00608   free(to_sort);
00609 
00610 #ifdef ENABLE_NETWORK
00611   NetworkAfterNewGRFScan();
00612 #endif
00613 }
00614 
00615 
00624 const GRFConfig *FindGRFConfig(uint32 grfid, FindGRFConfigMode mode, const uint8 *md5sum, uint32 desired_version)
00625 {
00626   assert((mode == FGCM_EXACT) != (md5sum == NULL));
00627   const GRFConfig *best = NULL;
00628   for (const GRFConfig *c = _all_grfs; c != NULL; c = c->next) {
00629     /* if md5sum is set, we look for an exact match and continue if not found */
00630     if (!c->ident.HasGrfIdentifier(grfid, md5sum)) continue;
00631     /* return it, if the exact same newgrf is found, or if we do not care about finding "the best" */
00632     if (md5sum != NULL || mode == FGCM_ANY) return c;
00633     /* Skip incompatible stuff, unless explicitly allowed */
00634     if (mode != FGCM_NEWEST && HasBit(c->flags, GCF_INVALID)) continue;
00635     /* check version compatibility */
00636     if (mode == FGCM_COMPATIBLE && (c->version < desired_version || c->min_loadable_version > desired_version)) continue;
00637     /* remember the newest one as "the best" */
00638     if (best == NULL || c->version > best->version) best = c;
00639   }
00640 
00641   return best;
00642 }
00643 
00644 #ifdef ENABLE_NETWORK
00645 
00647 struct UnknownGRF : public GRFIdentifier {
00648   UnknownGRF *next;
00649   char   name[NETWORK_GRF_NAME_LENGTH];
00650 };
00651 
00669 char *FindUnknownGRFName(uint32 grfid, uint8 *md5sum, bool create)
00670 {
00671   UnknownGRF *grf;
00672   static UnknownGRF *unknown_grfs = NULL;
00673 
00674   for (grf = unknown_grfs; grf != NULL; grf = grf->next) {
00675     if (grf->grfid == grfid) {
00676       if (memcmp(md5sum, grf->md5sum, sizeof(grf->md5sum)) == 0) return grf->name;
00677     }
00678   }
00679 
00680   if (!create) return NULL;
00681 
00682   grf = CallocT<UnknownGRF>(1);
00683   grf->grfid = grfid;
00684   grf->next  = unknown_grfs;
00685   strecpy(grf->name, UNKNOWN_GRF_NAME_PLACEHOLDER, lastof(grf->name));
00686   memcpy(grf->md5sum, md5sum, sizeof(grf->md5sum));
00687 
00688   unknown_grfs = grf;
00689   return grf->name;
00690 }
00691 
00692 #endif /* ENABLE_NETWORK */
00693 
00694 
00701 GRFConfig *GetGRFConfig(uint32 grfid, uint32 mask)
00702 {
00703   GRFConfig *c;
00704 
00705   for (c = _grfconfig; c != NULL; c = c->next) {
00706     if ((c->ident.grfid & mask) == (grfid & mask)) return c;
00707   }
00708 
00709   return NULL;
00710 }
00711 
00712 
00714 char *GRFBuildParamList(char *dst, const GRFConfig *c, const char *last)
00715 {
00716   uint i;
00717 
00718   /* Return an empty string if there are no parameters */
00719   if (c->num_params == 0) return strecpy(dst, "", last);
00720 
00721   for (i = 0; i < c->num_params; i++) {
00722     if (i > 0) dst = strecpy(dst, " ", last);
00723     dst += seprintf(dst, last, "%d", c->param[i]);
00724   }
00725   return dst;
00726 }
00727 
00729 static const uint32 OPENTTD_GRAPHICS_BASE_GRF_ID = BSWAP32(0xFF4F5400);
00730 
00735 bool GRFConfig::IsOpenTTDBaseGRF() const
00736 {
00737   return (this->ident.grfid & 0x00FFFFFF) == OPENTTD_GRAPHICS_BASE_GRF_ID;
00738 }

Generated on Thu Jan 20 22:57:37 2011 for OpenTTD by  doxygen 1.6.1