From f74e26ca7eb823ed1c82c578bbdbd8374e47bebf Mon Sep 17 00:00:00 2001 From: Rubidium Date: Wed, 19 Apr 2023 22:47:36 +0200 Subject: [PATCH] Codechange: replace error/usererror printf variant with fmt variant and rename --- src/CMakeLists.txt | 2 ++ src/aircraft_cmd.cpp | 3 ++- src/base_media_func.h | 3 ++- src/bootstrap_gui.cpp | 3 ++- src/core/alloc_func.cpp | 6 +++-- src/core/pool_func.hpp | 5 ++-- src/crashlog.cpp | 2 +- src/crashlog.h | 4 +-- src/driver.cpp | 11 ++++---- src/error.cpp | 21 ++++++++++++++++ src/error_func.h | 20 +++++++++++++++ src/fontcache/freetypefontcache.cpp | 3 ++- src/gfxinit.cpp | 12 ++++----- src/landscape.cpp | 3 ++- src/map.cpp | 3 ++- src/network/network_command.cpp | 3 ++- src/network/network_server.cpp | 2 +- src/newgrf.cpp | 3 ++- src/openttd.cpp | 37 +++++++++------------------ src/os/macosx/font_osx.cpp | 5 ++-- src/os/windows/font_win32.cpp | 5 ++-- src/random_access_file.cpp | 5 ++-- src/roadveh_cmd.cpp | 3 ++- src/settingsgen/CMakeLists.txt | 1 + src/settingsgen/settingsgen.cpp | 18 +++++-------- src/spritecache.cpp | 19 +++++++------- src/stdafx.h | 11 +++----- src/strgen/CMakeLists.txt | 1 + src/strgen/strgen.cpp | 39 +++++++++++++---------------- src/strgen/strgen_base.cpp | 3 ++- src/string.cpp | 3 ++- src/strings.cpp | 9 ++++--- src/train_cmd.cpp | 3 ++- src/video/allegro_v.cpp | 3 ++- src/video/cocoa/cocoa_v.mm | 5 ++-- src/video/dedicated_v.cpp | 5 ++-- src/video/sdl2_default_v.cpp | 7 +++--- src/video/sdl_v.cpp | 7 +++--- src/video/win32_v.cpp | 9 ++++--- 39 files changed, 176 insertions(+), 131 deletions(-) create mode 100644 src/error.cpp create mode 100644 src/error_func.h diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index b251378fad..6bd62e4224 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -151,6 +151,8 @@ add_files( engine_gui.h engine_type.h error.h + error.cpp + error_func.h error_gui.cpp fileio.cpp fileio_func.h diff --git a/src/aircraft_cmd.cpp b/src/aircraft_cmd.cpp index 1d2bb36f81..2b867caf7e 100644 --- a/src/aircraft_cmd.cpp +++ b/src/aircraft_cmd.cpp @@ -17,6 +17,7 @@ #include "newgrf_engine.h" #include "newgrf_sound.h" #include "spritecache.h" +#include "error_func.h" #include "strings_func.h" #include "command_func.h" #include "window_func.h" @@ -1600,7 +1601,7 @@ static void AircraftEventHandler_AtTerminal(Aircraft *v, const AirportFTAClass * static void AircraftEventHandler_General(Aircraft *v, const AirportFTAClass *apc) { - error("OK, you shouldn't be here, check your Airport Scheme!"); + FatalError("OK, you shouldn't be here, check your Airport Scheme!"); } static void AircraftEventHandler_TakeOff(Aircraft *v, const AirportFTAClass *apc) diff --git a/src/base_media_func.h b/src/base_media_func.h index b1300567d4..2dc66022b7 100644 --- a/src/base_media_func.h +++ b/src/base_media_func.h @@ -14,6 +14,7 @@ #include "debug.h" #include "ini_type.h" #include "string_func.h" +#include "error_func.h" extern void CheckExternalFiles(); @@ -346,7 +347,7 @@ template if (index == 0) return s; index--; } - error("Base" SET_TYPE "::GetSet(): index %d out of range", index); + FatalError("Base" SET_TYPE "::GetSet(): index {} out of range", index); } /** diff --git a/src/bootstrap_gui.cpp b/src/bootstrap_gui.cpp index a1ae02acf6..2a2b01a302 100644 --- a/src/bootstrap_gui.cpp +++ b/src/bootstrap_gui.cpp @@ -10,6 +10,7 @@ #include "stdafx.h" #include "base_media_base.h" #include "blitter/factory.hpp" +#include "error_func.h" #if defined(WITH_FREETYPE) || defined(WITH_UNISCRIBE) || defined(WITH_COCOA) @@ -334,6 +335,6 @@ bool HandleBootstrap() /* Failure to get enough working to get a graphics set. */ failure: - usererror("Failed to find a graphics set. Please acquire a graphics set for OpenTTD. See section 1.4 of README.md."); + UserError("Failed to find a graphics set. Please acquire a graphics set for OpenTTD. See section 1.4 of README.md."); return false; } diff --git a/src/core/alloc_func.cpp b/src/core/alloc_func.cpp index 86ba76623f..b02b1a84a4 100644 --- a/src/core/alloc_func.cpp +++ b/src/core/alloc_func.cpp @@ -9,6 +9,8 @@ #include "../stdafx.h" +#include "../error_func.h" + #include "../safeguards.h" /** @@ -17,7 +19,7 @@ */ void NORETURN MallocError(size_t size) { - error("Out of memory. Cannot allocate " PRINTF_SIZE " bytes", size); + FatalError("Out of memory. Cannot allocate {} bytes", size); } /** @@ -26,5 +28,5 @@ void NORETURN MallocError(size_t size) */ void NORETURN ReallocError(size_t size) { - error("Out of memory. Cannot reallocate " PRINTF_SIZE " bytes", size); + FatalError("Out of memory. Cannot reallocate {} bytes", size); } diff --git a/src/core/pool_func.hpp b/src/core/pool_func.hpp index ea4b7b860a..51962c35ba 100644 --- a/src/core/pool_func.hpp +++ b/src/core/pool_func.hpp @@ -13,6 +13,7 @@ #include "alloc_func.hpp" #include "mem_func.hpp" #include "pool_type.hpp" +#include "../error_func.h" #include "../saveload/saveload_error.hpp" // SlErrorCorruptFmt @@ -129,7 +130,7 @@ DEFINE_POOL_METHOD(inline void *)::AllocateItem(size_t size, size_t index) * Allocates new item * @param size size of item * @return pointer to allocated item - * @note error() on failure! (no free item) + * @note FatalError() on failure! (no free item) */ DEFINE_POOL_METHOD(void *)::GetNew(size_t size) { @@ -140,7 +141,7 @@ DEFINE_POOL_METHOD(void *)::GetNew(size_t size) this->checked--; #endif /* WITH_ASSERT */ if (index == NO_FREE_ITEM) { - error("%s: no more free items", this->name); + FatalError("{}: no more free items", this->name); } this->first_free = index + 1; diff --git a/src/crashlog.cpp b/src/crashlog.cpp index d00d9253a8..05f09d6dee 100644 --- a/src/crashlog.cpp +++ b/src/crashlog.cpp @@ -517,7 +517,7 @@ bool CrashLog::MakeCrashLog() const * Sets a message for the error message handler. * @param message The error message of the error. */ -/* static */ void CrashLog::SetErrorMessage(const char *message) +/* static */ void CrashLog::SetErrorMessage(const std::string &message) { CrashLog::message = message; } diff --git a/src/crashlog.h b/src/crashlog.h index 5f24fc80d6..90a06310e6 100644 --- a/src/crashlog.h +++ b/src/crashlog.h @@ -15,7 +15,7 @@ */ class CrashLog { private: - /** Error message coming from #error(const char *, ...). */ + /** Error message coming from #FatalError(format, ...). */ static std::string message; protected: /** @@ -114,7 +114,7 @@ public: */ static void InitThread(); - static void SetErrorMessage(const char *message); + static void SetErrorMessage(const std::string &message); static void AfterCrashLogCleanup(); }; diff --git a/src/driver.cpp b/src/driver.cpp index 417bde7072..29f1946fad 100644 --- a/src/driver.cpp +++ b/src/driver.cpp @@ -10,6 +10,7 @@ #include "stdafx.h" #include "debug.h" #include "error.h" +#include "error_func.h" #include "sound/sound_driver.hpp" #include "music/music_driver.hpp" #include "video/video_driver.hpp" @@ -86,8 +87,8 @@ void DriverFactoryBase::SelectDriver(const std::string &name, Driver::Type type) { if (!DriverFactoryBase::SelectDriverImpl(name, type)) { name.empty() ? - usererror("Failed to autoprobe %s driver", GetDriverTypeName(type)) : - usererror("Failed to select requested %s driver '%s'", GetDriverTypeName(type), name.c_str()); + UserError("Failed to autoprobe {} driver", GetDriverTypeName(type)) : + UserError("Failed to select requested {} driver '{}'", GetDriverTypeName(type), name.c_str()); } } @@ -137,7 +138,7 @@ bool DriverFactoryBase::SelectDriverImpl(const std::string &name, Driver::Type t } } } - usererror("Couldn't find any suitable %s driver", GetDriverTypeName(type)); + UserError("Couldn't find any suitable {} driver", GetDriverTypeName(type)); } else { /* Extract the driver name and put parameter list in parm */ std::istringstream buffer(name); @@ -167,7 +168,7 @@ bool DriverFactoryBase::SelectDriverImpl(const std::string &name, Driver::Type t const char *err = newd->Start(parms); if (err != nullptr) { delete newd; - usererror("Unable to load driver '%s'. The error was: %s", d->name, err); + UserError("Unable to load driver '{}'. The error was: {}", d->name, err); } Debug(driver, 1, "Successfully loaded {} driver '{}'", GetDriverTypeName(type), d->name); @@ -175,7 +176,7 @@ bool DriverFactoryBase::SelectDriverImpl(const std::string &name, Driver::Type t *GetActiveDriver(type) = newd; return true; } - usererror("No such %s driver: %s\n", GetDriverTypeName(type), dname.c_str()); + UserError("No such {} driver: {}\n", GetDriverTypeName(type), dname); } } diff --git a/src/error.cpp b/src/error.cpp new file mode 100644 index 0000000000..2d90a83e2b --- /dev/null +++ b/src/error.cpp @@ -0,0 +1,21 @@ +/* + * This file is part of OpenTTD. + * 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. + * 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. + * 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 . + */ + +/** @file error.cpp Reporting of errors. */ + +#include "stdafx.h" +#include "error_func.h" + +void NORETURN NotReachedError(int line, const char *file) +{ + FatalError("NOT_REACHED triggered at line {} of {}", line, file); +} + +void NORETURN AssertFailedError(int line, const char *file, const char *expression) +{ + FatalError("Assertion failed at line {} of {}: {}", line, file, expression); +} diff --git a/src/error_func.h b/src/error_func.h new file mode 100644 index 0000000000..a1fb7a2c33 --- /dev/null +++ b/src/error_func.h @@ -0,0 +1,20 @@ +/* + * This file is part of OpenTTD. + * 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. + * 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. + * 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 . + */ + +/** @file error_func.h Error reporting related functions. */ + +#ifndef ERROR_FUNC_H +#define ERROR_FUNC_H + +#include "3rdparty/fmt/format.h" + +void NORETURN UserErrorI(const std::string &str); +void NORETURN FatalErrorI(const std::string &str); +#define UserError(format_string, ...) UserErrorI(fmt::format(FMT_STRING(format_string), ## __VA_ARGS__)) +#define FatalError(format_string, ...) FatalErrorI(fmt::format(FMT_STRING(format_string), ## __VA_ARGS__)) + +#endif /* ERROR_FUNC_H */ diff --git a/src/fontcache/freetypefontcache.cpp b/src/fontcache/freetypefontcache.cpp index 4d6933669d..40d1ba9db5 100644 --- a/src/fontcache/freetypefontcache.cpp +++ b/src/fontcache/freetypefontcache.cpp @@ -15,6 +15,7 @@ #include "../core/math_func.hpp" #include "../zoom_func.h" #include "../fileio_func.h" +#include "../error_func.h" #include "truetypefontcache.h" #include "../table/control_codes.h" @@ -236,7 +237,7 @@ const Sprite *FreeTypeFontCache::InternalGetGlyph(GlyphID key, bool aa) uint height = std::max(1U, (uint)slot->bitmap.rows + shadow); /* Limit glyph size to prevent overflows later on. */ - if (width > MAX_GLYPH_DIM || height > MAX_GLYPH_DIM) usererror("Font glyph is too large"); + if (width > MAX_GLYPH_DIM || height > MAX_GLYPH_DIM) UserError("Font glyph is too large"); /* FreeType has rendered the glyph, now we allocate a sprite and copy the image into it */ SpriteLoader::Sprite sprite; diff --git a/src/gfxinit.cpp b/src/gfxinit.cpp index b4c1655b32..cc2f381539 100644 --- a/src/gfxinit.cpp +++ b/src/gfxinit.cpp @@ -52,19 +52,19 @@ static uint LoadGrfFile(const std::string &filename, uint load_index, bool needs Debug(sprite, 2, "Reading grf-file '{}'", filename); byte container_ver = file.GetContainerVersion(); - if (container_ver == 0) usererror("Base grf '%s' is corrupt", filename.c_str()); + if (container_ver == 0) UserError("Base grf '{}' is corrupt", filename); ReadGRFSpriteOffsets(file); if (container_ver >= 2) { /* Read compression. */ byte compression = file.ReadByte(); - if (compression != 0) usererror("Unsupported compression format"); + if (compression != 0) UserError("Unsupported compression format"); } while (LoadNextSprite(load_index, file, sprite_id)) { load_index++; sprite_id++; if (load_index >= MAX_SPRITES) { - usererror("Too many sprites. Recompile with higher MAX_SPRITES value or remove some custom GRF files."); + UserError("Too many sprites. Recompile with higher MAX_SPRITES value or remove some custom GRF files."); } } Debug(sprite, 2, "Currently {} sprites are loaded", load_index); @@ -89,12 +89,12 @@ static void LoadGrfFileIndexed(const std::string &filename, const SpriteID *inde Debug(sprite, 2, "Reading indexed grf-file '{}'", filename); byte container_ver = file.GetContainerVersion(); - if (container_ver == 0) usererror("Base grf '%s' is corrupt", filename.c_str()); + if (container_ver == 0) UserError("Base grf '{}' is corrupt", filename); ReadGRFSpriteOffsets(file); if (container_ver >= 2) { /* Read compression. */ byte compression = file.ReadByte(); - if (compression != 0) usererror("Unsupported compression format"); + if (compression != 0) UserError("Unsupported compression format"); } while ((start = *index_tbl++) != END) { @@ -248,7 +248,7 @@ static void RealChangeBlitter(const char *repl_blitter) if (!VideoDriver::GetInstance()->AfterBlitterChange()) { /* Failed to switch blitter, let's hope we can return to the old one. */ - if (BlitterFactory::SelectBlitter(cur_blitter) == nullptr || !VideoDriver::GetInstance()->AfterBlitterChange()) usererror("Failed to reinitialize video driver. Specify a fixed blitter in the config"); + if (BlitterFactory::SelectBlitter(cur_blitter) == nullptr || !VideoDriver::GetInstance()->AfterBlitterChange()) UserError("Failed to reinitialize video driver. Specify a fixed blitter in the config"); } /* Clear caches that might have sprites for another blitter. */ diff --git a/src/landscape.cpp b/src/landscape.cpp index ff3dd5bdcc..65fc4f0640 100644 --- a/src/landscape.cpp +++ b/src/landscape.cpp @@ -20,6 +20,7 @@ #include "tgp.h" #include "genworld.h" #include "fios.h" +#include "error_func.h" #include "date_func.h" #include "timer/timer_game_calendar.h" #include "timer/timer_game_tick.h" @@ -820,7 +821,7 @@ static void GenerateTerrain(int type, uint flag) /* Choose one of the templates from the graphics file. */ const Sprite *templ = GetSprite((((r >> 24) * _genterrain_tbl_1[type]) >> 8) + _genterrain_tbl_2[type] + SPR_MAPGEN_BEGIN, SpriteType::MapGen); - if (templ == nullptr) usererror("Map generator sprites could not be loaded"); + if (templ == nullptr) UserError("Map generator sprites could not be loaded"); /* Chose a random location to apply the template to. */ uint x = r & Map::MaxX(); diff --git a/src/map.cpp b/src/map.cpp index e5bbfac250..52aa621ca0 100644 --- a/src/map.cpp +++ b/src/map.cpp @@ -11,6 +11,7 @@ #include "debug.h" #include "core/alloc_func.hpp" #include "water_map.h" +#include "error_func.h" #include "string_func.h" #include "safeguards.h" @@ -44,7 +45,7 @@ extern "C" _CRTIMP void __cdecl _assert(void *, void *, unsigned); !IsInsideMM(size_y, MIN_MAP_SIZE, MAX_MAP_SIZE + 1) || (size_x & (size_x - 1)) != 0 || (size_y & (size_y - 1)) != 0) { - error("Invalid map size"); + FatalError("Invalid map size"); } Debug(map, 1, "Allocating map of size {}x{}", size_x, size_y); diff --git a/src/network/network_command.cpp b/src/network/network_command.cpp index ceb1df20da..06fee00798 100644 --- a/src/network/network_command.cpp +++ b/src/network/network_command.cpp @@ -22,6 +22,7 @@ #include "../dock_cmd.h" #include "../economy_cmd.h" #include "../engine_cmd.h" +#include "../error_func.h" #include "../goal_cmd.h" #include "../group_cmd.h" #include "../industry_cmd.h" @@ -328,7 +329,7 @@ void NetworkExecuteLocalCommandQueue() if (_frame_counter > cp->frame) { /* If we reach here, it means for whatever reason, we've already executed * past the command we need to execute. */ - error("[net] Trying to execute a packet in the past!"); + FatalError("[net] Trying to execute a packet in the past!"); } /* We can execute this command */ diff --git a/src/network/network_server.cpp b/src/network/network_server.cpp index c98ff56d1d..32b5343198 100644 --- a/src/network/network_server.cpp +++ b/src/network/network_server.cpp @@ -562,7 +562,7 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::SendMap() this->last_frame_server = _frame_counter; /* Make a dump of the current game */ - if (SaveWithFilter(this->savegame, true) != SL_OK) usererror("network savedump failed"); + if (SaveWithFilter(this->savegame, true) != SL_OK) UserError("network savedump failed"); } if (this->status == STATUS_MAP) { diff --git a/src/newgrf.cpp b/src/newgrf.cpp index 0b7ebca4be..83067fd57f 100644 --- a/src/newgrf.cpp +++ b/src/newgrf.cpp @@ -45,6 +45,7 @@ #include "smallmap_gui.h" #include "genworld.h" #include "error.h" +#include "error_func.h" #include "vehicle_func.h" #include "language.h" #include "vehicle_base.h" @@ -9624,7 +9625,7 @@ void LoadNewGRFFile(GRFConfig *config, GrfLoadingStage stage, Subdirectory subdi * processed once at initialization. */ if (stage != GLS_FILESCAN && stage != GLS_SAFETYSCAN && stage != GLS_LABELSCAN) { _cur.grffile = GetFileByFilename(filename); - if (_cur.grffile == nullptr) usererror("File '%s' lost in cache.\n", filename); + if (_cur.grffile == nullptr) UserError("File '{}' lost in cache.\n", filename); if (stage == GLS_RESERVE && config->status != GCS_INITIALISED) return; if (stage == GLS_ACTIVATION && !HasBit(config->flags, GCF_RESERVED)) return; } diff --git a/src/openttd.cpp b/src/openttd.cpp index ffd5ceca9c..606587b87f 100644 --- a/src/openttd.cpp +++ b/src/openttd.cpp @@ -17,6 +17,7 @@ #include "fontcache.h" #include "error.h" +#include "error_func.h" #include "gui.h" #include "base_media_base.h" @@ -112,19 +113,12 @@ static const Month _autosave_months[] = { /** * Error handling for fatal user errors. - * @param s the string to print. + * @param str the string to print. * @note Does NEVER return. */ -void CDECL usererror(const char *s, ...) +void UserErrorI(const std::string &str) { - va_list va; - char buf[512]; - - va_start(va, s); - vseprintf(buf, lastof(buf), s, va); - va_end(va); - - ShowOSErrorBox(buf, false); + ShowOSErrorBox(str.c_str(), false); if (VideoDriver::GetInstance() != nullptr) VideoDriver::GetInstance()->Stop(); #ifdef __EMSCRIPTEN__ @@ -141,24 +135,17 @@ void CDECL usererror(const char *s, ...) /** * Error handling for fatal non-user errors. - * @param s the string to print. + * @param str the string to print. * @note Does NEVER return. */ -void CDECL error(const char *s, ...) +void FatalErrorI(const std::string &str) { - va_list va; - char buf[2048]; - - va_start(va, s); - vseprintf(buf, lastof(buf), s, va); - va_end(va); - if (VideoDriver::GetInstance() == nullptr || VideoDriver::GetInstance()->HasGUI()) { - ShowOSErrorBox(buf, true); + ShowOSErrorBox(str.c_str(), true); } /* Set the error message for the crash log and then invoke it. */ - CrashLog::SetErrorMessage(buf); + CrashLog::SetErrorMessage(str); abort(); } @@ -742,8 +729,8 @@ int openttd_main(int argc, char *argv[]) BlitterFactory::SelectBlitter("32bpp-anim") == nullptr) { if (BlitterFactory::SelectBlitter(blitter) == nullptr) { blitter.empty() ? - usererror("Failed to autoprobe blitter") : - usererror("Failed to select requested blitter '%s'; does it exist?", blitter.c_str()); + UserError("Failed to autoprobe blitter") : + UserError("Failed to select requested blitter '{}'; does it exist?", blitter.c_str()); } } @@ -778,7 +765,7 @@ int openttd_main(int argc, char *argv[]) if (sounds_set.empty() && !BaseSounds::ini_set.empty()) sounds_set = BaseSounds::ini_set; if (!BaseSounds::SetSet(sounds_set)) { if (sounds_set.empty() || !BaseSounds::SetSet({})) { - usererror("Failed to find a sounds set. Please acquire a sounds set for OpenTTD. See section 1.4 of README.md."); + UserError("Failed to find a sounds set. Please acquire a sounds set for OpenTTD. See section 1.4 of README.md."); } else { ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_BASE_SOUNDS_NOT_FOUND); msg.SetDParamStr(0, sounds_set); @@ -790,7 +777,7 @@ int openttd_main(int argc, char *argv[]) if (music_set.empty() && !BaseMusic::ini_set.empty()) music_set = BaseMusic::ini_set; if (!BaseMusic::SetSet(music_set)) { if (music_set.empty() || !BaseMusic::SetSet({})) { - usererror("Failed to find a music set. Please acquire a music set for OpenTTD. See section 1.4 of README.md."); + UserError("Failed to find a music set. Please acquire a music set for OpenTTD. See section 1.4 of README.md."); } else { ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_BASE_MUSIC_NOT_FOUND); msg.SetDParamStr(0, music_set); diff --git a/src/os/macosx/font_osx.cpp b/src/os/macosx/font_osx.cpp index 443bd87956..7a46d8f3b1 100644 --- a/src/os/macosx/font_osx.cpp +++ b/src/os/macosx/font_osx.cpp @@ -11,6 +11,7 @@ #include "../../debug.h" #include "font_osx.h" #include "../../blitter/factory.hpp" +#include "../../error_func.h" #include "../../fileio_func.h" #include "../../fontdetection.h" #include "../../string_func.h" @@ -272,7 +273,7 @@ const Sprite *CoreTextFontCache::InternalGetGlyph(GlyphID key, bool use_aa) } else { bounds = CTFontGetBoundingRectsForGlyphs(this->font.get(), kCTFontOrientationDefault, &glyph, nullptr, 1); } - if (CGRectIsNull(bounds)) usererror("Unable to render font glyph"); + if (CGRectIsNull(bounds)) UserError("Unable to render font glyph"); uint bb_width = (uint)std::ceil(bounds.size.width) + 1; // Sometimes the glyph bounds are too tight and cut of the last pixel after rounding. uint bb_height = (uint)std::ceil(bounds.size.height); @@ -283,7 +284,7 @@ const Sprite *CoreTextFontCache::InternalGetGlyph(GlyphID key, bool use_aa) uint height = std::max(1U, bb_height + shadow); /* Limit glyph size to prevent overflows later on. */ - if (width > MAX_GLYPH_DIM || height > MAX_GLYPH_DIM) usererror("Font glyph is too large"); + if (width > MAX_GLYPH_DIM || height > MAX_GLYPH_DIM) UserError("Font glyph is too large"); SpriteLoader::Sprite sprite; sprite.AllocateData(ZOOM_LVL_NORMAL, width * height); diff --git a/src/os/windows/font_win32.cpp b/src/os/windows/font_win32.cpp index dafd5285cb..8a916db67a 100644 --- a/src/os/windows/font_win32.cpp +++ b/src/os/windows/font_win32.cpp @@ -12,6 +12,7 @@ #include "../../blitter/factory.hpp" #include "../../core/alloc_func.hpp" #include "../../core/math_func.hpp" +#include "../../error_func.h" #include "../../fileio_func.h" #include "../../fontdetection.h" #include "../../fontcache.h" @@ -439,7 +440,7 @@ void Win32FontCache::ClearFontCache() /* Call GetGlyphOutline with zero size initially to get required memory size. */ DWORD size = GetGlyphOutline(this->dc, key, GGO_GLYPH_INDEX | (aa ? GGO_GRAY8_BITMAP : GGO_BITMAP), &gm, 0, nullptr, &mat); - if (size == GDI_ERROR) usererror("Unable to render font glyph"); + if (size == GDI_ERROR) UserError("Unable to render font glyph"); /* Add 1 scaled pixel for the shadow on the medium font. Our sprite must be at least 1x1 pixel. */ uint shadow = (this->fs == FS_NORMAL) ? ScaleGUITrad(1) : 0; @@ -447,7 +448,7 @@ void Win32FontCache::ClearFontCache() uint height = std::max(1U, (uint)gm.gmBlackBoxY + shadow); /* Limit glyph size to prevent overflows later on. */ - if (width > MAX_GLYPH_DIM || height > MAX_GLYPH_DIM) usererror("Font glyph is too large"); + if (width > MAX_GLYPH_DIM || height > MAX_GLYPH_DIM) UserError("Font glyph is too large"); /* Call GetGlyphOutline again with size to actually render the glyph. */ byte *bmp = new byte[size]; diff --git a/src/random_access_file.cpp b/src/random_access_file.cpp index 5abfe7d9b4..a22903819f 100644 --- a/src/random_access_file.cpp +++ b/src/random_access_file.cpp @@ -11,6 +11,7 @@ #include "random_access_file_type.h" #include "debug.h" +#include "error_func.h" #include "fileio_func.h" #include "string_func.h" @@ -24,11 +25,11 @@ RandomAccessFile::RandomAccessFile(const std::string &filename, Subdirectory subdir) : filename(filename) { this->file_handle = FioFOpenFile(filename, "rb", subdir); - if (this->file_handle == nullptr) usererror("Cannot open file '%s'", filename.c_str()); + if (this->file_handle == nullptr) UserError("Cannot open file '{}'", filename); /* When files are in a tar-file, the begin of the file might not be at 0. */ long pos = ftell(this->file_handle); - if (pos < 0) usererror("Cannot read file '%s'", filename.c_str()); + if (pos < 0) UserError("Cannot read file '{}'", filename); /* Store the filename without path and extension */ auto t = filename.rfind(PATHSEPCHAR); diff --git a/src/roadveh_cmd.cpp b/src/roadveh_cmd.cpp index 791e768f5a..62550d847e 100644 --- a/src/roadveh_cmd.cpp +++ b/src/roadveh_cmd.cpp @@ -10,6 +10,7 @@ #include "stdafx.h" #include "roadveh.h" #include "command_func.h" +#include "error_func.h" #include "news_func.h" #include "pathfinder/npf/npf_func.h" #include "station_base.h" @@ -1205,7 +1206,7 @@ bool IndividualRoadVehicleController(RoadVehicle *v, const RoadVehicle *prev) } if (dir == INVALID_TRACKDIR) { - if (!v->IsFrontEngine()) error("Disconnecting road vehicle."); + if (!v->IsFrontEngine()) FatalError("Disconnecting road vehicle."); v->cur_speed = 0; return false; } diff --git a/src/settingsgen/CMakeLists.txt b/src/settingsgen/CMakeLists.txt index 43d5284e62..11d84453d2 100644 --- a/src/settingsgen/CMakeLists.txt +++ b/src/settingsgen/CMakeLists.txt @@ -7,6 +7,7 @@ if (NOT HOST_BINARY_DIR) settingsgen.cpp ../core/alloc_func.cpp ../misc/getoptdata.cpp + ../error.cpp ../ini_load.cpp ../string.cpp ) diff --git a/src/settingsgen/settingsgen.cpp b/src/settingsgen/settingsgen.cpp index 8dd9ff6f4a..dfd0494a41 100644 --- a/src/settingsgen/settingsgen.cpp +++ b/src/settingsgen/settingsgen.cpp @@ -13,8 +13,7 @@ #include "../misc/getoptdata.h" #include "../ini_type.h" #include "../core/smallvec_type.hpp" - -#include +#include "../error_func.h" #if !defined(_WIN32) || defined(__CYGWIN__) #include @@ -28,14 +27,9 @@ * @param s Format string. * @note Function does not return. */ -void NORETURN CDECL error(const char *s, ...) +void NORETURN FatalErrorI(const std::string &msg) { - char buf[1024]; - va_list va; - va_start(va, s); - vseprintf(buf, lastof(buf), s, va); - va_end(va); - fprintf(stderr, "FATAL: %s\n", buf); + fprintf(stderr, "FATAL: %s\n", msg.c_str()); exit(1); } @@ -181,7 +175,7 @@ struct SettingsIniFile : IniLoadFile { virtual void ReportFileError(const char * const pre, const char * const buffer, const char * const post) { - error("%s%s%s", pre, buffer, post); + FatalError("{}{}{}", pre, buffer, post); } }; @@ -385,7 +379,7 @@ static bool CompareFiles(const char *n1, const char *n2) FILE *f1 = fopen(n1, "rb"); if (f1 == nullptr) { fclose(f2); - error("can't open %s", n1); + FatalError("can't open {}", n1); } size_t l1, l2; @@ -530,7 +524,7 @@ int CDECL main(int argc, char *argv[]) #if defined(_WIN32) unlink(output_file); #endif - if (rename(tmp_output, output_file) == -1) error("rename() failed"); + if (rename(tmp_output, output_file) == -1) FatalError("rename() failed"); } } return 0; diff --git a/src/spritecache.cpp b/src/spritecache.cpp index 7159719c65..a110ce6322 100644 --- a/src/spritecache.cpp +++ b/src/spritecache.cpp @@ -12,6 +12,7 @@ #include "spriteloader/grf.hpp" #include "gfx_func.h" #include "error.h" +#include "error_func.h" #include "zoom_func.h" #include "settings_type.h" #include "blitter/factory.hpp" @@ -482,7 +483,7 @@ static void *ReadSprite(const SpriteCache *sc, SpriteID id, SpriteType sprite_ty if (sprite_avail == 0) { if (sprite_type == SpriteType::MapGen) return nullptr; - if (id == SPR_IMG_QUERY) usererror("Okay... something went horribly wrong. I couldn't load the fallback sprite. What should I do?"); + if (id == SPR_IMG_QUERY) UserError("Okay... something went horribly wrong. I couldn't load the fallback sprite. What should I do?"); return (void*)GetRawSprite(SPR_IMG_QUERY, SpriteType::Normal, allocator, encoder); } @@ -515,7 +516,7 @@ static void *ReadSprite(const SpriteCache *sc, SpriteID id, SpriteType sprite_ty } if (!ResizeSprites(sprite, sprite_avail, encoder)) { - if (id == SPR_IMG_QUERY) usererror("Okay... something went horribly wrong. I couldn't resize the fallback sprite. What should I do?"); + if (id == SPR_IMG_QUERY) UserError("Okay... something went horribly wrong. I couldn't resize the fallback sprite. What should I do?"); return (void*)GetRawSprite(SPR_IMG_QUERY, SpriteType::Normal, allocator, encoder); } @@ -656,13 +657,13 @@ bool LoadNextSprite(int load_index, SpriteFile &file, uint file_sprite_id) if (type == SpriteType::Invalid) return false; if (load_index >= MAX_SPRITES) { - usererror("Tried to load too many sprites (#%d; max %d)", load_index, MAX_SPRITES); + UserError("Tried to load too many sprites (#{}; max {})", load_index, MAX_SPRITES); } bool is_mapgen = IsMapgenSpriteID(load_index); if (is_mapgen) { - if (type != SpriteType::Normal) usererror("Uhm, would you be so kind not to load a NewGRF that changes the type of the map generator sprites?"); + if (type != SpriteType::Normal) UserError("Uhm, would you be so kind not to load a NewGRF that changes the type of the map generator sprites?"); type = SpriteType::MapGen; } @@ -836,7 +837,7 @@ static void DeleteEntryFromSpriteCache() /* Display an error message and die, in case we found no sprite at all. * This shouldn't really happen, unless all sprites are locked. */ - if (best == UINT_MAX) error("Out of sprite memory"); + if (best == UINT_MAX) FatalError("Out of sprite memory"); DeleteEntryFromSpriteCache(best); } @@ -893,7 +894,7 @@ void *SimpleSpriteAlloc(size_t size) * @param requested requested sprite type * @param sc the currently known sprite cache for the requested sprite * @return fallback sprite - * @note this function will do usererror() in the case the fallback sprite isn't available + * @note this function will do UserError() in the case the fallback sprite isn't available */ static void *HandleInvalidSpriteRequest(SpriteID sprite, SpriteType requested, SpriteCache *sc, AllocatorProc *allocator) { @@ -916,12 +917,12 @@ static void *HandleInvalidSpriteRequest(SpriteID sprite, SpriteType requested, S switch (requested) { case SpriteType::Normal: - if (sprite == SPR_IMG_QUERY) usererror("Uhm, would you be so kind not to load a NewGRF that makes the 'query' sprite a non-normal sprite?"); + if (sprite == SPR_IMG_QUERY) UserError("Uhm, would you be so kind not to load a NewGRF that makes the 'query' sprite a non-normal sprite?"); FALLTHROUGH; case SpriteType::Font: return GetRawSprite(SPR_IMG_QUERY, SpriteType::Normal, allocator); case SpriteType::Recolour: - if (sprite == PALETTE_TO_DARK_BLUE) usererror("Uhm, would you be so kind not to load a NewGRF that makes the 'PALETTE_TO_DARK_BLUE' sprite a non-remap sprite?"); + if (sprite == PALETTE_TO_DARK_BLUE) UserError("Uhm, would you be so kind not to load a NewGRF that makes the 'PALETTE_TO_DARK_BLUE' sprite a non-remap sprite?"); return GetRawSprite(PALETTE_TO_DARK_BLUE, SpriteType::Recolour, allocator); case SpriteType::MapGen: /* this shouldn't happen, overriding of SpriteType::MapGen sprites is checked in LoadNextSprite() @@ -997,7 +998,7 @@ static void GfxInitSpriteCache() delete[] reinterpret_cast(_spritecache_ptr); _spritecache_ptr = reinterpret_cast(new byte[_allocated_sprite_cache_size]); } else if (_allocated_sprite_cache_size < 2 * 1024 * 1024) { - usererror("Cannot allocate spritecache"); + UserError("Cannot allocate spritecache"); } else { /* Try again to allocate half. */ _allocated_sprite_cache_size >>= 1; diff --git a/src/stdafx.h b/src/stdafx.h index 5004978e62..f09cf88f72 100644 --- a/src/stdafx.h +++ b/src/stdafx.h @@ -304,17 +304,14 @@ # define OTTD_PRINTF64 "%I64d" # define OTTD_PRINTF64U "%I64u" # define OTTD_PRINTFHEX64 "%I64x" -# define PRINTF_SIZE "%Iu" #elif defined(__MINGW32__) # define OTTD_PRINTF64 "%I64d" # define OTTD_PRINTF64U "%I64llu" # define OTTD_PRINTFHEX64 "%I64x" -# define PRINTF_SIZE "%Iu" #else # define OTTD_PRINTF64 "%lld" # define OTTD_PRINTF64U "%llu" # define OTTD_PRINTFHEX64 "%llx" -# define PRINTF_SIZE "%zu" #endif /* @@ -477,14 +474,14 @@ static_assert(SIZE_MAX >= UINT32_MAX); /* For the FMT library we only want to use the headers, not link to some library. */ #define FMT_HEADER_ONLY -void NORETURN CDECL usererror(const char *str, ...) WARN_FORMAT(1, 2); -void NORETURN CDECL error(const char *str, ...) WARN_FORMAT(1, 2); -#define NOT_REACHED() error("NOT_REACHED triggered at line %i of %s", __LINE__, __FILE__) +void NORETURN NotReachedError(int line, const char *file); +void NORETURN AssertFailedError(int line, const char *file, const char *expression); +#define NOT_REACHED() NotReachedError(__LINE__, __FILE__) /* For non-debug builds with assertions enabled use the special assertion handler. */ #if defined(NDEBUG) && defined(WITH_ASSERT) # undef assert -# define assert(expression) if (unlikely(!(expression))) error("Assertion failed at line %i of %s: %s", __LINE__, __FILE__, #expression); +# define assert(expression) if (unlikely(!(expression))) AssertFailedError(__LINE__, __FILE__, #expression); #endif #if defined(OPENBSD) diff --git a/src/strgen/CMakeLists.txt b/src/strgen/CMakeLists.txt index 490f675f2e..a554dc2573 100644 --- a/src/strgen/CMakeLists.txt +++ b/src/strgen/CMakeLists.txt @@ -10,6 +10,7 @@ if (NOT HOST_BINARY_DIR) strgen_base.cpp ../core/alloc_func.cpp ../misc/getoptdata.cpp + ../error.cpp ../string.cpp ) add_definitions(-DSTRGEN) diff --git a/src/strgen/strgen.cpp b/src/strgen/strgen.cpp index 442364b26a..b0dad3f58e 100644 --- a/src/strgen/strgen.cpp +++ b/src/strgen/strgen.cpp @@ -9,6 +9,7 @@ #include "../stdafx.h" #include "../core/endian_func.hpp" +#include "../error_func.h" #include "../string_func.h" #include "../strings_type.h" #include "../misc/getoptdata.h" @@ -16,7 +17,6 @@ #include "strgen.h" -#include #include #if !defined(_WIN32) || defined(__CYGWIN__) @@ -64,14 +64,9 @@ void NORETURN StrgenFatalI(const std::string &msg) throw std::exception(); } -void NORETURN CDECL error(const char *s, ...) +void NORETURN FatalErrorI(const std::string &msg) { - char buf[1024]; - va_list va; - va_start(va, s); - vseprintf(buf, lastof(buf), s, va); - va_end(va); - fprintf(stderr, LINE_NUM_FMT("FATAL"), _file, _cur_line, buf); + fprintf(stderr, LINE_NUM_FMT("FATAL"), _file, _cur_line, msg.c_str()); #ifdef _MSC_VER fprintf(stderr, LINE_NUM_FMT("warning"), _file, _cur_line, "language is not compiled"); #endif @@ -93,7 +88,7 @@ struct FileStringReader : StringReader { StringReader(data, file, master, translation) { this->fh = fopen(file, "rb"); - if (this->fh == nullptr) error("Could not open %s", file); + if (this->fh == nullptr) FatalError("Could not open {}", file); } /** Free/close the file. */ @@ -114,7 +109,7 @@ struct FileStringReader : StringReader { this->StringReader::ParseFile(); if (StrEmpty(_lang.name) || StrEmpty(_lang.own_name) || StrEmpty(_lang.isocode)) { - error("Language must include ##name, ##ownname and ##isocode"); + FatalError("Language must include ##name, ##ownname and ##isocode"); } } }; @@ -135,7 +130,7 @@ void FileStringReader::HandlePragma(char *str) } else if (!memcmp(str + 8, "rtl", 3)) { _lang.text_dir = TD_RTL; } else { - error("Invalid textdir %s", str + 8); + FatalError("Invalid textdir {}", str + 8); } } else if (!memcmp(str, "digitsep ", 9)) { str += 9; @@ -150,37 +145,37 @@ void FileStringReader::HandlePragma(char *str) const char *buf = str + 10; long langid = strtol(buf, nullptr, 16); if (langid > (long)UINT16_MAX || langid < 0) { - error("Invalid winlangid %s", buf); + FatalError("Invalid winlangid {}", buf); } _lang.winlangid = (uint16)langid; } else if (!memcmp(str, "grflangid ", 10)) { const char *buf = str + 10; long langid = strtol(buf, nullptr, 16); if (langid >= 0x7F || langid < 0) { - error("Invalid grflangid %s", buf); + FatalError("Invalid grflangid {}", buf); } _lang.newgrflangid = (uint8)langid; } else if (!memcmp(str, "gender ", 7)) { - if (this->master) error("Genders are not allowed in the base translation."); + if (this->master) FatalError("Genders are not allowed in the base translation."); char *buf = str + 7; for (;;) { const char *s = ParseWord(&buf); if (s == nullptr) break; - if (_lang.num_genders >= MAX_NUM_GENDERS) error("Too many genders, max %d", MAX_NUM_GENDERS); + if (_lang.num_genders >= MAX_NUM_GENDERS) FatalError("Too many genders, max {}", MAX_NUM_GENDERS); strecpy(_lang.genders[_lang.num_genders], s, lastof(_lang.genders[_lang.num_genders])); _lang.num_genders++; } } else if (!memcmp(str, "case ", 5)) { - if (this->master) error("Cases are not allowed in the base translation."); + if (this->master) FatalError("Cases are not allowed in the base translation."); char *buf = str + 5; for (;;) { const char *s = ParseWord(&buf); if (s == nullptr) break; - if (_lang.num_cases >= MAX_NUM_CASES) error("Too many cases, max %d", MAX_NUM_CASES); + if (_lang.num_cases >= MAX_NUM_CASES) FatalError("Too many cases, max {}", MAX_NUM_CASES); strecpy(_lang.cases[_lang.num_cases], s, lastof(_lang.cases[_lang.num_cases])); _lang.num_cases++; } @@ -197,7 +192,7 @@ bool CompareFiles(const char *n1, const char *n2) FILE *f1 = fopen(n1, "rb"); if (f1 == nullptr) { fclose(f2); - error("can't open %s", n1); + FatalError("can't open {}", n1); } size_t l1, l2; @@ -234,7 +229,7 @@ struct FileWriter { this->fh = fopen(this->filename, "wb"); if (this->fh == nullptr) { - error("Could not open %s", this->filename); + FatalError("Could not open {}", this->filename); } } @@ -320,7 +315,7 @@ struct HeaderFileWriter : HeaderWriter, FileWriter { # if defined(_WIN32) unlink(this->real_filename); # endif - if (rename(this->filename, this->real_filename) == -1) error("rename() failed"); + if (rename(this->filename, this->real_filename) == -1) FatalError("rename() failed"); } } }; @@ -343,7 +338,7 @@ struct LanguageFileWriter : LanguageWriter, FileWriter { void Finalise() { if (fputc(0, this->fh) == EOF) { - error("Could not write to %s", this->filename); + FatalError("Could not write to {}", this->filename); } this->FileWriter::Finalise(); } @@ -351,7 +346,7 @@ struct LanguageFileWriter : LanguageWriter, FileWriter { void Write(const byte *buffer, size_t length) { if (fwrite(buffer, sizeof(*buffer), length, this->fh) != length) { - error("Could not write to %s", this->filename); + FatalError("Could not write to {}", this->filename); } } }; diff --git a/src/strgen/strgen_base.cpp b/src/strgen/strgen_base.cpp index fb896f3fb1..6c8ddccc1c 100644 --- a/src/strgen/strgen_base.cpp +++ b/src/strgen/strgen_base.cpp @@ -10,6 +10,7 @@ #include "../stdafx.h" #include "../core/alloc_func.hpp" #include "../core/endian_func.hpp" +#include "../error_func.h" #include "../string_func.h" #include "../table/control_codes.h" @@ -556,7 +557,7 @@ static const CmdStruct *ParseCommandString(const char **str, char *param, int *a StrgenError("Missing }} from command '{}'", start); return nullptr; } - if (s - start == MAX_COMMAND_PARAM_SIZE) error("param command too long"); + if (s - start == MAX_COMMAND_PARAM_SIZE) FatalError("param command too long"); *param++ = c; } } diff --git a/src/string.cpp b/src/string.cpp index 0886f2805a..6ce46ba29b 100644 --- a/src/string.cpp +++ b/src/string.cpp @@ -11,6 +11,7 @@ #include "debug.h" #include "core/alloc_func.hpp" #include "core/math_func.hpp" +#include "error_func.h" #include "string_func.h" #include "string_base.h" @@ -120,7 +121,7 @@ char *strecpy(char *dst, const char *src, const char *last) if (dst == last && *src != '\0') { #if defined(STRGEN) || defined(SETTINGSGEN) - error("String too long for destination buffer"); + FatalError("String too long for destination buffer"); #else /* STRGEN || SETTINGSGEN */ Debug(misc, 0, "String too long for destination buffer"); #endif /* STRGEN || SETTINGSGEN */ diff --git a/src/strings.cpp b/src/strings.cpp index aef1a6ef02..0b631cbd96 100644 --- a/src/strings.cpp +++ b/src/strings.cpp @@ -19,6 +19,7 @@ #include "signs_base.h" #include "fontdetection.h" #include "error.h" +#include "error_func.h" #include "strings_func.h" #include "rev.h" #include "core/endian_func.hpp" @@ -243,7 +244,7 @@ char *GetStringWithArgs(char *buffr, StringID string, StringParameters *args, co case TEXT_TAB_OLD_CUSTOM: /* Old table for custom names. This is no longer used */ if (!game_script) { - error("Incorrect conversion of custom name string."); + FatalError("Incorrect conversion of custom name string."); } break; @@ -264,7 +265,7 @@ char *GetStringWithArgs(char *buffr, StringID string, StringParameters *args, co if (game_script) { return GetStringWithArgs(buffr, STR_UNDEFINED, args, last); } - error("String 0x%X is invalid. You are probably using an old version of the .lng file.\n", string); + FatalError("String 0x{:X} is invalid. You are probably using an old version of the .lng file.\n", string); } return FormatString(buffr, GetStringPtr(string), args, last, case_index); @@ -2041,7 +2042,7 @@ void InitializeLanguagePacks() std::string path = FioGetDirectory(sp, LANG_DIR); GetLanguageList(path.c_str()); } - if (_languages.size() == 0) usererror("No available language packs (invalid versions?)"); + if (_languages.size() == 0) UserError("No available language packs (invalid versions?)"); /* Acquire the locale of the current system */ const char *lang = GetCurrentLocale("LC_MESSAGES"); @@ -2077,7 +2078,7 @@ void InitializeLanguagePacks() chosen_language = (language_fallback != nullptr) ? language_fallback : en_GB_fallback; } - if (!ReadLanguagePack(chosen_language)) usererror("Can't read language pack '%s'", chosen_language->file); + if (!ReadLanguagePack(chosen_language)) UserError("Can't read language pack '{}'", chosen_language->file); } /** diff --git a/src/train_cmd.cpp b/src/train_cmd.cpp index 21f33b3a5c..900f2fa9b6 100644 --- a/src/train_cmd.cpp +++ b/src/train_cmd.cpp @@ -11,6 +11,7 @@ #include "error.h" #include "articulated_vehicles.h" #include "command_func.h" +#include "error_func.h" #include "pathfinder/npf/npf_func.h" #include "pathfinder/yapf/yapf.hpp" #include "news_func.h" @@ -3513,7 +3514,7 @@ bool TrainController(Train *v, Vehicle *nomove, bool reverse) invalid_rail: /* We've reached end of line?? */ - if (prev != nullptr) error("Disconnecting train"); + if (prev != nullptr) FatalError("Disconnecting train"); reverse_train_direction: if (reverse) { diff --git a/src/video/allegro_v.cpp b/src/video/allegro_v.cpp index 84c55492fb..21386f3405 100644 --- a/src/video/allegro_v.cpp +++ b/src/video/allegro_v.cpp @@ -16,6 +16,7 @@ #include "../stdafx.h" #include "../openttd.h" +#include "../error_func.h" #include "../gfx_func.h" #include "../rev.h" #include "../blitter/factory.hpp" @@ -186,7 +187,7 @@ static void GetAvailableVideoMode(uint *w, uint *h) static bool CreateMainSurface(uint w, uint h) { int bpp = BlitterFactory::GetCurrentBlitter()->GetScreenDepth(); - if (bpp == 0) usererror("Can't use a blitter that blits 0 bpp for normal visuals"); + if (bpp == 0) UserError("Can't use a blitter that blits 0 bpp for normal visuals"); set_color_depth(bpp); GetAvailableVideoMode(&w, &h); diff --git a/src/video/cocoa/cocoa_v.mm b/src/video/cocoa/cocoa_v.mm index ca8df18311..54602e12aa 100644 --- a/src/video/cocoa/cocoa_v.mm +++ b/src/video/cocoa/cocoa_v.mm @@ -27,6 +27,7 @@ #include "../../openttd.h" #include "../../debug.h" +#include "../../error_func.h" #include "../../core/geometry_func.hpp" #include "../../core/math_func.hpp" #include "cocoa_v.h" @@ -447,7 +448,7 @@ bool VideoDriver_Cocoa::MakeWindow(int width, int height) CGColorSpaceRelease(this->color_space); this->color_space = CGColorSpaceCreateWithName(kCGColorSpaceSRGB); if (this->color_space == nullptr) this->color_space = CGColorSpaceCreateDeviceRGB(); - if (this->color_space == nullptr) error("Could not get a valid colour space for drawing."); + if (this->color_space == nullptr) FatalError("Could not get a valid colour space for drawing."); this->setup = false; @@ -679,7 +680,7 @@ void VideoDriver_CocoaQuartz::AllocateBackingStore(bool force) if (this->buffer_depth == 8) { free(this->pixel_buffer); this->pixel_buffer = malloc(this->window_width * this->window_height); - if (this->pixel_buffer == nullptr) usererror("Out of memory allocating pixel buffer"); + if (this->pixel_buffer == nullptr) UserError("Out of memory allocating pixel buffer"); } else { free(this->pixel_buffer); this->pixel_buffer = nullptr; diff --git a/src/video/dedicated_v.cpp b/src/video/dedicated_v.cpp index 99dc5ee691..bfd15425f8 100644 --- a/src/video/dedicated_v.cpp +++ b/src/video/dedicated_v.cpp @@ -10,6 +10,7 @@ #include "../stdafx.h" #include "../gfx_func.h" +#include "../error_func.h" #include "../network/network.h" #include "../network/network_internal.h" #include "../console_func.h" @@ -103,10 +104,10 @@ static void CreateWindowsConsoleThread() /* Create event to signal when console input is ready */ _hInputReady = CreateEvent(nullptr, false, false, nullptr); _hWaitForInputHandling = CreateEvent(nullptr, false, false, nullptr); - if (_hInputReady == nullptr || _hWaitForInputHandling == nullptr) usererror("Cannot create console event!"); + if (_hInputReady == nullptr || _hWaitForInputHandling == nullptr) UserError("Cannot create console event!"); _hThread = CreateThread(nullptr, 0, (LPTHREAD_START_ROUTINE)CheckForConsoleInput, nullptr, 0, &dwThreadId); - if (_hThread == nullptr) usererror("Cannot create console thread!"); + if (_hThread == nullptr) UserError("Cannot create console thread!"); Debug(driver, 2, "Windows console thread started"); } diff --git a/src/video/sdl2_default_v.cpp b/src/video/sdl2_default_v.cpp index e164e499e8..221b0f2776 100644 --- a/src/video/sdl2_default_v.cpp +++ b/src/video/sdl2_default_v.cpp @@ -9,6 +9,7 @@ #include "../stdafx.h" #include "../openttd.h" +#include "../error_func.h" #include "../gfx_func.h" #include "../rev.h" #include "../blitter/factory.hpp" @@ -59,7 +60,7 @@ void VideoDriver_SDL_Default::MakePalette() { if (_sdl_palette == nullptr) { _sdl_palette = SDL_AllocPalette(256); - if (_sdl_palette == nullptr) usererror("SDL2: Couldn't allocate palette: %s", SDL_GetError()); + if (_sdl_palette == nullptr) UserError("SDL2: Couldn't allocate palette: {}", SDL_GetError()); } CopyPalette(this->local_palette, true); @@ -133,7 +134,7 @@ bool VideoDriver_SDL_Default::AllocateBackingStore(int w, int h, bool force) int bpp = BlitterFactory::GetCurrentBlitter()->GetScreenDepth(); _sdl_real_surface = SDL_GetWindowSurface(this->sdl_window); - if (_sdl_real_surface == nullptr) usererror("SDL2: Couldn't get window surface: %s", SDL_GetError()); + if (_sdl_real_surface == nullptr) UserError("SDL2: Couldn't get window surface: {}", SDL_GetError()); if (!force && w == _sdl_real_surface->w && h == _sdl_real_surface->h) return false; @@ -145,7 +146,7 @@ bool VideoDriver_SDL_Default::AllocateBackingStore(int w, int h, bool force) if (bpp == 8) { _sdl_rgb_surface = SDL_CreateRGBSurface(0, w, h, 8, 0, 0, 0, 0); - if (_sdl_rgb_surface == nullptr) usererror("SDL2: Couldn't allocate shadow surface: %s", SDL_GetError()); + if (_sdl_rgb_surface == nullptr) UserError("SDL2: Couldn't allocate shadow surface: {}", SDL_GetError()); _sdl_surface = _sdl_rgb_surface; } else { diff --git a/src/video/sdl_v.cpp b/src/video/sdl_v.cpp index 667b738145..dde67c909b 100644 --- a/src/video/sdl_v.cpp +++ b/src/video/sdl_v.cpp @@ -11,6 +11,7 @@ #include "../stdafx.h" #include "../openttd.h" +#include "../error_func.h" #include "../gfx_func.h" #include "../rev.h" #include "../blitter/factory.hpp" @@ -176,7 +177,7 @@ static const Dimension _default_resolutions[] = { static void GetVideoModes() { SDL_Rect **modes = SDL_ListModes(nullptr, SDL_SWSURFACE | SDL_FULLSCREEN); - if (modes == nullptr) usererror("sdl: no modes available"); + if (modes == nullptr) UserError("sdl: no modes available"); _resolutions.clear(); @@ -195,7 +196,7 @@ static void GetVideoModes() if (std::find(_resolutions.begin(), _resolutions.end(), Dimension(w, h)) != _resolutions.end()) continue; _resolutions.emplace_back(w, h); } - if (_resolutions.empty()) usererror("No usable screen resolutions found!\n"); + if (_resolutions.empty()) UserError("No usable screen resolutions found!\n"); SortResolutions(); } } @@ -233,7 +234,7 @@ bool VideoDriver_SDL::CreateMainSurface(uint w, uint h) Debug(driver, 1, "SDL: using mode {}x{}x{}", w, h, bpp); - if (bpp == 0) usererror("Can't use a blitter that blits 0 bpp for normal visuals"); + if (bpp == 0) UserError("Can't use a blitter that blits 0 bpp for normal visuals"); std::string icon_path = FioFindFullPath(BASESET_DIR, "openttd.32.bmp"); if (!icon_path.empty()) { diff --git a/src/video/win32_v.cpp b/src/video/win32_v.cpp index 75bbdb2a74..b1c8cafae5 100644 --- a/src/video/win32_v.cpp +++ b/src/video/win32_v.cpp @@ -9,6 +9,7 @@ #include "../stdafx.h" #include "../openttd.h" +#include "../error_func.h" #include "../gfx_func.h" #include "../os/windows/win32.h" #include "../rev.h" @@ -219,7 +220,7 @@ bool VideoDriver_Win32Base::MakeWindow(bool full_screen, bool resize) seprintf(window_title, lastof(window_title), "OpenTTD %s", _openttd_revision); this->main_wnd = CreateWindow(L"OTTD", OTTD2FS(window_title).c_str(), style, x, y, w, h, 0, 0, GetModuleHandle(nullptr), this); - if (this->main_wnd == nullptr) usererror("CreateWindow failed"); + if (this->main_wnd == nullptr) UserError("CreateWindow failed"); ShowWindow(this->main_wnd, showstyle); } } @@ -768,7 +769,7 @@ static void RegisterWndClass() }; registered = true; - if (!RegisterClass(&wnd)) usererror("RegisterClass failed"); + if (!RegisterClass(&wnd)) UserError("RegisterClass failed"); } static const Dimension default_resolutions[] = { @@ -1072,7 +1073,7 @@ bool VideoDriver_Win32GDI::AllocateBackingStore(int w, int h, bool force) this->dib_sect = CreateDIBSection(dc, bi, DIB_RGB_COLORS, (VOID **)&this->buffer_bits, nullptr, 0); if (this->dib_sect == nullptr) { delete[] bi; - usererror("CreateDIBSection failed"); + UserError("CreateDIBSection failed"); } ReleaseDC(0, dc); @@ -1109,7 +1110,7 @@ void VideoDriver_Win32GDI::MakePalette() } this->gdi_palette = CreatePalette(pal); delete[] pal; - if (this->gdi_palette == nullptr) usererror("CreatePalette failed!\n"); + if (this->gdi_palette == nullptr) UserError("CreatePalette failed!\n"); } void VideoDriver_Win32GDI::UpdatePalette(HDC dc, uint start, uint count)