OpenTTD Source 15.0-beta2
base_media_func.h
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * 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.
4 * 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.
5 * 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/>.
6 */
7
12#include "base_media_base.h"
13#include "debug.h"
14#include "ini_type.h"
15#include "string_func.h"
16#include "error_func.h"
17
18extern void CheckExternalFiles();
19
24#define fetch_metadata(name) \
25 item = metadata->GetItem(name); \
26 if (item == nullptr || !item->value.has_value() || item->value->empty()) { \
27 Debug(grf, 0, "Base {}set detail loading: {} field missing.", BaseSet::SET_TYPE, name); \
28 Debug(grf, 0, " Is {} readable for the user running OpenTTD?", full_filename); \
29 return false; \
30 }
31
40template <class T>
41bool BaseSet<T>::FillSetDetails(const IniFile &ini, const std::string &path, const std::string &full_filename, bool allow_empty_filename)
42{
43 const IniGroup *metadata = ini.GetGroup("metadata");
44 if (metadata == nullptr) {
45 Debug(grf, 0, "Base {}set detail loading: metadata missing.", BaseSet<T>::SET_TYPE);
46 Debug(grf, 0, " Is {} readable for the user running OpenTTD?", full_filename);
47 return false;
48 }
49 const IniItem *item;
50
51 fetch_metadata("name");
52 this->name = *item->value;
53
54 fetch_metadata("description");
55 this->description[std::string{}] = *item->value;
56
57 item = metadata->GetItem("url");
58 if (item != nullptr) this->url = *item->value;
59
60 /* Add the translations of the descriptions too. */
61 for (const IniItem &titem : metadata->items) {
62 if (titem.name.compare(0, 12, "description.") != 0) continue;
63
64 this->description[titem.name.substr(12)] = titem.value.value_or("");
65 }
66
67 fetch_metadata("shortname");
68 for (uint i = 0; (*item->value)[i] != '\0' && i < 4; i++) {
69 this->shortname |= ((uint8_t)(*item->value)[i]) << (i * 8);
70 }
71
72 fetch_metadata("version");
73 this->version = atoi(item->value->c_str());
74
75 item = metadata->GetItem("fallback");
76 this->fallback = (item != nullptr && item->value && *item->value != "0" && *item->value != "false");
77
78 /* For each of the file types we want to find the file, MD5 checksums and warning messages. */
79 const IniGroup *files = ini.GetGroup("files");
80 const IniGroup *md5s = ini.GetGroup("md5s");
81 const IniGroup *origin = ini.GetGroup("origin");
82 auto file_names = BaseSet<T>::GetFilenames();
83
84 for (uint i = 0; i < BaseSet<T>::NUM_FILES; i++) {
85 MD5File *file = &this->files[i];
86 /* Find the filename first. */
87 item = files != nullptr ? files->GetItem(file_names[i]) : nullptr;
88 if (item == nullptr || (!item->value.has_value() && !allow_empty_filename)) {
89 Debug(grf, 0, "No {} file for: {} (in {})", BaseSet<T>::SET_TYPE, file_names[i], full_filename);
90 return false;
91 }
92
93 if (!item->value.has_value()) {
94 file->filename.clear();
95 /* If we list no file, that file must be valid */
96 this->valid_files++;
97 this->found_files++;
98 continue;
99 }
100
101 const std::string &filename = item->value.value();
102 file->filename = path + filename;
103
104 /* Then find the MD5 checksum */
105 item = md5s != nullptr ? md5s->GetItem(filename) : nullptr;
106 if (item == nullptr || !item->value.has_value()) {
107 Debug(grf, 0, "No MD5 checksum specified for: {} (in {})", filename, full_filename);
108 return false;
109 }
110 const char *c = item->value->c_str();
111 for (size_t i = 0; i < file->hash.size() * 2; i++, c++) {
112 uint j;
113 if ('0' <= *c && *c <= '9') {
114 j = *c - '0';
115 } else if ('a' <= *c && *c <= 'f') {
116 j = *c - 'a' + 10;
117 } else if ('A' <= *c && *c <= 'F') {
118 j = *c - 'A' + 10;
119 } else {
120 Debug(grf, 0, "Malformed MD5 checksum specified for: {} (in {})", filename, full_filename);
121 return false;
122 }
123 if (i % 2 == 0) {
124 file->hash[i / 2] = j << 4;
125 } else {
126 file->hash[i / 2] |= j;
127 }
128 }
129
130 /* Then find the warning message when the file's missing */
131 item = origin != nullptr ? origin->GetItem(filename) : nullptr;
132 if (item == nullptr) item = origin != nullptr ? origin->GetItem("default") : nullptr;
133 if (item == nullptr || !item->value.has_value()) {
134 Debug(grf, 1, "No origin warning message specified for: {}", filename);
135 file->missing_warning.clear();
136 } else {
137 file->missing_warning = item->value.value();
138 }
139
140 file->check_result = T::CheckMD5(file, BASESET_DIR);
141 switch (file->check_result) {
143 break;
144
146 this->valid_files++;
147 this->found_files++;
148 break;
149
151 Debug(grf, 1, "MD5 checksum mismatch for: {} (in {})", filename, full_filename);
152 this->found_files++;
153 break;
154
156 Debug(grf, 1, "The file {} specified in {} is missing", filename, full_filename);
157 break;
158 }
159 }
160
161 return true;
162}
163
164template <class Tbase_set>
165bool BaseMedia<Tbase_set>::AddFile(const std::string &filename, size_t basepath_length, const std::string &)
166{
167 bool ret = false;
168 Debug(grf, 1, "Checking {} for base {} set", filename, BaseSet<Tbase_set>::SET_TYPE);
169
170 Tbase_set *set = new Tbase_set();
171 IniFile ini{};
172 std::string path{ filename, basepath_length };
174
175 auto psep = path.rfind(PATHSEPCHAR);
176 if (psep != std::string::npos) {
177 path.erase(psep + 1);
178 } else {
179 path.clear();
180 }
181
182 if (set->FillSetDetails(ini, path, filename)) {
183 Tbase_set *duplicate = nullptr;
184 for (Tbase_set *c = BaseMedia<Tbase_set>::available_sets; c != nullptr; c = c->next) {
185 if (c->name == set->name || c->shortname == set->shortname) {
186 duplicate = c;
187 break;
188 }
189 }
190 if (duplicate != nullptr) {
191 /* The more complete set takes precedence over the version number. */
192 if ((duplicate->valid_files == set->valid_files && duplicate->version >= set->version) ||
193 duplicate->valid_files > set->valid_files) {
194 Debug(grf, 1, "Not adding {} ({}) as base {} set (duplicate, {})", set->name, set->version,
196 duplicate->valid_files > set->valid_files ? "less valid files" : "lower version");
199 } else {
201 while (*prev != duplicate) prev = &(*prev)->next;
203 *prev = set;
204 set->next = duplicate->next;
206 /* Keep baseset configuration, if compatible */
207 set->CopyCompatibleConfig(*duplicate);
208
209 /* If the duplicate set is currently used (due to rescanning this can happen)
210 * update the currently used set to the new one. This will 'lie' about the
211 * version number until a new game is started which isn't a big problem */
213
214 Debug(grf, 1, "Removing {} ({}) as base {} set (duplicate, {})", duplicate->name, duplicate->version,
216 duplicate->valid_files < set->valid_files ? "less valid files" : "lower version");
217 duplicate->next = BaseMedia<Tbase_set>::duplicate_sets;
219 ret = true;
220 }
221 } else {
222 Tbase_set **last = &BaseMedia<Tbase_set>::available_sets;
223 while (*last != nullptr) last = &(*last)->next;
224
225 *last = set;
226 ret = true;
227 }
228 if (ret) {
229 Debug(grf, 1, "Adding {} ({}) as base {} set", set->name, set->version, BaseSet<Tbase_set>::SET_TYPE);
230 }
231 } else {
232 delete set;
233 }
234
235 return ret;
236}
237
243template <class Tbase_set>
244/* static */ bool BaseMedia<Tbase_set>::SetSet(const Tbase_set *set)
245{
246 if (set == nullptr) {
247 if (!BaseMedia<Tbase_set>::DetermineBestSet()) return false;
248 } else {
250 }
252 return true;
253}
254
260template <class Tbase_set>
261/* static */ bool BaseMedia<Tbase_set>::SetSetByName(const std::string &name)
262{
263 if (name.empty()) {
264 return SetSet(nullptr);
265 }
266
267 for (const Tbase_set *s = BaseMedia<Tbase_set>::available_sets; s != nullptr; s = s->next) {
268 if (name == s->name) {
269 return SetSet(s);
270 }
271 }
272 return false;
273}
274
280template <class Tbase_set>
281/* static */ bool BaseMedia<Tbase_set>::SetSetByShortname(uint32_t shortname)
282{
283 if (shortname == 0) {
284 return SetSet(nullptr);
285 }
286
287 for (const Tbase_set *s = BaseMedia<Tbase_set>::available_sets; s != nullptr; s = s->next) {
288 if (shortname == s->shortname) {
289 return SetSet(s);
290 }
291 }
292 return false;
293}
294
299template <class Tbase_set>
300/* static */ void BaseMedia<Tbase_set>::GetSetsList(std::back_insert_iterator<std::string> &output_iterator)
301{
302 fmt::format_to(output_iterator, "List of {} sets:\n", BaseSet<Tbase_set>::SET_TYPE);
303 for (const Tbase_set *s = BaseMedia<Tbase_set>::available_sets; s != nullptr; s = s->next) {
304 fmt::format_to(output_iterator, "{:>18}: {}", s->name, s->GetDescription({}));
305 int invalid = s->GetNumInvalid();
306 if (invalid != 0) {
307 int missing = s->GetNumMissing();
308 if (missing == 0) {
309 fmt::format_to(output_iterator, " ({} corrupt file{})\n", invalid, invalid == 1 ? "" : "s");
310 } else {
311 fmt::format_to(output_iterator, " (unusable: {} missing file{})\n", missing, missing == 1 ? "" : "s");
312 }
313 } else {
314 fmt::format_to(output_iterator, "\n");
315 }
316 }
317 fmt::format_to(output_iterator, "\n");
318}
319
321
322template <class Tbase_set> const char *TryGetBaseSetFile(const ContentInfo &ci, bool md5sum, const Tbase_set *s)
323{
324 for (; s != nullptr; s = s->next) {
325 if (s->GetNumMissing() != 0) continue;
326
327 if (s->shortname != ci.unique_id) continue;
328 if (!md5sum) return s->files[0].filename.c_str();
329
330 MD5Hash md5;
331 for (const auto &file : s->files) {
332 md5 ^= file.hash;
333 }
334 if (md5 == ci.md5sum) return s->files[0].filename.c_str();
335 }
336 return nullptr;
337}
338
339template <class Tbase_set>
340/* static */ bool BaseMedia<Tbase_set>::HasSet(const ContentInfo &ci, bool md5sum)
341{
342 return (TryGetBaseSetFile(ci, md5sum, BaseMedia<Tbase_set>::available_sets) != nullptr) ||
344}
345
350template <class Tbase_set>
352{
353 int n = 0;
354 for (const Tbase_set *s = BaseMedia<Tbase_set>::available_sets; s != nullptr; s = s->next) {
355 if (s != BaseMedia<Tbase_set>::used_set && s->GetNumMissing() != 0) continue;
356 n++;
357 }
358 return n;
359}
360
365template <class Tbase_set>
367{
368 int n = 0;
369 for (const Tbase_set *s = BaseMedia<Tbase_set>::available_sets; s != nullptr; s = s->next) {
370 if (s == BaseMedia<Tbase_set>::used_set) return n;
371 if (s->GetNumMissing() != 0) continue;
372 n++;
373 }
374 return -1;
375}
376
381template <class Tbase_set>
382/* static */ const Tbase_set *BaseMedia<Tbase_set>::GetSet(int index)
383{
384 for (const Tbase_set *s = BaseMedia<Tbase_set>::available_sets; s != nullptr; s = s->next) {
385 if (s != BaseMedia<Tbase_set>::used_set && s->GetNumMissing() != 0) continue;
386 if (index == 0) return s;
387 index--;
388 }
389 FatalError("Base{}::GetSet(): index {} out of range", BaseSet<Tbase_set>::SET_TYPE, index);
390}
391
396template <class Tbase_set>
397/* static */ const Tbase_set *BaseMedia<Tbase_set>::GetUsedSet()
398{
400}
401
406template <class Tbase_set>
Generic functions for replacing base data (graphics, sounds).
const char * TryGetBaseSetFile(const ContentInfo &ci, bool md5sum, const Tbase_set *s)
Check whether there's a base set matching some information.
#define fetch_metadata(name)
Try to read a single piece of metadata and return false if it doesn't exist.
void CheckExternalFiles()
Checks whether the MD5 checksums of the files are correct.
Definition gfxinit.cpp:113
Base for all base media (graphics, sounds)
static const Tbase_set * GetUsedSet()
Return the used set.
bool AddFile(const std::string &filename, size_t basepath_length, const std::string &tar_filename) override
Add a file with the given filename.
static bool SetSetByShortname(uint32_t shortname)
Set the set to be used.
static void GetSetsList(std::back_insert_iterator< std::string > &output_iterator)
Returns a list with the sets.
static int GetNumSets()
Count the number of available graphics sets.
static bool HasSet(const ContentInfo &ci, bool md5sum)
Check whether we have an set with the exact characteristics as ci.
static const Tbase_set * GetSet(int index)
Get the name of the graphics set at the specified index.
static Tbase_set * GetAvailableSets()
Return the available sets.
static int GetIndexOfUsedSet()
Get the index of the currently active graphics set.
static bool SetSetByName(const std::string &name)
Set the set to be used.
static bool SetSet(const Tbase_set *set)
Set the set to be used.
Functions related to debugging.
#define Debug(category, level, format_string,...)
Output a line of debugging information.
Definition debug.h:37
Error reporting related functions.
@ BASESET_DIR
Subdirectory for all base data (base sets, intro game)
Types related to reading/writing '*.ini' files.
Functions related to low-level strings.
Information about a single base set.
uint valid_files
Number of the files that could be found and are valid.
static std::span< const std::string_view > GetFilenames()
Get the internal names of the files in this set.
bool FillSetDetails(const IniFile &ini, const std::string &path, const std::string &full_filename, bool allow_empty_filename=true)
Read the set information from a loaded ini.
Container for all important information about a piece of content.
uint32_t unique_id
Unique ID; either GRF ID or shortname.
MD5Hash md5sum
The MD5 checksum.
Ini file that supports both loading and saving.
Definition ini_type.h:88
A group within an ini file.
Definition ini_type.h:34
const IniItem * GetItem(std::string_view name) const
Get the item with the given name.
Definition ini_load.cpp:51
std::list< IniItem > items
all items in the group
Definition ini_type.h:35
A single "line" in an ini file.
Definition ini_type.h:23
std::optional< std::string > value
The value of this item.
Definition ini_type.h:25
void LoadFromDisk(const std::string &filename, Subdirectory subdir)
Load the Ini file's data from the disk.
Definition ini_load.cpp:186
const IniGroup * GetGroup(std::string_view name) const
Get the group with the given name.
Definition ini_load.cpp:118
Structure holding filename and MD5 information about a single file.
std::string missing_warning
warning when this file is missing
ChecksumResult check_result
cached result of md5 check
@ CR_MATCH
The file did exist and the md5 checksum did match.
@ CR_MISMATCH
The file did exist, just the md5 checksum did not match.
@ CR_NO_FILE
The file did not exist.
@ CR_UNKNOWN
The file has not been checked yet.
MD5Hash hash
md5 sum of the file
std::string filename
filename
Basic types related to the content on the content server.