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/>.
8 /** @file gfxinit.cpp Initializing of the (GRF) graphics. */
13 #include "3rdparty/md5/md5.h"
14 #include "fontcache.h"
16 #include "transparency.h"
17 #include "blitter/factory.hpp"
18 #include "video/video_driver.hpp"
19 #include "window_func.h"
20 #include "palette_func.h"
22 /* The type of set we're replacing */
23 #define SET_TYPE "graphics"
24 #include "base_media_func.h"
26 #include "table/sprites.h"
28 #include "safeguards.h"
30 #include "table/landscape_sprite.h"
32 /** Offsets for loading the different "replacement" sprites in the files. */
33 static const SpriteID
* const _landscape_spriteindexes
[] = {
34 _landscape_spriteindexes_arctic
,
35 _landscape_spriteindexes_tropic
,
36 _landscape_spriteindexes_toyland
,
40 * Load an old fashioned GRF file.
41 * @param filename The name of the file to open.
42 * @param load_index The offset of the first sprite.
43 * @param needs_palette_remap Whether the colours in the GRF file need a palette remap.
44 * @return The number of loaded sprites.
46 static uint
LoadGrfFile(const std::string
&filename
, uint load_index
, bool needs_palette_remap
)
48 uint load_index_org
= load_index
;
51 SpriteFile
&file
= OpenCachedSpriteFile(filename
, BASESET_DIR
, needs_palette_remap
);
53 Debug(sprite
, 2, "Reading grf-file '{}'", filename
);
55 uint8_t container_ver
= file
.GetContainerVersion();
56 if (container_ver
== 0) UserError("Base grf '{}' is corrupt", filename
);
57 ReadGRFSpriteOffsets(file
);
58 if (container_ver
>= 2) {
59 /* Read compression. */
60 uint8_t compression
= file
.ReadByte();
61 if (compression
!= 0) UserError("Unsupported compression format");
64 while (LoadNextSprite(load_index
, file
, sprite_id
)) {
67 if (load_index
>= MAX_SPRITES
) {
68 UserError("Too many sprites. Recompile with higher MAX_SPRITES value or remove some custom GRF files.");
71 Debug(sprite
, 2, "Currently {} sprites are loaded", load_index
);
73 return load_index
- load_index_org
;
77 * Load an old fashioned GRF file to replace already loaded sprites.
78 * @param filename The name of the file to open.
79 * @param index_tbl The offsets of each of the sprites.
80 * @param needs_palette_remap Whether the colours in the GRF file need a palette remap.
81 * @return The number of loaded sprites.
83 static void LoadGrfFileIndexed(const std::string
&filename
, const SpriteID
*index_tbl
, bool needs_palette_remap
)
88 SpriteFile
&file
= OpenCachedSpriteFile(filename
, BASESET_DIR
, needs_palette_remap
);
90 Debug(sprite
, 2, "Reading indexed grf-file '{}'", filename
);
92 uint8_t container_ver
= file
.GetContainerVersion();
93 if (container_ver
== 0) UserError("Base grf '{}' is corrupt", filename
);
94 ReadGRFSpriteOffsets(file
);
95 if (container_ver
>= 2) {
96 /* Read compression. */
97 uint8_t compression
= file
.ReadByte();
98 if (compression
!= 0) UserError("Unsupported compression format");
101 while ((start
= *index_tbl
++) != END
) {
102 uint end
= *index_tbl
++;
105 [[maybe_unused
]] bool b
= LoadNextSprite(start
, file
, sprite_id
);
108 } while (++start
<= end
);
113 * Checks whether the MD5 checksums of the files are correct.
115 * @note Also checks sample.cat and other required non-NewGRF GRFs for corruption.
117 void CheckExternalFiles()
119 if (BaseGraphics::GetUsedSet() == nullptr || BaseSounds::GetUsedSet() == nullptr) return;
121 const GraphicsSet
*used_set
= BaseGraphics::GetUsedSet();
123 Debug(grf
, 1, "Using the {} base graphics set", used_set
->name
);
125 std::string error_msg
;
126 auto output_iterator
= std::back_inserter(error_msg
);
127 if (used_set
->GetNumInvalid() != 0) {
128 /* Not all files were loaded successfully, see which ones */
129 fmt::format_to(output_iterator
, "Trying to load graphics set '{}', but it is incomplete. The game will probably not run correctly until you properly install this set or select another one. See section 4.1 of README.md.\n\nThe following files are corrupted or missing:\n", used_set
->name
);
130 for (const auto &file
: used_set
->files
) {
131 MD5File::ChecksumResult res
= GraphicsSet::CheckMD5(&file
, BASESET_DIR
);
132 if (res
!= MD5File::CR_MATCH
) fmt::format_to(output_iterator
, "\t{} is {} ({})\n", file
.filename
, res
== MD5File::CR_MISMATCH
? "corrupt" : "missing", file
.missing_warning
);
134 fmt::format_to(output_iterator
, "\n");
137 const SoundsSet
*sounds_set
= BaseSounds::GetUsedSet();
138 if (sounds_set
->GetNumInvalid() != 0) {
139 fmt::format_to(output_iterator
, "Trying to load sound set '{}', but it is incomplete. The game will probably not run correctly until you properly install this set or select another one. See section 4.1 of README.md.\n\nThe following files are corrupted or missing:\n", sounds_set
->name
);
141 static_assert(SoundsSet::NUM_FILES
== 1);
142 /* No need to loop each file, as long as there is only a single
144 fmt::format_to(output_iterator
, "\t{} is {} ({})\n", sounds_set
->files
->filename
, SoundsSet::CheckMD5(sounds_set
->files
, BASESET_DIR
) == MD5File::CR_MISMATCH
? "corrupt" : "missing", sounds_set
->files
->missing_warning
);
147 if (!error_msg
.empty()) ShowInfoI(error_msg
);
150 /** Actually load the sprite tables. */
151 static void LoadSpriteTables()
153 const GraphicsSet
*used_set
= BaseGraphics::GetUsedSet();
155 LoadGrfFile(used_set
->files
[GFT_BASE
].filename
, 0, PAL_DOS
!= used_set
->palette
);
158 * The second basic file always starts at the given location and does
159 * contain a different amount of sprites depending on the "type"; DOS
160 * has a few sprites less. However, we do not care about those missing
161 * sprites as they are not shown anyway (logos in intro game).
163 LoadGrfFile(used_set
->files
[GFT_LOGOS
].filename
, 4793, PAL_DOS
!= used_set
->palette
);
166 * Load additional sprites for climates other than temperate.
167 * This overwrites some of the temperate sprites, such as foundations
168 * and the ground sprites.
170 if (_settings_game
.game_creation
.landscape
!= LT_TEMPERATE
) {
172 used_set
->files
[GFT_ARCTIC
+ _settings_game
.game_creation
.landscape
- 1].filename
,
173 _landscape_spriteindexes
[_settings_game
.game_creation
.landscape
- 1],
174 PAL_DOS
!= used_set
->palette
178 /* Initialize the unicode to sprite mapping table */
179 InitializeUnicodeGlyphMap();
182 * Load the base and extra NewGRF with OTTD required graphics as first NewGRF.
183 * However, we do not want it to show up in the list of used NewGRFs,
184 * so we have to manually add it, and then remove it later.
186 GRFConfig
*top
= _grfconfig
;
188 /* Default extra graphics */
189 static const char *master_filename
= "OPENTTD.GRF";
190 GRFConfig
*master
= new GRFConfig(master_filename
);
191 master
->palette
|= GRFP_GRF_DOS
;
192 FillGRFDetails(master
, false, BASESET_DIR
);
193 ClrBit(master
->flags
, GCF_INIT_ONLY
);
195 /* Baseset extra graphics */
196 GRFConfig
*extra
= new GRFConfig(used_set
->GetOrCreateExtraConfig());
197 if (extra
->num_params
== 0) extra
->SetParameterDefaults();
198 ClrBit(extra
->flags
, GCF_INIT_ONLY
);
201 master
->next
= extra
;
204 LoadNewGRF(SPR_NEWGRFS_BASE
, 2);
206 uint total_extra_graphics
= SPR_NEWGRFS_BASE
- SPR_OPENTTD_BASE
;
207 Debug(sprite
, 4, "Checking sprites from fallback grf");
208 _missing_extra_graphics
= GetSpriteCountForFile(master_filename
, SPR_OPENTTD_BASE
, SPR_NEWGRFS_BASE
);
209 Debug(sprite
, 1, "{} extra sprites, {} from baseset, {} from fallback", total_extra_graphics
, total_extra_graphics
- _missing_extra_graphics
, _missing_extra_graphics
);
211 /* The original baseset extra graphics intentionally make use of the fallback graphics.
212 * Let's say everything which provides less than 500 sprites misses the rest intentionally. */
213 if (500 + _missing_extra_graphics
> total_extra_graphics
) _missing_extra_graphics
= 0;
215 /* Free and remove the top element. */
222 static void RealChangeBlitter(const std::string_view repl_blitter
)
224 const std::string_view cur_blitter
= BlitterFactory::GetCurrentBlitter()->GetName();
225 if (cur_blitter
== repl_blitter
) return;
227 Debug(driver
, 1, "Switching blitter from '{}' to '{}'... ", cur_blitter
, repl_blitter
);
228 Blitter
*new_blitter
= BlitterFactory::SelectBlitter(repl_blitter
);
229 if (new_blitter
== nullptr) NOT_REACHED();
230 Debug(driver
, 1, "Successfully switched to {}.", repl_blitter
);
232 if (!VideoDriver::GetInstance()->AfterBlitterChange()) {
233 /* Failed to switch blitter, let's hope we can return to the old one. */
234 if (BlitterFactory::SelectBlitter(cur_blitter
) == nullptr || !VideoDriver::GetInstance()->AfterBlitterChange()) UserError("Failed to reinitialize video driver. Specify a fixed blitter in the config");
237 /* Clear caches that might have sprites for another blitter. */
238 VideoDriver::GetInstance()->ClearSystemSprites();
240 GfxClearSpriteCache();
241 ReInitAllWindows(false);
245 * Check blitter needed by NewGRF config and switch if needed.
246 * @return False when nothing changed, true otherwise.
248 static bool SwitchNewGRFBlitter()
250 /* Never switch if the blitter was specified by the user. */
251 if (!_blitter_autodetected
) return false;
253 /* Null driver => dedicated server => do nothing. */
254 if (BlitterFactory::GetCurrentBlitter()->GetScreenDepth() == 0) return false;
256 /* Get preferred depth.
257 * - depth_wanted_by_base: Depth required by the baseset, i.e. the majority of the sprites.
258 * - depth_wanted_by_grf: Depth required by some NewGRF.
259 * Both can force using a 32bpp blitter. depth_wanted_by_base is used to select
260 * between multiple 32bpp blitters, which perform differently with 8bpp sprites.
262 uint depth_wanted_by_base
= BaseGraphics::GetUsedSet()->blitter
== BLT_32BPP
? 32 : 8;
263 uint depth_wanted_by_grf
= _support8bpp
!= S8BPP_NONE
? 8 : 32;
264 for (GRFConfig
*c
= _grfconfig
; c
!= nullptr; c
= c
->next
) {
265 if (c
->status
== GCS_DISABLED
|| c
->status
== GCS_NOT_FOUND
|| HasBit(c
->flags
, GCF_INIT_ONLY
)) continue;
266 if (c
->palette
& GRFP_BLT_32BPP
) depth_wanted_by_grf
= 32;
268 /* We need a 32bpp blitter for font anti-alias. */
269 if (GetFontAAState()) depth_wanted_by_grf
= 32;
271 /* Search the best blitter. */
272 static const struct {
273 const std::string_view name
;
274 uint animation
; ///< 0: no support, 1: do support, 2: both
275 uint min_base_depth
, max_base_depth
, min_grf_depth
, max_grf_depth
;
276 } replacement_blitters
[] = {
277 { "8bpp-optimized", 2, 8, 8, 8, 8 },
278 { "40bpp-anim", 2, 8, 32, 8, 32 },
280 { "32bpp-sse4", 0, 32, 32, 8, 32 },
281 { "32bpp-ssse3", 0, 32, 32, 8, 32 },
282 { "32bpp-sse2", 0, 32, 32, 8, 32 },
283 { "32bpp-sse4-anim", 1, 32, 32, 8, 32 },
285 { "32bpp-optimized", 0, 8, 32, 8, 32 },
287 { "32bpp-sse2-anim", 1, 8, 32, 8, 32 },
289 { "32bpp-anim", 1, 8, 32, 8, 32 },
292 const bool animation_wanted
= HasBit(_display_opt
, DO_FULL_ANIMATION
);
293 const std::string_view cur_blitter
= BlitterFactory::GetCurrentBlitter()->GetName();
295 for (const auto &replacement_blitter
: replacement_blitters
) {
296 if (animation_wanted
&& (replacement_blitter
.animation
== 0)) continue;
297 if (!animation_wanted
&& (replacement_blitter
.animation
== 1)) continue;
299 if (!IsInsideMM(depth_wanted_by_base
, replacement_blitter
.min_base_depth
, replacement_blitter
.max_base_depth
+ 1)) continue;
300 if (!IsInsideMM(depth_wanted_by_grf
, replacement_blitter
.min_grf_depth
, replacement_blitter
.max_grf_depth
+ 1)) continue;
302 if (replacement_blitter
.name
== cur_blitter
) {
305 if (BlitterFactory::GetBlitterFactory(replacement_blitter
.name
) == nullptr) continue;
307 /* Inform the video driver we want to switch blitter as soon as possible. */
308 VideoDriver::GetInstance()->QueueOnMainThread(std::bind(&RealChangeBlitter
, replacement_blitter
.name
));
315 /** Check whether we still use the right blitter, or use another (better) one. */
318 if (!SwitchNewGRFBlitter()) return;
321 GfxClearSpriteCache();
322 ReInitAllWindows(false);
325 /** Initialise and load all the sprites. */
326 void GfxLoadSprites()
328 Debug(sprite
, 2, "Loading sprite set {}", _settings_game
.game_creation
.landscape
);
330 SwitchNewGRFBlitter();
331 VideoDriver::GetInstance()->ClearSystemSprites();
340 GraphicsSet::GraphicsSet()
341 : BaseSet
<GraphicsSet
, MAX_GFT
, true>{}, palette
{}, blitter
{}
343 // instantiate here, because unique_ptr needs a complete type
346 GraphicsSet::~GraphicsSet()
348 // instantiate here, because unique_ptr needs a complete type
351 bool GraphicsSet::FillSetDetails(const IniFile
&ini
, const std::string
&path
, const std::string
&full_filename
)
353 bool ret
= this->BaseSet
<GraphicsSet
, MAX_GFT
, true>::FillSetDetails(ini
, path
, full_filename
, false);
355 const IniGroup
*metadata
= ini
.GetGroup("metadata");
356 assert(metadata
!= nullptr); /* ret can't be true if metadata isn't present. */
359 fetch_metadata("palette");
360 this->palette
= ((*item
->value
)[0] == 'D' || (*item
->value
)[0] == 'd') ? PAL_DOS
: PAL_WINDOWS
;
362 /* Get optional blitter information. */
363 item
= metadata
->GetItem("blitter");
364 this->blitter
= (item
!= nullptr && (*item
->value
)[0] == '3') ? BLT_32BPP
: BLT_8BPP
;
370 * Return configuration for the extra GRF, or lazily create it.
371 * @return NewGRF configuration
373 GRFConfig
&GraphicsSet::GetOrCreateExtraConfig() const
375 if (!this->extra_cfg
) {
376 this->extra_cfg
.reset(new GRFConfig(this->files
[GFT_EXTRA
].filename
));
378 /* We know the palette of the base set, so if the base NewGRF is not
379 * setting one, use the palette of the base set and not the global
380 * one which might be the wrong palette for this base NewGRF.
381 * The value set here might be overridden via action14 later. */
382 switch (this->palette
) {
383 case PAL_DOS
: this->extra_cfg
->palette
|= GRFP_GRF_DOS
; break;
384 case PAL_WINDOWS
: this->extra_cfg
->palette
|= GRFP_GRF_WINDOWS
; break;
387 FillGRFDetails(this->extra_cfg
.get(), false, BASESET_DIR
);
389 return *this->extra_cfg
;
392 bool GraphicsSet::IsConfigurable() const
394 const GRFConfig
&cfg
= this->GetOrCreateExtraConfig();
395 /* This check is more strict than the one for NewGRF Settings.
396 * There are no legacy basesets with parameters, but without Action14 */
397 return !cfg
.param_info
.empty();
400 void GraphicsSet::CopyCompatibleConfig(const GraphicsSet
&src
)
402 const GRFConfig
*src_cfg
= src
.GetExtraConfig();
403 if (src_cfg
== nullptr || src_cfg
->num_params
== 0) return;
404 GRFConfig
&dest_cfg
= this->GetOrCreateExtraConfig();
405 if (dest_cfg
.IsCompatible(src_cfg
->version
)) return;
406 dest_cfg
.CopyParams(*src_cfg
);
410 * Calculate and check the MD5 hash of the supplied GRF.
411 * @param file The file get the hash of.
412 * @param subdir The sub directory to get the files from.
414 * - #CR_MATCH if the MD5 hash matches
415 * - #CR_MISMATCH if the MD5 does not match
416 * - #CR_NO_FILE if the file misses
418 /* static */ MD5File::ChecksumResult
GraphicsSet::CheckMD5(const MD5File
*file
, Subdirectory subdir
)
421 auto f
= FioFOpenFile(file
->filename
, "rb", subdir
, &size
);
422 if (!f
.has_value()) return MD5File::CR_NO_FILE
;
424 size_t max
= GRFGetSizeOfDataSection(*f
);
426 return file
->CheckMD5(subdir
, max
);
431 * Calculate and check the MD5 hash of the supplied filename.
432 * @param subdir The sub directory to get the files from
433 * @param max_size Only calculate the hash for this many bytes from the file start.
435 * - #CR_MATCH if the MD5 hash matches
436 * - #CR_MISMATCH if the MD5 does not match
437 * - #CR_NO_FILE if the file misses
439 MD5File::ChecksumResult
MD5File::CheckMD5(Subdirectory subdir
, size_t max_size
) const
442 auto f
= FioFOpenFile(this->filename
, "rb", subdir
, &size
);
443 if (!f
.has_value()) return CR_NO_FILE
;
445 size
= std::min(size
, max_size
);
448 uint8_t buffer
[1024];
452 while ((len
= fread(buffer
, 1, (size
> sizeof(buffer
)) ? sizeof(buffer
) : size
, *f
)) != 0 && size
!= 0) {
454 checksum
.Append(buffer
, len
);
457 checksum
.Finish(digest
);
458 return this->hash
== digest
? CR_MATCH
: CR_MISMATCH
;
461 /** Names corresponding to the GraphicsFileType */
462 static const char * const _graphics_file_names
[] = { "base", "logos", "arctic", "tropical", "toyland", "extra" };
464 /** Implementation */
465 template <class T
, size_t Tnum_files
, bool Tsearch_in_tars
>
466 /* static */ const char * const *BaseSet
<T
, Tnum_files
, Tsearch_in_tars
>::file_names
= _graphics_file_names
;
468 template <class Tbase_set
>
469 /* static */ bool BaseMedia
<Tbase_set
>::DetermineBestSet()
471 if (BaseMedia
<Tbase_set
>::used_set
!= nullptr) return true;
473 const Tbase_set
*best
= nullptr;
474 for (const Tbase_set
*c
= BaseMedia
<Tbase_set
>::available_sets
; c
!= nullptr; c
= c
->next
) {
475 /* Skip unusable sets */
476 if (c
->GetNumMissing() != 0) continue;
478 if (best
== nullptr ||
479 (best
->fallback
&& !c
->fallback
) ||
480 best
->valid_files
< c
->valid_files
||
481 (best
->valid_files
== c
->valid_files
&& (
482 (best
->shortname
== c
->shortname
&& best
->version
< c
->version
) ||
483 (best
->palette
!= PAL_DOS
&& c
->palette
== PAL_DOS
)))) {
488 BaseMedia
<Tbase_set
>::used_set
= best
;
489 return BaseMedia
<Tbase_set
>::used_set
!= nullptr;
492 template <class Tbase_set
>
493 /* static */ const char *BaseMedia
<Tbase_set
>::GetExtension()
495 return ".obg"; // OpenTTD Base Graphics
498 INSTANTIATE_BASE_MEDIA_METHODS(BaseMedia
<GraphicsSet
>, GraphicsSet
)