Merge branch 'master' into jgrpp

# Conflicts:
#	src/cheat_gui.cpp
#	src/industry_gui.cpp
#	src/linkgraph/linkgraphschedule.cpp
#	src/misc/getoptdata.h
#	src/music/dmusic.cpp
#	src/network/core/os_abstraction.cpp
#	src/newgrf_engine.cpp
#	src/openttd.cpp
#	src/order_gui.cpp
#	src/os/windows/win32.cpp
#	src/pathfinder/npf/queue.cpp
#	src/smallmap_gui.cpp
#	src/strgen/strgen.cpp
This commit is contained in:
Jonathan G Rennison
2024-06-08 22:55:56 +01:00
31 changed files with 202 additions and 278 deletions

View File

@@ -336,39 +336,38 @@ struct CheatWindow : Window {
uint width = 0; uint width = 0;
uint lines = 0; uint lines = 0;
for (int i = 0; i != lengthof(_cheats_ui); i++) { for (const CheatEntry &ce : _cheats_ui) {
const CheatEntry *ce = &_cheats_ui[i]; if (!IsCheatAllowed(ce.mode)) continue;
if (!IsCheatAllowed(ce->mode)) continue;
lines++; lines++;
switch (ce->type) { switch (ce.type) {
case SLF_ALLOW_CONTROL: case SLF_ALLOW_CONTROL:
/* Change inflation factors */ /* Change inflation factors */
break; break;
case SLE_BOOL: case SLE_BOOL:
SetDParam(0, STR_CONFIG_SETTING_ON); SetDParam(0, STR_CONFIG_SETTING_ON);
width = std::max(width, GetStringBoundingBox(ce->str).width); width = std::max(width, GetStringBoundingBox(ce.str).width);
SetDParam(0, STR_CONFIG_SETTING_OFF); SetDParam(0, STR_CONFIG_SETTING_OFF);
width = std::max(width, GetStringBoundingBox(ce->str).width); width = std::max(width, GetStringBoundingBox(ce.str).width);
break; break;
default: default:
switch (ce->str) { switch (ce.str) {
/* Display date for change date cheat */ /* Display date for change date cheat */
case STR_CHEAT_CHANGE_DATE: case STR_CHEAT_CHANGE_DATE:
SetDParam(0, CalTime::ConvertYMDToDate(CalTime::MAX_YEAR, 11, 31)); SetDParam(0, CalTime::ConvertYMDToDate(CalTime::MAX_YEAR, 11, 31));
width = std::max(width, GetStringBoundingBox(ce->str).width); width = std::max(width, GetStringBoundingBox(ce.str).width);
break; break;
/* Draw coloured flag for change company cheat */ /* Draw coloured flag for change company cheat */
case STR_CHEAT_CHANGE_COMPANY: case STR_CHEAT_CHANGE_COMPANY:
SetDParamMaxValue(0, MAX_COMPANIES); SetDParamMaxValue(0, MAX_COMPANIES);
width = std::max(width, GetStringBoundingBox(ce->str).width + WidgetDimensions::scaled.hsep_wide * 4); width = std::max(width, GetStringBoundingBox(ce.str).width + WidgetDimensions::scaled.hsep_wide * 4);
break; break;
default: default:
SetDParam(0, INT64_MAX); SetDParam(0, INT64_MAX);
width = std::max(width, GetStringBoundingBox(ce->str).width); width = std::max(width, GetStringBoundingBox(ce.str).width);
break; break;
} }
break; break;

View File

@@ -2379,8 +2379,8 @@ struct CompanyWindow : Window
case WID_C_DESC_VEHICLE_COUNTS: case WID_C_DESC_VEHICLE_COUNTS:
SetDParamMaxValue(0, 5000); // Maximum number of vehicles SetDParamMaxValue(0, 5000); // Maximum number of vehicles
for (uint i = 0; i < lengthof(_company_view_vehicle_count_strings); i++) { for (const auto &count_string : _company_view_vehicle_count_strings) {
size.width = std::max(size.width, GetStringBoundingBox(_company_view_vehicle_count_strings[i]).width + padding.width); size.width = std::max(size.width, GetStringBoundingBox(count_string).width + padding.width);
} }
break; break;

View File

@@ -202,7 +202,7 @@ static FILE *FioFOpenFileSp(const std::string &filename, const char *mode, Searc
* a string, but a variable, it 'renames' the variable, * a string, but a variable, it 'renames' the variable,
* so make that variable to makes it compile happily */ * so make that variable to makes it compile happily */
wchar_t Lmode[5]; wchar_t Lmode[5];
MultiByteToWideChar(CP_ACP, 0, mode, -1, Lmode, lengthof(Lmode)); MultiByteToWideChar(CP_ACP, 0, mode, -1, Lmode, static_cast<int>(std::size(Lmode)));
#endif #endif
FILE *f = nullptr; FILE *f = nullptr;
std::string buf; std::string buf;

View File

@@ -84,16 +84,16 @@ void SpriteFontCache::InitializeUnicodeGlyphMap()
this->SetUnicodeGlyph(i + SCC_SPRITE_START, sprite); this->SetUnicodeGlyph(i + SCC_SPRITE_START, sprite);
} }
for (uint i = 0; i < lengthof(_default_unicode_map); i++) { for (const auto &unicode_map : _default_unicode_map) {
uint8_t key = _default_unicode_map[i].key; uint8_t key = unicode_map.key;
if (key == CLRA) { if (key == CLRA) {
/* Clear the glyph. This happens if the glyph at this code point /* Clear the glyph. This happens if the glyph at this code point
* is non-standard and should be accessed by an SCC_xxx enum * is non-standard and should be accessed by an SCC_xxx enum
* entry only. */ * entry only. */
this->SetUnicodeGlyph(_default_unicode_map[i].code, 0); this->SetUnicodeGlyph(unicode_map.code, 0);
} else { } else {
SpriteID sprite = base + key - ASCII_LETTERSTART; SpriteID sprite = base + key - ASCII_LETTERSTART;
this->SetUnicodeGlyph(_default_unicode_map[i].code, sprite); this->SetUnicodeGlyph(unicode_map.code, sprite);
} }
} }
font_height_cache[this->fs] = this->GetHeight(); font_height_cache[this->fs] = this->GetHeight();

View File

@@ -291,8 +291,8 @@ private:
this->column_size[VGC_PROFIT].width = 0; this->column_size[VGC_PROFIT].width = 0;
this->column_size[VGC_PROFIT].height = 0; this->column_size[VGC_PROFIT].height = 0;
static const SpriteID profit_sprites[] = {SPR_PROFIT_NA, SPR_PROFIT_NEGATIVE, SPR_PROFIT_SOME, SPR_PROFIT_LOT}; static const SpriteID profit_sprites[] = {SPR_PROFIT_NA, SPR_PROFIT_NEGATIVE, SPR_PROFIT_SOME, SPR_PROFIT_LOT};
for (uint i = 0; i < lengthof(profit_sprites); i++) { for (const auto &profit_sprite : profit_sprites) {
Dimension d = GetSpriteSize(profit_sprites[i]); Dimension d = GetSpriteSize(profit_sprite);
this->column_size[VGC_PROFIT] = maxdim(this->column_size[VGC_PROFIT], d); this->column_size[VGC_PROFIT] = maxdim(this->column_size[VGC_PROFIT], d);
} }
this->tiny_step_height = std::max(this->tiny_step_height, this->column_size[VGC_PROFIT].height); this->tiny_step_height = std::max(this->tiny_step_height, this->column_size[VGC_PROFIT].height);

View File

@@ -830,13 +830,7 @@ static void UpdateIndustryProduction(Industry *i);
static inline bool IsProductionAlterable(const Industry *i) static inline bool IsProductionAlterable(const Industry *i)
{ {
const IndustrySpec *is = GetIndustrySpec(i->type); const IndustrySpec *is = GetIndustrySpec(i->type);
bool has_prod = false; bool has_prod = std::any_of(std::begin(is->production_rate), std::end(is->production_rate), [](auto rate) { return rate != 0; });
for (size_t j = 0; j < std::size(is->production_rate); j++) {
if (is->production_rate[j] != 0) {
has_prod = true;
break;
}
}
return ((_game_mode == GM_EDITOR || _cheats.setup_prod.value) && return ((_game_mode == GM_EDITOR || _cheats.setup_prod.value) &&
(has_prod || is->IsRawIndustry()) && (has_prod || is->IsRawIndustry()) &&
!_networking); !_networking);

View File

@@ -188,7 +188,7 @@ STR_COLOUR_ORANGE :Laranja
STR_COLOUR_BROWN :Marrom STR_COLOUR_BROWN :Marrom
STR_COLOUR_GREY :Cinza STR_COLOUR_GREY :Cinza
STR_COLOUR_WHITE :Branco STR_COLOUR_WHITE :Branco
STR_COLOUR_RANDOM :Aleatório STR_COLOUR_RANDOM :Aleatória
###length 17 ###length 17
STR_COLOUR_SECONDARY_DARK_BLUE :Azul Escuro STR_COLOUR_SECONDARY_DARK_BLUE :Azul Escuro

View File

@@ -3921,7 +3921,7 @@ STR_NEWGRF_ERROR_MULTIPLE_ACTION_8 :Zawiera wiele w
STR_NEWGRF_ERROR_READ_BOUNDS :Odczyt poza obszar pseudo-sprite'u (sprite {3:NUM}) STR_NEWGRF_ERROR_READ_BOUNDS :Odczyt poza obszar pseudo-sprite'u (sprite {3:NUM})
STR_NEWGRF_ERROR_GRM_FAILED :Potrzebne źródło GRF nie jest dostępne (sprite {3:NUM}) STR_NEWGRF_ERROR_GRM_FAILED :Potrzebne źródło GRF nie jest dostępne (sprite {3:NUM})
STR_NEWGRF_ERROR_FORCEFULLY_DISABLED :{1:STRING} został wyłączony przez {STRING} STR_NEWGRF_ERROR_FORCEFULLY_DISABLED :{1:STRING} został wyłączony przez {STRING}
STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT :Niepoprawny/nieznany format układu sprite'u (sprite {3:NUM}) STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT :Nieprawidłowy/nieznany format układu sprite'a (sprite {3:NUM})
STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG :Zbyt wiele elementów na liście wartości właściwości (sprite {3:NUM}, właściwość {4:HEX}) STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG :Zbyt wiele elementów na liście wartości właściwości (sprite {3:NUM}, właściwość {4:HEX})
STR_NEWGRF_ERROR_INDPROD_CALLBACK :Nieprawidłowe wywołanie zwrotne produkcji przedsiębiorstwa (sprite {3:NUM}, „{2:STRING}”) STR_NEWGRF_ERROR_INDPROD_CALLBACK :Nieprawidłowe wywołanie zwrotne produkcji przedsiębiorstwa (sprite {3:NUM}, „{2:STRING}”)

View File

@@ -152,9 +152,9 @@ void LinkGraphSchedule::JoinNext()
*/ */
/* static */ void LinkGraphSchedule::Run(LinkGraphJob *job) /* static */ void LinkGraphSchedule::Run(LinkGraphJob *job)
{ {
for (uint i = 0; i < lengthof(instance.handlers); ++i) { for (const auto &handler : instance.handlers) {
if (job->IsJobAborted()) return; if (job->IsJobAborted()) return;
instance.handlers[i]->Run(*job); handler->Run(*job);
} }
/* /*

View File

@@ -21,23 +21,20 @@
*/ */
int GetOptData::GetOpt() int GetOptData::GetOpt()
{ {
const OptionData *odata; const char *s = this->cont;
char *s = this->cont;
if (s == nullptr) { if (s == nullptr) {
if (this->numleft == 0) return -1; // No arguments left -> finished. if (this->arguments.empty()) return -1; // No arguments left -> finished.
s = this->argv[0]; s = this->arguments[0];
if (*s != '-') return -1; // No leading '-' -> not an option -> finished. if (*s != '-') return -1; // No leading '-' -> not an option -> finished.
this->argv++; this->arguments = this->arguments.subspan(1);
this->numleft--;
/* Is it a long option? */ /* Is it a long option? */
for (odata = this->options; odata->flags != ODF_END; odata++) { for (auto &option : this->options) {
if (odata->longname != nullptr && !strcmp(odata->longname, s)) { // Long options always use the entire argument. if (option.longname != nullptr && !strcmp(option.longname, s)) { // Long options always use the entire argument.
this->cont = nullptr; this->cont = nullptr;
goto set_optval; return this->GetOpt(option);
} }
} }
@@ -45,39 +42,41 @@ int GetOptData::GetOpt()
} }
/* Is it a short option? */ /* Is it a short option? */
for (odata = this->options; odata->flags != ODF_END; odata++) { for (auto &option : this->options) {
if (odata->shortname != '\0' && *s == odata->shortname) { if (option.shortname != '\0' && *s == option.shortname) {
this->cont = (s[1] != '\0') ? s + 1 : nullptr; this->cont = (s[1] != '\0') ? s + 1 : nullptr;
return this->GetOpt(option);
set_optval: // Handle option value of *odata .
this->opt = nullptr;
switch (odata->flags) {
case ODF_NO_VALUE:
return odata->id;
case ODF_HAS_VALUE:
case ODF_OPTIONAL_VALUE:
if (this->cont != nullptr) { // Remainder of the argument is the option value.
this->opt = this->cont;
this->cont = nullptr;
return odata->id;
}
/* No more arguments, either return an error or a value-less option. */
if (this->numleft == 0) return (odata->flags == ODF_HAS_VALUE) ? -2 : odata->id;
/* Next argument looks like another option, let's not return it as option value. */
if (odata->flags == ODF_OPTIONAL_VALUE && this->argv[0][0] == '-') return odata->id;
this->opt = this->argv[0]; // Next argument is the option value.
this->argv++;
this->numleft--;
return odata->id;
default: NOT_REACHED();
}
} }
} }
return -2; // No other ways to interpret the text -> error. return -2; // No other ways to interpret the text -> error.
} }
int GetOptData::GetOpt(const OptionData &option)
{
this->opt = nullptr;
switch (option.type) {
case ODF_NO_VALUE:
return option.id;
case ODF_HAS_VALUE:
case ODF_OPTIONAL_VALUE:
if (this->cont != nullptr) { // Remainder of the argument is the option value.
this->opt = this->cont;
this->cont = nullptr;
return option.id;
}
/* No more arguments, either return an error or a value-less option. */
if (this->arguments.empty()) return (option.type == ODF_HAS_VALUE) ? -2 : option.id;
/* Next argument looks like another option, let's not return it as option value. */
if (option.type == ODF_OPTIONAL_VALUE && this->arguments[0][0] == '-') return option.id;
this->opt = this->arguments[0]; // Next argument is the option value.
this->arguments = this->arguments.subspan(1);
return option.id;
default: NOT_REACHED();
}
}

View File

@@ -11,100 +11,39 @@
#define GETOPTDATA_H #define GETOPTDATA_H
/** Flags of an option. */ /** Flags of an option. */
enum OptionDataFlags { enum OptionDataType : uint8_t {
ODF_NO_VALUE, ///< A plain option (no value attached to it). ODF_NO_VALUE, ///< A plain option (no value attached to it).
ODF_HAS_VALUE, ///< An option with a value. ODF_HAS_VALUE, ///< An option with a value.
ODF_OPTIONAL_VALUE, ///< An option with an optional value. ODF_OPTIONAL_VALUE, ///< An option with an optional value.
ODF_END, ///< Terminator (data is not parsed further).
}; };
/** Data of an option. */ /** Data of an option. */
struct OptionData { struct OptionData {
uint8_t id; ///< Unique identification of this option data, often the same as #shortname. OptionDataType type; ///< The type of option.
char shortname; ///< Short option letter if available, else use \c '\0'. char id; ///< Unique identification of this option data, often the same as #shortname.
uint16_t flags; ///< Option data flags. @see OptionDataFlags char shortname = '\0'; ///< Short option letter if available, else use \c '\0'.
const char *longname; ///< Long option name including '-'/'--' prefix, use \c nullptr if not available. const char *longname = nullptr; ///< Long option name including '-'/'--' prefix, use \c nullptr if not available.
}; };
/** Data storage for parsing command line options. */ /** Data storage for parsing command line options. */
struct GetOptData { struct GetOptData {
char *opt; ///< Option value, if available (else \c nullptr). using OptionSpan = std::span<const OptionData>;
int numleft; ///< Number of arguments left in #argv. using ArgumentSpan = std::span<char * const>;
char **argv; ///< Remaining command line arguments.
const OptionData *options; ///< Command line option descriptions. ArgumentSpan arguments; ///< Remaining command line arguments.
char *cont; ///< Next call to #GetOpt should start here (in the middle of an argument). const OptionSpan options; ///< Command line option descriptions.
const char *opt = nullptr; ///< Option value, if available (else \c nullptr).
const char *cont = nullptr; ///< Next call to #GetOpt should start here (in the middle of an argument).
/** /**
* Constructor of the data store. * Constructor of the data store.
* @param argc Number of command line arguments, excluding the program name. * @param argument The command line arguments, excluding the program name.
* @param argv Command line arguments, excluding the program name.
* @param options Command line option descriptions. * @param options Command line option descriptions.
*/ */
GetOptData(int argc, char **argv, const OptionData *options) : GetOptData(ArgumentSpan arguments, OptionSpan options) : arguments(arguments), options(options) {}
opt(nullptr),
numleft(argc),
argv(argv),
options(options),
cont(nullptr)
{
}
int GetOpt(); int GetOpt();
int GetOpt(const OptionData &option);
}; };
/**
* General macro for creating an option.
* @param id Identification of the option.
* @param shortname Short option name. Use \c '\0' if not used.
* @param longname Long option name including leading '-' or '--'. Use \c nullptr if not used.
* @param flags Flags of the option.
*/
#define GETOPT_GENERAL(id, shortname, longname, flags) { id, shortname, flags, longname }
/**
* Short option without value.
* @param shortname Short option name. Use \c '\0' if not used.
* @param longname Long option name including leading '-' or '--'. Use \c nullptr if not used.
*/
#define GETOPT_NOVAL(shortname, longname) GETOPT_GENERAL(shortname, shortname, longname, ODF_NO_VALUE)
/**
* Short option with value.
* @param shortname Short option name. Use \c '\0' if not used.
* @param longname Long option name including leading '-' or '--'. Use \c nullptr if not used.
*/
#define GETOPT_VALUE(shortname, longname) GETOPT_GENERAL(shortname, shortname, longname, ODF_HAS_VALUE)
/**
* Short option with optional value.
* @param shortname Short option name. Use \c '\0' if not used.
* @param longname Long option name including leading '-' or '--'. Use \c nullptr if not used.
* @note Options with optional values are hopelessly ambiguous, eg "-opt -value", avoid them.
*/
#define GETOPT_OPTVAL(shortname, longname) GETOPT_GENERAL(shortname, shortname, longname, ODF_OPTIONAL_VALUE)
/**
* Short option without value.
* @param shortname Short option name. Use \c '\0' if not used.
*/
#define GETOPT_SHORT_NOVAL(shortname) GETOPT_NOVAL(shortname, nullptr)
/**
* Short option with value.
* @param shortname Short option name. Use \c '\0' if not used.
*/
#define GETOPT_SHORT_VALUE(shortname) GETOPT_VALUE(shortname, nullptr)
/**
* Short option with optional value.
* @param shortname Short option name. Use \c '\0' if not used.
* @note Options with optional values are hopelessly ambiguous, eg "-opt -value", avoid them.
*/
#define GETOPT_SHORT_OPTVAL(shortname) GETOPT_OPTVAL(shortname, nullptr)
/** Option terminator. */
#define GETOPT_END() { '\0', '\0', ODF_END, nullptr}
#endif /* GETOPTDATA_H */ #endif /* GETOPTDATA_H */

View File

@@ -885,7 +885,7 @@ static const char *LoadDefaultDLSFile(const char *user_dls)
DWORD buf_size = sizeof(dls_path); // Buffer size as to be given in bytes! DWORD buf_size = sizeof(dls_path); // Buffer size as to be given in bytes!
if (SUCCEEDED(RegQueryValueEx(hkDM, L"GMFilePath", nullptr, nullptr, (LPBYTE)dls_path, &buf_size))) { if (SUCCEEDED(RegQueryValueEx(hkDM, L"GMFilePath", nullptr, nullptr, (LPBYTE)dls_path, &buf_size))) {
wchar_t expand_path[MAX_PATH * 2]; wchar_t expand_path[MAX_PATH * 2];
ExpandEnvironmentStrings(dls_path, expand_path, lengthof(expand_path)); ExpandEnvironmentStrings(dls_path, expand_path, static_cast<DWORD>(std::size(expand_path)));
if (!dls_file.LoadFile(expand_path)) DEBUG(driver, 1, "Failed to load default GM DLS file from registry"); if (!dls_file.LoadFile(expand_path)) DEBUG(driver, 1, "Failed to load default GM DLS file from registry");
} }
RegCloseKey(hkDM); RegCloseKey(hkDM);
@@ -895,7 +895,7 @@ static const char *LoadDefaultDLSFile(const char *user_dls)
if (dls_file.instruments.empty()) { if (dls_file.instruments.empty()) {
static const wchar_t *DLS_GM_FILE = L"%windir%\\System32\\drivers\\gm.dls"; static const wchar_t *DLS_GM_FILE = L"%windir%\\System32\\drivers\\gm.dls";
wchar_t path[MAX_PATH]; wchar_t path[MAX_PATH];
ExpandEnvironmentStrings(DLS_GM_FILE, path, lengthof(path)); ExpandEnvironmentStrings(DLS_GM_FILE, path, static_cast<DWORD>(std::size(path)));
if (!dls_file.LoadFile(path)) return "Can't load GM DLS collection"; if (!dls_file.LoadFile(path)) return "Can't load GM DLS collection";
} }

View File

@@ -107,7 +107,7 @@ void MusicSystem::BuildPlaylists()
const MusicSet *set = BaseMusic::GetUsedSet(); const MusicSet *set = BaseMusic::GetUsedSet();
/* Clear current playlists */ /* Clear current playlists */
for (size_t i = 0; i < lengthof(this->standard_playlists); ++i) this->standard_playlists[i].clear(); for (auto &playlist : this->standard_playlists) playlist.clear();
this->music_set.clear(); this->music_set.clear();
/* Build standard playlists, and a list of available music */ /* Build standard playlists, and a list of available music */

View File

@@ -78,7 +78,7 @@ static std::string GetLastErrorAsString()
DWORD error_code = GetLastError(); DWORD error_code = GetLastError();
if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_FROM_HMODULE | FORMAT_MESSAGE_IGNORE_INSERTS, GetModuleHandle(L"winhttp.dll"), error_code, if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_FROM_HMODULE | FORMAT_MESSAGE_IGNORE_INSERTS, GetModuleHandle(L"winhttp.dll"), error_code,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buffer, lengthof(buffer), nullptr) == 0) { MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buffer, static_cast<DWORD>(std::size(buffer)), nullptr) == 0) {
return fmt::format("unknown error {}", error_code); return fmt::format("unknown error {}", error_code);
} }
@@ -222,11 +222,11 @@ void NetworkHTTPRequest::Connect()
/* Convert the URL to its components. */ /* Convert the URL to its components. */
url_components.dwStructSize = sizeof(url_components); url_components.dwStructSize = sizeof(url_components);
url_components.lpszScheme = scheme; url_components.lpszScheme = scheme;
url_components.dwSchemeLength = lengthof(scheme); url_components.dwSchemeLength = static_cast<DWORD>(std::size(scheme));
url_components.lpszHostName = hostname; url_components.lpszHostName = hostname;
url_components.dwHostNameLength = lengthof(hostname); url_components.dwHostNameLength = static_cast<DWORD>(std::size(hostname));
url_components.lpszUrlPath = url_path; url_components.lpszUrlPath = url_path;
url_components.dwUrlPathLength = lengthof(url_path); url_components.dwUrlPathLength = static_cast<DWORD>(std::size(url_path));
WinHttpCrackUrl(this->uri.c_str(), 0, 0, &url_components); WinHttpCrackUrl(this->uri.c_str(), 0, 0, &url_components);
/* Create the HTTP connection. */ /* Create the HTTP connection. */

View File

@@ -82,7 +82,7 @@ const char *NetworkError::AsString() const
#if defined(_WIN32) #if defined(_WIN32)
wchar_t buffer[512]; wchar_t buffer[512];
if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, this->error, if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, this->error,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buffer, lengthof(buffer), nullptr) == 0) { MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buffer, static_cast<DWORD>(std::size(buffer)), nullptr) == 0) {
char errbuffer[32]; char errbuffer[32];
seprintf(errbuffer, lastof(errbuffer), "Unknown error %d", this->error); seprintf(errbuffer, lastof(errbuffer), "Unknown error %d", this->error);
this->message.assign(errbuffer); this->message.assign(errbuffer);

View File

@@ -1591,11 +1591,11 @@ void FillNewGRFVehicleCache(const Vehicle *v)
static_assert(NCVV_END == lengthof(cache_entries) + lengthof(partial_cache_entries)); static_assert(NCVV_END == lengthof(cache_entries) + lengthof(partial_cache_entries));
/* Resolve all the variables, so their caches are set. */ /* Resolve all the variables, so their caches are set. */
for (size_t i = 0; i < lengthof(cache_entries); i++) { for (const auto &cache_entry : cache_entries) {
/* Only resolve when the cache isn't valid. */ /* Only resolve when the cache isn't valid. */
if (HasBit(v->grf_cache.cache_valid, cache_entries[i][1])) continue; if (HasBit(v->grf_cache.cache_valid, cache_entry[1])) continue;
GetVariableExtra extra; GetVariableExtra extra;
ro.GetScope(VSG_SCOPE_SELF)->GetVariable(cache_entries[i][0], 0, &extra); ro.GetScope(VSG_SCOPE_SELF)->GetVariable(cache_entry[0], 0, &extra);
} }
/* Make sure really all bits are set. */ /* Make sure really all bits are set. */

View File

@@ -98,8 +98,8 @@ static GenericCallbackList _gcl[GSF_END];
*/ */
void ResetGenericCallbacks() void ResetGenericCallbacks()
{ {
for (uint8_t feature = 0; feature < lengthof(_gcl); feature++) { for (auto &gcl : _gcl) {
_gcl[feature].clear(); gcl.clear();
} }
} }

View File

@@ -728,39 +728,31 @@ void PostMainLoop()
extern void DedicatedFork(); extern void DedicatedFork();
#endif #endif
/** Options of OpenTTD. */ /**
static const OptionData _options[] = { * Create all the options that OpenTTD supports. Each option is
GETOPT_SHORT_VALUE('I'), * always a single character with no, an optional or a required value.
GETOPT_SHORT_VALUE('S'), * @return The available options.
GETOPT_SHORT_VALUE('M'), */
GETOPT_SHORT_VALUE('m'), static std::vector<OptionData> CreateOptions()
GETOPT_SHORT_VALUE('s'), {
GETOPT_SHORT_VALUE('v'), std::vector<OptionData> options;
GETOPT_SHORT_VALUE('b'), /* Options that require a parameter. */
GETOPT_SHORT_OPTVAL('D'), for (char c : "GIMPSbcmnpqrstv") options.push_back({ .type = ODF_HAS_VALUE, .id = c, .shortname = c });
GETOPT_SHORT_VALUE('n'),
GETOPT_SHORT_VALUE('p'),
GETOPT_SHORT_VALUE('P'),
#if !defined(_WIN32) #if !defined(_WIN32)
GETOPT_SHORT_NOVAL('f'), options.push_back({ .type = ODF_HAS_VALUE, .id = 'f', .shortname = 'f' });
#endif #endif
GETOPT_SHORT_VALUE('r'),
GETOPT_SHORT_VALUE('t'), /* Options with an optional parameter. */
GETOPT_SHORT_OPTVAL('d'), for (char c : "Ddg") options.push_back({ .type = ODF_OPTIONAL_VALUE, .id = c, .shortname = c });
GETOPT_SHORT_NOVAL('e'),
GETOPT_SHORT_OPTVAL('g'), /* Options without a parameter. */
GETOPT_SHORT_VALUE('G'), for (char c : "QXehx") options.push_back({ .type = ODF_NO_VALUE, .id = c, .shortname = c });
GETOPT_SHORT_VALUE('c'),
GETOPT_SHORT_NOVAL('x'), /* Non-upstream options */
GETOPT_SHORT_NOVAL('X'), for (char c : "KJZ") options.push_back({ .type = ODF_HAS_VALUE, .id = c, .shortname = c });
GETOPT_SHORT_VALUE('q'),
GETOPT_SHORT_VALUE('K'), return options;
GETOPT_SHORT_NOVAL('h'), }
GETOPT_SHORT_NOVAL('Q'),
GETOPT_SHORT_VALUE('J'),
GETOPT_SHORT_NOVAL('Z'),
GETOPT_END()
};
/** /**
* Main entry point for this lovely game. * Main entry point for this lovely game.
@@ -795,7 +787,8 @@ int openttd_main(int argc, char *argv[])
_game_mode = GM_MENU; _game_mode = GM_MENU;
_switch_mode = SM_MENU; _switch_mode = SM_MENU;
GetOptData mgo(argc - 1, argv + 1, _options); auto options = CreateOptions();
GetOptData mgo(std::span(argv + 1, argc - 1), options);
int ret = 0; int ret = 0;
int i; int i;
@@ -942,7 +935,7 @@ int openttd_main(int argc, char *argv[])
if (i == -2) break; if (i == -2) break;
} }
if (i == -2 || mgo.numleft > 0) { if (i == -2 || !mgo.arguments.empty()) {
/* Either the user typed '-h', they made an error, or they added unrecognized command line arguments. /* Either the user typed '-h', they made an error, or they added unrecognized command line arguments.
* In all cases, print the help, and exit. * In all cases, print the help, and exit.
* *

View File

@@ -1988,11 +1988,11 @@ public:
case WID_O_COND_VARIABLE: { case WID_O_COND_VARIABLE: {
Dimension d = {0, 0}; Dimension d = {0, 0};
for (uint i = 0; i < lengthof(_order_conditional_variable); i++) { for (const auto &ocv : _order_conditional_variable) {
if (this->vehicle->type != VEH_TRAIN && _order_conditional_variable[i] == OCV_FREE_PLATFORMS) { if (this->vehicle->type != VEH_TRAIN && ocv == OCV_FREE_PLATFORMS) {
continue; continue;
} }
d = maxdim(d, GetStringBoundingBox(OrderStringForVariable(this->vehicle, _order_conditional_variable[i]))); d = maxdim(d, GetStringBoundingBox(OrderStringForVariable(this->vehicle, ocv)));
} }
d.width += padding.width; d.width += padding.width;
d.height += padding.height; d.height += padding.height;
@@ -3135,23 +3135,23 @@ public:
break; break;
case WID_O_COND_VARIABLE: { case WID_O_COND_VARIABLE: {
const OrderConditionVariable ocv = this->vehicle->GetOrder(this->OrderGetSel())->GetConditionVariable(); const OrderConditionVariable current_ocv = this->vehicle->GetOrder(this->OrderGetSel())->GetConditionVariable();
DropDownList list; DropDownList list;
for (uint i = 0; i < lengthof(_order_conditional_variable); i++) { for (const auto &ocv : _order_conditional_variable) {
if (this->vehicle->type != VEH_TRAIN && _order_conditional_variable[i] == OCV_FREE_PLATFORMS) { if (this->vehicle->type != VEH_TRAIN && ocv == OCV_FREE_PLATFORMS) {
continue; continue;
} }
if (ocv != _order_conditional_variable[i]) { if (current_ocv != ocv) {
if (_order_conditional_variable[i] == OCV_COUNTER_VALUE && !_settings_client.gui.show_adv_tracerestrict_features) { if (ocv == OCV_COUNTER_VALUE && !_settings_client.gui.show_adv_tracerestrict_features) {
continue; continue;
} }
if ((_order_conditional_variable[i] == OCV_DISPATCH_SLOT) && this->vehicle->orders->GetScheduledDispatchScheduleCount() == 0) { if ((ocv == OCV_DISPATCH_SLOT) && this->vehicle->orders->GetScheduledDispatchScheduleCount() == 0) {
continue; continue;
} }
} }
list.push_back(MakeDropDownListStringItem(OrderStringForVariable(this->vehicle, _order_conditional_variable[i]), _order_conditional_variable[i], false)); list.push_back(MakeDropDownListStringItem(OrderStringForVariable(this->vehicle, ocv), ocv, false));
} }
ShowDropDownList(this, std::move(list), ocv, WID_O_COND_VARIABLE); ShowDropDownList(this, std::move(list), current_ocv, WID_O_COND_VARIABLE);
break; break;
} }

View File

@@ -22,7 +22,7 @@ static std::string GetLoadError()
wchar_t buffer[512]; wchar_t buffer[512];
if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, error_code, if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, error_code,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buffer, lengthof(buffer), nullptr) == 0) { MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buffer, static_cast<DWORD>(std::size(buffer)), nullptr) == 0) {
return fmt::format("Unknown error {}", error_code); return fmt::format("Unknown error {}", error_code);
} }

View File

@@ -199,7 +199,7 @@ void FiosGetDrives(FileList &file_list)
wchar_t drives[256]; wchar_t drives[256];
const wchar_t *s; const wchar_t *s;
GetLogicalDriveStrings(lengthof(drives), drives); GetLogicalDriveStrings(static_cast<DWORD>(std::size(drives)), drives);
for (s = drives; *s != '\0';) { for (s = drives; *s != '\0';) {
FiosItem *fios = &file_list.emplace_back(); FiosItem *fios = &file_list.emplace_back();
fios->type = FIOS_TYPE_DRIVE; fios->type = FIOS_TYPE_DRIVE;
@@ -419,7 +419,7 @@ void DetermineBasePaths(const char *exe)
/* Use the folder of the config file as working directory. */ /* Use the folder of the config file as working directory. */
wchar_t config_dir[MAX_PATH]; wchar_t config_dir[MAX_PATH];
wcsncpy(path, convert_to_fs(_config_file, path, lengthof(path)), lengthof(path)); wcsncpy(path, convert_to_fs(_config_file, path, lengthof(path)), lengthof(path));
if (!GetFullPathName(path, lengthof(config_dir), config_dir, nullptr)) { if (!GetFullPathName(path, static_cast<DWORD>(std::size(config_dir)), config_dir, nullptr)) {
DEBUG(misc, 0, "GetFullPathName failed (%lu)\n", GetLastError()); DEBUG(misc, 0, "GetFullPathName failed (%lu)\n", GetLastError());
_searchpaths[SP_WORKING_DIR].clear(); _searchpaths[SP_WORKING_DIR].clear();
} else { } else {
@@ -431,13 +431,13 @@ void DetermineBasePaths(const char *exe)
} }
} }
if (!GetModuleFileName(nullptr, path, lengthof(path))) { if (!GetModuleFileName(nullptr, path, static_cast<DWORD>(std::size(path)))) {
DEBUG(misc, 0, "GetModuleFileName failed (%lu)\n", GetLastError()); DEBUG(misc, 0, "GetModuleFileName failed (%lu)\n", GetLastError());
_searchpaths[SP_BINARY_DIR].clear(); _searchpaths[SP_BINARY_DIR].clear();
} else { } else {
wchar_t exec_dir[MAX_PATH]; wchar_t exec_dir[MAX_PATH];
wcsncpy(path, convert_to_fs(exe, path, lengthof(path)), lengthof(path)); wcsncpy(path, convert_to_fs(exe, path, std::size(path)), lengthof(path));
if (!GetFullPathName(path, lengthof(exec_dir), exec_dir, nullptr)) { if (!GetFullPathName(path, static_cast<DWORD>(std::size(exec_dir)), exec_dir, nullptr)) {
DEBUG(misc, 0, "GetFullPathName failed (%lu)\n", GetLastError()); DEBUG(misc, 0, "GetFullPathName failed (%lu)\n", GetLastError());
_searchpaths[SP_BINARY_DIR].clear(); _searchpaths[SP_BINARY_DIR].clear();
} else { } else {
@@ -551,8 +551,8 @@ const char *GetCurrentLocale(const char *)
const LCID userUiLocale = MAKELCID(userUiLang, SORT_DEFAULT); const LCID userUiLocale = MAKELCID(userUiLang, SORT_DEFAULT);
char lang[9], country[9]; char lang[9], country[9];
if (GetLocaleInfoA(userUiLocale, LOCALE_SISO639LANGNAME, lang, lengthof(lang)) == 0 || if (GetLocaleInfoA(userUiLocale, LOCALE_SISO639LANGNAME, lang, static_cast<int>(std::size(lang))) == 0 ||
GetLocaleInfoA(userUiLocale, LOCALE_SISO3166CTRYNAME, country, lengthof(country)) == 0) { GetLocaleInfoA(userUiLocale, LOCALE_SISO3166CTRYNAME, country, static_cast<int>(std::size(country))) == 0) {
/* Unable to retrieve the locale. */ /* Unable to retrieve the locale. */
return nullptr; return nullptr;
} }
@@ -578,7 +578,7 @@ void Win32SetCurrentLocaleName(std::string iso_code)
} }
} }
MultiByteToWideChar(CP_UTF8, 0, iso_code.c_str(), -1, _cur_iso_locale, lengthof(_cur_iso_locale)); MultiByteToWideChar(CP_UTF8, 0, iso_code.c_str(), -1, _cur_iso_locale, static_cast<int>(std::size(_cur_iso_locale)));
} }
int OTTDStringCompare(std::string_view s1, std::string_view s2) int OTTDStringCompare(std::string_view s1, std::string_view s2)

View File

@@ -2841,7 +2841,7 @@ bool AfterLoadGame()
uint8_t old_start; uint8_t old_start;
uint8_t num_frames; uint8_t num_frames;
}; };
static const AirportTileConversion atc[] = { static const AirportTileConversion atcs[] = {
{31, 12}, // APT_RADAR_GRASS_FENCE_SW {31, 12}, // APT_RADAR_GRASS_FENCE_SW
{50, 4}, // APT_GRASS_FENCE_NE_FLAG {50, 4}, // APT_GRASS_FENCE_NE_FLAG
{62, 2}, // 1 unused tile {62, 2}, // 1 unused tile
@@ -2856,17 +2856,17 @@ bool AfterLoadGame()
if (IsAirportTile(t)) { if (IsAirportTile(t)) {
StationGfx old_gfx = GetStationGfx(t); StationGfx old_gfx = GetStationGfx(t);
uint8_t offset = 0; uint8_t offset = 0;
for (uint i = 0; i < lengthof(atc); i++) { for (const auto &atc : atcs) {
if (old_gfx < atc[i].old_start) { if (old_gfx < atc.old_start) {
SetStationGfx(t, old_gfx - offset); SetStationGfx(t, old_gfx - offset);
break; break;
} }
if (old_gfx < atc[i].old_start + atc[i].num_frames) { if (old_gfx < atc.old_start + atc.num_frames) {
SetAnimationFrame(t, old_gfx - atc[i].old_start); SetAnimationFrame(t, old_gfx - atc.old_start);
SetStationGfx(t, atc[i].old_start - offset); SetStationGfx(t, atc.old_start - offset);
break; break;
} }
offset += atc[i].num_frames - 1; offset += atc.num_frames - 1;
} }
} }
} }

View File

@@ -47,8 +47,8 @@ bool ScriptInfo::CheckMethod(const char *name) const
"GetDate", "GetDate",
"CreateInstance", "CreateInstance",
}; };
for (size_t i = 0; i < lengthof(required_functions); i++) { for (const auto &required_function : required_functions) {
if (!info->CheckMethod(required_functions[i])) return SQ_ERROR; if (!info->CheckMethod(required_function)) return SQ_ERROR;
} }
/* Get location information of the scanner */ /* Get location information of the scanner */

View File

@@ -2863,8 +2863,8 @@ struct GameSettingsWindow : Window {
STR_CONFIG_SETTING_TYPE_COMPANY_MENU, STR_CONFIG_SETTING_TYPE_COMPANY_INGAME, STR_CONFIG_SETTING_TYPE_COMPANY_MENU, STR_CONFIG_SETTING_TYPE_COMPANY_INGAME,
STR_CONFIG_SETTING_TYPE_GAME_MENU, STR_CONFIG_SETTING_TYPE_GAME_INGAME, STR_CONFIG_SETTING_TYPE_GAME_MENU, STR_CONFIG_SETTING_TYPE_GAME_INGAME,
}; };
for (uint i = 0; i < lengthof(setting_types); i++) { for (const auto &setting_type : setting_types) {
SetDParam(0, setting_types[i]); SetDParam(0, setting_type);
size.width = std::max(size.width, GetStringBoundingBox(STR_CONFIG_SETTING_TYPE).width + padding.width); size.width = std::max(size.width, GetStringBoundingBox(STR_CONFIG_SETTING_TYPE).width + padding.width);
} }
size.height = 2 * GetCharacterHeight(FS_NORMAL) + WidgetDimensions::scaled.vsep_normal + size.height = 2 * GetCharacterHeight(FS_NORMAL) + WidgetDimensions::scaled.vsep_normal +

View File

@@ -391,12 +391,11 @@ static bool CompareFiles(const char *n1, const char *n2)
/** Options of settingsgen. */ /** Options of settingsgen. */
static const OptionData _opts[] = { static const OptionData _opts[] = {
GETOPT_NOVAL( 'h', "--help"), { .type = ODF_NO_VALUE, .id = 'h', .shortname = 'h', .longname = "--help" },
GETOPT_GENERAL('h', '?', nullptr, ODF_NO_VALUE), { .type = ODF_NO_VALUE, .id = 'h', .shortname = '?' },
GETOPT_VALUE( 'o', "--output"), { .type = ODF_HAS_VALUE, .id = 'o', .shortname = 'o', .longname = "--output" },
GETOPT_VALUE( 'b', "--before"), { .type = ODF_HAS_VALUE, .id = 'b', .shortname = 'b', .longname = "--before" },
GETOPT_VALUE( 'a', "--after"), { .type = ODF_HAS_VALUE, .id = 'a', .shortname = 'a', .longname = "--after" },
GETOPT_END(),
}; };
/** /**
@@ -442,7 +441,7 @@ int CDECL main(int argc, char *argv[])
const char *before_file = nullptr; const char *before_file = nullptr;
const char *after_file = nullptr; const char *after_file = nullptr;
GetOptData mgo(argc - 1, argv + 1, _opts); GetOptData mgo(std::span(argv + 1, argc - 1), _opts);
for (;;) { for (;;) {
int i = mgo.GetOpt(); int i = mgo.GetOpt();
if (i == -1) break; if (i == -1) break;
@@ -479,7 +478,7 @@ int CDECL main(int argc, char *argv[])
_stored_output.Clear(); _stored_output.Clear();
_post_amble_output.Clear(); _post_amble_output.Clear();
for (int i = 0; i < mgo.numleft; i++) ProcessIniFile(mgo.argv[i]); for (auto &argument : mgo.arguments) ProcessIniFile(argument);
/* Write output. */ /* Write output. */
if (output_file == nullptr) { if (output_file == nullptr) {

View File

@@ -1100,16 +1100,16 @@ void SmallMapWindow::RebuildColourIndexIfNecessary()
/* Rebuild colour indices if necessary. */ /* Rebuild colour indices if necessary. */
if (SmallMapWindow::map_height_limit == _settings_game.construction.map_height_limit) return; if (SmallMapWindow::map_height_limit == _settings_game.construction.map_height_limit) return;
for (uint n = 0; n < lengthof(_heightmap_schemes); n++) { for (auto &heightmap_scheme : _heightmap_schemes) {
/* The heights go from 0 up to and including maximum. */ /* The heights go from 0 up to and including maximum. */
int heights = _settings_game.construction.map_height_limit + 1; int heights = _settings_game.construction.map_height_limit + 1;
_heightmap_schemes[n].height_colours = ReallocT<uint32_t>(_heightmap_schemes[n].height_colours, heights); heightmap_scheme.height_colours = ReallocT<uint32_t>(heightmap_scheme.height_colours, heights);
for (int z = 0; z < heights; z++) { for (int z = 0; z < heights; z++) {
size_t access_index = (_heightmap_schemes[n].colour_count * z) / heights; size_t access_index = (heightmap_scheme.colour_count * z) / heights;
/* Choose colour by mapping the range (0..max heightlevel) on the complete colour table. */ /* Choose colour by mapping the range (0..max heightlevel) on the complete colour table. */
_heightmap_schemes[n].height_colours[z] = _heightmap_schemes[n].height_colours_base[access_index]; heightmap_scheme.height_colours[z] = heightmap_scheme.height_colours_base[access_index];
} }
} }

View File

@@ -24,8 +24,8 @@ static uint8_t GetGRFContainerVersion(SpriteFile &file)
if (file.ReadWord() == 0) { if (file.ReadWord() == 0) {
/* Check for GRF container version 2, which is identified by the bytes /* Check for GRF container version 2, which is identified by the bytes
* '47 52 46 82 0D 0A 1A 0A' at the start of the file. */ * '47 52 46 82 0D 0A 1A 0A' at the start of the file. */
for (uint i = 0; i < lengthof(_grf_cont_v2_sig); i++) { for (const auto &expected_sig_byte : _grf_cont_v2_sig) {
if (file.ReadByte() != _grf_cont_v2_sig[i]) return 0; // Invalid format if (file.ReadByte() != expected_sig_byte) return 0; // Invalid format
} }
return 2; return 2;

View File

@@ -494,37 +494,38 @@ static inline char *mkpath(char *buf, const char *last, const char *path, const
* this for all Windows machines to keep identical behaviour, * this for all Windows machines to keep identical behaviour,
* no matter what your compiler was. * no matter what your compiler was.
*/ */
static inline char *replace_pathsep(char *s) static std::string replace_pathsep(std::string s)
{ {
for (char *c = s; *c != '\0'; c++) if (*c == '/') *c = '\\'; for (char &c : s) {
if (c == '/') c = '\\';
}
return s; return s;
} }
#else #else
static inline char *replace_pathsep(char *s) { return s; } static std::string replace_pathsep(std::string s) { return s; }
#endif #endif
/** Options of strgen. */ /** Options of strgen. */
static const OptionData _opts[] = { static const OptionData _opts[] = {
GETOPT_GENERAL('C', '\0', "-export-commands", ODF_NO_VALUE), { .type = ODF_NO_VALUE, .id = 'C', .longname = "-export-commands" },
GETOPT_GENERAL('L', '\0', "-export-plurals", ODF_NO_VALUE), { .type = ODF_NO_VALUE, .id = 'L', .longname = "-export-plurals" },
GETOPT_GENERAL('P', '\0', "-export-pragmas", ODF_NO_VALUE), { .type = ODF_NO_VALUE, .id = 'P', .longname = "-export-pragmas" },
GETOPT_NOVAL( 't', "--todo"), { .type = ODF_NO_VALUE, .id = 't', .shortname = 't', .longname = "--todo" },
GETOPT_NOVAL( 'w', "--warning"), { .type = ODF_NO_VALUE, .id = 'w', .shortname = 'w', .longname = "--warning" },
GETOPT_NOVAL( 'h', "--help"), { .type = ODF_NO_VALUE, .id = 'h', .shortname = 'h', .longname = "--help" },
GETOPT_GENERAL('h', '?', nullptr, ODF_NO_VALUE), { .type = ODF_NO_VALUE, .id = 'h', .shortname = '?' },
GETOPT_VALUE( 's', "--source_dir"), { .type = ODF_HAS_VALUE, .id = 's', .shortname = 's', .longname = "--source_dir" },
GETOPT_VALUE( 'd', "--dest_dir"), { .type = ODF_HAS_VALUE, .id = 'd', .shortname = 'd', .longname = "--dest_dir" },
GETOPT_END(),
}; };
int CDECL main(int argc, char *argv[]) int CDECL main(int argc, char *argv[])
{ {
char pathbuf[MAX_PATH]; char pathbuf[MAX_PATH];
char pathbuf2[MAX_PATH]; char pathbuf2[MAX_PATH];
const char *src_dir = "."; std::string src_dir = ".";
const char *dest_dir = nullptr; std::string dest_dir;
GetOptData mgo(argc - 1, argv + 1, _opts); GetOptData mgo(std::span(argv + 1, argc - 1), _opts);
for (;;) { for (;;) {
int i = mgo.GetOpt(); int i = mgo.GetOpt();
if (i == -1) break; if (i == -1) break;
@@ -556,9 +557,9 @@ int CDECL main(int argc, char *argv[])
case 'P': case 'P':
printf("name\tflags\tdefault\tdescription\n"); printf("name\tflags\tdefault\tdescription\n");
for (size_t j = 0; j < lengthof(_pragmas); j++) { for (const auto &pragma : _pragmas) {
printf("\"%s\"\t%s\t\"%s\"\t\"%s\"\n", printf("\"%s\"\t%s\t\"%s\"\t\"%s\"\n",
_pragmas[j][0], _pragmas[j][1], _pragmas[j][2], _pragmas[j][3]); pragma[0], pragma[1], pragma[2], pragma[3]);
} }
return 0; return 0;
@@ -601,16 +602,16 @@ int CDECL main(int argc, char *argv[])
} }
} }
if (dest_dir == nullptr) dest_dir = src_dir; // if dest_dir is not specified, it equals src_dir if (dest_dir.empty()) dest_dir = src_dir; // if dest_dir is not specified, it equals src_dir
try { try {
/* strgen has two modes of operation. If no (free) arguments are passed /* strgen has two modes of operation. If no (free) arguments are passed
* strgen generates strings.h to the destination directory. If it is supplied * strgen generates strings.h to the destination directory. If it is supplied
* with a (free) parameter the program will translate that language to destination * with a (free) parameter the program will translate that language to destination
* directory. As input english.txt is parsed from the source directory */ * directory. As input english.txt is parsed from the source directory */
if (mgo.numleft == 0) { if (mgo.arguments.empty()) {
mkpath(pathbuf, lastof(pathbuf), src_dir, "english.txt"); mkpath(pathbuf, lastof(pathbuf), src_dir.c_str(), "english.txt");
mkpath2(pathbuf2, lastof(pathbuf2), src_dir, "extra", "english.txt"); mkpath2(pathbuf2, lastof(pathbuf2), src_dir.c_str(), "extra", "english.txt");
/* parse master file */ /* parse master file */
StringData data(TEXT_TAB_END); StringData data(TEXT_TAB_END);
@@ -619,41 +620,41 @@ int CDECL main(int argc, char *argv[])
if (_errors != 0) return 1; if (_errors != 0) return 1;
/* write strings.h */ /* write strings.h */
ottd_mkdir(dest_dir); ottd_mkdir(dest_dir.c_str());
mkpath(pathbuf, lastof(pathbuf), dest_dir, "strings.h"); mkpath(pathbuf, lastof(pathbuf), dest_dir.c_str(), "strings.h");
HeaderFileWriter writer(pathbuf); HeaderFileWriter writer(pathbuf);
writer.WriteHeader(data); writer.WriteHeader(data);
writer.Finalise(data); writer.Finalise(data);
if (_errors != 0) return 1; if (_errors != 0) return 1;
} else if (mgo.numleft >= 1) { } else {
char *r; char *r;
mkpath(pathbuf, lastof(pathbuf), src_dir, "english.txt"); mkpath(pathbuf, lastof(pathbuf), src_dir.c_str(), "english.txt");
mkpath2(pathbuf2, lastof(pathbuf2), src_dir, "extra", "english.txt"); mkpath2(pathbuf2, lastof(pathbuf2), src_dir.c_str(), "extra", "english.txt");
StringData data(TEXT_TAB_END); StringData data(TEXT_TAB_END);
/* parse master file and check if target file is correct */ /* parse master file and check if target file is correct */
FileStringReader master_reader(data, pathbuf, pathbuf2, true, false); FileStringReader master_reader(data, pathbuf, pathbuf2, true, false);
master_reader.ParseFile(); master_reader.ParseFile();
for (int i = 0; i < mgo.numleft; i++) { for (auto &argument : mgo.arguments) {
data.FreeTranslation(); data.FreeTranslation();
const char *translation = replace_pathsep(mgo.argv[i]); std::string translation = replace_pathsep(argument);
const char *file = strrchr(translation, PATHSEPCHAR); const char *file = strrchr(translation.c_str(), PATHSEPCHAR);
const char *translation2 = nullptr; const char *translation2 = nullptr;
if (file != nullptr) { if (file != nullptr) {
mkpath2(pathbuf2, lastof(pathbuf2), src_dir, "extra", file + 1); mkpath2(pathbuf2, lastof(pathbuf2), src_dir.c_str(), "extra", file + 1);
translation2 = pathbuf2; translation2 = pathbuf2;
} }
FileStringReader translation_reader(data, translation, translation2, false, file == nullptr || strcmp(file + 1, "english.txt") != 0); FileStringReader translation_reader(data, translation.c_str(), translation2, false, file == nullptr || strcmp(file + 1, "english.txt") != 0);
translation_reader.ParseFile(); // target file translation_reader.ParseFile(); // target file
if (_errors != 0) return 1; if (_errors != 0) return 1;
/* get the targetfile, strip any directories and append to destination path */ /* get the targetfile, strip any directories and append to destination path */
r = strrchr(mgo.argv[i], PATHSEPCHAR); r = strrchr(argument, PATHSEPCHAR);
mkpath(pathbuf, lastof(pathbuf), dest_dir, (r != nullptr) ? &r[1] : mgo.argv[i]); mkpath(pathbuf, lastof(pathbuf), dest_dir.c_str(), (r != nullptr) ? &r[1] : argument);
/* rename the .txt (input-extension) to .lng */ /* rename the .txt (input-extension) to .lng */
r = strrchr(pathbuf, '.'); r = strrchr(pathbuf, '.');

View File

@@ -3089,8 +3089,8 @@ struct VehicleDetailsWindow : Window {
STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED_MAX_TE, STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED_MAX_TE,
STR_VEHICLE_INFO_RELIABILITY_BREAKDOWNS STR_VEHICLE_INFO_RELIABILITY_BREAKDOWNS
}; };
for (uint i = 0; i < lengthof(info_strings); i++) { for (const auto &info_string : info_strings) {
dim = maxdim(dim, GetStringBoundingBox(info_strings[i])); dim = maxdim(dim, GetStringBoundingBox(info_string));
} }
StringID last_year_profit_str = EconTime::UsingWallclockUnits() ? STR_VEHICLE_INFO_PROFIT_THIS_PERIOD_LAST_PERIOD : STR_VEHICLE_INFO_PROFIT_THIS_YEAR_LAST_YEAR; StringID last_year_profit_str = EconTime::UsingWallclockUnits() ? STR_VEHICLE_INFO_PROFIT_THIS_PERIOD_LAST_PERIOD : STR_VEHICLE_INFO_PROFIT_THIS_YEAR_LAST_YEAR;
if (v->type == VEH_TRAIN && _settings_client.gui.show_train_length_in_details) { if (v->type == VEH_TRAIN && _settings_client.gui.show_train_length_in_details) {

View File

@@ -187,9 +187,9 @@ static void GetVideoModes()
_all_modes = (SDL_ListModes(nullptr, SDL_SWSURFACE | (_fullscreen ? SDL_FULLSCREEN : 0)) == (void*)-1); _all_modes = (SDL_ListModes(nullptr, SDL_SWSURFACE | (_fullscreen ? SDL_FULLSCREEN : 0)) == (void*)-1);
if (modes == (void*)-1) { if (modes == (void*)-1) {
for (uint i = 0; i < lengthof(_default_resolutions); i++) { for (const auto &default_resolution : _default_resolutions) {
if (SDL_VideoModeOK(_default_resolutions[i].width, _default_resolutions[i].height, 8, SDL_FULLSCREEN) != 0) { if (SDL_VideoModeOK(default_resolution.width, default_resolution.height, 8, SDL_FULLSCREEN) != 0) {
_resolutions.push_back(_default_resolutions[i]); _resolutions.push_back(default_resolution);
} }
} }
} else { } else {

View File

@@ -6761,9 +6761,9 @@ static ViewportSSCSS _vp_sprite_sorters[] = {
/** Choose the "best" sprite sorter and set _vp_sprite_sorter. */ /** Choose the "best" sprite sorter and set _vp_sprite_sorter. */
void InitializeSpriteSorter() void InitializeSpriteSorter()
{ {
for (uint i = 0; i < lengthof(_vp_sprite_sorters); i++) { for (const auto &sprite_sorter : _vp_sprite_sorters) {
if (_vp_sprite_sorters[i].fct_checker()) { if (sprite_sorter.fct_checker()) {
_vp_sprite_sorter = _vp_sprite_sorters[i].fct_sorter; _vp_sprite_sorter = sprite_sorter.fct_sorter;
break; break;
} }
} }