From f1189326439122811d9db35674d7f356575d2863 Mon Sep 17 00:00:00 2001 From: rubidium Date: Sun, 9 Aug 2009 16:54:03 +0000 Subject: [PATCH] (svn r17133) -Codechange: generalise the code that searches for base graphics --- projects/openttd_vs80.vcproj | 8 + projects/openttd_vs90.vcproj | 8 + source.list | 2 + src/base_media_base.h | 193 ++++++++++ src/base_media_func.h | 301 +++++++++++++++ src/gfxinit.cpp | 552 +++++----------------------- src/gfxinit.h | 13 - src/network/network_content.cpp | 4 +- src/network/network_content_gui.cpp | 4 +- src/openttd.cpp | 13 +- src/settings.cpp | 2 +- src/settings_gui.cpp | 28 +- src/table/settings.h | 2 +- 13 files changed, 633 insertions(+), 497 deletions(-) create mode 100644 src/base_media_base.h create mode 100644 src/base_media_func.h diff --git a/projects/openttd_vs80.vcproj b/projects/openttd_vs80.vcproj index 2b8d7257ae..2be80fe4e5 100644 --- a/projects/openttd_vs80.vcproj +++ b/projects/openttd_vs80.vcproj @@ -827,6 +827,14 @@ RelativePath=".\..\src\aystar.h" > + + + + diff --git a/projects/openttd_vs90.vcproj b/projects/openttd_vs90.vcproj index 5b65ba9773..f4260c1849 100644 --- a/projects/openttd_vs90.vcproj +++ b/projects/openttd_vs90.vcproj @@ -824,6 +824,14 @@ RelativePath=".\..\src\aystar.h" > + + + + diff --git a/source.list b/source.list index ca42b24307..1d24b045ac 100644 --- a/source.list +++ b/source.list @@ -135,6 +135,8 @@ autoreplace_gui.h autoreplace_type.h autoslope.h aystar.h +base_media_base.h +base_media_func.h base_station_base.h bmp.h bridge.h diff --git a/src/base_media_base.h b/src/base_media_base.h new file mode 100644 index 0000000000..e5e2d5171a --- /dev/null +++ b/src/base_media_base.h @@ -0,0 +1,193 @@ +/* $Id$ */ + +/** @file base_media_base.h Generic functions for replacing base data (graphics, sounds). */ + +#ifndef BASE_MEDIA_BASE_H +#define BASE_MEDIA_BASE_H + +#include "fileio_func.h" + +/** Structure holding filename and MD5 information about a single file */ +struct MD5File { + const char *filename; ///< filename + uint8 hash[16]; ///< md5 sum of the file + const char *missing_warning; ///< warning when this file is missing + + bool CheckMD5() const; +}; + +/** + * Information about a single base set. + * @tparam T the real class we're going to be + * @tparam Tnum_files the number of files in the set + */ +template +struct BaseSet { + /** Number of files in this set */ + static const size_t NUM_FILES = Tnum_files; + + /** Internal names of the files in this set. */ + static const char *file_names[Tnum_files]; + + const char *name; ///< The name of the base set + const char *description; ///< Description of the base set + uint32 shortname; ///< Four letter short variant of the name + uint32 version; ///< The version of this base set + + MD5File files[NUM_FILES]; ///< All files part of this set + uint found_files; ///< Number of the files that could be found + + T *next; ///< The next base set in this list + + /** Free everything we allocated */ + ~BaseSet() + { + free((void*)this->name); + free((void*)this->description); + for (uint i = 0; i < NUM_FILES; i++) { + free((void*)this->files[i].filename); + free((void*)this->files[i].missing_warning); + } + + delete this->next; + } + + /** + * Get the number of missing files. + * @return the number + */ + int GetNumMissing() const + { + return Tnum_files - this->found_files; + } + + /** + * Read the set information from a loaded ini. + * @param ini the ini to read from + * @param path the path to this ini file (for filenames) + * @return true if loading was successful. + */ + bool FillSetDetails(struct IniFile *ini, const char *path); +}; + +/** + * Base for all base media (graphics, sound) + * @tparam Tbase_set the real set we're going to be + */ +template +class BaseMedia : FileScanner { +protected: + static Tbase_set *available_sets; ///< All available sets + static const Tbase_set *used_set; ///< The currently used set + + /* virtual */ bool AddFile(const char *filename, size_t basepath_length); + + /** + * Get the extension that is used to identify this set. + * @return the extension + */ + static const char *GetExtension(); +public: + /** The set as saved in the config file. */ + static const char *ini_set; + + /** + * Determine the graphics pack that has to be used. + * The one with the most correct files wins. + * @return true if a best set has been found. + */ + static bool DetermineBestSet(); + + /** Do the scan for files. */ + static uint FindSets() + { + BaseMedia fs; + return fs.Scan(GetExtension(), DATA_DIR); + } + + /** + * Set the set to be used. + * @param name of the set to use + * @return true if it could be loaded + */ + static bool SetSet(const char *name); + + /** + * Returns a list with the sets. + * @param p where to print to + * @param last the last character to print to + * @return the last printed character + */ + static char *GetSetsList(char *p, const char *last); + + /** + * Count the number of available graphics sets. + * @return the number of sets + */ + static int GetNumSets(); + + /** + * Get the index of the currently active graphics set + * @return the current set's index + */ + static int GetIndexOfUsedSet(); + + /** + * Get the name of the graphics set at the specified index + * @return the name of the set + */ + static const Tbase_set *GetSet(int index); + /** + * Return the used set. + * @return the used set. + */ + static const Tbase_set *GetUsedSet(); + + /** + * Check whether we have an set with the exact characteristics as ci. + * @param ci the characteristics to search on (shortname and md5sum) + * @param md5sum whether to check the MD5 checksum + * @return true iff we have an set matching. + */ + static bool HasSet(const struct ContentInfo *ci, bool md5sum); +}; + + +/** Types of graphics in the base graphics set */ +enum GraphicsFileType { + GFT_BASE, ///< Base sprites for all climates + GFT_LOGOS, ///< Logos, landscape icons and original terrain generator sprites + GFT_ARCTIC, ///< Landscape replacement sprites for arctic + GFT_TROPICAL, ///< Landscape replacement sprites for tropical + GFT_TOYLAND, ///< Landscape replacement sprites for toyland + GFT_EXTRA, ///< Extra sprites that were not part of the original sprites + MAX_GFT ///< We are looking for this amount of GRFs +}; + +/** All data of a graphics set. */ +struct GraphicsSet : BaseSet { + PaletteType palette; ///< Palette of this graphics set + + /** + * Is this set useable? Are enough files found to think it exists. + * @return true if it's useable. + */ + bool IsUseable() const + { + /* Do not find 'only' openttd[dw].grf */ + return this->found_files > 1; + } + + bool FillSetDetails(struct IniFile *ini, const char *path); +}; + +/** All data/functions related with replacing the base graphics. */ +class BaseGraphics : public BaseMedia { +public: + /** + * Determine the palette of the current graphics set. + */ + static void DeterminePalette(); +}; + +#endif /* BASE_MEDIA_BASE_H */ diff --git a/src/base_media_func.h b/src/base_media_func.h new file mode 100644 index 0000000000..ba09259522 --- /dev/null +++ b/src/base_media_func.h @@ -0,0 +1,301 @@ +/* $Id$ */ + +/** @file base_media_func.h Generic function implementations for base data (graphics, sounds). */ + +#include "base_media_base.h" +#include "string_func.h" +#include "ini_type.h" + +template /* static */ const char *BaseMedia::ini_set; +template /* static */ const Tbase_set *BaseMedia::used_set; +template /* static */ Tbase_set *BaseMedia::available_sets; + +/** + * Try to read a single piece of metadata and return false if it doesn't exist. + * @param name the name of the item to fetch. + */ +#define fetch_metadata(name) \ + item = metadata->GetItem(name, false); \ + if (item == NULL || strlen(item->value) == 0) { \ + DEBUG(grf, 0, "Base " SET_TYPE "set detail loading: %s field missing", name); \ + return false; \ + } + +template +bool BaseSet::FillSetDetails(IniFile *ini, const char *path) +{ + memset(this, 0, sizeof(*this)); + + IniGroup *metadata = ini->GetGroup("metadata"); + IniItem *item; + + fetch_metadata("name"); + this->name = strdup(item->value); + + fetch_metadata("description"); + this->description = strdup(item->value); + + fetch_metadata("shortname"); + for (uint i = 0; item->value[i] != '\0' && i < 4; i++) { + this->shortname |= ((uint8)item->value[i]) << (i * 8); + } + + fetch_metadata("version"); + this->version = atoi(item->value); + + /* For each of the file types we want to find the file, MD5 checksums and warning messages. */ + IniGroup *files = ini->GetGroup("files"); + IniGroup *md5s = ini->GetGroup("md5s"); + IniGroup *origin = ini->GetGroup("origin"); + for (uint i = 0; i < Tnum_files; i++) { + MD5File *file = &this->files[i]; + /* Find the filename first. */ + item = files->GetItem(BaseSet::file_names[i], false); + if (item == NULL) { + DEBUG(grf, 0, "No " SET_TYPE " file for: %s", BaseSet::file_names[i]); + return false; + } + + const char *filename = item->value; + file->filename = str_fmt("%s%s", path, filename); + + /* Then find the MD5 checksum */ + item = md5s->GetItem(filename, false); + if (item == NULL) { + DEBUG(grf, 0, "No MD5 checksum specified for: %s", filename); + return false; + } + char *c = item->value; + for (uint i = 0; i < sizeof(file->hash) * 2; i++, c++) { + uint j; + if ('0' <= *c && *c <= '9') { + j = *c - '0'; + } else if ('a' <= *c && *c <= 'f') { + j = *c - 'a' + 10; + } else if ('A' <= *c && *c <= 'F') { + j = *c - 'A' + 10; + } else { + DEBUG(grf, 0, "Malformed MD5 checksum specified for: %s", filename); + return false; + } + if (i % 2 == 0) { + file->hash[i / 2] = j << 4; + } else { + file->hash[i / 2] |= j; + } + } + + /* Then find the warning message when the file's missing */ + item = origin->GetItem(filename, false); + if (item == NULL) item = origin->GetItem("default", false); + if (item == NULL) { + DEBUG(grf, 1, "No origin warning message specified for: %s", filename); + file->missing_warning = strdup(""); + } else { + file->missing_warning = strdup(item->value); + } + + if (file->CheckMD5()) this->found_files++; + } + + return true; +} + +template +bool BaseMedia::AddFile(const char *filename, size_t basepath_length) +{ + bool ret = false; + DEBUG(grf, 1, "Checking %s for base " SET_TYPE " set", filename); + + Tbase_set *set = new Tbase_set();; + IniFile *ini = new IniFile(); + ini->LoadFromDisk(filename); + + char *path = strdup(filename + basepath_length); + char *psep = strrchr(path, PATHSEPCHAR); + if (psep != NULL) { + psep[1] = '\0'; + } else { + *path = '\0'; + } + + if (set->FillSetDetails(ini, path)) { + Tbase_set *duplicate = NULL; + for (Tbase_set *c = BaseMedia::available_sets; c != NULL; c = c->next) { + if (strcmp(c->name, set->name) == 0 || c->shortname == set->shortname) { + duplicate = c; + break; + } + } + if (duplicate != NULL) { + /* The more complete set takes precedence over the version number. */ + if ((duplicate->found_files == set->found_files && duplicate->version >= set->version) || + duplicate->found_files > set->found_files) { + DEBUG(grf, 1, "Not adding %s (%i) as base " SET_TYPE " set (duplicate)", set->name, set->version); + delete set; + } else { + Tbase_set **prev = &BaseMedia::available_sets; + while (*prev != duplicate) prev = &(*prev)->next; + + *prev = set; + set->next = duplicate->next; + /* don't allow recursive delete of all remaining items */ + duplicate->next = NULL; + + DEBUG(grf, 1, "Removing %s (%i) as base " SET_TYPE " set (duplicate)", duplicate->name, duplicate->version); + delete duplicate; + ret = true; + } + } else { + Tbase_set **last = &BaseMedia::available_sets; + while (*last != NULL) last = &(*last)->next; + + *last = set; + ret = true; + } + if (ret) { + DEBUG(grf, 1, "Adding %s (%i) as base " SET_TYPE " set", set->name, set->version); + } + } else { + delete set; + } + free(path); + + delete ini; + return ret; +} + +template +/* static */ bool BaseMedia::SetSet(const char *name) +{ + extern void CheckExternalFiles(); + + if (StrEmpty(name)) { + if (!BaseMedia::DetermineBestSet()) return false; + CheckExternalFiles(); + return true; + } + + for (const Tbase_set *s = BaseMedia::available_sets; s != NULL; s = s->next) { + if (strcmp(name, s->name) == 0) { + BaseMedia::used_set = s; + CheckExternalFiles(); + return true; + } + } + return false; +} + +template +/* static */ char *BaseMedia::GetSetsList(char *p, const char *last) +{ + p += seprintf(p, last, "List of " SET_TYPE " sets:\n"); + for (const Tbase_set *s = BaseMedia::available_sets; s != NULL; s = s->next) { + if (!s->IsUseable()) continue; + + p += seprintf(p, last, "%18s: %s", s->name, s->description); + int missing = s->GetNumMissing(); + if (missing != 0) { + p += seprintf(p, last, " (missing %i file%s)\n", missing, missing == 1 ? "" : "s"); + } else { + p += seprintf(p, last, "\n"); + } + } + p += seprintf(p, last, "\n"); + + return p; +} + +#if defined(ENABLE_NETWORK) +#include "network/network_content.h" + +template +/* static */ bool BaseMedia::HasSet(const ContentInfo *ci, bool md5sum) +{ + for (const Tbase_set *s = BaseMedia::available_sets; s != NULL; s = s->next) { + if (!s->IsUseable()) continue; + + if (s->shortname != ci->unique_id) continue; + if (!md5sum) return true; + + byte md5[16]; + memset(md5, 0, sizeof(md5)); + for (uint i = 0; i < Tbase_set::NUM_FILES; i++) { + for (uint j = 0; j < sizeof(md5); j++) { + md5[j] ^= s->files[i].hash[j]; + } + } + if (memcmp(md5, ci->md5sum, sizeof(md5)) == 0) return true; + } + + return false; +} + +#else + +template +/* static */ bool BaseMedia::HasSet(const ContentInfo *ci, bool md5sum) +{ + return false; +} + +#endif /* ENABLE_NETWORK */ + +template +/* static */ int BaseMedia::GetNumSets() +{ + int n = 0; + for (const Tbase_set *s = BaseMedia::available_sets; s != NULL; s = s->next) { + if (s != BaseMedia::used_set && !s->IsUseable()) continue; + n++; + } + return n; +} + +template +/* static */ int BaseMedia::GetIndexOfUsedSet() +{ + int n = 0; + for (const Tbase_set *s = BaseMedia::available_sets; s != NULL; s = s->next) { + if (s == BaseMedia::used_set) return n; + if (!s->IsUseable()) continue; + n++; + } + return -1; +} + +template +/* static */ const Tbase_set *BaseMedia::GetSet(int index) +{ + for (const Tbase_set *s = BaseMedia::available_sets; s != NULL; s = s->next) { + if (s != BaseMedia::used_set && !s->IsUseable()) continue; + if (index == 0) return s; + index--; + } + error("Base" SET_TYPE "::GetSet(): index %d out of range", index); +} + +template +/* static */ const Tbase_set *BaseMedia::GetUsedSet() +{ + return BaseMedia::used_set; +} + +/** + * Force instantiation of methods so we don't get linker errors. + * @param repl_type the type of the BaseMedia to instantiate + * @param set_type the type of the BaseSet to instantiate + */ +#define INSTANTIATE_BASE_MEDIA_METHODS(repl_type, set_type) \ + template const char *repl_type::ini_set; \ + template const char *repl_type::GetExtension(); \ + template bool repl_type::AddFile(const char *filename, size_t pathlength); \ + template bool repl_type::HasSet(const struct ContentInfo *ci, bool md5sum); \ + template bool repl_type::SetSet(const char *name); \ + template char *repl_type::GetSetsList(char *p, const char *last); \ + template int repl_type::GetNumSets(); \ + template int repl_type::GetIndexOfUsedSet(); \ + template const set_type *repl_type::GetSet(int index); \ + template const set_type *repl_type::GetUsedSet(); \ + template bool repl_type::DetermineBestSet(); + diff --git a/src/gfxinit.cpp b/src/gfxinit.cpp index 6878af28fc..32a9815eab 100644 --- a/src/gfxinit.cpp +++ b/src/gfxinit.cpp @@ -13,7 +13,10 @@ #include "gfx_func.h" #include "settings_type.h" #include "string_func.h" -#include "ini_type.h" + +/* The type of set we're replacing */ +#define SET_TYPE "graphics" +#include "base_media_func.h" #include "table/sprites.h" #include "table/palette_convert.h" @@ -27,58 +30,6 @@ const byte *_palette_remap = NULL; /** Palette map to go from the _use_palette to the !_use_palette */ const byte *_palette_reverse_remap = NULL; -char *_ini_graphics_set; - -/** Structure holding filename and MD5 information about a single file */ -struct MD5File { - const char *filename; ///< filename - uint8 hash[16]; ///< md5 sum of the file - const char *missing_warning; ///< warning when this file is missing -}; - -/** Types of graphics in the base graphics set */ -enum GraphicsFileType { - GFT_BASE, ///< Base sprites for all climates - GFT_LOGOS, ///< Logos, landscape icons and original terrain generator sprites - GFT_ARCTIC, ///< Landscape replacement sprites for arctic - GFT_TROPICAL, ///< Landscape replacement sprites for tropical - GFT_TOYLAND, ///< Landscape replacement sprites for toyland - GFT_EXTRA, ///< Extra sprites that were not part of the original sprites - MAX_GFT ///< We are looking for this amount of GRFs -}; - -/** Information about a single graphics set. */ -struct GraphicsSet { - const char *name; ///< The name of the graphics set - const char *description; ///< Description of the graphics set - uint32 shortname; ///< Four letter short variant of the name - uint32 version; ///< The version of this graphics set - PaletteType palette; ///< Palette of this graphics set - - MD5File files[MAX_GFT]; ///< All GRF files part of this set - uint found_grfs; ///< Number of the GRFs that could be found - - GraphicsSet *next; ///< The next graphics set in this list - - /** Free everything we allocated */ - ~GraphicsSet() - { - free((void*)this->name); - free((void*)this->description); - for (uint i = 0; i < MAX_GFT; i++) { - free((void*)this->files[i].filename); - free((void*)this->files[i].missing_warning); - } - - delete this->next; - } -}; - -/** All graphics sets currently available */ -static GraphicsSet *_available_graphics_sets = NULL; -/** The one and only graphics set that is currently being used. */ -static const GraphicsSet *_used_graphics_set = NULL; - #include "table/files.h" #include "table/landscape_sprite.h" @@ -136,88 +87,6 @@ static void LoadGrfIndexed(const char *filename, const SpriteID *index_tbl, int } -/** - * Calculate and check the MD5 hash of the supplied filename. - * @param file filename and expected MD5 hash for the given filename. - * @return true if the checksum is correct. - */ -static bool FileMD5(const MD5File file) -{ - size_t size; - FILE *f = FioFOpenFile(file.filename, "rb", DATA_DIR, &size); - - if (f != NULL) { - Md5 checksum; - uint8 buffer[1024]; - uint8 digest[16]; - size_t len; - - while ((len = fread(buffer, 1, (size > sizeof(buffer)) ? sizeof(buffer) : size, f)) != 0 && size != 0) { - size -= len; - checksum.Append(buffer, len); - } - - FioFCloseFile(f); - - checksum.Finish(digest); - return memcmp(file.hash, digest, sizeof(file.hash)) == 0; - } else { // file not found - return false; - } -} - -/** - * Determine the graphics pack that has to be used. - * The one with the most correct files wins. - */ -static bool DetermineGraphicsPack() -{ - if (_used_graphics_set != NULL) return true; - - const GraphicsSet *best = _available_graphics_sets; - for (const GraphicsSet *c = _available_graphics_sets; c != NULL; c = c->next) { - if (best->found_grfs < c->found_grfs || - (best->found_grfs == c->found_grfs && ( - (best->shortname == c->shortname && best->version < c->version) || - (best->palette != _use_palette && c->palette == _use_palette)))) { - best = c; - } - } - - _used_graphics_set = best; - return _used_graphics_set != NULL; -} - -extern void UpdateNewGRFConfigPalette(); - -/** - * Determine the palette that has to be used. - * - forced palette via command line -> leave it that way - * - otherwise -> palette based on the graphics pack - */ -static void DeterminePalette() -{ - assert(_used_graphics_set != NULL); - if (_use_palette >= MAX_PAL) _use_palette = _used_graphics_set->palette; - - switch (_use_palette) { - case PAL_DOS: - _palette_remap = _palmap_w2d; - _palette_reverse_remap = _palmap_d2w; - break; - - case PAL_WINDOWS: - _palette_remap = _palmap_d2w; - _palette_reverse_remap = _palmap_w2d; - break; - - default: - NOT_REACHED(); - } - - UpdateNewGRFConfigPalette(); -} - /** * Checks whether the MD5 checksums of the files are correct. * @@ -225,9 +94,10 @@ static void DeterminePalette() */ void CheckExternalFiles() { - DeterminePalette(); + BaseGraphics::DeterminePalette(); + const GraphicsSet *used_set = BaseGraphics::GetUsedSet(); - DEBUG(grf, 1, "Using the %s base graphics set with the %s palette", _used_graphics_set->name, _use_palette == PAL_DOS ? "DOS" : "Windows"); + DEBUG(grf, 1, "Using the %s base graphics set with the %s palette", used_set->name, _use_palette == PAL_DOS ? "DOS" : "Windows"); static const size_t ERROR_MESSAGE_LENGTH = 128; char error_msg[ERROR_MESSAGE_LENGTH * (MAX_GFT + 1)]; @@ -235,15 +105,15 @@ void CheckExternalFiles() char *add_pos = error_msg; const char *last = lastof(error_msg); - for (uint i = 0; i < lengthof(_used_graphics_set->files); i++) { - if (!FileMD5(_used_graphics_set->files[i])) { - add_pos += seprintf(add_pos, last, "Your '%s' file is corrupted or missing! %s\n", _used_graphics_set->files[i].filename, _used_graphics_set->files[i].missing_warning); + for (uint i = 0; i < lengthof(used_set->files); i++) { + if (!used_set->files[i].CheckMD5()) { + add_pos += seprintf(add_pos, last, "Your '%s' file is corrupted or missing! %s\n", used_set->files[i].filename, used_set->files[i].missing_warning); } } bool sound = false; for (uint i = 0; !sound && i < lengthof(_sound_sets); i++) { - sound = FileMD5(_sound_sets[i]); + sound = _sound_sets[i].CheckMD5(); } if (!sound) { @@ -258,9 +128,10 @@ static void LoadSpriteTables() { memset(_palette_remap_grf, 0, sizeof(_palette_remap_grf)); uint i = FIRST_GRF_SLOT; + const GraphicsSet *used_set = BaseGraphics::GetUsedSet(); - _palette_remap_grf[i] = (_use_palette != _used_graphics_set->palette); - LoadGrfFile(_used_graphics_set->files[GFT_BASE].filename, 0, i++); + _palette_remap_grf[i] = (_use_palette != used_set->palette); + LoadGrfFile(used_set->files[GFT_BASE].filename, 0, i++); /* * The second basic file always starts at the given location and does @@ -268,8 +139,8 @@ static void LoadSpriteTables() * has a few sprites less. However, we do not care about those missing * sprites as they are not shown anyway (logos in intro game). */ - _palette_remap_grf[i] = (_use_palette != _used_graphics_set->palette); - LoadGrfFile(_used_graphics_set->files[GFT_LOGOS].filename, 4793, i++); + _palette_remap_grf[i] = (_use_palette != used_set->palette); + LoadGrfFile(used_set->files[GFT_LOGOS].filename, 4793, i++); /* * Load additional sprites for climates other than temperate. @@ -277,9 +148,9 @@ static void LoadSpriteTables() * and the ground sprites. */ if (_settings_game.game_creation.landscape != LT_TEMPERATE) { - _palette_remap_grf[i] = (_use_palette != _used_graphics_set->palette); + _palette_remap_grf[i] = (_use_palette != used_set->palette); LoadGrfIndexed( - _used_graphics_set->files[GFT_ARCTIC + _settings_game.game_creation.landscape - 1].filename, + used_set->files[GFT_ARCTIC + _settings_game.game_creation.landscape - 1].filename, _landscape_spriteindexes[_settings_game.game_creation.landscape - 1], i++ ); @@ -295,9 +166,9 @@ static void LoadSpriteTables() */ GRFConfig *top = _grfconfig; GRFConfig *master = CallocT(1); - master->filename = strdup(_used_graphics_set->files[GFT_EXTRA].filename); + master->filename = strdup(used_set->files[GFT_EXTRA].filename); FillGRFDetails(master, false); - master->windows_paletted = (_used_graphics_set->palette == PAL_WINDOWS); + master->windows_paletted = (used_set->palette == PAL_WINDOWS); ClrBit(master->flags, GCF_INIT_ONLY); master->next = top; _grfconfig = master; @@ -319,341 +190,106 @@ void GfxLoadSprites() GfxInitPalettes(); } -/** - * Try to read a single piece of metadata and return false if it doesn't exist. - * @param name the name of the item to fetch. - */ -#define fetch_metadata(name) \ - item = metadata->GetItem(name, false); \ - if (item == NULL || strlen(item->value) == 0) { \ - DEBUG(grf, 0, "Base graphics set detail loading: %s field missing", name); \ - return false; \ - } - -/** Names corresponding to the GraphicsFileType */ -static const char *_gft_names[MAX_GFT] = { "base", "logos", "arctic", "tropical", "toyland", "extra" }; - -/** - * Read the graphics set information from a loaded ini. - * @param graphics the graphics set to write to - * @param ini the ini to read from - * @param path the path to this ini file (for filenames) - * @return true if loading was successful. - */ -static bool FillGraphicsSetDetails(GraphicsSet *graphics, IniFile *ini, const char *path) +bool GraphicsSet::FillSetDetails(IniFile *ini, const char *path) { - memset(graphics, 0, sizeof(*graphics)); + bool ret = this->BaseSet::FillSetDetails(ini, path); + if (ret) { + IniGroup *metadata = ini->GetGroup("metadata"); + IniItem *item; - IniGroup *metadata = ini->GetGroup("metadata"); - IniItem *item; - - fetch_metadata("name"); - graphics->name = strdup(item->value); - - fetch_metadata("description"); - graphics->description = strdup(item->value); - - fetch_metadata("shortname"); - for (uint i = 0; item->value[i] != '\0' && i < 4; i++) { - graphics->shortname |= ((uint8)item->value[i]) << (i * 8); + fetch_metadata("palette"); + this->palette = (*item->value == 'D' || *item->value == 'd') ? PAL_DOS : PAL_WINDOWS; } - - fetch_metadata("version"); - graphics->version = atoi(item->value); - - fetch_metadata("palette"); - graphics->palette = (*item->value == 'D' || *item->value == 'd') ? PAL_DOS : PAL_WINDOWS; - - /* For each of the graphics file types we want to find the file, MD5 checksums and warning messages. */ - IniGroup *files = ini->GetGroup("files"); - IniGroup *md5s = ini->GetGroup("md5s"); - IniGroup *origin = ini->GetGroup("origin"); - for (uint i = 0; i < MAX_GFT; i++) { - MD5File *file = &graphics->files[i]; - /* Find the filename first. */ - item = files->GetItem(_gft_names[i], false); - if (item == NULL) { - DEBUG(grf, 0, "No graphics file for: %s", _gft_names[i]); - return false; - } - - const char *filename = item->value; - file->filename = str_fmt("%s%s", path, filename); - - /* Then find the MD5 checksum */ - item = md5s->GetItem(filename, false); - if (item == NULL) { - DEBUG(grf, 0, "No MD5 checksum specified for: %s", filename); - return false; - } - char *c = item->value; - for (uint i = 0; i < sizeof(file->hash) * 2; i++, c++) { - uint j; - if ('0' <= *c && *c <= '9') { - j = *c - '0'; - } else if ('a' <= *c && *c <= 'f') { - j = *c - 'a' + 10; - } else if ('A' <= *c && *c <= 'F') { - j = *c - 'A' + 10; - } else { - DEBUG(grf, 0, "Malformed MD5 checksum specified for: %s", filename); - return false; - } - if (i % 2 == 0) { - file->hash[i / 2] = j << 4; - } else { - file->hash[i / 2] |= j; - } - } - - /* Then find the warning message when the file's missing */ - item = origin->GetItem(filename, false); - if (item == NULL) item = origin->GetItem("default", false); - if (item == NULL) { - DEBUG(grf, 1, "No origin warning message specified for: %s", filename); - file->missing_warning = strdup(""); - } else { - file->missing_warning = strdup(item->value); - } - - if (FileMD5(*file)) graphics->found_grfs++; - } - return true; } -/** Helper for scanning for files with GRF as extension */ -class OBGFileScanner : FileScanner { -public: - /* virtual */ bool AddFile(const char *filename, size_t basepath_length); - - /** Do the scan for OBGs. */ - static uint DoScan() - { - OBGFileScanner fs; - return fs.Scan(".obg", DATA_DIR); - } -}; /** - * Try to add a graphics set with the given filename. - * @param filename the full path to the file to read - * @param basepath_length amount of characters to chop of before to get a relative DATA_DIR filename - * @return true if the file is added. + * Calculate and check the MD5 hash of the supplied filename. + * @return true if the checksum is correct. */ -bool OBGFileScanner::AddFile(const char *filename, size_t basepath_length) +bool MD5File::CheckMD5() const { - bool ret = false; - DEBUG(grf, 1, "Checking %s for base graphics set", filename); + size_t size; + FILE *f = FioFOpenFile(this->filename, "rb", DATA_DIR, &size); - GraphicsSet *graphics = new GraphicsSet();; - IniFile *ini = new IniFile(); - ini->LoadFromDisk(filename); + if (f != NULL) { + Md5 checksum; + uint8 buffer[1024]; + uint8 digest[16]; + size_t len; - char *path = strdup(filename + basepath_length); - char *psep = strrchr(path, PATHSEPCHAR); - if (psep != NULL) { - psep[1] = '\0'; - } else { - *path = '\0'; + while ((len = fread(buffer, 1, (size > sizeof(buffer)) ? sizeof(buffer) : size, f)) != 0 && size != 0) { + size -= len; + checksum.Append(buffer, len); + } + + FioFCloseFile(f); + + checksum.Finish(digest); + return memcmp(this->hash, digest, sizeof(this->hash)) == 0; + } else { // file not found + return false; } - - if (FillGraphicsSetDetails(graphics, ini, path)) { - GraphicsSet *duplicate = NULL; - for (GraphicsSet *c = _available_graphics_sets; c != NULL; c = c->next) { - if (strcmp(c->name, graphics->name) == 0 || c->shortname == graphics->shortname) { - duplicate = c; - break; - } - } - if (duplicate != NULL) { - /* The more complete graphics set takes precedence over the version number. */ - if ((duplicate->found_grfs == graphics->found_grfs && duplicate->version >= graphics->version) || - duplicate->found_grfs > graphics->found_grfs) { - DEBUG(grf, 1, "Not adding %s (%i) as base graphics set (duplicate)", graphics->name, graphics->version); - delete graphics; - } else { - GraphicsSet **prev = &_available_graphics_sets; - while (*prev != duplicate) prev = &(*prev)->next; - - *prev = graphics; - graphics->next = duplicate->next; - /* don't allow recursive delete of all remaining items */ - duplicate->next = NULL; - - DEBUG(grf, 1, "Removing %s (%i) as base graphics set (duplicate)", duplicate->name, duplicate->version); - delete duplicate; - ret = true; - } - } else { - GraphicsSet **last = &_available_graphics_sets; - while (*last != NULL) last = &(*last)->next; - - *last = graphics; - ret = true; - } - if (ret) { - DEBUG(grf, 1, "Adding %s (%i) as base graphics set", graphics->name, graphics->version); - } - } else { - delete graphics; - } - free(path); - - delete ini; - return ret; } +/** Names corresponding to the GraphicsFileType */ +template +/* static */ const char *BaseSet::file_names[Tnum_files] = { "base", "logos", "arctic", "tropical", "toyland", "extra" }; - -/** Scan for all Grahpics sets */ -void FindGraphicsSets() -{ - DEBUG(grf, 1, "Scanning for Graphics sets"); - OBGFileScanner::DoScan(); -} +extern void UpdateNewGRFConfigPalette(); /** - * Set the graphics set to be used. - * @param name of the graphics set to use - * @return true if it could be loaded + * Determine the palette that has to be used. + * - forced palette via command line -> leave it that way + * - otherwise -> palette based on the graphics pack */ -bool SetGraphicsSet(const char *name) +/* static */ void BaseGraphics::DeterminePalette() { - if (StrEmpty(name)) { - if (!DetermineGraphicsPack()) return false; - CheckExternalFiles(); - return true; + assert(BaseGraphics::used_set != NULL); + if (_use_palette >= MAX_PAL) _use_palette = BaseGraphics::used_set->palette; + + switch (_use_palette) { + case PAL_DOS: + _palette_remap = _palmap_w2d; + _palette_reverse_remap = _palmap_d2w; + break; + + case PAL_WINDOWS: + _palette_remap = _palmap_d2w; + _palette_reverse_remap = _palmap_w2d; + break; + + default: + NOT_REACHED(); } - for (const GraphicsSet *g = _available_graphics_sets; g != NULL; g = g->next) { - if (strcmp(name, g->name) == 0) { - _used_graphics_set = g; - CheckExternalFiles(); - return true; + UpdateNewGRFConfigPalette(); +} + +template +/* static */ bool BaseMedia::DetermineBestSet() +{ + if (BaseMedia::used_set != NULL) return true; + + const Tbase_set *best = BaseMedia::available_sets; + for (const Tbase_set *c = BaseMedia::available_sets; c != NULL; c = c->next) { + if (best->found_files < c->found_files || + (best->found_files == c->found_files && ( + (best->shortname == c->shortname && best->version < c->version) || + (best->palette != _use_palette && c->palette == _use_palette)))) { + best = c; } } - return false; + + BaseMedia::used_set = best; + return BaseMedia::used_set != NULL; } -/** - * Returns a list with the graphics sets. - * @param p where to print to - * @param last the last character to print to - * @return the last printed character - */ -char *GetGraphicsSetsList(char *p, const char *last) +template +/* static */ const char *BaseMedia::GetExtension() { - p += seprintf(p, last, "List of graphics sets:\n"); - for (const GraphicsSet *g = _available_graphics_sets; g != NULL; g = g->next) { - if (g->found_grfs <= 1) continue; - - p += seprintf(p, last, "%18s: %s", g->name, g->description); - int difference = MAX_GFT - g->found_grfs; - if (difference != 0) { - p += seprintf(p, last, " (missing %i file%s)\n", difference, difference == 1 ? "" : "s"); - } else { - p += seprintf(p, last, "\n"); - } - } - p += seprintf(p, last, "\n"); - - return p; + return ".obg"; // OpenTTD Base Graphics } -#if defined(ENABLE_NETWORK) -#include "network/network_content.h" - -/** - * Check whether we have an graphics with the exact characteristics as ci. - * @param ci the characteristics to search on (shortname and md5sum) - * @param md5sum whether to check the MD5 checksum - * @return true iff we have an graphics set matching. - */ -bool HasGraphicsSet(const ContentInfo *ci, bool md5sum) -{ - assert(ci->type == CONTENT_TYPE_BASE_GRAPHICS); - for (const GraphicsSet *g = _available_graphics_sets; g != NULL; g = g->next) { - if (g->found_grfs <= 1) continue; - - if (g->shortname != ci->unique_id) continue; - if (!md5sum) return true; - - byte md5[16]; - memset(md5, 0, sizeof(md5)); - for (uint i = 0; i < MAX_GFT; i++) { - for (uint j = 0; j < sizeof(md5); j++) { - md5[j] ^= g->files[i].hash[j]; - } - } - if (memcmp(md5, ci->md5sum, sizeof(md5)) == 0) return true; - } - - return false; -} - -#endif /* ENABLE_NETWORK */ - -/** - * Count the number of available graphics sets. - */ -int GetNumGraphicsSets() -{ - int n = 0; - for (const GraphicsSet *g = _available_graphics_sets; g != NULL; g = g->next) { - if (g != _used_graphics_set && g->found_grfs <= 1) continue; - n++; - } - return n; -} - -/** - * Get the index of the currently active graphics set - */ -int GetIndexOfCurrentGraphicsSet() -{ - int n = 0; - for (const GraphicsSet *g = _available_graphics_sets; g != NULL; g = g->next) { - if (g == _used_graphics_set) return n; - if (g->found_grfs <= 1) continue; - n++; - } - return -1; -} - -/** - * Get the graphics set at the specified index - */ -static const GraphicsSet *GetGraphicsSetAtIndex(int index) -{ - for (const GraphicsSet *g = _available_graphics_sets; g != NULL; g = g->next) { - if (g != _used_graphics_set && g->found_grfs <= 1) continue; - if (index == 0) return g; - index--; - } - error("GetGraphicsSetAtIndex: index %d out of range", index); -} - -/** - * Get the name of the graphics set at the specified index - */ -const char *GetGraphicsSetName(int index) -{ - return GetGraphicsSetAtIndex(index)->name; -} - -/** - * Get the description of the graphics set at the specified index - */ -const char *GetGraphicsSetDescription(int index) -{ - return GetGraphicsSetAtIndex(index)->description; -} - -/** - * Get the number of missing/corrupted files of the graphics set at the specified index - */ -int GetGraphicsSetNumMissingFiles(int index) -{ - return MAX_GFT - GetGraphicsSetAtIndex(index)->found_grfs; -} +INSTANTIATE_BASE_MEDIA_METHODS(BaseMedia, GraphicsSet) diff --git a/src/gfxinit.h b/src/gfxinit.h index ae3718a026..6136654e86 100644 --- a/src/gfxinit.h +++ b/src/gfxinit.h @@ -7,20 +7,7 @@ #include "gfx_type.h" -void CheckExternalFiles(); void GfxLoadSprites(); void LoadSpritesIndexed(int file_index, uint *sprite_id, const SpriteID *index_tbl); -void FindGraphicsSets(); -bool SetGraphicsSet(const char *name); -char *GetGraphicsSetsList(char *p, const char *last); - -int GetNumGraphicsSets(); -int GetIndexOfCurrentGraphicsSet(); -const char *GetGraphicsSetName(int index); -const char *GetGraphicsSetDescription(int index); -int GetGraphicsSetNumMissingFiles(int index); - -extern char *_ini_graphics_set; - #endif /* GFXINIT_H */ diff --git a/src/network/network_content.cpp b/src/network/network_content.cpp index b10d2cf856..5f1590f15b 100644 --- a/src/network/network_content.cpp +++ b/src/network/network_content.cpp @@ -12,6 +12,7 @@ #include "../window_func.h" #include "../gui.h" #include "../variables.h" +#include "../base_media_base.h" #include "network_content.h" #include "table/strings.h" @@ -21,7 +22,6 @@ #endif extern bool TarListAddFile(const char *filename); -extern bool HasGraphicsSet(const ContentInfo *ci, bool md5sum); extern bool HasScenario(const ContentInfo *ci, bool md5sum); ClientNetworkContentSocketHandler _network_content_client; @@ -79,7 +79,7 @@ DEF_CONTENT_RECEIVE_COMMAND(Client, PACKET_CONTENT_SERVER_INFO) break; case CONTENT_TYPE_BASE_GRAPHICS: - proc = HasGraphicsSet; + proc = BaseGraphics::HasSet; break; case CONTENT_TYPE_AI: diff --git a/src/network/network_content_gui.cpp b/src/network/network_content_gui.cpp index 84fca14aeb..44f5456d75 100644 --- a/src/network/network_content_gui.cpp +++ b/src/network/network_content_gui.cpp @@ -11,7 +11,7 @@ #include "../window_gui.h" #include "../gui.h" #include "../ai/ai.hpp" -#include "../gfxinit.h" +#include "../base_media_base.h" #include "../sortlist_type.h" #include "../querystring_gui.h" #include "network_content.h" @@ -92,7 +92,7 @@ public: break; case CONTENT_TYPE_BASE_GRAPHICS: - FindGraphicsSets(); + BaseGraphics::FindSets(); break; case CONTENT_TYPE_NEWGRF: diff --git a/src/openttd.cpp b/src/openttd.cpp index 046717db53..e77a781a1e 100644 --- a/src/openttd.cpp +++ b/src/openttd.cpp @@ -21,6 +21,7 @@ #include "sound_func.h" #include "window_func.h" +#include "base_media_base.h" #include "saveload/saveload.h" #include "landscape.h" #include "company_func.h" @@ -183,7 +184,7 @@ static void ShowHelp() ); /* List the graphics packs */ - p = GetGraphicsSetsList(p, lastof(buf)); + p = BaseGraphics::GetSetsList(p, lastof(buf)); /* List the drivers */ p = VideoDriverFactoryBase::GetDriversInfo(p, lastof(buf)); @@ -524,7 +525,7 @@ int ttd_main(int argc, char *argv[]) * We can't do them earlier because then we can't show it on * the debug console as that hasn't been configured yet. */ DeterminePaths(argv[0]); - FindGraphicsSets(); + BaseGraphics::FindSets(); ShowHelp(); return 0; } @@ -536,7 +537,7 @@ int ttd_main(int argc, char *argv[]) #endif DeterminePaths(argv[0]); - FindGraphicsSets(); + BaseGraphics::FindSets(); #if defined(UNIX) && !defined(__MORPHOS__) /* We must fork here, or we'll end up without some resources we need (like sockets) */ @@ -593,8 +594,8 @@ int ttd_main(int argc, char *argv[]) /* This must be done early, since functions use the InvalidateWindow* calls */ InitWindowSystem(); - if (graphics_set == NULL && _ini_graphics_set != NULL) graphics_set = strdup(_ini_graphics_set); - if (!SetGraphicsSet(graphics_set)) { + if (graphics_set == NULL && BaseGraphics::ini_set != NULL) graphics_set = strdup(BaseGraphics::ini_set); + if (!BaseGraphics::SetSet(graphics_set)) { StrEmpty(graphics_set) ? usererror("Failed to find a graphics set. Please acquire a graphics set for OpenTTD.") : usererror("Failed to select requested graphics set '%s'", graphics_set); @@ -727,7 +728,7 @@ int ttd_main(int argc, char *argv[]) /* Reset windowing system, stop drivers, free used memory, ... */ ShutdownGame(); - free(_ini_graphics_set); + free(const_cast(BaseGraphics::ini_set)); free(_ini_musicdriver); free(_ini_sounddriver); free(_ini_videodriver); diff --git a/src/settings.cpp b/src/settings.cpp index 1dcccaef51..a90a68b855 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -48,7 +48,7 @@ #include "sound/sound_driver.hpp" #include "music/music_driver.hpp" #include "blitter/factory.hpp" -#include "gfxinit.h" +#include "base_media_base.h" #include "gamelog.h" #include "station_func.h" #include "map_type.h" diff --git a/src/settings_gui.cpp b/src/settings_gui.cpp index 71d6931e35..602ed2c0cb 100644 --- a/src/settings_gui.cpp +++ b/src/settings_gui.cpp @@ -24,7 +24,7 @@ #include "widgets/dropdown_func.h" #include "station_func.h" #include "highscore.h" -#include "gfxinit.h" +#include "base_media_base.h" #include "company_base.h" #include "company_func.h" #include @@ -153,12 +153,12 @@ static void ShowCustCurrency(); static void ShowGraphicsSetMenu(Window *w) { - int n = GetNumGraphicsSets(); - int current = GetIndexOfCurrentGraphicsSet(); + int n = BaseGraphics::GetNumSets(); + int current = BaseGraphics::GetIndexOfUsedSet(); DropDownList *list = new DropDownList(); for (int i = 0; i < n; i++) { - list->push_back(new DropDownListCharStringItem(GetGraphicsSetName(i), i, (_game_mode == GM_MENU) ? false : (current != i))); + list->push_back(new DropDownListCharStringItem(BaseGraphics::GetSet(i)->name, i, (_game_mode == GM_MENU) ? false : (current != i))); } ShowDropDownList(w, list, current, GOW_BASE_GRF_DROPDOWN); @@ -194,8 +194,8 @@ struct GameOptionsWindow : Window { case GOW_LANG_DROPDOWN: SetDParam(0, SPECSTR_LANGUAGE_START + _dynlang.curr); break; case GOW_RESOLUTION_DROPDOWN: SetDParam(0, GetCurRes() == _num_resolutions ? STR_RES_OTHER : SPECSTR_RESOLUTION_START + GetCurRes()); break; case GOW_SCREENSHOT_DROPDOWN: SetDParam(0, SPECSTR_SCREENSHOT_START + _cur_screenshot_format); break; - case GOW_BASE_GRF_DROPDOWN: SetDParamStr(0, GetGraphicsSetName(GetIndexOfCurrentGraphicsSet())); break; - case GOW_BASE_GRF_STATUS: SetDParam(0, GetGraphicsSetNumMissingFiles(GetIndexOfCurrentGraphicsSet())); break; + case GOW_BASE_GRF_DROPDOWN: SetDParamStr(0, BaseGraphics::GetUsedSet()->name); break; + case GOW_BASE_GRF_STATUS: SetDParam(0, BaseGraphics::GetUsedSet()->GetNumMissing()); break; } } @@ -208,7 +208,7 @@ struct GameOptionsWindow : Window { { if (widget != GOW_BASE_GRF_DESCRIPTION) return; - SetDParamStr(0, GetGraphicsSetDescription(GetIndexOfCurrentGraphicsSet())); + SetDParamStr(0, BaseGraphics::GetUsedSet()->description); DrawStringMultiLine(r.left, r.right, r.top, UINT16_MAX, STR_BLACK_RAW_STRING); } @@ -217,8 +217,8 @@ struct GameOptionsWindow : Window { if (widget != GOW_BASE_GRF_DESCRIPTION) return; /* Find the biggest description for the default size. */ - for (int i = 0; i < GetNumGraphicsSets(); i++) { - SetDParamStr(0, GetGraphicsSetDescription(i)); + for (int i = 0; i < BaseGraphics::GetNumSets(); i++) { + SetDParamStr(0, BaseGraphics::GetSet(i)->description); size->height = max(size->height, (uint)GetStringHeight(STR_BLACK_RAW_STRING, size->width)); } } @@ -348,12 +348,12 @@ struct GameOptionsWindow : Window { case GOW_BASE_GRF_DROPDOWN: if (_game_mode == GM_MENU) { - const char *name = GetGraphicsSetName(index); + const char *name = BaseGraphics::GetSet(index)->name; - free(_ini_graphics_set); - _ini_graphics_set = strdup(name); + free(const_cast(BaseGraphics::ini_set)); + BaseGraphics::ini_set = strdup(name); - SetGraphicsSet(name); + BaseGraphics::SetSet(name); this->reload = true; this->SetDirty(); this->OnInvalidateData(0); @@ -366,7 +366,7 @@ struct GameOptionsWindow : Window { { this->SetWidgetLoweredState(GOW_FULLSCREEN_BUTTON, _fullscreen); - bool missing_files = GetGraphicsSetNumMissingFiles(GetIndexOfCurrentGraphicsSet()) == 0; + bool missing_files = BaseGraphics::GetUsedSet()->GetNumMissing() == 0; this->nested_array[GOW_BASE_GRF_STATUS]->SetDataTip(missing_files ? STR_EMPTY : STR_GAME_OPTIONS_BASE_GRF_STATUS, STR_NULL); } }; diff --git a/src/table/settings.h b/src/table/settings.h index b2c855e493..71f3b52266 100644 --- a/src/table/settings.h +++ b/src/table/settings.h @@ -237,7 +237,7 @@ static const SettingDescGlobVarList _misc_settings[] = { SDTG_MMANY("display_opt", SLE_UINT8, S, 0, _display_opt, (1 << DO_SHOW_TOWN_NAMES | 1 << DO_SHOW_STATION_NAMES | 1 << DO_SHOW_SIGNS | 1 << DO_FULL_ANIMATION | 1 << DO_FULL_DETAIL | 1 << DO_SHOW_WAYPOINT_NAMES), "SHOW_TOWN_NAMES|SHOW_STATION_NAMES|SHOW_SIGNS|FULL_ANIMATION||FULL_DETAIL|WAYPOINTS", STR_NULL, NULL), SDTG_BOOL("news_ticker_sound", S, 0, _news_ticker_sound, true, STR_NULL, NULL), SDTG_BOOL("fullscreen", S, 0, _fullscreen, false, STR_NULL, NULL), - SDTG_STR("graphicsset", SLE_STRQ, S, 0, _ini_graphics_set, NULL, STR_NULL, NULL), + SDTG_STR("graphicsset", SLE_STRQ, S, 0, BaseGraphics::ini_set, NULL, STR_NULL, NULL), SDTG_STR("videodriver", SLE_STRQ, S, 0, _ini_videodriver, NULL, STR_NULL, NULL), SDTG_STR("musicdriver", SLE_STRQ, S, 0, _ini_musicdriver, NULL, STR_NULL, NULL), SDTG_STR("sounddriver", SLE_STRQ, S, 0, _ini_sounddriver, NULL, STR_NULL, NULL),