From 9910240f0e9ada1586810f4928d38e88911bc574 Mon Sep 17 00:00:00 2001 From: PeterN Date: Sun, 23 Apr 2023 17:46:14 +0100 Subject: [PATCH 01/27] Cleanup: Remove obsolete (Make)EnumPropsT. (#10697) This was used by the command system to help extract p1/p2 parameters, which no longer happens. --- src/company_type.h | 3 --- src/core/enum_type.hpp | 30 ------------------------------ src/direction_type.h | 10 ---------- src/economy_type.h | 3 --- src/gfx_type.h | 1 - src/linkgraph/linkgraph_type.h | 5 ----- src/livery.h | 2 -- src/newgrf_roadstop.h | 3 --- src/newgrf_station.h | 1 - src/order_type.h | 3 --- src/rail_type.h | 2 -- src/road_type.h | 4 ---- src/signal_type.h | 3 --- src/story_base.h | 6 ------ src/town_type.h | 2 -- src/track_type.h | 6 ------ src/transport_type.h | 2 -- src/vehicle_type.h | 2 -- src/water_map.h | 2 -- 19 files changed, 90 deletions(-) diff --git a/src/company_type.h b/src/company_type.h index cdd9a414d6..5bd1d6b40c 100644 --- a/src/company_type.h +++ b/src/company_type.h @@ -45,9 +45,6 @@ static const uint MAX_COMPANY_SHARE_OWNERS = 4; ///< The maximum number static const uint MIN_COMPETITORS_INTERVAL = 0; ///< The minimum interval (in minutes) between competitors. static const uint MAX_COMPETITORS_INTERVAL = 500; ///< The maximum interval (in minutes) between competitors. -/** Define basic enum properties */ -template <> struct EnumPropsT : MakeEnumPropsT {}; - typedef Owner CompanyID; typedef uint16 CompanyMask; diff --git a/src/core/enum_type.hpp b/src/core/enum_type.hpp index f094bae914..273a5b077e 100644 --- a/src/core/enum_type.hpp +++ b/src/core/enum_type.hpp @@ -38,34 +38,4 @@ inline constexpr mask_t operator ~(mask_t m) {return (mask_t)(~(std::underlying_type::type)m);} -/** - * Informative template class exposing basic enumeration properties used by several - * other templates below. Here we have only forward declaration. For each enum type - * we will create specialization derived from MakeEnumPropsT<>. - * i.e.: - * template <> struct EnumPropsT : MakeEnumPropsT {}; - */ -template struct EnumPropsT; - -/** - * Helper template class that makes basic properties of given enumeration type visible - * from outsize. It is used as base class of several EnumPropsT specializations each - * dedicated to one of commonly used enumeration types. - * @param Tenum_t enumeration type that you want to describe - * @param Tstorage_t what storage type would be sufficient (i.e. byte) - * @param Tbegin first valid value from the contiguous range (i.e. TRACK_BEGIN) - * @param Tend one past the last valid value from the contiguous range (i.e. TRACK_END) - * @param Tinvalid value used as invalid value marker (i.e. INVALID_TRACK) - * @param Tnum_bits Number of bits for storing the enum in command parameters - */ -template -struct MakeEnumPropsT { - typedef Tenum_t type; ///< enum type (i.e. Trackdir) - typedef Tstorage_t storage; ///< storage type (i.e. byte) - static const Tenum_t begin = Tbegin; ///< lowest valid value (i.e. TRACKDIR_BEGIN) - static const Tenum_t end = Tend; ///< one after the last valid value (i.e. TRACKDIR_END) - static const Tenum_t invalid = Tinvalid; ///< what value is used as invalid value (i.e. INVALID_TRACKDIR) - static const uint num_bits = Tnum_bits; ///< Number of bits for storing the enum in command parameters -}; - #endif /* ENUM_TYPE_HPP */ diff --git a/src/direction_type.h b/src/direction_type.h index cb4595f09a..a7983a5c3d 100644 --- a/src/direction_type.h +++ b/src/direction_type.h @@ -38,10 +38,6 @@ enum Direction : byte { /** Allow incrementing of Direction variables */ DECLARE_POSTFIX_INCREMENT(Direction) -/** Define basic enum properties */ -template <> struct EnumPropsT : MakeEnumPropsT {}; - - /** * Enumeration for the difference between two directions. * @@ -87,10 +83,6 @@ enum DiagDirection : byte { /** Allow incrementing of DiagDirection variables */ DECLARE_POSTFIX_INCREMENT(DiagDirection) -/** Define basic enum properties */ -template <> struct EnumPropsT : MakeEnumPropsT {}; - - /** * Enumeration for the difference between to DiagDirection. * @@ -128,7 +120,5 @@ enum Axis : byte { AXIS_END, ///< Used for iterations INVALID_AXIS = 0xFF, ///< Flag for an invalid Axis }; -/** Helper information for extract tool. */ -template <> struct EnumPropsT : MakeEnumPropsT {}; #endif /* DIRECTION_TYPE_H */ diff --git a/src/economy_type.h b/src/economy_type.h index 8b4b0901e8..f0f3fbe706 100644 --- a/src/economy_type.h +++ b/src/economy_type.h @@ -172,9 +172,6 @@ enum ExpensesType : byte { INVALID_EXPENSES = 0xFF, ///< Invalid expense type. }; -/** Define basic enum properties for ExpensesType */ -template <> struct EnumPropsT : MakeEnumPropsT {}; - /** * Categories of a price bases. */ diff --git a/src/gfx_type.h b/src/gfx_type.h index 88cdbabacc..12d2b2c794 100644 --- a/src/gfx_type.h +++ b/src/gfx_type.h @@ -251,7 +251,6 @@ enum Colours : byte { COLOUR_END, INVALID_COLOUR = 0xFF, }; -template <> struct EnumPropsT : MakeEnumPropsT {}; /** Colour of the strings, see _string_colourmap in table/string_colours.h or docs/ottd-colourtext-palette.png */ enum TextColour { diff --git a/src/linkgraph/linkgraph_type.h b/src/linkgraph/linkgraph_type.h index 1839633bf6..89abef4e43 100644 --- a/src/linkgraph/linkgraph_type.h +++ b/src/linkgraph/linkgraph_type.h @@ -31,11 +31,6 @@ enum DistributionType : byte { DT_END = 3 }; -/* It needs to be 8bits, because we save and load it as such - * Define basic enum properties - */ -template <> struct EnumPropsT : MakeEnumPropsT {}; - /** * Special modes for updating links. 'Restricted' means that vehicles with * 'no loading' orders are serving the link. If a link is only served by diff --git a/src/livery.h b/src/livery.h index 352cf6972e..730c29da33 100644 --- a/src/livery.h +++ b/src/livery.h @@ -57,8 +57,6 @@ enum LiveryScheme : byte { }; DECLARE_POSTFIX_INCREMENT(LiveryScheme) -/** Helper information for extract tool. */ -template <> struct EnumPropsT : MakeEnumPropsT {}; /** List of different livery classes, used only by the livery GUI. */ enum LiveryClass { diff --git a/src/newgrf_roadstop.h b/src/newgrf_roadstop.h index fa05c30ba1..0ee524b0b3 100644 --- a/src/newgrf_roadstop.h +++ b/src/newgrf_roadstop.h @@ -161,9 +161,6 @@ struct RoadStopSpec { static const RoadStopSpec *Get(uint16 index); }; -template <> -struct EnumPropsT : MakeEnumPropsT {}; - typedef NewGRFClass RoadStopClass; void DrawRoadStopTile(int x, int y, RoadType roadtype, const RoadStopSpec *spec, StationType type, int view); diff --git a/src/newgrf_station.h b/src/newgrf_station.h index 5273625ae6..c1f7235cdd 100644 --- a/src/newgrf_station.h +++ b/src/newgrf_station.h @@ -86,7 +86,6 @@ enum StationClassID : byte { STAT_CLASS_WAYP, ///< Waypoint class. STAT_CLASS_MAX = 255, ///< Maximum number of classes. }; -template <> struct EnumPropsT : MakeEnumPropsT {}; /** Allow incrementing of StationClassID variables */ DECLARE_POSTFIX_INCREMENT(StationClassID) diff --git a/src/order_type.h b/src/order_type.h index 1a0687794a..77fdb714db 100644 --- a/src/order_type.h +++ b/src/order_type.h @@ -152,7 +152,6 @@ enum ModifyOrderFlags : byte { MOF_COND_DESTINATION,///< Change the destination of a conditional order. MOF_END }; -template <> struct EnumPropsT : MakeEnumPropsT {}; /** * Depot action to switch to when doing a #MOF_DEPOT_ACTION. @@ -173,8 +172,6 @@ enum ModifyTimetableFlags : byte { MTF_TRAVEL_SPEED, ///< Set max travel speed. MTF_END }; -template <> struct EnumPropsT : MakeEnumPropsT {}; - /** Clone actions. */ enum CloneOptions : byte { diff --git a/src/rail_type.h b/src/rail_type.h index 874a8ebbb6..6824007921 100644 --- a/src/rail_type.h +++ b/src/rail_type.h @@ -36,8 +36,6 @@ enum RailType : byte { /** Allow incrementing of Track variables */ DECLARE_POSTFIX_INCREMENT(RailType) -/** Define basic enum properties */ -template <> struct EnumPropsT : MakeEnumPropsT {}; /** * The different railtypes we support, but then a bitmask of them. diff --git a/src/road_type.h b/src/road_type.h index a792db7ba5..58ac0a6010 100644 --- a/src/road_type.h +++ b/src/road_type.h @@ -27,7 +27,6 @@ enum RoadType : byte { INVALID_ROADTYPE = 63, ///< flag for invalid roadtype }; DECLARE_POSTFIX_INCREMENT(RoadType) -template <> struct EnumPropsT : MakeEnumPropsT {}; /** * The different roadtypes we support, but then a bitmask of them. @@ -66,7 +65,6 @@ enum RoadBits : byte { ROAD_END = ROAD_ALL + 1, ///< Out-of-range roadbits, used for iterations }; DECLARE_ENUM_AS_BIT_SET(RoadBits) -template <> struct EnumPropsT : MakeEnumPropsT {}; /** Which directions are disallowed ? */ enum DisallowedRoadDirections : byte { @@ -77,7 +75,5 @@ enum DisallowedRoadDirections : byte { DRD_END, ///< Sentinel }; DECLARE_ENUM_AS_BIT_SET(DisallowedRoadDirections) -/** Helper information for extract tool. */ -template <> struct EnumPropsT : MakeEnumPropsT {}; #endif /* ROAD_TYPE_H */ diff --git a/src/signal_type.h b/src/signal_type.h index ff5dd3b553..b28c9ef108 100644 --- a/src/signal_type.h +++ b/src/signal_type.h @@ -32,9 +32,6 @@ enum SignalType : byte { SIGTYPE_LAST = SIGTYPE_PBS_ONEWAY, SIGTYPE_LAST_NOPBS = SIGTYPE_COMBO, }; -/** Helper information for extract tool. */ -template <> struct EnumPropsT : MakeEnumPropsT {}; - /** * These are states in which a signal can be. Currently these are only two, so diff --git a/src/story_base.h b/src/story_base.h index 09a8291fb6..52dcaa0c3b 100644 --- a/src/story_base.h +++ b/src/story_base.h @@ -38,9 +38,6 @@ enum StoryPageElementType : byte { INVALID_SPET = 0xFF, }; -/** Define basic enum properties */ -template <> struct EnumPropsT : MakeEnumPropsT {}; - /** Flags available for buttons */ enum StoryPageButtonFlags : byte { SPBF_NONE = 0, @@ -110,9 +107,6 @@ enum StoryPageButtonCursor : byte { INVALID_SPBC = 0xFF }; -/** Define basic enum properties */ -template <> struct EnumPropsT : MakeEnumPropsT {}; - /** * Checks if a StoryPageButtonCursor value is valid. * diff --git a/src/town_type.h b/src/town_type.h index d1dcdcfc42..80d6652d7a 100644 --- a/src/town_type.h +++ b/src/town_type.h @@ -24,7 +24,6 @@ enum TownSize : byte { TSZ_END, ///< Number of available town sizes. }; -template <> struct EnumPropsT : MakeEnumPropsT {}; enum Ratings { /* These refer to the maximums, so Appalling is -1000 to -400 @@ -88,7 +87,6 @@ enum TownLayout : byte { NUM_TLS, ///< Number of town layouts }; -template <> struct EnumPropsT : MakeEnumPropsT {}; /** Town founding setting values. It needs to be 8bits, because we save and load it as such */ enum TownFounding : byte { diff --git a/src/track_type.h b/src/track_type.h index 70278c58d9..d7a200e28a 100644 --- a/src/track_type.h +++ b/src/track_type.h @@ -30,9 +30,6 @@ enum Track : byte { /** Allow incrementing of Track variables */ DECLARE_POSTFIX_INCREMENT(Track) -/** Define basic enum properties */ -template <> struct EnumPropsT : MakeEnumPropsT {}; - /** Bitfield corresponding to Track */ enum TrackBits : byte { @@ -89,9 +86,6 @@ enum Trackdir : byte { INVALID_TRACKDIR = 0xFF, ///< Flag for an invalid trackdir }; -/** Define basic enum properties */ -template <> struct EnumPropsT : MakeEnumPropsT {}; - /** * Enumeration of bitmasks for the TrackDirs * diff --git a/src/transport_type.h b/src/transport_type.h index 172649aba5..7784e9205d 100644 --- a/src/transport_type.h +++ b/src/transport_type.h @@ -31,7 +31,5 @@ enum TransportType : byte { TRANSPORT_END, ///< End of iterations. INVALID_TRANSPORT = 0xff, ///< Sentinel for invalid transport types. }; -/** Helper information for extract tool. */ -template <> struct EnumPropsT : MakeEnumPropsT {}; #endif /* TRANSPORT_TYPE_H */ diff --git a/src/vehicle_type.h b/src/vehicle_type.h index c302f5b9f5..ce8c606358 100644 --- a/src/vehicle_type.h +++ b/src/vehicle_type.h @@ -35,8 +35,6 @@ enum VehicleType : byte { VEH_INVALID = 0xFF, ///< Non-existing type of vehicle. }; DECLARE_POSTFIX_INCREMENT(VehicleType) -/** Helper information for extract tool. */ -template <> struct EnumPropsT : MakeEnumPropsT {}; struct Vehicle; struct Train; diff --git a/src/water_map.h b/src/water_map.h index 97808d176b..9a0779b908 100644 --- a/src/water_map.h +++ b/src/water_map.h @@ -50,8 +50,6 @@ enum WaterClass : byte { WATER_CLASS_RIVER, ///< River. WATER_CLASS_INVALID, ///< Used for industry tiles on land (also for oilrig if newgrf says so). }; -/** Helper information for extract tool. */ -template <> struct EnumPropsT : MakeEnumPropsT {}; /** * Checks if a water class is valid. From e9f6bbada2c30031ddf4fa8b7db47899ee520152 Mon Sep 17 00:00:00 2001 From: translators Date: Sun, 23 Apr 2023 18:41:11 +0000 Subject: [PATCH 02/27] Update: Translations from eints english (au): 1 change by krysclarke english (us): 1 change by 2TallTyler galician: 36 changes by pvillaverde korean: 14 changes by telk5093 italian: 1 change by Rivarossi russian: 1 change by Ln-Wolf turkish: 2 changes by densxd --- src/lang/english_AU.txt | 1 + src/lang/english_US.txt | 1 + src/lang/galician.txt | 46 ++++++++++++++++++++++++++++++++--------- src/lang/italian.txt | 1 + src/lang/korean.txt | 22 +++++++++++++------- src/lang/russian.txt | 1 + src/lang/turkish.txt | 3 ++- 7 files changed, 56 insertions(+), 19 deletions(-) diff --git a/src/lang/english_AU.txt b/src/lang/english_AU.txt index dcf69b67c6..0cab037e5a 100644 --- a/src/lang/english_AU.txt +++ b/src/lang/english_AU.txt @@ -5110,6 +5110,7 @@ STR_ERROR_NO_BUOY :{WHITE}There is STR_ERROR_CAN_T_TIMETABLE_VEHICLE :{WHITE}Can't timetable vehicle... STR_ERROR_TIMETABLE_ONLY_WAIT_AT_STATIONS :{WHITE}Vehicles can only wait at stations STR_ERROR_TIMETABLE_NOT_STOPPING_HERE :{WHITE}This vehicle is not stopping at this station +STR_ERROR_TIMETABLE_INCOMPLETE :{WHITE}... timetable is incomplete # Sign related errors STR_ERROR_TOO_MANY_SIGNS :{WHITE}... too many signs diff --git a/src/lang/english_US.txt b/src/lang/english_US.txt index 355043283c..b99660e710 100644 --- a/src/lang/english_US.txt +++ b/src/lang/english_US.txt @@ -5110,6 +5110,7 @@ STR_ERROR_NO_BUOY :{WHITE}There is STR_ERROR_CAN_T_TIMETABLE_VEHICLE :{WHITE}Can't timetable vehicle... STR_ERROR_TIMETABLE_ONLY_WAIT_AT_STATIONS :{WHITE}Vehicles can only wait at stations STR_ERROR_TIMETABLE_NOT_STOPPING_HERE :{WHITE}This vehicle is not stopping at this station +STR_ERROR_TIMETABLE_INCOMPLETE :{WHITE}... timetable is incomplete # Sign related errors STR_ERROR_TOO_MANY_SIGNS :{WHITE}... too many signs diff --git a/src/lang/galician.txt b/src/lang/galician.txt index 3381f4f61e..351b206d26 100644 --- a/src/lang/galician.txt +++ b/src/lang/galician.txt @@ -196,6 +196,7 @@ STR_UNITS_VELOCITY_IMPERIAL :{COMMA} mph STR_UNITS_VELOCITY_METRIC :{COMMA} km/h STR_UNITS_VELOCITY_SI :{COMMA} m/s STR_UNITS_VELOCITY_GAMEUNITS :{DECIMAL}{NBSP}cadros/día +STR_UNITS_VELOCITY_KNOTS :{COMMA}{NBSP}nudos STR_UNITS_POWER_IMPERIAL :{COMMA}cv STR_UNITS_POWER_METRIC :{COMMA}cv @@ -344,9 +345,9 @@ STR_GOTO_ORDER_VIEW_TOOLTIP :{BLACK}Abre a v ###length 31 STR_TOOLBAR_TOOLTIP_PAUSE_GAME :{BLACK}Pausar partida STR_TOOLBAR_TOOLTIP_FORWARD :{BLACK}Avance rápido da partida -STR_TOOLBAR_TOOLTIP_OPTIONS :{BLACK}Opcións -STR_TOOLBAR_TOOLTIP_SAVE_GAME_ABANDON_GAME :{BLACK}Gravar partida, abandonar partida, saír -STR_TOOLBAR_TOOLTIP_DISPLAY_MAP :{BLACK}Amosa-lo mapa, ventá extra ou lista de rótulos +STR_TOOLBAR_TOOLTIP_OPTIONS :{BLACK}Opcións e axustes +STR_TOOLBAR_TOOLTIP_SAVE_GAME_ABANDON_GAME :{BLACK}Gravar, cargar ou abandonar partida, saír do programa +STR_TOOLBAR_TOOLTIP_DISPLAY_MAP :{BLACK}Amosa-lo mapa, ventá extra, fluxo de carga ou lista de rótulos STR_TOOLBAR_TOOLTIP_DISPLAY_TOWN_DIRECTORY :{BLACK}Amosa-lo directorio de cidades STR_TOOLBAR_TOOLTIP_DISPLAY_SUBSIDIES :{BLACK}Amosa-las subvencións STR_TOOLBAR_TOOLTIP_DISPLAY_LIST_OF_COMPANY_STATIONS :{BLACK}Amosa-la lista das estacións da compañía @@ -354,9 +355,9 @@ STR_TOOLBAR_TOOLTIP_DISPLAY_COMPANY_FINANCES :{BLACK}Amosa-la STR_TOOLBAR_TOOLTIP_DISPLAY_COMPANY_GENERAL :{BLACK}Amosa-la información xeral da compañía STR_TOOLBAR_TOOLTIP_DISPLAY_STORY_BOOK :{BLACK}Mostrar historial STR_TOOLBAR_TOOLTIP_DISPLAY_GOALS_LIST :{BLACK} Mostrar lista de obxectivos -STR_TOOLBAR_TOOLTIP_DISPLAY_GRAPHS :{BLACK}Amosa-las gráficas +STR_TOOLBAR_TOOLTIP_DISPLAY_GRAPHS :{BLACK}Mostrar gráficos de compañías e taxas de pago de carga. STR_TOOLBAR_TOOLTIP_DISPLAY_COMPANY_LEAGUE :{BLACK}Amosa-lo cadro da liga de compañías -STR_TOOLBAR_TOOLTIP_FUND_CONSTRUCTION_OF_NEW :{BLACK}Financia-la construción dunha nova industria ou listar tódalas industrias +STR_TOOLBAR_TOOLTIP_FUND_CONSTRUCTION_OF_NEW :{BLACK}Examinar as industrias ou financiar a construción dunha nova industria. STR_TOOLBAR_TOOLTIP_DISPLAY_LIST_OF_COMPANY_TRAINS :{BLACK}Amosa-la lista dos trens da compañía. Ctrl+Click alterna entre lista de grupos/vehículos STR_TOOLBAR_TOOLTIP_DISPLAY_LIST_OF_COMPANY_ROAD_VEHICLES :{BLACK}Amosa-la lista dos vehículos de estrada da compañía. Ctrl+Click alterna entre lista de grupos/vehículos STR_TOOLBAR_TOOLTIP_DISPLAY_LIST_OF_COMPANY_SHIPS :{BLACK}Amosar a lista dos barcos da compañía. Ctrl+Click alterna entre lista de grupos/vehículos @@ -370,8 +371,8 @@ STR_TOOLBAR_TOOLTIP_BUILD_SHIP_DOCKS :{BLACK}Constru STR_TOOLBAR_TOOLTIP_BUILD_AIRPORTS :{BLACK}Construír aeroportos STR_TOOLBAR_TOOLTIP_LANDSCAPING :{BLACK}Abri-la ferramenta de terreo para subir/baixar terreo, plantar árbores, etc. STR_TOOLBAR_TOOLTIP_SHOW_SOUND_MUSIC_WINDOW :{BLACK}Amosa-la ventá de son/música -STR_TOOLBAR_TOOLTIP_SHOW_LAST_MESSAGE_NEWS :{BLACK}Amosa-la última mensaxe/nova, amosa-las opcións das mensaxes -STR_TOOLBAR_TOOLTIP_LAND_BLOCK_INFORMATION :{BLACK}Información dunha área de terreo, consola, depuración de scripts, capturas de pantalla, acerca de OpenTTD +STR_TOOLBAR_TOOLTIP_SHOW_LAST_MESSAGE_NEWS :{BLACK}Amosa-la última mensaxe/nova, histórico de mensaxes ou borra todas as mensaxes +STR_TOOLBAR_TOOLTIP_LAND_BLOCK_INFORMATION :{BLACK}Información sobre a área de terra, capturas de pantalla, sobre OpenTTD e ferramentas de desenvolvedor. STR_TOOLBAR_TOOLTIP_SWITCH_TOOLBAR :{BLACK}Intercambiar barras de ferramentas # Extra tooltips for the scenario editor toolbar @@ -1712,7 +1713,7 @@ STR_CONFIG_SETTING_SCRIPT_MAX_MEMORY_HELPTEXT :Canta memoria p STR_CONFIG_SETTING_SCRIPT_MAX_MEMORY_VALUE :{COMMA} MiB STR_CONFIG_SETTING_SERVINT_ISPERCENT :Intervalos de servizo en porcentaxes: {STRING} -STR_CONFIG_SETTING_SERVINT_ISPERCENT_HELPTEXT :Permite escoller se o mantemento de vehículos comezará debido ao tempo transcurrido dende o último mantemento ou por unha redución da fiabilidade cando se sobrepase unha porcentaxe determinado +STR_CONFIG_SETTING_SERVINT_ISPERCENT_HELPTEXT :Cando está habilitado, os vehículos intentan ser reparados cando a súa fiabilidade baixa unha porcentaxe dada da fiabilidade máxima.{}{}Por exemplo, se a fiabilidade máxima dun vehículo é do 90% e o intervalo de mantemento é do 20%, o vehículo tentará ser reparado cando alcance unha fiabilidade do 72%. STR_CONFIG_SETTING_SERVINT_TRAINS :Intervalo de mantemento por defecto para trens: {STRING} STR_CONFIG_SETTING_SERVINT_TRAINS_HELPTEXT :Fixa o intervalo de mantemento por defecto para trens novos, o cal se empregará no caso de que non se defina explicitamente un novo intervalo de mantemento para o vehículo @@ -1809,7 +1810,9 @@ STR_CONFIG_SETTING_ALLOW_SHARES_HELPTEXT :Cando se activa STR_CONFIG_SETTING_MIN_YEARS_FOR_SHARES :Idade mínima da compañía para compraventa de accións: {STRING} STR_CONFIG_SETTING_MIN_YEARS_FOR_SHARES_HELPTEXT :Establece a idade mínima dunha compañía para que outros poidan comprar e vender accións dela. +STR_CONFIG_SETTING_MIN_YEARS_FOR_SHARES_VALUE :{COMMA} ano{P "" s} ###setting-zero-is-special +STR_CONFIG_SETTING_MIN_YEARS_FOR_SHARES_NO_MIN :Sen mínimo STR_CONFIG_SETTING_FEEDER_PAYMENT_SHARE :Porcentaxe do beneficio parcial a pagar en sistemas transitivos: {STRING} STR_CONFIG_SETTING_FEEDER_PAYMENT_SHARE_HELPTEXT :Porcentaxe dos beneficios asignados ás partes intermedias da ruta en sistemas transitivos, dando un maior control sobre os ingresos @@ -1924,6 +1927,10 @@ STR_CONFIG_SETTING_LARGER_TOWNS_DISABLED :Ningunha STR_CONFIG_SETTING_CITY_SIZE_MULTIPLIER :Multiplicador inicial do tamaño da cidade: {STRING} STR_CONFIG_SETTING_CITY_SIZE_MULTIPLIER_HELPTEXT :Relación entre o tamaño medio das cidades e o dos pobos ao inicio da partida +STR_CONFIG_SETTING_LINKGRAPH_RECALC_INTERVAL :Actualizar o grafo de distribución cada {STRING}{NBSP}segundo{P 0:2 "" s}. +STR_CONFIG_SETTING_LINKGRAPH_RECALC_INTERVAL_HELPTEXT :Tempo entre recálculos sucesivos do grafo de ligazóns. Cada recálculo calcula os plans para un compoñente do grafo. Iso significa que un valor X para esta configuración non significa que o grafo completo sexa actualizado cada X segundos. Só algúns compoñentes o serán. Canto máis curto sexa o tempo establecido, máis tempo de CPU será necesario para calculalo. Canto máis longo sexa o tempo establecido, máis tempo levará ata que a distribución de carga comece a percorrer novas rutas. +STR_CONFIG_SETTING_LINKGRAPH_RECALC_TIME :Toma {STRING}{NBSP}segundo{P 0:2 "" s} para o recálculo do grafo de distribución. +STR_CONFIG_SETTING_LINKGRAPH_RECALC_TIME_HELPTEXT :Tempo necesario para cada recalculación dun compoñente do grafo de ligazóns. Cando se inicia unha recalculación, abrese un fío que se pode executar durante este número de segundos. Canto máis curto o establezas, máis probable é que o fío non remate cando se supón que debe facelo. Entón, o xogo detense ata que o fío remata («lag»). Canto máis longo o estabelezas, máis tempo levará actualizar a distribución cando cambien as rutas. STR_CONFIG_SETTING_DISTRIBUTION_PAX :Modo de distribución para pasaxeiros: {STRING} STR_CONFIG_SETTING_DISTRIBUTION_PAX_HELPTEXT :"Simétrico" significa que máis ou menos o mesmo número de pasaxeiros irán dende a estación A cada a estación B e tamén da B cara a A. "Asimétrico" significa que calquera número de pasaxeiros pode ir en calquera dirección. "manual" significa que non haberá distribución automática para os pasaxeiros. @@ -1949,13 +1956,15 @@ STR_CONFIG_SETTING_DEMAND_SIZE_HELPTEXT :Fixar esta opci STR_CONFIG_SETTING_SHORT_PATH_SATURATION :Saturación de rutas curtas antes de empregar rutas con capacidade: {STRING} STR_CONFIG_SETTING_SHORT_PATH_SATURATION_HELPTEXT :Frecuentemente hai múltiples rutas posíbeis entre dúas estacións dadas. En primero lugar intentarase satura-la ruta máis curta, para posteriormente satura-la segunda máis curta e así sucesivamente. A saturación está determinada por unha estimación de capacidade e uso planificado. Unha vez saturadas tódalas rutas, se aínda queda demanda, sobrecargaranse as rutas comezando por aquelas de maior capacidade. A maior parte das veces, o algoritmo non estimará a capacidade con precisión. Esta opción permite especificar ata que porcentaxe de saturación pode ter unha ruta curta na primeira volta do algoritmo antes de escolle-la seguinte máis curta. Fíxao en menos do 100% para evitar estacións sobrecargadas no caso de que se sobreestime a capacidade. -STR_CONFIG_SETTING_LOCALISATION_UNITS_VELOCITY :Unidades de velocidade: {STRING} +STR_CONFIG_SETTING_LOCALISATION_UNITS_VELOCITY :Unidades de velocidade (terra): {STRING} +STR_CONFIG_SETTING_LOCALISATION_UNITS_VELOCITY_NAUTICAL :Unidade de velocidade (náutica): {STRING} STR_CONFIG_SETTING_LOCALISATION_UNITS_VELOCITY_HELPTEXT :Cando unha velocidade apareza na interfaz de usuario, facelo nas unidades seleccionadas ###length 5 STR_CONFIG_SETTING_LOCALISATION_UNITS_VELOCITY_IMPERIAL :Imperial (mph) STR_CONFIG_SETTING_LOCALISATION_UNITS_VELOCITY_METRIC :Métrico (km/h) STR_CONFIG_SETTING_LOCALISATION_UNITS_VELOCITY_SI :SI (m/s) STR_CONFIG_SETTING_LOCALISATION_UNITS_VELOCITY_GAMEUNITS :Unidades do xogo (cadros/día) +STR_CONFIG_SETTING_LOCALISATION_UNITS_VELOCITY_KNOTS :Nudos STR_CONFIG_SETTING_LOCALISATION_UNITS_POWER :Unidades de potencia dos vehículos: {STRING} STR_CONFIG_SETTING_LOCALISATION_UNITS_POWER_HELPTEXT :Cando a potencia dun vehículo se amose na interfaz de usuario, facelo nas unidades seleccionadas @@ -2356,6 +2365,8 @@ STR_NETWORK_CLIENT_LIST_NEW_COMPANY :(Nova compañí STR_NETWORK_CLIENT_LIST_NEW_COMPANY_TOOLTIP :{BLACK}Crear unha nova compañía e unirte a ela STR_NETWORK_CLIENT_LIST_PLAYER_ICON_SELF_TOOLTIP :{BLACK}Este es ti STR_NETWORK_CLIENT_LIST_PLAYER_ICON_HOST_TOOLTIP :{BLACK}Este é o anfitrión da partida +STR_NETWORK_CLIENT_LIST_CLIENT_COMPANY_COUNT :{BLACK}{NUM} cliente{P "" s} - {NUM}/{NUM} compañía{P "" "s"} +STR_NETWORK_CLIENT_LIST_CLIENT_COMPANY_COUNT_TOOLTIP :{BLACK}O número de clientes conectados actualmente, o número de compañías e o número máximo de compañías permitidas polo administrador do servidor. # Matches ConnectionType ###length 5 @@ -4580,7 +4591,9 @@ STR_AI_CONFIG_AILIST_TOOLTIP :{BLACK}As IAs q STR_AI_CONFIG_HUMAN_PLAYER :Xogador humano STR_AI_CONFIG_RANDOM_AI :IA aleatoria STR_AI_CONFIG_NONE :(ningunha) +STR_AI_CONFIG_NAME_VERSION :{STRING} {YELLOW}v{NUM} STR_AI_CONFIG_MAX_COMPETITORS :{LTBLUE}Nº máximo de opoñentes: {ORANGE}{COMMA} +STR_AI_CONFIG_COMPETITORS_INTERVAL :{LTBLUE}Intervalo entre o comezo dos competidores: {ORANGE}{COMMA} minuto{P "" s} STR_AI_CONFIG_MOVE_UP :{BLACK}Subir STR_AI_CONFIG_MOVE_UP_TOOLTIP :{BLACK}Mover a IA seleccionada cara arriba na lista @@ -4593,7 +4606,7 @@ STR_AI_CONFIG_AI :{SILVER}IAs STR_AI_CONFIG_CHANGE_AI :{BLACK}Seleccionar IA STR_AI_CONFIG_CHANGE_GAMESCRIPT :{BLACK}Seleccionar script do xogo -STR_AI_CONFIG_CHANGE_TOOLTIP :{BLACK}Cargar outro script +STR_AI_CONFIG_CHANGE_TOOLTIP :{BLACK}Cargar outro script. Ctrl+Click amosa todas as versións dispoñibles STR_AI_CONFIG_CONFIGURE :{BLACK}Configurar STR_AI_CONFIG_CONFIGURE_TOOLTIP :{BLACK}Configurar os parámetros do script @@ -5081,11 +5094,24 @@ STR_ERROR_TOO_FAR_FROM_PREVIOUS_DESTINATION :{WHITE}... dema STR_ERROR_AIRCRAFT_NOT_ENOUGH_RANGE :{WHITE}... o avión non ten autonomía suficiente # Extra messages which go on the third line of errors, explaining why orders failed +STR_ERROR_NO_RAIL_STATION :{WHITE}Non hai estación de ferrocarril +STR_ERROR_NO_BUS_STATION :{WHITE}Non hai estación de bus +STR_ERROR_NO_TRUCK_STATION :{WHITE}Non hai estación de camións +STR_ERROR_NO_DOCK :{WHITE}Non hai porto +STR_ERROR_NO_AIRPORT :{WHITE}Non hai aeroporto/heliporto +STR_ERROR_NO_STOP_COMPATIBLE_ROAD_TYPE :{WHITE}Non hai paradas con un tipo de estrada compatible. +STR_ERROR_NO_STOP_COMPATIBLE_TRAM_TYPE :{WHITE}Non hai paradas con un tipo de tranvía compatible +STR_ERROR_NO_STOP_ARTICULATED_VEHICLE :{WHITE}Non hai paradas que sexan axeitadas para vehículos articulados.{} Os vehículos articulados requiren dunha parada na que se poida pasar directamente, non unha parada en baía. +STR_ERROR_AIRPORT_NO_PLANES :{WHITE}Este avión non pode aterrar neste heliporto +STR_ERROR_AIRPORT_NO_HELICOPTERS :{WHITE}Este helicóptero non pode aterrar neste aeroporto +STR_ERROR_NO_RAIL_WAYPOINT :{WHITE}Non hai punto de ruta da liña férrea +STR_ERROR_NO_BUOY :{WHITE}Non hai boia # Timetable related errors STR_ERROR_CAN_T_TIMETABLE_VEHICLE :{WHITE}Non se pode axusta-lo horario do vehículo... STR_ERROR_TIMETABLE_ONLY_WAIT_AT_STATIONS :{WHITE}Os vehículos só poden parar nas estacións STR_ERROR_TIMETABLE_NOT_STOPPING_HERE :{WHITE}Este vehículo non para nesta estación +STR_ERROR_TIMETABLE_INCOMPLETE :{WHITE}... horario incompleto # Sign related errors STR_ERROR_TOO_MANY_SIGNS :{WHITE}... demasiados sinais diff --git a/src/lang/italian.txt b/src/lang/italian.txt index 5bed11d88f..b7f01771e4 100644 --- a/src/lang/italian.txt +++ b/src/lang/italian.txt @@ -5151,6 +5151,7 @@ STR_ERROR_NO_BUOY :{WHITE}Non c'è STR_ERROR_CAN_T_TIMETABLE_VEHICLE :{WHITE}Impossibile dare un orario al veicolo... STR_ERROR_TIMETABLE_ONLY_WAIT_AT_STATIONS :{WHITE}I veicoli possono attendere solo alle stazioni STR_ERROR_TIMETABLE_NOT_STOPPING_HERE :{WHITE}Il veicolo non ferma a questa stazione +STR_ERROR_TIMETABLE_INCOMPLETE :{WHITE}... l'orario è incompleto # Sign related errors STR_ERROR_TOO_MANY_SIGNS :{WHITE}... troppi cartelli diff --git a/src/lang/korean.txt b/src/lang/korean.txt index 40042e9426..eeeea82408 100644 --- a/src/lang/korean.txt +++ b/src/lang/korean.txt @@ -345,9 +345,9 @@ STR_GOTO_ORDER_VIEW_TOOLTIP :{BLACK}경로 ###length 31 STR_TOOLBAR_TOOLTIP_PAUSE_GAME :{BLACK}게임을 일시 정지합니다. STR_TOOLBAR_TOOLTIP_FORWARD :{BLACK}게임 시간을 빠르게 가도록 합니다. -STR_TOOLBAR_TOOLTIP_OPTIONS :{BLACK}게임 기본 설정을 엽니다. -STR_TOOLBAR_TOOLTIP_SAVE_GAME_ABANDON_GAME :{BLACK}게임을 저장하거나, 그만두거나, 게임을 종료합니다 -STR_TOOLBAR_TOOLTIP_DISPLAY_MAP :{BLACK}지도, 외부 화면, 팻말 목록을 보여줍니다. +STR_TOOLBAR_TOOLTIP_OPTIONS :{BLACK}게임 기본 설정을 엽니다 +STR_TOOLBAR_TOOLTIP_SAVE_GAME_ABANDON_GAME :{BLACK}게임을 저장하거나, 불러오거나, 그만두거나, 게임을 종료합니다 +STR_TOOLBAR_TOOLTIP_DISPLAY_MAP :{BLACK}지도, 외부 화면, 화물 흐름, 팻말 목록을 보여줍니다. STR_TOOLBAR_TOOLTIP_DISPLAY_TOWN_DIRECTORY :{BLACK}도시 메뉴를 표시합니다. STR_TOOLBAR_TOOLTIP_DISPLAY_SUBSIDIES :{BLACK}보조금 메뉴를 표시합니다. STR_TOOLBAR_TOOLTIP_DISPLAY_LIST_OF_COMPANY_STATIONS :{BLACK}각 회사의 정거장 목록을 표시합니다. @@ -355,9 +355,9 @@ STR_TOOLBAR_TOOLTIP_DISPLAY_COMPANY_FINANCES :{BLACK}각 회 STR_TOOLBAR_TOOLTIP_DISPLAY_COMPANY_GENERAL :{BLACK}각 회사의 기본 정보를 표시합니다. STR_TOOLBAR_TOOLTIP_DISPLAY_STORY_BOOK :{BLACK}스토리 북을 엽니다. STR_TOOLBAR_TOOLTIP_DISPLAY_GOALS_LIST :{BLACK}목표 목록을 보여줍니다. -STR_TOOLBAR_TOOLTIP_DISPLAY_GRAPHS :{BLACK}그래프 메뉴를 표시합니다. +STR_TOOLBAR_TOOLTIP_DISPLAY_GRAPHS :{BLACK}회사 그래프와 화물 운송단가 비율 창을 보여줍니다 STR_TOOLBAR_TOOLTIP_DISPLAY_COMPANY_LEAGUE :{BLACK}회사의 성취도 순위를 표시합니다. -STR_TOOLBAR_TOOLTIP_FUND_CONSTRUCTION_OF_NEW :{BLACK}새 산업시설에 투자하거나 산업시설의 목록을 표시합니다. +STR_TOOLBAR_TOOLTIP_FUND_CONSTRUCTION_OF_NEW :{BLACK}새 산업시설의 위치를 무작위로 찾거나 원하는 위치에 새로운 산업시설을 건설합니다 STR_TOOLBAR_TOOLTIP_DISPLAY_LIST_OF_COMPANY_TRAINS :{BLACK}각 회사의 열차 목록을 표시합니다. CTRL+클릭하면 그룹화된 창은 일반 창으로, 일반 창은 그룹화된 창으로 표시됩니다. STR_TOOLBAR_TOOLTIP_DISPLAY_LIST_OF_COMPANY_ROAD_VEHICLES :{BLACK}각 회사의 차량 목록을 표시합니다. CTRL+클릭하면 그룹화된 창은 일반 창으로, 일반 창은 그룹화된 창으로 표시됩니다. STR_TOOLBAR_TOOLTIP_DISPLAY_LIST_OF_COMPANY_SHIPS :{BLACK}각 회사의 선박 목록을 표시합니다. CTRL+클릭하면 그룹화된 창은 일반 창으로, 일반 창은 그룹화된 창으로 표시됩니다. @@ -371,8 +371,8 @@ STR_TOOLBAR_TOOLTIP_BUILD_SHIP_DOCKS :{BLACK}항만 STR_TOOLBAR_TOOLTIP_BUILD_AIRPORTS :{BLACK}항공 시설을 건설합니다. STR_TOOLBAR_TOOLTIP_LANDSCAPING :{BLACK}땅 올리기/내리기, 나무 심기 등의 일를 하기 위한 지형편집창을 엽니다. STR_TOOLBAR_TOOLTIP_SHOW_SOUND_MUSIC_WINDOW :{BLACK}효과음/배경 음악 창을 엽니다. -STR_TOOLBAR_TOOLTIP_SHOW_LAST_MESSAGE_NEWS :{BLACK}최근 메시지/뉴스 기록이나 메시지 설정을 엽니다. -STR_TOOLBAR_TOOLTIP_LAND_BLOCK_INFORMATION :{BLACK}지역 정보, 콘솔, 스크립트 디버그, 스크린샷, OpenTTD에 대한 정보를 보여줍니다. +STR_TOOLBAR_TOOLTIP_SHOW_LAST_MESSAGE_NEWS :{BLACK}최근 메시지/뉴스 기록을 보거나, 모든 메시지를 삭제합니다 +STR_TOOLBAR_TOOLTIP_LAND_BLOCK_INFORMATION :{BLACK}지역 정보, 스크린샷, OpenTTD에 대한 정보, 개발자 도구 등을 보여줍니다 STR_TOOLBAR_TOOLTIP_SWITCH_TOOLBAR :{BLACK}툴바를 변경합니다. # Extra tooltips for the scenario editor toolbar @@ -1713,7 +1713,7 @@ STR_CONFIG_SETTING_SCRIPT_MAX_MEMORY_HELPTEXT :스크립트 STR_CONFIG_SETTING_SCRIPT_MAX_MEMORY_VALUE :{COMMA} MiB STR_CONFIG_SETTING_SERVINT_ISPERCENT :신뢰도에 따른 점검 설정: {STRING} -STR_CONFIG_SETTING_SERVINT_ISPERCENT_HELPTEXT :차량 점검 방식을 "마지막 점검 이후 지난 시간 (또는) 최대 신뢰도에 대한 차량 신뢰도의 일정 퍼센트 하락 여부" 중에 하나로 선택합니다. +STR_CONFIG_SETTING_SERVINT_ISPERCENT_HELPTEXT :이 설정을 켜면, 차량의 신뢰도가 최대 신뢰도에 비해 일정 비율만큼 하락했을 때 점검을 하러 가려고 합니다.{}{}예를 들어, 차량의 최대 신뢰도가 90%이고 점검 주기를 20%로 설정하면, 그 차량은 신뢰도가 72%가 되었을 때 점검을 하러 가게 됩니다. STR_CONFIG_SETTING_SERVINT_TRAINS :열차에 대한 기본 점검 기준: {STRING} STR_CONFIG_SETTING_SERVINT_TRAINS_HELPTEXT :열차에 따로 점검 기간이 설정되어있지 않은 경우에 사용할 기본 점검 기간을 설정합니다. @@ -1927,6 +1927,10 @@ STR_CONFIG_SETTING_LARGER_TOWNS_DISABLED :없음 STR_CONFIG_SETTING_CITY_SIZE_MULTIPLIER :초기 대도시 크기 비율: 일반 도시보다 {STRING}배 크게 시작 STR_CONFIG_SETTING_CITY_SIZE_MULTIPLIER_HELPTEXT :게임을 시작했을 때 일반 도시에 대한 대도시의 평균 크기를 설정합니다 +STR_CONFIG_SETTING_LINKGRAPH_RECALC_INTERVAL :분배 그래프를 매 {STRING}초마다 업데이트 +STR_CONFIG_SETTING_LINKGRAPH_RECALC_INTERVAL_HELPTEXT :각 연결 그래프의 하위 시퀀스 재계산 사이의 시간입니다. 각 재계산은 그래프의 한 구성 요소에 대한 계획을 계산합니다. 즉, 이 설정을 X로 설정한다고 해서 전체 그래프를 X초마다 업데이트한다는 뜻은 아닙니다. 일부 구성 요소만 X초마다 업데이트됩니다. 이 값을 더 짧게 설정할 수록 계산하는데 더 많은 CPU 계산 시간이 필요합니다. 값을 더 길게 설정하면 화물 분배가 새 경로로 이뤄지기까지 더 오랜 시간이 걸리게 됩니다. +STR_CONFIG_SETTING_LINKGRAPH_RECALC_TIME :분배 그래프의 재계산을 위해 {STRING}초 사용 +STR_CONFIG_SETTING_LINKGRAPH_RECALC_TIME_HELPTEXT :각 연결 그래프의 구성 요소를 재계산하는데 걸리는 시간입니다. 재계산이 시작되면, 이 시간(초) 동안 실행할 수 있는 스레드가 생성됩니다. 이 값을 더 짧게 설정할수록 스레드가 완료되어야 할 때 완료되지 못할 가능성이 높아집니다. 그러면 이를 완료하기 전까지는 게임이 멈추게 됩니다. 값을 더 길게 설정하면 경로가 변경되었을 때 분배가 업데이트되는 데 더 오래 걸립니다. STR_CONFIG_SETTING_DISTRIBUTION_PAX :승객에 대한 분배 형식: {STRING} STR_CONFIG_SETTING_DISTRIBUTION_PAX_HELPTEXT :"대칭"은 A역에서 B역으로 가려는 승객의 수가 B에서 A로 가려는 승객의 수와 비슷하다는 뜻입니다. "비대칭"은 승객이 아무 방향이나 임의의 양만큼 가게 됨을 뜻합니다. "수동"은 자동적인 승객 분배가 일어나지 않고 기존 방식을 사용하겠음을 뜻합니다. @@ -4589,6 +4593,7 @@ STR_AI_CONFIG_RANDOM_AI :무작위 인 STR_AI_CONFIG_NONE :(없음) STR_AI_CONFIG_NAME_VERSION :{STRING} {YELLOW}v{NUM} STR_AI_CONFIG_MAX_COMPETITORS :{LTBLUE}최대 경쟁자수: {ORANGE}{COMMA} +STR_AI_CONFIG_COMPETITORS_INTERVAL :{LTBLUE}새 경쟁사가 나타나기 위해 필요한 최소 시간: {ORANGE}{COMMA}분 STR_AI_CONFIG_MOVE_UP :{BLACK}위로 이동 STR_AI_CONFIG_MOVE_UP_TOOLTIP :{BLACK}목록에서 선택한 인공지능의 순서를 한 칸 위로 옮깁니다 @@ -5106,6 +5111,7 @@ STR_ERROR_NO_BUOY :{WHITE}부표 STR_ERROR_CAN_T_TIMETABLE_VEHICLE :{WHITE}차량의 시간표를 정할 수 없습니다... STR_ERROR_TIMETABLE_ONLY_WAIT_AT_STATIONS :{WHITE}차량은 정거장에서만 기다릴 수 있습니다 STR_ERROR_TIMETABLE_NOT_STOPPING_HERE :{WHITE}이 차량은 이 정거장에 서지 않습니다 +STR_ERROR_TIMETABLE_INCOMPLETE :{WHITE}... 시간표가 모두 작성되지 않았습니다 # Sign related errors STR_ERROR_TOO_MANY_SIGNS :{WHITE}... 팻말 수가 너무 많습니다 diff --git a/src/lang/russian.txt b/src/lang/russian.txt index e96ca4d49b..8523941347 100644 --- a/src/lang/russian.txt +++ b/src/lang/russian.txt @@ -5297,6 +5297,7 @@ STR_ERROR_NO_BUOY :{WHITE}Буи STR_ERROR_CAN_T_TIMETABLE_VEHICLE :{WHITE}Не удалось составить график движения для этого транспорта... STR_ERROR_TIMETABLE_ONLY_WAIT_AT_STATIONS :{WHITE}Транспорт может ждать только на станции STR_ERROR_TIMETABLE_NOT_STOPPING_HERE :{WHITE}Это транспортное средство не останавливается на этой станции +STR_ERROR_TIMETABLE_INCOMPLETE :{WHITE}... график движения неполный # Sign related errors STR_ERROR_TOO_MANY_SIGNS :{WHITE}... слишком много табличек diff --git a/src/lang/turkish.txt b/src/lang/turkish.txt index a6ab7390ca..e06cdd0856 100644 --- a/src/lang/turkish.txt +++ b/src/lang/turkish.txt @@ -157,7 +157,7 @@ STR_ABBREV_COLA :{TINY_FONT}KO STR_ABBREV_CANDYFLOSS :{TINY_FONT}PŞ STR_ABBREV_BUBBLES :{TINY_FONT}BA STR_ABBREV_TOFFEE :{TINY_FONT}ŞL -STR_ABBREV_BATTERIES :{TINY_FONT}PİL +STR_ABBREV_BATTERIES :{TINY_FONT}PL STR_ABBREV_PLASTIC :{TINY_FONT}PL STR_ABBREV_FIZZY_DRINKS :{TINY_FONT}İÇ STR_ABBREV_NONE :{TINY_FONT}YO @@ -5111,6 +5111,7 @@ STR_ERROR_NO_BUOY :{WHITE}Şamand STR_ERROR_CAN_T_TIMETABLE_VEHICLE :{WHITE}Aracın zaman çizelgesi oluşturulamıyor... STR_ERROR_TIMETABLE_ONLY_WAIT_AT_STATIONS :{WHITE}Araçlar sadece istasyonlarda bekleyebilir STR_ERROR_TIMETABLE_NOT_STOPPING_HERE :{WHITE}Araç bu istasyonda durmuyor +STR_ERROR_TIMETABLE_INCOMPLETE :{WHITE}... zaman çizelgesi eksik # Sign related errors STR_ERROR_TOO_MANY_SIGNS :{WHITE}... çok fazla tabela var From 7c6bf977e07f09a3e5e128d64c5f306590758991 Mon Sep 17 00:00:00 2001 From: Tyler Trahan Date: Sun, 23 Apr 2023 15:20:56 -0400 Subject: [PATCH 03/27] Cleanup: Fix and add comments to date cheat callback (#10699) --- src/cheat_gui.cpp | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/src/cheat_gui.cpp b/src/cheat_gui.cpp index be931e6c1a..19914da905 100644 --- a/src/cheat_gui.cpp +++ b/src/cheat_gui.cpp @@ -98,22 +98,27 @@ extern void EnginesMonthlyLoop(); /** * Handle changing of the current year. - * @param new_value Unused. + * @param new_value The chosen year to change to. * @param change_direction +1 (increase) or -1 (decrease). * @return New year. */ static int32 ClickChangeDateCheat(int32 new_value, int32 change_direction) { - YearMonthDay ymd; - ConvertDateToYMD(_date, &ymd); - + /* Don't allow changing to an invalid year, or the current year. */ new_value = Clamp(new_value, MIN_YEAR, MAX_YEAR); if (new_value == _cur_year) return _cur_year; + YearMonthDay ymd; + ConvertDateToYMD(_date, &ymd); Date new_date = ConvertYMDToDate(new_value, ymd.month, ymd.day); + + /* Change the date. */ + SetDate(new_date, _date_fract); + + /* Shift cached dates. */ for (auto v : Vehicle::Iterate()) v->ShiftDates(new_date - _date); LinkGraphSchedule::instance.ShiftDates(new_date - _date); - SetDate(new_date, _date_fract); + EnginesMonthlyLoop(); SetWindowDirty(WC_STATUS_BAR, 0); InvalidateWindowClassesData(WC_BUILD_STATION, 0); From 3f811246b1d541d6695b906482a5f29565ce919c Mon Sep 17 00:00:00 2001 From: Peter Nelson Date: Sun, 23 Apr 2023 12:58:05 +0100 Subject: [PATCH 04/27] Codechange: Rename control_point_t to ControlPoint. The _t suffix is reserved by POSIX 1003.1. --- src/tgp.cpp | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/src/tgp.cpp b/src/tgp.cpp index 863fb60327..b7f543b495 100644 --- a/src/tgp.cpp +++ b/src/tgp.cpp @@ -549,24 +549,24 @@ static void HeightMapCurves(uint level) height_t mh = TGPGetMaxHeight() - I2H(1); // height levels above sea level only /** Basically scale height X to height Y. Everything in between is interpolated. */ - struct control_point_t { + struct ControlPoint { height_t x; ///< The height to scale from. height_t y; ///< The height to scale to. }; /* Scaled curve maps; value is in height_ts. */ #define F(fraction) ((height_t)(fraction * mh)) - const control_point_t curve_map_1[] = { { F(0.0), F(0.0) }, { F(0.8), F(0.13) }, { F(1.0), F(0.4) } }; - const control_point_t curve_map_2[] = { { F(0.0), F(0.0) }, { F(0.53), F(0.13) }, { F(0.8), F(0.27) }, { F(1.0), F(0.6) } }; - const control_point_t curve_map_3[] = { { F(0.0), F(0.0) }, { F(0.53), F(0.27) }, { F(0.8), F(0.57) }, { F(1.0), F(0.8) } }; - const control_point_t curve_map_4[] = { { F(0.0), F(0.0) }, { F(0.4), F(0.3) }, { F(0.7), F(0.8) }, { F(0.92), F(0.99) }, { F(1.0), F(0.99) } }; + const ControlPoint curve_map_1[] = { { F(0.0), F(0.0) }, { F(0.8), F(0.13) }, { F(1.0), F(0.4) } }; + const ControlPoint curve_map_2[] = { { F(0.0), F(0.0) }, { F(0.53), F(0.13) }, { F(0.8), F(0.27) }, { F(1.0), F(0.6) } }; + const ControlPoint curve_map_3[] = { { F(0.0), F(0.0) }, { F(0.53), F(0.27) }, { F(0.8), F(0.57) }, { F(1.0), F(0.8) } }; + const ControlPoint curve_map_4[] = { { F(0.0), F(0.0) }, { F(0.4), F(0.3) }, { F(0.7), F(0.8) }, { F(0.92), F(0.99) }, { F(1.0), F(0.99) } }; #undef F /** Helper structure to index the different curve maps. */ - struct control_point_list_t { - size_t length; ///< The length of the curve map. - const control_point_t *list; ///< The actual curve map. + struct ControlPointList { + size_t length; ///< The length of the curve map. + const ControlPoint *list; ///< The actual curve map. }; - const control_point_list_t curve_maps[] = { + static const ControlPointList curve_maps[] = { { lengthof(curve_map_1), curve_map_1 }, { lengthof(curve_map_2), curve_map_2 }, { lengthof(curve_map_3), curve_map_3 }, @@ -647,10 +647,10 @@ static void HeightMapCurves(uint level) if (!HasBit(corner_bits, t)) continue; [[maybe_unused]] bool found = false; - const control_point_t *cm = curve_maps[t].list; + const ControlPoint *cm = curve_maps[t].list; for (uint i = 0; i < curve_maps[t].length - 1; i++) { - const control_point_t &p1 = cm[i]; - const control_point_t &p2 = cm[i + 1]; + const ControlPoint &p1 = cm[i]; + const ControlPoint &p2 = cm[i + 1]; if (*h >= p1.x && *h < p2.x) { ht[t] = p1.y + (*h - p1.x) * (p2.y - p1.y) / (p2.x - p1.x); From c3cea45ebc3d123d1ec92fcd6422f50942fbdb02 Mon Sep 17 00:00:00 2001 From: Peter Nelson Date: Sun, 23 Apr 2023 13:05:24 +0100 Subject: [PATCH 05/27] Codechange: Rename height_t/amplitude_t to Height/Amplitude. --- src/tgp.cpp | 104 ++++++++++++++++++++++++++-------------------------- 1 file changed, 52 insertions(+), 52 deletions(-) diff --git a/src/tgp.cpp b/src/tgp.cpp index b7f543b495..931c2cc117 100644 --- a/src/tgp.cpp +++ b/src/tgp.cpp @@ -151,17 +151,17 @@ */ /** Fixed point type for heights */ -typedef int16 height_t; +using Height = int16; static const int height_decimal_bits = 4; /** Fixed point array for amplitudes (and percent values) */ -typedef int amplitude_t; +using Amplitude = int; static const int amplitude_decimal_bits = 10; /** Height map - allocated array of heights (MapSizeX() + 1) x (MapSizeY() + 1) */ struct HeightMap { - std::vector h; //< array of heights + std::vector h; //< array of heights /* Even though the sizes are always positive, there are many cases where * X and Y need to be signed integers due to subtractions. */ int dim_x; //< height map size_x Map::SizeX() + 1 @@ -174,7 +174,7 @@ struct HeightMap * @param y Y position * @return height as fixed point number */ - inline height_t &height(uint x, uint y) + inline Height &height(uint x, uint y) { return h[x + y * dim_x]; } @@ -183,24 +183,24 @@ struct HeightMap /** Global height map instance */ static HeightMap _height_map = { {}, 0, 0, 0 }; -/** Conversion: int to height_t */ +/** Conversion: int to Height */ #define I2H(i) ((i) << height_decimal_bits) -/** Conversion: height_t to int */ +/** Conversion: Height to int */ #define H2I(i) ((i) >> height_decimal_bits) -/** Conversion: int to amplitude_t */ +/** Conversion: int to Amplitude */ #define I2A(i) ((i) << amplitude_decimal_bits) -/** Conversion: amplitude_t to int */ +/** Conversion: Amplitude to int */ #define A2I(i) ((i) >> amplitude_decimal_bits) -/** Conversion: amplitude_t to height_t */ +/** Conversion: Amplitude to Height */ #define A2H(a) ((a) >> (amplitude_decimal_bits - height_decimal_bits)) /** Maximum number of TGP noise frequencies. */ static const int MAX_TGP_FREQUENCIES = 10; /** Desired water percentage (100% == 1024) - indexed by _settings_game.difficulty.quantity_sea_lakes */ -static const amplitude_t _water_percent[4] = {70, 170, 270, 420}; +static const Amplitude _water_percent[4] = {70, 170, 270, 420}; /** * Gets the maximum allowed height while generating a map based on @@ -208,7 +208,7 @@ static const amplitude_t _water_percent[4] = {70, 170, 270, 420}; * @return The maximum height for the map generation. * @note Values should never be lower than 3 since the minimum snowline height is 2. */ -static height_t TGPGetMaxHeight() +static Height TGPGetMaxHeight() { if (_settings_game.difficulty.terrain_type == CUSTOM_TERRAIN_TYPE_NUMBER_DIFFICULTY) { /* TGP never reaches this height; this means that if a user inputs "2", @@ -261,10 +261,10 @@ uint GetEstimationTGPMapHeight() * @param frequency The frequency to get the amplitudes for * @return The amplitudes to apply to the map. */ -static amplitude_t GetAmplitude(int frequency) +static Amplitude GetAmplitude(int frequency) { /* Base noise amplitudes (multiplied by 1024) and indexed by "smoothness setting" and log2(frequency). */ - static const amplitude_t amplitudes[][7] = { + static const Amplitude amplitudes[][7] = { /* lowest frequency ...... highest (every corner) */ {16000, 5600, 1968, 688, 240, 16, 16}, ///< Very smooth {24000, 12800, 6400, 2700, 1024, 128, 16}, ///< Smooth @@ -287,14 +287,14 @@ static amplitude_t GetAmplitude(int frequency) /* Get the table index, and return that value if possible. */ int index = frequency - MAX_TGP_FREQUENCIES + lengthof(amplitudes[smoothness]); - amplitude_t amplitude = amplitudes[smoothness][std::max(0, index)]; + Amplitude amplitude = amplitudes[smoothness][std::max(0, index)]; if (index >= 0) return amplitude; /* We need to extrapolate the amplitude. */ double extrapolation_factor = extrapolation_factors[smoothness]; int height_range = I2H(16); do { - amplitude = (amplitude_t)(extrapolation_factor * (double)amplitude); + amplitude = (Amplitude)(extrapolation_factor * (double)amplitude); height_range <<= 1; index++; } while (index < 0); @@ -344,7 +344,7 @@ static inline void FreeHeightMap() * @param rMax Limit of result * @return generated height */ -static inline height_t RandomHeight(amplitude_t rMax) +static inline Height RandomHeight(Amplitude rMax) { /* Spread height into range -rMax..+rMax */ return A2H(RandomRange(2 * rMax + 1) - rMax); @@ -366,7 +366,7 @@ static void HeightMapGenerate() bool first = true; for (int frequency = start; frequency < MAX_TGP_FREQUENCIES; frequency++) { - const amplitude_t amplitude = GetAmplitude(frequency); + const Amplitude amplitude = GetAmplitude(frequency); /* Ignore zero amplitudes; it means our map isn't height enough for this * amplitude, so ignore it and continue with the next set of amplitude. */ @@ -378,7 +378,7 @@ static void HeightMapGenerate() /* This is first round, we need to establish base heights with step = size_min */ for (int y = 0; y <= _height_map.size_y; y += step) { for (int x = 0; x <= _height_map.size_x; x += step) { - height_t height = (amplitude > 0) ? RandomHeight(amplitude) : 0; + Height height = (amplitude > 0) ? RandomHeight(amplitude) : 0; _height_map.height(x, y) = height; } } @@ -390,9 +390,9 @@ static void HeightMapGenerate() * Interpolate height values at odd x, even y tiles */ for (int y = 0; y <= _height_map.size_y; y += 2 * step) { for (int x = 0; x <= _height_map.size_x - 2 * step; x += 2 * step) { - height_t h00 = _height_map.height(x + 0 * step, y); - height_t h02 = _height_map.height(x + 2 * step, y); - height_t h01 = (h00 + h02) / 2; + Height h00 = _height_map.height(x + 0 * step, y); + Height h02 = _height_map.height(x + 2 * step, y); + Height h01 = (h00 + h02) / 2; _height_map.height(x + 1 * step, y) = h01; } } @@ -400,9 +400,9 @@ static void HeightMapGenerate() /* Interpolate height values at odd y tiles */ for (int y = 0; y <= _height_map.size_y - 2 * step; y += 2 * step) { for (int x = 0; x <= _height_map.size_x; x += step) { - height_t h00 = _height_map.height(x, y + 0 * step); - height_t h20 = _height_map.height(x, y + 2 * step); - height_t h10 = (h00 + h20) / 2; + Height h00 = _height_map.height(x, y + 0 * step); + Height h20 = _height_map.height(x, y + 2 * step); + Height h10 = (h00 + h20) / 2; _height_map.height(x, y + 1 * step) = h10; } } @@ -417,21 +417,21 @@ static void HeightMapGenerate() } /** Returns min, max and average height from height map */ -static void HeightMapGetMinMaxAvg(height_t *min_ptr, height_t *max_ptr, height_t *avg_ptr) +static void HeightMapGetMinMaxAvg(Height *min_ptr, Height *max_ptr, Height *avg_ptr) { - height_t h_min, h_max, h_avg; + Height h_min, h_max, h_avg; int64 h_accu = 0; h_min = h_max = _height_map.height(0, 0); /* Get h_min, h_max and accumulate heights into h_accu */ - for (const height_t &h : _height_map.h) { + for (const Height &h : _height_map.h) { if (h < h_min) h_min = h; if (h > h_max) h_max = h; h_accu += h; } /* Get average height */ - h_avg = (height_t)(h_accu / (_height_map.size_x * _height_map.size_y)); + h_avg = (Height)(h_accu / (_height_map.size_x * _height_map.size_y)); /* Return required results */ if (min_ptr != nullptr) *min_ptr = h_min; @@ -440,12 +440,12 @@ static void HeightMapGetMinMaxAvg(height_t *min_ptr, height_t *max_ptr, height_t } /** Dill histogram and return pointer to its base point - to the count of zero heights */ -static int *HeightMapMakeHistogram(height_t h_min, height_t h_max, int *hist_buf) +static int *HeightMapMakeHistogram(Height h_min, Height h_max, int *hist_buf) { int *hist = hist_buf - h_min; /* Count the heights and fill the histogram */ - for (const height_t &h : _height_map.h){ + for (const Height &h : _height_map.h){ assert(h >= h_min); assert(h <= h_max); hist[h]++; @@ -454,9 +454,9 @@ static int *HeightMapMakeHistogram(height_t h_min, height_t h_max, int *hist_buf } /** Applies sine wave redistribution onto height map */ -static void HeightMapSineTransform(height_t h_min, height_t h_max) +static void HeightMapSineTransform(Height h_min, Height h_max) { - for (height_t &h : _height_map.h) { + for (Height &h : _height_map.h) { double fheight; if (h < h_min) continue; @@ -522,7 +522,7 @@ static void HeightMapSineTransform(height_t h_min, height_t h_max) break; } /* Transform it back into h_min..h_max space */ - h = (height_t)(fheight * (h_max - h_min) + h_min); + h = (Height)(fheight * (h_max - h_min) + h_min); if (h < 0) h = I2H(0); if (h >= h_max) h = h_max - 1; } @@ -546,15 +546,15 @@ static void HeightMapSineTransform(height_t h_min, height_t h_max) */ static void HeightMapCurves(uint level) { - height_t mh = TGPGetMaxHeight() - I2H(1); // height levels above sea level only + Height mh = TGPGetMaxHeight() - I2H(1); // height levels above sea level only /** Basically scale height X to height Y. Everything in between is interpolated. */ struct ControlPoint { - height_t x; ///< The height to scale from. - height_t y; ///< The height to scale to. + Height x; ///< The height to scale from. + Height y; ///< The height to scale to. }; /* Scaled curve maps; value is in height_ts. */ -#define F(fraction) ((height_t)(fraction * mh)) +#define F(fraction) ((Height)(fraction * mh)) const ControlPoint curve_map_1[] = { { F(0.0), F(0.0) }, { F(0.8), F(0.13) }, { F(1.0), F(0.4) } }; const ControlPoint curve_map_2[] = { { F(0.0), F(0.0) }, { F(0.53), F(0.13) }, { F(0.8), F(0.27) }, { F(1.0), F(0.6) } }; const ControlPoint curve_map_3[] = { { F(0.0), F(0.0) }, { F(0.53), F(0.27) }, { F(0.8), F(0.57) }, { F(1.0), F(0.8) } }; @@ -573,7 +573,7 @@ static void HeightMapCurves(uint level) { lengthof(curve_map_4), curve_map_4 }, }; - height_t ht[lengthof(curve_maps)]; + Height ht[lengthof(curve_maps)]; MemSetT(ht, 0, lengthof(ht)); /* Set up a grid to choose curve maps based on location; attempt to get a somewhat square grid */ @@ -634,7 +634,7 @@ static void HeightMapCurves(uint level) corner_bits |= 1 << corner_c; corner_bits |= 1 << corner_d; - height_t *h = &_height_map.height(x, y); + Height *h = &_height_map.height(x, y); /* Do not touch sea level */ if (*h < I2H(1)) continue; @@ -664,7 +664,7 @@ static void HeightMapCurves(uint level) } /* Apply interpolation of curve map results. */ - *h = (height_t)((ht[corner_a] * yri + ht[corner_b] * yr) * xri + (ht[corner_c] * yri + ht[corner_d] * yr) * xr); + *h = (Height)((ht[corner_a] * yri + ht[corner_b] * yr) * xri + (ht[corner_c] * yri + ht[corner_d] * yr) * xr); /* Readd sea level */ *h += I2H(1); @@ -673,9 +673,9 @@ static void HeightMapCurves(uint level) } /** Adjusts heights in height map to contain required amount of water tiles */ -static void HeightMapAdjustWaterLevel(amplitude_t water_percent, height_t h_max_new) +static void HeightMapAdjustWaterLevel(Amplitude water_percent, Height h_max_new) { - height_t h_min, h_max, h_avg, h_water_level; + Height h_min, h_max, h_avg, h_water_level; int64 water_tiles, desired_water_tiles; int *hist; @@ -701,9 +701,9 @@ static void HeightMapAdjustWaterLevel(amplitude_t water_percent, height_t h_max_ * values from range: h_water_level..h_max are transformed into 0..h_max_new * where h_max_new is depending on terrain type and map size. */ - for (height_t &h : _height_map.h) { + for (Height &h : _height_map.h) { /* Transform height from range h_water_level..h_max into 0..h_max_new range */ - h = (height_t)(((int)h_max_new) * (h - h_water_level) / (h_max - h_water_level)) + I2H(1); + h = (Height)(((int)h_max_new) * (h - h_water_level) / (h_max - h_water_level)) + I2H(1); /* Make sure all values are in the proper range (0..h_max_new) */ if (h < 0) h = I2H(0); if (h >= h_max_new) h = h_max_new - 1; @@ -799,8 +799,8 @@ static void HeightMapSmoothCoastInDirection(int org_x, int org_y, int dir_x, int int ed; // coast distance from edge int depth; - height_t h_prev = I2H(1); - height_t h; + Height h_prev = I2H(1); + Height h; assert(IsValidXY(org_x, org_y)); @@ -849,17 +849,17 @@ static void HeightMapSmoothCoasts(uint8 water_borders) * the most it can change is one level. When OTTD can support cliffs, this * routine may not be necessary. */ -static void HeightMapSmoothSlopes(height_t dh_max) +static void HeightMapSmoothSlopes(Height dh_max) { for (int y = 0; y <= (int)_height_map.size_y; y++) { for (int x = 0; x <= (int)_height_map.size_x; x++) { - height_t h_max = std::min(_height_map.height(x > 0 ? x - 1 : x, y), _height_map.height(x, y > 0 ? y - 1 : y)) + dh_max; + Height h_max = std::min(_height_map.height(x > 0 ? x - 1 : x, y), _height_map.height(x, y > 0 ? y - 1 : y)) + dh_max; if (_height_map.height(x, y) > h_max) _height_map.height(x, y) = h_max; } } for (int y = _height_map.size_y; y >= 0; y--) { for (int x = _height_map.size_x; x >= 0; x--) { - height_t h_max = std::min(_height_map.height(x < _height_map.size_x ? x + 1 : x, y), _height_map.height(x, y < _height_map.size_y ? y + 1 : y)) + dh_max; + Height h_max = std::min(_height_map.height(x < _height_map.size_x ? x + 1 : x, y), _height_map.height(x, y < _height_map.size_y ? y + 1 : y)) + dh_max; if (_height_map.height(x, y) > h_max) _height_map.height(x, y) = h_max; } } @@ -875,9 +875,9 @@ static void HeightMapSmoothSlopes(height_t dh_max) static void HeightMapNormalize() { int sea_level_setting = _settings_game.difficulty.quantity_sea_lakes; - const amplitude_t water_percent = sea_level_setting != (int)CUSTOM_SEA_LEVEL_NUMBER_DIFFICULTY ? _water_percent[sea_level_setting] : _settings_game.game_creation.custom_sea_level * 1024 / 100; - const height_t h_max_new = TGPGetMaxHeight(); - const height_t roughness = 7 + 3 * _settings_game.game_creation.tgen_smoothness; + const Amplitude water_percent = sea_level_setting != (int)CUSTOM_SEA_LEVEL_NUMBER_DIFFICULTY ? _water_percent[sea_level_setting] : _settings_game.game_creation.custom_sea_level * 1024 / 100; + const Height h_max_new = TGPGetMaxHeight(); + const Height roughness = 7 + 3 * _settings_game.game_creation.tgen_smoothness; HeightMapAdjustWaterLevel(water_percent, h_max_new); From 9f26e74e1e112fe290f650617a7e0eaad14088fb Mon Sep 17 00:00:00 2001 From: Peter Nelson Date: Sun, 23 Apr 2023 13:56:25 +0100 Subject: [PATCH 06/27] Codechange: Rename item_t to Item. --- src/misc/dbg_helpers.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/misc/dbg_helpers.h b/src/misc/dbg_helpers.h index 53033110d8..b807ef25f1 100644 --- a/src/misc/dbg_helpers.h +++ b/src/misc/dbg_helpers.h @@ -25,7 +25,7 @@ template struct ArrayT; /** Helper template class that provides C array length and item type */ template struct ArrayT { static const size_t length = N; - typedef T item_t; + using Item = T; }; @@ -34,7 +34,7 @@ template struct ArrayT { * or t_unk when index is out of bounds. */ template -inline typename ArrayT::item_t ItemAtT(E idx, const T &t, typename ArrayT::item_t t_unk) +inline typename ArrayT::Item ItemAtT(E idx, const T &t, typename ArrayT::Item t_unk) { if ((size_t)idx >= ArrayT::length) { return t_unk; @@ -48,7 +48,7 @@ inline typename ArrayT::item_t ItemAtT(E idx, const T &t, typename ArrayT: * or t_unk when index is out of bounds. */ template -inline typename ArrayT::item_t ItemAtT(E idx, const T &t, typename ArrayT::item_t t_unk, E idx_inv, typename ArrayT::item_t t_inv) +inline typename ArrayT::Item ItemAtT(E idx, const T &t, typename ArrayT::Item t_unk, E idx_inv, typename ArrayT::Item t_inv) { if ((size_t)idx < ArrayT::length) { return t[idx]; From 075671bcfccba8aed73763becc5f677d3da44324 Mon Sep 17 00:00:00 2001 From: Peter Nelson Date: Mon, 24 Apr 2023 08:08:11 +0100 Subject: [PATCH 07/27] Codechange: Rename DECLARE_ENUM_AS_BIT_SET parameter to enum_type. It works on enums not masks. --- src/core/enum_type.hpp | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/core/enum_type.hpp b/src/core/enum_type.hpp index 273a5b077e..c5e2945802 100644 --- a/src/core/enum_type.hpp +++ b/src/core/enum_type.hpp @@ -28,14 +28,14 @@ /** Operators to allow to work with enum as with type safe bit set in C++ */ -# define DECLARE_ENUM_AS_BIT_SET(mask_t) \ - inline constexpr mask_t operator | (mask_t m1, mask_t m2) {return (mask_t)((std::underlying_type::type)m1 | (std::underlying_type::type)m2);} \ - inline constexpr mask_t operator & (mask_t m1, mask_t m2) {return (mask_t)((std::underlying_type::type)m1 & (std::underlying_type::type)m2);} \ - inline constexpr mask_t operator ^ (mask_t m1, mask_t m2) {return (mask_t)((std::underlying_type::type)m1 ^ (std::underlying_type::type)m2);} \ - inline constexpr mask_t& operator |= (mask_t& m1, mask_t m2) {m1 = m1 | m2; return m1;} \ - inline constexpr mask_t& operator &= (mask_t& m1, mask_t m2) {m1 = m1 & m2; return m1;} \ - inline constexpr mask_t& operator ^= (mask_t& m1, mask_t m2) {m1 = m1 ^ m2; return m1;} \ - inline constexpr mask_t operator ~(mask_t m) {return (mask_t)(~(std::underlying_type::type)m);} +#define DECLARE_ENUM_AS_BIT_SET(enum_type) \ + inline constexpr enum_type operator | (enum_type m1, enum_type m2) {return (enum_type)((std::underlying_type::type)m1 | (std::underlying_type::type)m2);} \ + inline constexpr enum_type operator & (enum_type m1, enum_type m2) {return (enum_type)((std::underlying_type::type)m1 & (std::underlying_type::type)m2);} \ + inline constexpr enum_type operator ^ (enum_type m1, enum_type m2) {return (enum_type)((std::underlying_type::type)m1 ^ (std::underlying_type::type)m2);} \ + inline constexpr enum_type& operator |= (enum_type& m1, enum_type m2) {m1 = m1 | m2; return m1;} \ + inline constexpr enum_type& operator &= (enum_type& m1, enum_type m2) {m1 = m1 & m2; return m1;} \ + inline constexpr enum_type& operator ^= (enum_type& m1, enum_type m2) {m1 = m1 ^ m2; return m1;} \ + inline constexpr enum_type operator ~(enum_type m) {return (enum_type)(~(std::underlying_type::type)m);} #endif /* ENUM_TYPE_HPP */ From 8b93e45e22a8e9900d77321da5629588a510f9a5 Mon Sep 17 00:00:00 2001 From: Rubidium Date: Wed, 19 Apr 2023 07:04:43 +0200 Subject: [PATCH 08/27] Codechange: use string/fmt instead of printf for squirrel's PRINTFUNC --- src/3rdparty/squirrel/include/squirrel.h | 2 +- src/3rdparty/squirrel/sqstdlib/sqstdaux.cpp | 39 ++++++++--------- src/3rdparty/squirrel/squirrel/sqbaselib.cpp | 2 +- src/3rdparty/squirrel/squirrel/sqcompiler.cpp | 19 ++++----- src/script/script_instance.cpp | 4 +- src/script/squirrel.cpp | 42 ++++++------------- src/script/squirrel.hpp | 6 +-- 7 files changed, 47 insertions(+), 67 deletions(-) diff --git a/src/3rdparty/squirrel/include/squirrel.h b/src/3rdparty/squirrel/include/squirrel.h index 87e0ac0d69..0c3f608952 100644 --- a/src/3rdparty/squirrel/include/squirrel.h +++ b/src/3rdparty/squirrel/include/squirrel.h @@ -174,7 +174,7 @@ typedef SQObject HSQOBJECT; typedef SQInteger (*SQFUNCTION)(HSQUIRRELVM); typedef SQInteger (*SQRELEASEHOOK)(SQUserPointer,SQInteger size); typedef void (*SQCOMPILERERROR)(HSQUIRRELVM,const SQChar * /*desc*/,const SQChar * /*source*/,SQInteger /*line*/,SQInteger /*column*/); -typedef void (*SQPRINTFUNCTION)(HSQUIRRELVM,const SQChar * ,...); +typedef void (*SQPRINTFUNCTION)(HSQUIRRELVM,const std::string &); typedef SQInteger (*SQWRITEFUNC)(SQUserPointer,SQUserPointer,SQInteger); typedef SQInteger (*SQREADFUNC)(SQUserPointer,SQUserPointer,SQInteger); diff --git a/src/3rdparty/squirrel/sqstdlib/sqstdaux.cpp b/src/3rdparty/squirrel/sqstdlib/sqstdaux.cpp index 4eaa2cb3cd..1bdee97e69 100644 --- a/src/3rdparty/squirrel/sqstdlib/sqstdaux.cpp +++ b/src/3rdparty/squirrel/sqstdlib/sqstdaux.cpp @@ -5,6 +5,7 @@ #include #include +#include "../../fmt/format.h" #include "../../../safeguards.h" void sqstd_printcallstack(HSQUIRRELVM v) @@ -38,7 +39,7 @@ void sqstd_printcallstack(HSQUIRRELVM v) src = si.source; } } - pf(v,"*FUNCTION [%s()] %s line [" OTTD_PRINTF64 "]\n",fn,src,si.line); + pf(v,fmt::format("*FUNCTION [{}()] {} line [{}]\n",fn,src,si.line)); level++; } level=0; @@ -52,56 +53,56 @@ void sqstd_printcallstack(HSQUIRRELVM v) switch(sq_gettype(v,-1)) { case OT_NULL: - pf(v,"[%s] NULL\n",name); + pf(v,fmt::format("[{}] NULL\n",name)); break; case OT_INTEGER: sq_getinteger(v,-1,&i); - pf(v,"[%s] " OTTD_PRINTF64 "\n",name,i); + pf(v,fmt::format("[{}] {}\n",name,i)); break; case OT_FLOAT: sq_getfloat(v,-1,&f); - pf(v,"[%s] %.14g\n",name,f); + pf(v,fmt::format("[{}] {:14g}\n",name,f)); break; case OT_USERPOINTER: - pf(v,"[%s] USERPOINTER\n",name); + pf(v,fmt::format("[{}] USERPOINTER\n",name)); break; case OT_STRING: sq_getstring(v,-1,&s); - pf(v,"[%s] \"%s\"\n",name,s); + pf(v,fmt::format("[{}] \"{}\"\n",name,s)); break; case OT_TABLE: - pf(v,"[%s] TABLE\n",name); + pf(v,fmt::format("[{}] TABLE\n",name)); break; case OT_ARRAY: - pf(v,"[%s] ARRAY\n",name); + pf(v,fmt::format("[{}] ARRAY\n",name)); break; case OT_CLOSURE: - pf(v,"[%s] CLOSURE\n",name); + pf(v,fmt::format("[{}] CLOSURE\n",name)); break; case OT_NATIVECLOSURE: - pf(v,"[%s] NATIVECLOSURE\n",name); + pf(v,fmt::format("[{}] NATIVECLOSURE\n",name)); break; case OT_GENERATOR: - pf(v,"[%s] GENERATOR\n",name); + pf(v,fmt::format("[{}] GENERATOR\n",name)); break; case OT_USERDATA: - pf(v,"[%s] USERDATA\n",name); + pf(v,fmt::format("[{}] USERDATA\n",name)); break; case OT_THREAD: - pf(v,"[%s] THREAD\n",name); + pf(v,fmt::format("[{}] THREAD\n",name)); break; case OT_CLASS: - pf(v,"[%s] CLASS\n",name); + pf(v,fmt::format("[{}] CLASS\n",name)); break; case OT_INSTANCE: - pf(v,"[%s] INSTANCE\n",name); + pf(v,fmt::format("[{}] INSTANCE\n",name)); break; case OT_WEAKREF: - pf(v,"[%s] WEAKREF\n",name); + pf(v,fmt::format("[{}] WEAKREF\n",name)); break; case OT_BOOL:{ sq_getbool(v,-1,&b); - pf(v,"[%s] %s\n",name,b?"true":"false"); + pf(v,fmt::format("[{}] {}\n",name,b?"true":"false")); } break; default: assert(0); break; @@ -119,7 +120,7 @@ static SQInteger _sqstd_aux_printerror(HSQUIRRELVM v) const SQChar *sErr = nullptr; if(sq_gettop(v)>=1) { if(SQ_SUCCEEDED(sq_getstring(v,2,&sErr))) { - pf(v,"\nAN ERROR HAS OCCURRED [%s]\n",sErr); + pf(v,fmt::format("\nAN ERROR HAS OCCURRED [{}]\n",sErr)); } else{ pf(v,"\nAN ERROR HAS OCCURRED [unknown]\n"); @@ -134,7 +135,7 @@ void _sqstd_compiler_error(HSQUIRRELVM v,const SQChar *sErr,const SQChar *sSourc { SQPRINTFUNCTION pf = sq_getprintfunc(v); if(pf) { - pf(v,"%s line = (" OTTD_PRINTF64 ") column = (" OTTD_PRINTF64 ") : error %s\n",sSource,line,column,sErr); + pf(v,fmt::format("{} line = ({}) column = ({}) : error {}\n",sSource,line,column,sErr)); } } diff --git a/src/3rdparty/squirrel/squirrel/sqbaselib.cpp b/src/3rdparty/squirrel/squirrel/sqbaselib.cpp index c542ee5a47..7ec370ca6c 100644 --- a/src/3rdparty/squirrel/squirrel/sqbaselib.cpp +++ b/src/3rdparty/squirrel/squirrel/sqbaselib.cpp @@ -172,7 +172,7 @@ static SQInteger base_print(HSQUIRRELVM v) const SQChar *str; sq_tostring(v,2); sq_getstring(v,-1,&str); - if(_ss(v)->_printfunc) _ss(v)->_printfunc(v,"%s",str); + if(_ss(v)->_printfunc) _ss(v)->_printfunc(v,str); return 0; } diff --git a/src/3rdparty/squirrel/squirrel/sqcompiler.cpp b/src/3rdparty/squirrel/squirrel/sqcompiler.cpp index 9ba1597120..649de6372d 100644 --- a/src/3rdparty/squirrel/squirrel/sqcompiler.cpp +++ b/src/3rdparty/squirrel/squirrel/sqcompiler.cpp @@ -4,6 +4,8 @@ #include "../../../stdafx.h" +#include "../../fmt/format.h" + #include #include "sqpcheader.h" #include @@ -65,16 +67,11 @@ public: } NORETURN static void ThrowError(void *ud, const SQChar *s) { SQCompiler *c = (SQCompiler *)ud; - c->Error("%s", s); + c->Error(s); } - NORETURN void Error(const SQChar *s, ...) WARN_FORMAT(2, 3) + NORETURN void Error(const std::string &msg) { - static SQChar temp[256]; - va_list vl; - va_start(vl, s); - vseprintf(temp, lastof(temp), s, vl); - va_end(vl); - throw temp; + throw msg; } void Lex(){ _token = _lex.Lex();} void PushExpState(){ _expstates.push_back(ExpState()); } @@ -120,9 +117,9 @@ public: default: etypename = _lex.Tok2Str(tok); } - Error("expected '%s'", etypename); + Error(fmt::format("expected '{}'", etypename)); } - Error("expected '%c'", (char)tok); + Error(fmt::format("expected '{:c}'", tok)); } } SQObjectPtr ret; @@ -647,7 +644,7 @@ public: Expect('.'); constid = Expect(TK_IDENTIFIER); if(!_table(constant)->Get(constid,constval)) { constval.Null(); - Error("invalid constant [%s.%s]", _stringval(id),_stringval(constid)); + Error(fmt::format("invalid constant [{}.{}]", _stringval(id),_stringval(constid))); } } else { diff --git a/src/script/script_instance.cpp b/src/script/script_instance.cpp index 18f8ef39b6..c6ab1d6008 100644 --- a/src/script/script_instance.cpp +++ b/src/script/script_instance.cpp @@ -44,10 +44,10 @@ ScriptStorage::~ScriptStorage() * @param error_msg Is this an error message? * @param message The actual message text. */ -static void PrintFunc(bool error_msg, const SQChar *message) +static void PrintFunc(bool error_msg, const std::string &message) { /* Convert to OpenTTD internal capable string */ - ScriptController::Print(error_msg, message); + ScriptController::Print(error_msg, message.c_str()); } ScriptInstance::ScriptInstance(const char *APIName) : diff --git a/src/script/squirrel.cpp b/src/script/squirrel.cpp index cd98739071..30d1a5945b 100644 --- a/src/script/squirrel.cpp +++ b/src/script/squirrel.cpp @@ -208,36 +208,27 @@ size_t Squirrel::GetAllocatedMemory() const noexcept void Squirrel::CompileError(HSQUIRRELVM vm, const SQChar *desc, const SQChar *source, SQInteger line, SQInteger column) { - SQChar buf[1024]; - - seprintf(buf, lastof(buf), "Error %s:" OTTD_PRINTF64 "/" OTTD_PRINTF64 ": %s", source, line, column, desc); + std::string msg = fmt::format("Error {}:{}/{}: {}", source, line, column, desc); /* Check if we have a custom print function */ Squirrel *engine = (Squirrel *)sq_getforeignptr(vm); engine->crashed = true; SQPrintFunc *func = engine->print_func; if (func == nullptr) { - Debug(misc, 0, "[Squirrel] Compile error: {}", buf); + Debug(misc, 0, "[Squirrel] Compile error: {}", msg); } else { - (*func)(true, buf); + (*func)(true, msg); } } -void Squirrel::ErrorPrintFunc(HSQUIRRELVM vm, const SQChar *s, ...) +void Squirrel::ErrorPrintFunc(HSQUIRRELVM vm, const std::string &s) { - va_list arglist; - SQChar buf[1024]; - - va_start(arglist, s); - vseprintf(buf, lastof(buf), s, arglist); - va_end(arglist); - /* Check if we have a custom print function */ SQPrintFunc *func = ((Squirrel *)sq_getforeignptr(vm))->print_func; if (func == nullptr) { - fprintf(stderr, "%s", buf); + fprintf(stderr, "%s", s.c_str()); } else { - (*func)(true, buf); + (*func)(true, s); } } @@ -248,14 +239,13 @@ void Squirrel::RunError(HSQUIRRELVM vm, const SQChar *error) sq_setprintfunc(vm, &Squirrel::ErrorPrintFunc); /* Check if we have a custom print function */ - SQChar buf[1024]; - seprintf(buf, lastof(buf), "Your script made an error: %s\n", error); + std::string msg = fmt::format("Your script made an error: {}\n", error); Squirrel *engine = (Squirrel *)sq_getforeignptr(vm); SQPrintFunc *func = engine->print_func; if (func == nullptr) { - fprintf(stderr, "%s", buf); + fprintf(stderr, "%s", msg.c_str()); } else { - (*func)(true, buf); + (*func)(true, msg); } /* Print below the error the stack, so the users knows what is happening */ @@ -279,22 +269,14 @@ SQInteger Squirrel::_RunError(HSQUIRRELVM vm) return 0; } -void Squirrel::PrintFunc(HSQUIRRELVM vm, const SQChar *s, ...) +void Squirrel::PrintFunc(HSQUIRRELVM vm, const std::string &s) { - va_list arglist; - SQChar buf[1024]; - - va_start(arglist, s); - vseprintf(buf, lastof(buf) - 2, s, arglist); - va_end(arglist); - strecat(buf, "\n", lastof(buf)); - /* Check if we have a custom print function */ SQPrintFunc *func = ((Squirrel *)sq_getforeignptr(vm))->print_func; if (func == nullptr) { - printf("%s", buf); + printf("%s", s.c_str()); } else { - (*func)(false, buf); + (*func)(false, s); } } diff --git a/src/script/squirrel.hpp b/src/script/squirrel.hpp index 4917ab2781..444e8a3a0d 100644 --- a/src/script/squirrel.hpp +++ b/src/script/squirrel.hpp @@ -24,7 +24,7 @@ class Squirrel { friend class ScriptAllocatorScope; private: - typedef void (SQPrintFunc)(bool error_msg, const SQChar *message); + typedef void (SQPrintFunc)(bool error_msg, const std::string &message); HSQUIRRELVM vm; ///< The VirtualMachine instance for squirrel void *global_pointer; ///< Can be set by who ever initializes Squirrel @@ -63,12 +63,12 @@ protected: /** * If a user runs 'print' inside a script, this function gets the params. */ - static void PrintFunc(HSQUIRRELVM vm, const SQChar *s, ...) WARN_FORMAT(2, 3); + static void PrintFunc(HSQUIRRELVM vm, const std::string &s); /** * If an error has to be print, this function is called. */ - static void ErrorPrintFunc(HSQUIRRELVM vm, const SQChar *s, ...) WARN_FORMAT(2, 3); + static void ErrorPrintFunc(HSQUIRRELVM vm, const std::string &s); public: Squirrel(const char *APIName); From 5733142b0d681f67810aa98eb1813c9a2ac4aff1 Mon Sep 17 00:00:00 2001 From: Rubidium Date: Wed, 19 Apr 2023 20:11:01 +0200 Subject: [PATCH 09/27] Codechange: use string/fmt instead of printf for Squirrel's Raise_Error --- src/3rdparty/squirrel/squirrel/sqapi.cpp | 3 +- src/3rdparty/squirrel/squirrel/sqbaselib.cpp | 3 +- src/3rdparty/squirrel/squirrel/sqcompiler.cpp | 1 - src/3rdparty/squirrel/squirrel/sqdebug.cpp | 18 +++----- src/3rdparty/squirrel/squirrel/sqobject.cpp | 5 ++- src/3rdparty/squirrel/squirrel/sqvm.cpp | 45 ++++++++++--------- src/3rdparty/squirrel/squirrel/sqvm.h | 2 +- 7 files changed, 37 insertions(+), 40 deletions(-) diff --git a/src/3rdparty/squirrel/squirrel/sqapi.cpp b/src/3rdparty/squirrel/squirrel/sqapi.cpp index 80c5d816e8..0be573bcc4 100644 --- a/src/3rdparty/squirrel/squirrel/sqapi.cpp +++ b/src/3rdparty/squirrel/squirrel/sqapi.cpp @@ -3,6 +3,7 @@ */ #include "../../../stdafx.h" +#include "../../fmt/format.h" #include #include "sqpcheader.h" @@ -26,7 +27,7 @@ bool sq_aux_gettypedarg(HSQUIRRELVM v,SQInteger idx,SQObjectType type,SQObjectPt *o = &stack_get(v,idx); if(type(**o) != type){ SQObjectPtr oval = v->PrintObjVal(**o); - v->Raise_Error("wrong argument type, expected '%s' got '%.50s'",IdType2Name(type),_stringval(oval)); + v->Raise_Error(fmt::format("wrong argument type, expected '{}' got '{:.50s}'",IdType2Name(type),_stringval(oval))); return false; } return true; diff --git a/src/3rdparty/squirrel/squirrel/sqbaselib.cpp b/src/3rdparty/squirrel/squirrel/sqbaselib.cpp index 7ec370ca6c..e69b28f27f 100644 --- a/src/3rdparty/squirrel/squirrel/sqbaselib.cpp +++ b/src/3rdparty/squirrel/squirrel/sqbaselib.cpp @@ -3,6 +3,7 @@ */ #include "../../../stdafx.h" +#include "../../fmt/format.h" #include "sqpcheader.h" #include "sqvm.h" @@ -214,7 +215,7 @@ static SQInteger base_array(HSQUIRRELVM v) SQInteger nInitialSize = tointeger(stack_get(v,2)); SQInteger ret = 1; if (nInitialSize < 0) { - v->Raise_Error("can't create/resize array with/to size " OTTD_PRINTF64, nInitialSize); + v->Raise_Error(fmt::format("can't create/resize array with/to size {}", nInitialSize)); nInitialSize = 0; ret = -1; } diff --git a/src/3rdparty/squirrel/squirrel/sqcompiler.cpp b/src/3rdparty/squirrel/squirrel/sqcompiler.cpp index 649de6372d..5dd6ae733e 100644 --- a/src/3rdparty/squirrel/squirrel/sqcompiler.cpp +++ b/src/3rdparty/squirrel/squirrel/sqcompiler.cpp @@ -3,7 +3,6 @@ */ #include "../../../stdafx.h" - #include "../../fmt/format.h" #include diff --git a/src/3rdparty/squirrel/squirrel/sqdebug.cpp b/src/3rdparty/squirrel/squirrel/sqdebug.cpp index 44f767c297..46ffb3131e 100644 --- a/src/3rdparty/squirrel/squirrel/sqdebug.cpp +++ b/src/3rdparty/squirrel/squirrel/sqdebug.cpp @@ -3,6 +3,7 @@ */ #include "../../../stdafx.h" +#include "../../fmt/format.h" #include #include "sqpcheader.h" @@ -63,16 +64,9 @@ SQRESULT sq_stackinfos(HSQUIRRELVM v, SQInteger level, SQStackInfos *si) return SQ_ERROR; } -void SQVM::Raise_Error(const SQChar *s, ...) +void SQVM::Raise_Error(const std::string &msg) { - va_list vl; - va_start(vl, s); - size_t len = strlen(s)+(NUMBER_MAX_CHAR*2); - char *buffer = MallocT(len + 1); - vseprintf(buffer, buffer + len, s, vl); - va_end(vl); - _lasterror = SQString::Create(_ss(this),buffer,-1); - free(buffer); + _lasterror = SQString::Create(_ss(this),msg.c_str(),-1); } void SQVM::Raise_Error(SQObjectPtr &desc) @@ -99,13 +93,13 @@ SQString *SQVM::PrintObjVal(const SQObject &o) void SQVM::Raise_IdxError(const SQObject &o) { SQObjectPtr oval = PrintObjVal(o); - Raise_Error("the index '%.50s' does not exist", _stringval(oval)); + Raise_Error(fmt::format("the index '{:.50s}' does not exist", _stringval(oval))); } void SQVM::Raise_CompareError(const SQObject &o1, const SQObject &o2) { SQObjectPtr oval1 = PrintObjVal(o1), oval2 = PrintObjVal(o2); - Raise_Error("comparison between '%.50s' and '%.50s'", _stringval(oval1), _stringval(oval2)); + Raise_Error(fmt::format("comparison between '{:.50s}' and '{:.50s}'", _stringval(oval1), _stringval(oval2))); } @@ -122,5 +116,5 @@ void SQVM::Raise_ParamTypeError(SQInteger nparam,SQInteger typemask,SQInteger ty StringCat(exptypes,SQString::Create(_ss(this), IdType2Name((SQObjectType)mask), -1), exptypes); } } - Raise_Error("parameter " OTTD_PRINTF64 " has an invalid type '%s' ; expected: '%s'", nparam, IdType2Name((SQObjectType)type), _stringval(exptypes)); + Raise_Error(fmt::format("parameter {} has an invalid type '{}' ; expected: '{}'", nparam, IdType2Name((SQObjectType)type), _stringval(exptypes))); } diff --git a/src/3rdparty/squirrel/squirrel/sqobject.cpp b/src/3rdparty/squirrel/squirrel/sqobject.cpp index ca105fd5ef..a0f9c75363 100644 --- a/src/3rdparty/squirrel/squirrel/sqobject.cpp +++ b/src/3rdparty/squirrel/squirrel/sqobject.cpp @@ -3,6 +3,7 @@ */ #include "../../../stdafx.h" +#include "../../fmt/format.h" #include "sqpcheader.h" #include "sqvm.h" @@ -283,7 +284,7 @@ bool WriteObject(HSQUIRRELVM v,SQUserPointer up,SQWRITEFUNC write,SQObjectPtr &o case OT_NULL: break; default: - v->Raise_Error("cannot serialize a %s",GetTypeName(o)); + v->Raise_Error(fmt::format("cannot serialize a {}",GetTypeName(o))); return false; } return true; @@ -313,7 +314,7 @@ bool ReadObject(HSQUIRRELVM v,SQUserPointer up,SQREADFUNC read,SQObjectPtr &o) o=_null_; break; default: - v->Raise_Error("cannot serialize a %s",IdType2Name(t)); + v->Raise_Error(fmt::format("cannot serialize a {}",IdType2Name(t))); return false; } return true; diff --git a/src/3rdparty/squirrel/squirrel/sqvm.cpp b/src/3rdparty/squirrel/squirrel/sqvm.cpp index e643e25984..a8ccf0f2f4 100644 --- a/src/3rdparty/squirrel/squirrel/sqvm.cpp +++ b/src/3rdparty/squirrel/squirrel/sqvm.cpp @@ -3,6 +3,7 @@ */ #include "../../../stdafx.h" +#include "../../fmt/format.h" #include #include "sqpcheader.h" @@ -54,7 +55,7 @@ bool SQVM::BW_OP(SQUnsignedInteger op,SQObjectPtr &trg,const SQObjectPtr &o1,con default: { Raise_Error("internal vm error bitwise op failed"); return false; } } } - else { Raise_Error("bitwise op between '%s' and '%s'",GetTypeName(o1),GetTypeName(o2)); return false;} + else { Raise_Error(fmt::format("bitwise op between '{}' and '{}'",GetTypeName(o1),GetTypeName(o2))); return false;} trg = res; return true; } @@ -94,7 +95,7 @@ bool SQVM::ARITH_OP(SQUnsignedInteger op,SQObjectPtr &trg,const SQObjectPtr &o1, if(!StringCat(o1, o2, trg)) return false; } else if(!ArithMetaMethod(op,o1,o2,trg)) { - Raise_Error("arith op %c on between '%s' and '%s'",(char)op,GetTypeName(o1),GetTypeName(o2)); return false; + Raise_Error(fmt::format("arith op {} on between '{}' and '{}'",(char)op,GetTypeName(o1),GetTypeName(o2))); return false; } } return true; @@ -183,7 +184,7 @@ bool SQVM::NEG_OP(SQObjectPtr &trg,const SQObjectPtr &o) } default:break; //shutup compiler } - Raise_Error("attempt to negate a %s", GetTypeName(o)); + Raise_Error(fmt::format("attempt to negate a {}", GetTypeName(o))); return false; } @@ -540,14 +541,14 @@ bool SQVM::FOREACH_OP(SQObjectPtr &o1,SQObjectPtr &o2,SQObjectPtr } FALLTHROUGH; default: - Raise_Error("cannot iterate %s", GetTypeName(o1)); + Raise_Error(fmt::format("cannot iterate {}", GetTypeName(o1))); } return false; //cannot be hit(just to avoid warnings) } bool SQVM::DELEGATE_OP(SQObjectPtr &trg,SQObjectPtr &o1,SQObjectPtr &o2) { - if(type(o1) != OT_TABLE) { Raise_Error("delegating a '%s'", GetTypeName(o1)); return false; } + if(type(o1) != OT_TABLE) { Raise_Error(fmt::format("delegating a '{}'", GetTypeName(o1))); return false; } switch(type(o2)) { case OT_TABLE: if(!_table(o1)->SetDelegate(_table(o2))){ @@ -559,7 +560,7 @@ bool SQVM::DELEGATE_OP(SQObjectPtr &trg,SQObjectPtr &o1,SQObjectPtr &o2) _table(o1)->SetDelegate(nullptr); break; default: - Raise_Error("using '%s' as delegate", GetTypeName(o2)); + Raise_Error(fmt::format("using '{}' as delegate", GetTypeName(o2))); return false; break; } @@ -615,7 +616,7 @@ bool SQVM::GETVARGV_OP(SQObjectPtr &target,SQObjectPtr &index,CallInfo *ci) return false; } if(!sq_isnumeric(index)){ - Raise_Error("indexing 'vargv' with %s",GetTypeName(index)); + Raise_Error(fmt::format("indexing 'vargv' with {}",GetTypeName(index))); return false; } SQInteger idx = tointeger(index); @@ -629,7 +630,7 @@ bool SQVM::CLASS_OP(SQObjectPtr &target,SQInteger baseclass,SQInteger attributes SQClass *base = nullptr; SQObjectPtr attrs; if(baseclass != -1) { - if(type(_stack._vals[_stackbase+baseclass]) != OT_CLASS) { Raise_Error("trying to inherit from a %s",GetTypeName(_stack._vals[_stackbase+baseclass])); return false; } + if(type(_stack._vals[_stackbase+baseclass]) != OT_CLASS) { Raise_Error(fmt::format("trying to inherit from a {}",GetTypeName(_stack._vals[_stackbase+baseclass]))); return false; } base = _class(_stack._vals[_stackbase + baseclass]); } if(attributes != MAX_FUNC_STACKSIZE) { @@ -684,7 +685,7 @@ bool SQVM::GETPARENT_OP(SQObjectPtr &o,SQObjectPtr &target) case OT_CLASS: target = _class(o)->_base?_class(o)->_base:_null_; break; default: - Raise_Error("the %s type doesn't have a parent slot", GetTypeName(o)); + Raise_Error(fmt::format("the {} type doesn't have a parent slot", GetTypeName(o))); return false; } return true; @@ -839,11 +840,11 @@ common_call: STK(ct_target) = clo; break; } - Raise_Error("attempt to call '%s'", GetTypeName(clo)); + Raise_Error(fmt::format("attempt to call '{}'", GetTypeName(clo))); SQ_THROW(); } default: - Raise_Error("attempt to call '%s'", GetTypeName(clo)); + Raise_Error(fmt::format("attempt to call '{}'", GetTypeName(clo))); SQ_THROW(); } } @@ -945,7 +946,7 @@ common_call: case _OP_EXISTS: TARGET = Get(STK(arg1), STK(arg2), temp_reg, true,false)?_true_:_false_;continue; case _OP_INSTANCEOF: if(type(STK(arg1)) != OT_CLASS || type(STK(arg2)) != OT_INSTANCE) - {Raise_Error("cannot apply instanceof between a %s and a %s",GetTypeName(STK(arg1)),GetTypeName(STK(arg2))); SQ_THROW();} + {Raise_Error(fmt::format("cannot apply instanceof between a {} and a {}",GetTypeName(STK(arg1)),GetTypeName(STK(arg2)))); SQ_THROW();} TARGET = _instance(STK(arg2))->InstanceOf(_class(STK(arg1)))?_true_:_false_; continue; case _OP_AND: @@ -968,7 +969,7 @@ common_call: TARGET = SQInteger(~t); continue; } - Raise_Error("attempt to perform a bitwise op on a %s", GetTypeName(STK(arg1))); + Raise_Error(fmt::format("attempt to perform a bitwise op on a {}", GetTypeName(STK(arg1)))); SQ_THROW(); case _OP_CLOSURE: { SQClosure *c = ci->_closure._unVal.pClosure; @@ -983,7 +984,7 @@ common_call: traps -= ci->_etraps; if(sarg1 != MAX_FUNC_STACKSIZE) STK(arg1) = temp_reg; } - else { Raise_Error("trying to yield a '%s',only genenerator can be yielded", GetTypeName(ci->_closure)); SQ_THROW();} + else { Raise_Error(fmt::format("trying to yield a '{}',only genenerator can be yielded", GetTypeName(ci->_closure))); SQ_THROW();} if(Return(arg0, arg1, temp_reg)){ assert(traps == 0); outres = temp_reg; @@ -993,7 +994,7 @@ common_call: } continue; case _OP_RESUME: - if(type(STK(arg1)) != OT_GENERATOR){ Raise_Error("trying to resume a '%s',only genenerator can be resumed", GetTypeName(STK(arg1))); SQ_THROW();} + if(type(STK(arg1)) != OT_GENERATOR){ Raise_Error(fmt::format("trying to resume a '{}',only genenerator can be resumed", GetTypeName(STK(arg1)))); SQ_THROW();} _GUARD(_generator(STK(arg1))->Resume(this, arg0)); traps += ci->_etraps; continue; @@ -1009,7 +1010,7 @@ common_call: case _OP_DELEGATE: _GUARD(DELEGATE_OP(TARGET,STK(arg1),STK(arg2))); continue; case _OP_CLONE: if(!Clone(STK(arg1), TARGET)) - { Raise_Error("cloning a %s", GetTypeName(STK(arg1))); SQ_THROW();} + { Raise_Error(fmt::format("cloning a {}", GetTypeName(STK(arg1)))); SQ_THROW();} continue; case _OP_TYPEOF: TypeOf(STK(arg1), TARGET); continue; case _OP_PUSHTRAP:{ @@ -1348,10 +1349,10 @@ bool SQVM::Set(const SQObjectPtr &self,const SQObjectPtr &key,const SQObjectPtr } break; case OT_ARRAY: - if(!sq_isnumeric(key)) {Raise_Error("indexing %s with %s",GetTypeName(self),GetTypeName(key)); return false; } + if(!sq_isnumeric(key)) {Raise_Error(fmt::format("indexing {} with {}",GetTypeName(self),GetTypeName(key))); return false; } return _array(self)->Set(tointeger(key),val); default: - Raise_Error("trying to set '%s'",GetTypeName(self)); + Raise_Error(fmt::format("trying to set '{}'",GetTypeName(self))); return false; } if(fetchroot) { @@ -1420,13 +1421,13 @@ bool SQVM::NewSlot(const SQObjectPtr &self,const SQObjectPtr &key,const SQObject } else { SQObjectPtr oval = PrintObjVal(key); - Raise_Error("the property '%s' already exists",_stringval(oval)); + Raise_Error(fmt::format("the property '{}' already exists",_stringval(oval))); return false; } } break; default: - Raise_Error("indexing %s with %s",GetTypeName(self),GetTypeName(key)); + Raise_Error(fmt::format("indexing {} with {}",GetTypeName(self),GetTypeName(key))); return false; break; } @@ -1457,7 +1458,7 @@ bool SQVM::DeleteSlot(const SQObjectPtr &self,const SQObjectPtr &key,SQObjectPtr } } else { - Raise_Error("cannot delete a slot from %s",GetTypeName(self)); + Raise_Error(fmt::format("cannot delete a slot from {}",GetTypeName(self))); return false; } } @@ -1465,7 +1466,7 @@ bool SQVM::DeleteSlot(const SQObjectPtr &self,const SQObjectPtr &key,SQObjectPtr } break; default: - Raise_Error("attempt to delete a slot from a %s",GetTypeName(self)); + Raise_Error(fmt::format("attempt to delete a slot from a {}",GetTypeName(self))); return false; } return true; diff --git a/src/3rdparty/squirrel/squirrel/sqvm.h b/src/3rdparty/squirrel/squirrel/sqvm.h index 6389058923..86ac4aacdc 100644 --- a/src/3rdparty/squirrel/squirrel/sqvm.h +++ b/src/3rdparty/squirrel/squirrel/sqvm.h @@ -80,7 +80,7 @@ public: SQString *PrintObjVal(const SQObject &o); - void Raise_Error(const SQChar *s, ...) WARN_FORMAT(2, 3); + void Raise_Error(const std::string &msg); void Raise_Error(SQObjectPtr &desc); void Raise_IdxError(const SQObject &o); void Raise_CompareError(const SQObject &o1, const SQObject &o2); From 484883e6e18ce221f6f3e1f3c825bb3d742b5f04 Mon Sep 17 00:00:00 2001 From: Rubidium Date: Wed, 19 Apr 2023 20:19:00 +0200 Subject: [PATCH 10/27] Cleanup: remove (unused) Squirrel code that used a hack to work around printf safety --- src/3rdparty/squirrel/include/sqstdstring.h | 2 - .../squirrel/sqstdlib/sqstdstring.cpp | 95 ------------------- 2 files changed, 97 deletions(-) diff --git a/src/3rdparty/squirrel/include/sqstdstring.h b/src/3rdparty/squirrel/include/sqstdstring.h index 856c33f791..65dae348b3 100644 --- a/src/3rdparty/squirrel/include/sqstdstring.h +++ b/src/3rdparty/squirrel/include/sqstdstring.h @@ -18,8 +18,6 @@ SQBool sqstd_rex_searchrange(SQRex* exp,const SQChar* text_begin,const SQChar* t SQInteger sqstd_rex_getsubexpcount(SQRex* exp); SQBool sqstd_rex_getsubexp(SQRex* exp, SQInteger n, SQRexMatch *subexp); -SQRESULT sqstd_format(HSQUIRRELVM v,SQInteger nformatstringidx,SQInteger *outlen,SQChar **output); - SQRESULT sqstd_register_stringlib(HSQUIRRELVM v); #endif /*_SQSTD_STRING_H_*/ diff --git a/src/3rdparty/squirrel/sqstdlib/sqstdstring.cpp b/src/3rdparty/squirrel/sqstdlib/sqstdstring.cpp index 8639b6456a..b6efa13148 100644 --- a/src/3rdparty/squirrel/sqstdlib/sqstdstring.cpp +++ b/src/3rdparty/squirrel/sqstdlib/sqstdstring.cpp @@ -53,101 +53,6 @@ static SQInteger validate_format(HSQUIRRELVM v, SQChar *fmt, const SQChar *src, return n; } -/* - * Little hack to remove the "format not a string literal, argument types not checked" warning. - * This check has been added to OpenTTD to make sure that nobody passes wrong string literals, - * but three lines in Squirrel have a little problem with those. Therefor we use this hack - * which basically uses vsnprintf instead of sprintf as vsnprintf is not testing for the right - * string literal at compile time. - */ -static void _append_string(SQInteger &i, SQChar *dest, SQInteger allocated, const SQChar *fmt, ...) -{ - va_list va; - va_start(va, fmt); - i += vsnprintf(&dest[i],allocated-i,fmt,va); - va_end(va); -} - - -SQRESULT sqstd_format(HSQUIRRELVM v,SQInteger nformatstringidx,SQInteger *outlen,SQChar **output) -{ - const SQChar *format; - SQChar *dest; - SQChar fmt[MAX_FORMAT_LEN]; - sq_getstring(v,nformatstringidx,&format); - SQInteger allocated = (sq_getsize(v,nformatstringidx)+2)*sizeof(SQChar); - dest = sq_getscratchpad(v,allocated); - SQInteger n = 0,i = 0, nparam = nformatstringidx+1, w = 0; - while(format[n] != '\0') { - if(format[n] != '%') { - assert(i < allocated); - dest[i++] = format[n]; - n++; - } - else if(format[n+1] == '%') { //handles %% - dest[i++] = '%'; - n += 2; - } - else { - n++; - if( nparam > sq_gettop(v) ) - return sq_throwerror(v,"not enough paramters for the given format string"); - n = validate_format(v,fmt,format,n,w); - if(n < 0) return -1; - SQInteger addlen = 0; - SQInteger valtype = 0; - const SQChar *ts; - SQInteger ti; - SQFloat tf; - switch(format[n]) { - case 's': - if(SQ_FAILED(sq_getstring(v,nparam,&ts))) - return sq_throwerror(v,"string expected for the specified format"); - addlen = (sq_getsize(v,nparam)*sizeof(SQChar))+((w+1)*sizeof(SQChar)); - valtype = 's'; - break; - case 'i': case 'd': case 'c':case 'o': case 'u': case 'x': case 'X': - if(SQ_FAILED(sq_getinteger(v,nparam,&ti))) - return sq_throwerror(v,"integer expected for the specified format"); - addlen = (ADDITIONAL_FORMAT_SPACE)+((w+1)*sizeof(SQChar)); - valtype = 'i'; - break; - case 'f': case 'g': case 'G': case 'e': case 'E': - if(SQ_FAILED(sq_getfloat(v,nparam,&tf))) - return sq_throwerror(v,"float expected for the specified format"); - addlen = (ADDITIONAL_FORMAT_SPACE)+((w+1)*sizeof(SQChar)); - valtype = 'f'; - break; - default: - return sq_throwerror(v,"invalid format"); - } - n++; - allocated += addlen + sizeof(SQChar); - dest = sq_getscratchpad(v,allocated); - switch(valtype) { - case 's': _append_string(i,dest,allocated,fmt,ts); break; - case 'i': _append_string(i,dest,allocated,fmt,ti); break; - case 'f': _append_string(i,dest,allocated,fmt,tf); break; - }; - nparam ++; - } - } - *outlen = i; - dest[i] = '\0'; - *output = dest; - return SQ_OK; -} - -static SQInteger _string_format(HSQUIRRELVM v) -{ - SQChar *dest = NULL; - SQInteger length = 0; - if(SQ_FAILED(sqstd_format(v,2,&length,&dest))) - return -1; - sq_pushstring(v,dest,length); - return 1; -} - static void __strip_l(const SQChar *str,const SQChar **start) { const SQChar *t = str; From 8f2490184315bdc8e9d64cf30a16316ed1ab5006 Mon Sep 17 00:00:00 2001 From: Rubidium Date: Wed, 19 Apr 2023 22:08:00 +0200 Subject: [PATCH 11/27] Codechange: replace printf with PRINTF macros by fmt::format for scripts --- src/3rdparty/squirrel/squirrel/sqdebug.cpp | 7 ++----- src/3rdparty/squirrel/squirrel/sqfuncstate.cpp | 11 ++++++----- src/3rdparty/squirrel/squirrel/sqvm.cpp | 12 ++++++------ src/script/api/script_text.cpp | 6 +++--- src/script/squirrel.cpp | 10 ++++------ 5 files changed, 21 insertions(+), 25 deletions(-) diff --git a/src/3rdparty/squirrel/squirrel/sqdebug.cpp b/src/3rdparty/squirrel/squirrel/sqdebug.cpp index 46ffb3131e..6a7eea5169 100644 --- a/src/3rdparty/squirrel/squirrel/sqdebug.cpp +++ b/src/3rdparty/squirrel/squirrel/sqdebug.cpp @@ -76,15 +76,12 @@ void SQVM::Raise_Error(SQObjectPtr &desc) SQString *SQVM::PrintObjVal(const SQObject &o) { - char buf[NUMBER_MAX_CHAR+1]; switch(type(o)) { case OT_STRING: return _string(o); case OT_INTEGER: - seprintf(buf, lastof(buf), OTTD_PRINTF64, _integer(o)); - return SQString::Create(_ss(this), buf); + return SQString::Create(_ss(this), fmt::format("{}", _integer(o)).c_str()); case OT_FLOAT: - seprintf(buf, lastof(buf), "%.14g", _float(o)); - return SQString::Create(_ss(this), buf); + return SQString::Create(_ss(this), fmt::format("{:.14g}", _float(o)).c_str()); default: return SQString::Create(_ss(this), GetTypeName(o)); } diff --git a/src/3rdparty/squirrel/squirrel/sqfuncstate.cpp b/src/3rdparty/squirrel/squirrel/sqfuncstate.cpp index 2baca100e0..0992658c84 100644 --- a/src/3rdparty/squirrel/squirrel/sqfuncstate.cpp +++ b/src/3rdparty/squirrel/squirrel/sqfuncstate.cpp @@ -3,6 +3,7 @@ */ #include "../../../stdafx.h" +#include "../../fmt/format.h" #include "sqpcheader.h" #include "sqcompiler.h" @@ -83,11 +84,11 @@ SQInstructionDesc g_InstrDesc[]={ void DumpLiteral(SQObjectPtr &o) { switch(type(o)){ - case OT_STRING: printf("\"%s\"",_stringval(o));break; - case OT_FLOAT: printf("{%f}",_float(o));break; - case OT_INTEGER: printf("{" OTTD_PRINTF64 "}",_integer(o));break; - case OT_BOOL: printf("%s",_integer(o)?"true":"false");break; - default: printf("(%s %p)",GetTypeName(o),(void*)_rawval(o));break; break; //shut up compiler + case OT_STRING: fmt::print("\"{}\"",_stringval(o));break; + case OT_FLOAT: fmt::print("{{{}}}",_float(o));break; + case OT_INTEGER: fmt::print("{{{}}}",_integer(o));break; + case OT_BOOL: fmt::print(_integer(o)?"true":"false");break; + default: fmt::print("({} {})",GetTypeName(o),(size_t)(void*)_rawval(o));break; break; //shut up compiler } } #endif diff --git a/src/3rdparty/squirrel/squirrel/sqvm.cpp b/src/3rdparty/squirrel/squirrel/sqvm.cpp index a8ccf0f2f4..a976a91093 100644 --- a/src/3rdparty/squirrel/squirrel/sqvm.cpp +++ b/src/3rdparty/squirrel/squirrel/sqvm.cpp @@ -262,19 +262,19 @@ bool SQVM::CMP_OP(CmpOP op, const SQObjectPtr &o1,const SQObjectPtr &o2,SQObject void SQVM::ToString(const SQObjectPtr &o,SQObjectPtr &res) { - char buf[64]; + std::string str; switch(type(o)) { case OT_STRING: res = o; return; case OT_FLOAT: - seprintf(buf, lastof(buf),"%g",_float(o)); + str = fmt::format("{}",_float(o)); break; case OT_INTEGER: - seprintf(buf, lastof(buf),OTTD_PRINTF64,_integer(o)); + str = fmt::format("{}",_integer(o)); break; case OT_BOOL: - seprintf(buf, lastof(buf),_integer(o)?"true":"false"); + str = _integer(o)?"true":"false"; break; case OT_TABLE: case OT_USERDATA: @@ -289,9 +289,9 @@ void SQVM::ToString(const SQObjectPtr &o,SQObjectPtr &res) } FALLTHROUGH; default: - seprintf(buf, lastof(buf),"(%s : 0x%p)",GetTypeName(o),(void*)_rawval(o)); + str = fmt::format("({} : 0x{:08X})",GetTypeName(o),(size_t)(void*)_rawval(o)); } - res = SQString::Create(_ss(this),buf); + res = SQString::Create(_ss(this),str.c_str()); } diff --git a/src/script/api/script_text.cpp b/src/script/api/script_text.cpp index 228b6954c4..2445d2044f 100644 --- a/src/script/api/script_text.cpp +++ b/src/script/api/script_text.cpp @@ -196,7 +196,7 @@ char *ScriptText::_GetEncodedText(char *p, char *lastofp, int ¶m_count, Stri /* No more extra parameters, assume SQInteger are expected. */ if (cur_idx >= this->paramc) throw Script_FatalError(fmt::format("{}: Not enough parameters", name)); if (!std::holds_alternative(this->param[cur_idx])) throw Script_FatalError(fmt::format("{}: Parameter {} expects an integer", name, param_count + i)); - p += seprintf(p, lastofp, ":" OTTD_PRINTFHEX64, std::get(this->param[cur_idx++])); + p = strecpy(p, fmt::format(":{:X}", std::get(this->param[cur_idx++])).c_str(), lastofp); } } if (prev_idx == prev_count) { @@ -213,7 +213,7 @@ char *ScriptText::_GetEncodedText(char *p, char *lastofp, int ¶m_count, Stri case StringParam::STRING: { if (!std::holds_alternative(this->param[cur_idx])) throw Script_FatalError(fmt::format("{}: Parameter {} expects a substring", name, param_count)); int count = 0; - p += seprintf(p, lastofp, ":"); + p = strecpy(p, ":", lastofp); p = std::get(this->param[cur_idx++])->_GetEncodedText(p, lastofp, count, seen_ids); if (++count != cur_param.consumes) { ScriptLog::Error(fmt::format("{}: Parameter {} substring consumes {}, but expected {} to be consumed", name, param_count, count - 1, cur_param.consumes - 1).c_str()); @@ -233,7 +233,7 @@ char *ScriptText::_GetEncodedText(char *p, char *lastofp, int ¶m_count, Stri if (cur_idx + cur_param.consumes > this->paramc) throw Script_FatalError(fmt::format("{}: Not enough parameters", name)); for (int i = 0; i < cur_param.consumes; i++) { if (!std::holds_alternative(this->param[cur_idx])) throw Script_FatalError(fmt::format("{}: Parameter {} expects an integer", name, param_count + i)); - p += seprintf(p, lastofp, ":" OTTD_PRINTFHEX64, std::get(this->param[cur_idx++])); + p = strecpy(p, fmt::format(":{:X}", std::get(this->param[cur_idx++])).c_str(), lastofp); } } } diff --git a/src/script/squirrel.cpp b/src/script/squirrel.cpp index 30d1a5945b..0ab56049f1 100644 --- a/src/script/squirrel.cpp +++ b/src/script/squirrel.cpp @@ -74,12 +74,11 @@ struct ScriptAllocator { * already as then the allocation is for throwing that error in Squirrel, the * associated stack trace information and while cleaning up the AI. */ this->error_thrown = true; - char buff[128]; - seprintf(buff, lastof(buff), "Maximum memory allocation exceeded by " PRINTF_SIZE " bytes when allocating " PRINTF_SIZE " bytes", + std::string msg = fmt::format("Maximum memory allocation exceeded by {} bytes when allocating {} bytes", this->allocated_size + requested_size - this->allocation_limit, requested_size); /* Don't leak the rejected allocation. */ free(p); - throw Script_FatalError(buff); + throw Script_FatalError(msg); } if (p == nullptr) { @@ -93,9 +92,8 @@ struct ScriptAllocator { } this->error_thrown = true; - char buff[64]; - seprintf(buff, lastof(buff), "Out of memory. Cannot allocate " PRINTF_SIZE " bytes", requested_size); - throw Script_FatalError(buff); + std::string msg = fmt::format("Out of memory. Cannot allocate {} bytes", requested_size); + throw Script_FatalError(msg); } } From f5f6306af3d0c58adc04e18014dada9695a62f71 Mon Sep 17 00:00:00 2001 From: Rubidium Date: Tue, 18 Apr 2023 19:41:29 +0200 Subject: [PATCH 12/27] Codechange: use string/fmt instead of printf for ShowInfo(F) --- src/console_cmds.cpp | 2 +- src/debug.cpp | 4 ++-- src/debug.h | 6 +++--- src/fontcache/freetypefontcache.cpp | 4 ++-- src/gfxinit.cpp | 2 +- src/ini.cpp | 2 +- src/openttd.cpp | 24 +++++------------------- src/os/macosx/font_osx.cpp | 4 ++-- src/os/os2/os2.cpp | 4 ++-- src/os/unix/font_unix.cpp | 2 +- src/os/unix/unix.cpp | 4 ++-- src/os/windows/font_win32.cpp | 4 ++-- src/os/windows/win32.cpp | 10 +++++----- src/osk_gui.cpp | 10 +++++----- src/saveload/afterload.cpp | 2 +- 15 files changed, 35 insertions(+), 49 deletions(-) diff --git a/src/console_cmds.cpp b/src/console_cmds.cpp index 36b9900c64..ab4d63c363 100644 --- a/src/console_cmds.cpp +++ b/src/console_cmds.cpp @@ -1606,7 +1606,7 @@ DEF_CONSOLE_CMD(ConDebugLevel) if (argc == 1) { IConsolePrint(CC_DEFAULT, "Current debug-level: '{}'", GetDebugString()); } else { - SetDebugString(argv[1], [](const char *err) { IConsolePrint(CC_ERROR, std::string(err)); }); + SetDebugString(argv[1], [](const std::string &err) { IConsolePrint(CC_ERROR, err); }); } return true; diff --git a/src/debug.cpp b/src/debug.cpp index 7dc90b2bb7..25c90fa12c 100644 --- a/src/debug.cpp +++ b/src/debug.cpp @@ -161,7 +161,7 @@ void DebugPrint(const char *level, const std::string &message) * @param s Text describing the wanted debugging levels. * @param error_func The function to call if a parse error occurs. */ -void SetDebugString(const char *s, void (*error_func)(const char *)) +void SetDebugString(const char *s, void (*error_func)(const std::string &)) { int v; char *end; @@ -207,7 +207,7 @@ void SetDebugString(const char *s, void (*error_func)(const char *)) new_levels[found->name] = v; } else { std::string error_string = fmt::format("Unknown debug level '{}'", std::string(t, s - t)); - error_func(error_string.c_str()); + error_func(error_string); return; } } diff --git a/src/debug.h b/src/debug.h index e7db3ee0e3..125c5403c5 100644 --- a/src/debug.h +++ b/src/debug.h @@ -57,7 +57,7 @@ extern int _debug_random_level; #endif char *DumpDebugFacilityNames(char *buf, char *last); -void SetDebugString(const char *s, void (*error_func)(const char *)); +void SetDebugString(const char *s, void (*error_func)(const std::string &)); const char *GetDebugString(); /* Shorter form for passing filename and linenumber */ @@ -117,8 +117,8 @@ const char *GetDebugString(); } -void ShowInfo(const char *str); -void CDECL ShowInfoF(const char *str, ...) WARN_FORMAT(1, 2); +void ShowInfoI(const std::string &str); +#define ShowInfo(format_string, ...) ShowInfoI(fmt::format(FMT_STRING(format_string), ## __VA_ARGS__)) const char *GetLogPrefix(); diff --git a/src/fontcache/freetypefontcache.cpp b/src/fontcache/freetypefontcache.cpp index a4f329505f..4d6933669d 100644 --- a/src/fontcache/freetypefontcache.cpp +++ b/src/fontcache/freetypefontcache.cpp @@ -128,7 +128,7 @@ void LoadFreeTypeFont(FontSize fs) if (_library == nullptr) { if (FT_Init_FreeType(&_library) != FT_Err_Ok) { - ShowInfoF("Unable to initialize FreeType, using sprite fonts instead"); + ShowInfo("Unable to initialize FreeType, using sprite fonts instead"); return; } @@ -190,7 +190,7 @@ void LoadFreeTypeFont(FontSize fs) FT_Done_Face(face); - ShowInfoF("Unable to use '%s' for %s font, FreeType reported error 0x%X, using sprite font instead", font_name, FontSizeToName(fs), error); + ShowInfo("Unable to use '{}' for {} font, FreeType reported error 0x{:X}, using sprite font instead", font_name, FontSizeToName(fs), error); return; found_face: diff --git a/src/gfxinit.cpp b/src/gfxinit.cpp index d2d33fc438..2028eaf901 100644 --- a/src/gfxinit.cpp +++ b/src/gfxinit.cpp @@ -152,7 +152,7 @@ void CheckExternalFiles() add_pos += seprintf(add_pos, last, "\t%s is %s (%s)\n", sounds_set->files->filename, SoundsSet::CheckMD5(sounds_set->files, BASESET_DIR) == MD5File::CR_MISMATCH ? "corrupt" : "missing", sounds_set->files->missing_warning); } - if (add_pos != error_msg) ShowInfoF("%s", error_msg); + if (add_pos != error_msg) ShowInfoI(error_msg); } /** Actually load the sprite tables. */ diff --git a/src/ini.cpp b/src/ini.cpp index fe6cbaa083..b1eb776502 100644 --- a/src/ini.cpp +++ b/src/ini.cpp @@ -132,5 +132,5 @@ bool IniFile::SaveToDisk(const std::string &filename) /* virtual */ void IniFile::ReportFileError(const char * const pre, const char * const buffer, const char * const post) { - ShowInfoF("%s%s%s", pre, buffer, post); + ShowInfo("{}{}{}", pre, buffer, post); } diff --git a/src/openttd.cpp b/src/openttd.cpp index 494ff22de2..3c498049f7 100644 --- a/src/openttd.cpp +++ b/src/openttd.cpp @@ -163,20 +163,6 @@ void CDECL error(const char *s, ...) abort(); } -/** - * Shows some information on the console/a popup box depending on the OS. - * @param str the text to show. - */ -void CDECL ShowInfoF(const char *str, ...) -{ - va_list va; - char buf[1024]; - va_start(va, str); - vseprintf(buf, lastof(buf), str, va); - va_end(va); - ShowInfo(buf); -} - /** * Show the help message when someone passed a wrong parameter. */ @@ -257,7 +243,7 @@ static void ShowHelp() #if !defined(_WIN32) printf("%s\n", buf); #else - ShowInfo(buf); + ShowInfoI(buf); #endif } @@ -295,7 +281,7 @@ static void WriteSavegameInfo(const char *name) #if !defined(_WIN32) printf("%s\n", buf); #else - ShowInfo(buf); + ShowInfoI(buf); #endif } @@ -310,7 +296,7 @@ static void ParseResolution(Dimension *res, const char *s) { const char *t = strchr(s, 'x'); if (t == nullptr) { - ShowInfoF("Invalid resolution '%s'", s); + ShowInfo("Invalid resolution '{}'", s); return; } @@ -581,7 +567,7 @@ int openttd_main(int argc, char *argv[]) videodriver = "dedicated"; blitter = "null"; dedicated = true; - SetDebugString("net=4", ShowInfo); + SetDebugString("net=4", ShowInfoI); if (mgo.opt != nullptr) { scanner->dedicated_host = ParseFullConnectionString(mgo.opt, scanner->dedicated_port); } @@ -605,7 +591,7 @@ int openttd_main(int argc, char *argv[]) #if defined(_WIN32) CreateConsole(); #endif - if (mgo.opt != nullptr) SetDebugString(mgo.opt, ShowInfo); + if (mgo.opt != nullptr) SetDebugString(mgo.opt, ShowInfoI); break; } case 'e': _switch_mode = (_switch_mode == SM_LOAD_GAME || _switch_mode == SM_LOAD_SCENARIO ? SM_LOAD_SCENARIO : SM_EDITOR); break; diff --git a/src/os/macosx/font_osx.cpp b/src/os/macosx/font_osx.cpp index a5341bef7d..443bd87956 100644 --- a/src/os/macosx/font_osx.cpp +++ b/src/os/macosx/font_osx.cpp @@ -386,7 +386,7 @@ void LoadCoreTextFont(FontSize fs) font_ref.reset((CTFontDescriptorRef)CFArrayGetValueAtIndex(descs.get(), 0)); CFRetain(font_ref.get()); } else { - ShowInfoF("Unable to load file '%s' for %s font, using default OS font selection instead", settings->font.c_str(), FontSizeToName(fs)); + ShowInfo("Unable to load file '{}' for {} font, using default OS font selection instead", settings->font, FontSizeToName(fs)); } } } @@ -410,7 +410,7 @@ void LoadCoreTextFont(FontSize fs) } if (!font_ref) { - ShowInfoF("Unable to use '%s' for %s font, using sprite font instead", settings->font.c_str(), FontSizeToName(fs)); + ShowInfo("Unable to use '{}' for {} font, using sprite font instead", settings->font, FontSizeToName(fs)); return; } diff --git a/src/os/os2/os2.cpp b/src/os/os2/os2.cpp index f18e50c4c3..fbcd230eb7 100644 --- a/src/os/os2/os2.cpp +++ b/src/os/os2/os2.cpp @@ -133,7 +133,7 @@ bool FiosIsHiddenFile(const struct dirent *ent) return ent->d_name[0] == '.'; } -void ShowInfo(const char *str) +void ShowInfoI(const std::string &str) { HAB hab; HMQ hmq; @@ -143,7 +143,7 @@ void ShowInfo(const char *str) hmq = WinCreateMsgQueue((hab = WinInitialize(0)), 0); /* display the box */ - rc = WinMessageBox(HWND_DESKTOP, HWND_DESKTOP, (const unsigned char *)str, (const unsigned char *)"OpenTTD", 0, MB_OK | MB_MOVEABLE | MB_INFORMATION); + rc = WinMessageBox(HWND_DESKTOP, HWND_DESKTOP, (const unsigned char *)str.c_str(), (const unsigned char *)"OpenTTD", 0, MB_OK | MB_MOVEABLE | MB_INFORMATION); /* terminate PM env. */ WinDestroyMsgQueue(hmq); diff --git a/src/os/unix/font_unix.cpp b/src/os/unix/font_unix.cpp index 98543c1bdc..e2315e3fc1 100644 --- a/src/os/unix/font_unix.cpp +++ b/src/os/unix/font_unix.cpp @@ -30,7 +30,7 @@ FT_Error GetFontByFaceName(const char *font_name, FT_Face *face) FT_Error err = FT_Err_Cannot_Open_Resource; if (!FcInit()) { - ShowInfoF("Unable to load font configuration"); + ShowInfo("Unable to load font configuration"); } else { FcPattern *match; FcPattern *pat; diff --git a/src/os/unix/unix.cpp b/src/os/unix/unix.cpp index e3f6496488..249020458a 100644 --- a/src/os/unix/unix.cpp +++ b/src/os/unix/unix.cpp @@ -210,9 +210,9 @@ std::string FS2OTTD(const std::string &name) #endif /* WITH_ICONV */ -void ShowInfo(const char *str) +void ShowInfoI(const std::string &str) { - fprintf(stderr, "%s\n", str); + fprintf(stderr, "%s\n", str.c_str()); } #if !defined(__APPLE__) diff --git a/src/os/windows/font_win32.cpp b/src/os/windows/font_win32.cpp index 9fe18431ae..dafd5285cb 100644 --- a/src/os/windows/font_win32.cpp +++ b/src/os/windows/font_win32.cpp @@ -609,7 +609,7 @@ void LoadWin32Font(FontSize fs) logfont.lfWeight = strcasestr(font_name, " bold") != nullptr || strcasestr(font_name, "-bold") != nullptr ? FW_BOLD : FW_NORMAL; // Poor man's way to allow selecting bold fonts. } } else { - ShowInfoF("Unable to load file '%s' for %s font, using default windows font selection instead", font_name, FontSizeToName(fs)); + ShowInfo("Unable to load file '{}' for {} font, using default windows font selection instead", font_name, FontSizeToName(fs)); } } } @@ -621,7 +621,7 @@ void LoadWin32Font(FontSize fs) HFONT font = CreateFontIndirect(&logfont); if (font == nullptr) { - ShowInfoF("Unable to use '%s' for %s font, Win32 reported error 0x%lX, using sprite font instead", font_name, FontSizeToName(fs), GetLastError()); + ShowInfo("Unable to use '{}' for {} font, Win32 reported error 0x{:X}, using sprite font instead", font_name, FontSizeToName(fs), GetLastError()); return; } DeleteObject(font); diff --git a/src/os/windows/win32.cpp b/src/os/windows/win32.cpp index 47cb27a3cc..24d37ae4b1 100644 --- a/src/os/windows/win32.cpp +++ b/src/os/windows/win32.cpp @@ -318,27 +318,27 @@ static INT_PTR CALLBACK HelpDialogFunc(HWND wnd, UINT msg, WPARAM wParam, LPARAM return FALSE; } -void ShowInfo(const char *str) +void ShowInfoI(const std::string &str) { if (_has_console) { - fprintf(stderr, "%s\n", str); + fprintf(stderr, "%s\n", str.c_str()); } else { bool old; ReleaseCapture(); _left_button_clicked = _left_button_down = false; old = MyShowCursor(true); - if (strlen(str) > 2048) { + if (str.size() > 2048) { /* The minimum length of the help message is 2048. Other messages sent via * ShowInfo are much shorter, or so long they need this way of displaying * them anyway. */ - _help_msg = str; + _help_msg = str.c_str(); DialogBox(GetModuleHandle(nullptr), MAKEINTRESOURCE(101), nullptr, HelpDialogFunc); } else { /* We need to put the text in a separate buffer because the default * buffer in OTTD2FS might not be large enough (512 chars). */ wchar_t help_msg_buf[8192]; - MessageBox(GetActiveWindow(), convert_to_fs(str, help_msg_buf, lengthof(help_msg_buf)), L"OpenTTD", MB_ICONINFORMATION | MB_OK); + MessageBox(GetActiveWindow(), convert_to_fs(str.c_str(), help_msg_buf, lengthof(help_msg_buf)), L"OpenTTD", MB_ICONINFORMATION | MB_OK); } MyShowCursor(old); } diff --git a/src/osk_gui.cpp b/src/osk_gui.cpp index 630cd18f2d..72e2ae169c 100644 --- a/src/osk_gui.cpp +++ b/src/osk_gui.cpp @@ -392,11 +392,11 @@ void GetKeyboardLayout() } if (has_error) { - ShowInfoF("The keyboard layout you selected contains invalid chars. Please check those chars marked with ^."); - ShowInfoF("Normal keyboard: %s", keyboard[0]); - ShowInfoF(" %s", errormark[0]); - ShowInfoF("Caps Lock: %s", keyboard[1]); - ShowInfoF(" %s", errormark[1]); + ShowInfo("The keyboard layout you selected contains invalid chars. Please check those chars marked with ^."); + ShowInfo("Normal keyboard: {}", keyboard[0]); + ShowInfo(" {}", errormark[0]); + ShowInfo("Caps Lock: {}", keyboard[1]); + ShowInfo(" {}", errormark[1]); } } diff --git a/src/saveload/afterload.cpp b/src/saveload/afterload.cpp index 1c8e35473a..86d98f0607 100644 --- a/src/saveload/afterload.cpp +++ b/src/saveload/afterload.cpp @@ -424,7 +424,7 @@ static void CDECL HandleSavegameLoadCrash(int signum) "Please file a bug report and attach this savegame.\n"); } - ShowInfo(buffer); + ShowInfoI(buffer); SignalHandlerPointer call = nullptr; switch (signum) { From 7aa2b9ab0ae93ec1b7abe67bcff72132b54059b0 Mon Sep 17 00:00:00 2001 From: Patric Stout Date: Mon, 24 Apr 2023 17:56:01 +0200 Subject: [PATCH 13/27] Codechange: move all date-related variables inside the timer (#10706) --- src/aircraft_cmd.cpp | 8 ++--- src/cheat_gui.cpp | 16 +++++----- src/command.cpp | 4 +-- src/company_cmd.cpp | 3 +- src/company_gui.cpp | 6 ++-- src/console_cmds.cpp | 5 +-- src/core/random_func.cpp | 4 +-- src/crashlog.cpp | 5 +-- src/currency.cpp | 7 ++--- src/date.cpp | 22 ------------- src/date_func.h | 5 --- src/date_gui.cpp | 3 +- src/date_type.h | 6 ++-- src/disaster_vehicle.cpp | 3 +- src/economy.cpp | 17 +++++----- src/engine.cpp | 20 ++++++------ src/genworld.cpp | 3 +- src/goal_gui.cpp | 1 - src/graph_gui.cpp | 6 ++-- src/highscore_gui.cpp | 3 +- src/industry_cmd.cpp | 12 +++---- src/landscape.cpp | 3 +- src/linkgraph/linkgraph.cpp | 14 ++++----- src/linkgraph/linkgraph.h | 8 ++--- src/linkgraph/linkgraphjob.cpp | 2 +- src/linkgraph/linkgraphjob.h | 2 +- src/linkgraph/linkgraphschedule.cpp | 16 +++++----- src/misc.cpp | 2 +- src/network/core/game_info.cpp | 3 +- src/network/network.cpp | 20 ++++++------ src/network/network_admin.cpp | 3 +- src/network/network_client.cpp | 4 +-- src/network/network_server.cpp | 15 +++++---- src/newgrf.cpp | 32 +++++++++---------- src/newgrf_airport.cpp | 6 ++-- src/newgrf_engine.cpp | 12 +++---- src/newgrf_object.cpp | 7 +++-- src/newgrf_profiling.cpp | 2 +- src/newgrf_railtype.cpp | 6 ++-- src/newgrf_roadstop.cpp | 4 +-- src/newgrf_roadtype.cpp | 6 ++-- src/newgrf_station.cpp | 3 +- src/news_gui.cpp | 15 ++++----- src/object_cmd.cpp | 4 +-- src/openttd.cpp | 11 +++---- src/rail.cpp | 6 ++-- src/rail_cmd.cpp | 4 +-- src/rail_gui.cpp | 9 +++--- src/road.cpp | 6 ++-- src/road_cmd.cpp | 4 +-- src/road_gui.cpp | 3 +- src/roadveh_cmd.cpp | 6 ++-- src/saveload/afterload.cpp | 18 +++++------ src/saveload/misc_sl.cpp | 7 +++-- src/saveload/oldloader_sl.cpp | 17 +++++----- src/saveload/saveload.cpp | 4 +-- src/script/api/script_bridge.cpp | 4 +-- src/script/api/script_date.cpp | 3 +- src/ship_cmd.cpp | 6 ++-- src/station.cpp | 3 +- src/station_cmd.cpp | 18 +++++------ src/statusbar_gui.cpp | 3 +- src/story.cpp | 4 +-- src/story_gui.cpp | 1 - src/subsidy_gui.cpp | 7 +++-- src/timer/timer_game_calendar.cpp | 49 +++++++++++++++++++++-------- src/timer/timer_game_calendar.h | 9 ++++++ src/timetable_cmd.cpp | 8 ++--- src/timetable_gui.cpp | 10 +++--- src/toolbar_gui.cpp | 4 +-- src/town_cmd.cpp | 4 +-- src/train_cmd.cpp | 9 +++--- src/tunnelbridge_cmd.cpp | 4 +-- src/vehicle.cpp | 10 +++--- src/water_cmd.cpp | 4 +-- src/waypoint_cmd.cpp | 6 ++-- 76 files changed, 308 insertions(+), 301 deletions(-) diff --git a/src/aircraft_cmd.cpp b/src/aircraft_cmd.cpp index 171260b572..1d2bb36f81 100644 --- a/src/aircraft_cmd.cpp +++ b/src/aircraft_cmd.cpp @@ -20,7 +20,7 @@ #include "strings_func.h" #include "command_func.h" #include "window_func.h" -#include "date_func.h" +#include "timer/timer_game_calendar.h" #include "vehicle_func.h" #include "sound_func.h" #include "cheat_type.h" @@ -337,8 +337,8 @@ CommandCost CmdBuildAircraft(DoCommandFlag flags, TileIndex tile, const Engine * v->SetServiceInterval(Company::Get(_current_company)->settings.vehicle.servint_aircraft); - v->date_of_last_service = _date; - v->build_year = u->build_year = _cur_year; + v->date_of_last_service = TimerGameCalendar::date; + v->build_year = u->build_year = TimerGameCalendar::year; v->sprite_cache.sprite_seq.Set(SPR_IMG_QUERY); u->sprite_cache.sprite_seq.Set(SPR_IMG_QUERY); @@ -1555,7 +1555,7 @@ static void AircraftEventHandler_AtTerminal(Aircraft *v, const AirportFTAClass * if (_settings_game.order.serviceathelipad) { if (v->subtype == AIR_HELICOPTER && apc->num_helipads > 0) { /* an excerpt of ServiceAircraft, without the invisibility stuff */ - v->date_of_last_service = _date; + v->date_of_last_service = TimerGameCalendar::date; v->breakdowns_since_last_service = 0; v->reliability = v->GetEngine()->reliability; SetWindowDirty(WC_VEHICLE_DETAILS, v->index); diff --git a/src/cheat_gui.cpp b/src/cheat_gui.cpp index 19914da905..48a2fd5073 100644 --- a/src/cheat_gui.cpp +++ b/src/cheat_gui.cpp @@ -106,18 +106,18 @@ static int32 ClickChangeDateCheat(int32 new_value, int32 change_direction) { /* Don't allow changing to an invalid year, or the current year. */ new_value = Clamp(new_value, MIN_YEAR, MAX_YEAR); - if (new_value == _cur_year) return _cur_year; + if (new_value == TimerGameCalendar::year) return TimerGameCalendar::year; YearMonthDay ymd; - ConvertDateToYMD(_date, &ymd); + ConvertDateToYMD(TimerGameCalendar::date, &ymd); Date new_date = ConvertYMDToDate(new_value, ymd.month, ymd.day); /* Change the date. */ - SetDate(new_date, _date_fract); + TimerGameCalendar::SetDate(new_date, TimerGameCalendar::date_fract); /* Shift cached dates. */ - for (auto v : Vehicle::Iterate()) v->ShiftDates(new_date - _date); - LinkGraphSchedule::instance.ShiftDates(new_date - _date); + for (auto v : Vehicle::Iterate()) v->ShiftDates(new_date - TimerGameCalendar::date); + LinkGraphSchedule::instance.ShiftDates(new_date - TimerGameCalendar::date); EnginesMonthlyLoop(); SetWindowDirty(WC_STATUS_BAR, 0); @@ -126,7 +126,7 @@ static int32 ClickChangeDateCheat(int32 new_value, int32 change_direction) InvalidateWindowClassesData(WC_TRUCK_STATION, 0); InvalidateWindowClassesData(WC_BUILD_OBJECT, 0); ResetSignalVariant(); - return _cur_year; + return TimerGameCalendar::year; } /** @@ -202,7 +202,7 @@ static const CheatEntry _cheats_ui[] = { {SLE_BOOL, STR_CHEAT_NO_JETCRASH, &_cheats.no_jetcrash.value, &_cheats.no_jetcrash.been_used, nullptr }, {SLE_BOOL, STR_CHEAT_SETUP_PROD, &_cheats.setup_prod.value, &_cheats.setup_prod.been_used, &ClickSetProdCheat }, {SLE_UINT8, STR_CHEAT_EDIT_MAX_HL, &_settings_game.construction.map_height_limit, &_cheats.edit_max_hl.been_used, &ClickChangeMaxHlCheat }, - {SLE_INT32, STR_CHEAT_CHANGE_DATE, &_cur_year, &_cheats.change_date.been_used, &ClickChangeDateCheat }, + {SLE_INT32, STR_CHEAT_CHANGE_DATE, &TimerGameCalendar::year, &_cheats.change_date.been_used, &ClickChangeDateCheat }, }; static_assert(CHT_NUM_CHEATS == lengthof(_cheats_ui)); @@ -281,7 +281,7 @@ struct CheatWindow : Window { switch (ce->str) { /* Display date for change date cheat */ - case STR_CHEAT_CHANGE_DATE: SetDParam(0, _date); break; + case STR_CHEAT_CHANGE_DATE: SetDParam(0, TimerGameCalendar::date); break; /* Draw coloured flag for change company cheat */ case STR_CHEAT_CHANGE_COMPANY: { diff --git a/src/command.cpp b/src/command.cpp index 410e4fd4a8..49a72db30c 100644 --- a/src/command.cpp +++ b/src/command.cpp @@ -18,7 +18,7 @@ #include "strings_func.h" #include "texteff.hpp" #include "town.h" -#include "date_func.h" +#include "timer/timer_game_calendar.h" #include "company_func.h" #include "company_base.h" #include "signal_func.h" @@ -276,7 +276,7 @@ void CommandHelperBase::InternalPostResult(const CommandCost &res, TileIndex til /** Helper to make a desync log for a command. */ void CommandHelperBase::LogCommandExecution(Commands cmd, StringID err_message, TileIndex tile, const CommandDataBuffer &args, bool failed) { - Debug(desync, 1, "{}: {:08x}; {:02x}; {:02x}; {:08x}; {:08x}; {:06x}; {} ({})", failed ? "cmdf" : "cmd", _date, _date_fract, (int)_current_company, cmd, err_message, tile, FormatArrayAsHex(args), GetCommandName(cmd)); + Debug(desync, 1, "{}: {:08x}; {:02x}; {:02x}; {:08x}; {:08x}; {:06x}; {} ({})", failed ? "cmdf" : "cmd", TimerGameCalendar::date, TimerGameCalendar::date_fract, (int)_current_company, cmd, err_message, tile, FormatArrayAsHex(args), GetCommandName(cmd)); } /** diff --git a/src/company_cmd.cpp b/src/company_cmd.cpp index e9639bfcbf..ea8f2c85eb 100644 --- a/src/company_cmd.cpp +++ b/src/company_cmd.cpp @@ -23,7 +23,6 @@ #include "company_manager_face.h" #include "window_func.h" #include "strings_func.h" -#include "date_func.h" #include "sound_func.h" #include "rail.h" #include "core/pool_func.hpp" @@ -570,7 +569,7 @@ Company *DoStartupNewCompany(bool is_ai, CompanyID company = INVALID_COMPANY) c->avail_railtypes = GetCompanyRailtypes(c->index); c->avail_roadtypes = GetCompanyRoadTypes(c->index); - c->inaugurated_year = _cur_year; + c->inaugurated_year = TimerGameCalendar::year; /* If starting a player company in singleplayer and a favorite company manager face is selected, choose it. Otherwise, use a random face. * In a network game, we'll choose the favorite face later in CmdCompanyCtrl to sync it to all clients. */ diff --git a/src/company_gui.cpp b/src/company_gui.cpp index 3dcafa00fa..8d9f2d2db6 100644 --- a/src/company_gui.cpp +++ b/src/company_gui.cpp @@ -22,7 +22,7 @@ #include "newgrf.h" #include "company_manager_face.h" #include "strings_func.h" -#include "date_func.h" +#include "timer/timer_game_calendar.h" #include "widgets/dropdown_type.h" #include "tilehighlight_func.h" #include "company_base.h" @@ -434,10 +434,10 @@ struct CompanyFinancesWindow : Window { case WID_CF_EXPS_PRICE2: case WID_CF_EXPS_PRICE3: { const Company *c = Company::Get((CompanyID)this->window_number); - int age = std::min(_cur_year - c->inaugurated_year, 2); + int age = std::min(TimerGameCalendar::year - c->inaugurated_year, 2); int wid_offset = widget - WID_CF_EXPS_PRICE1; if (wid_offset <= age) { - DrawYearColumn(r, _cur_year - (age - wid_offset), c->yearly_expenses[age - wid_offset]); + DrawYearColumn(r, TimerGameCalendar::year - (age - wid_offset), c->yearly_expenses[age - wid_offset]); } break; } diff --git a/src/console_cmds.cpp b/src/console_cmds.cpp index ab4d63c363..e307d49f4f 100644 --- a/src/console_cmds.cpp +++ b/src/console_cmds.cpp @@ -30,6 +30,7 @@ #include "viewport_func.h" #include "window_func.h" #include "date_func.h" +#include "timer/timer_game_calendar.h" #include "company_func.h" #include "gamelog.h" #include "ai/ai.hpp" @@ -1451,7 +1452,7 @@ DEF_CONSOLE_CMD(ConGetDate) } YearMonthDay ymd; - ConvertDateToYMD(_date, &ymd); + ConvertDateToYMD(TimerGameCalendar::date, &ymd); IConsolePrint(CC_DEFAULT, "Date: {:04d}-{:02d}-{:02d}", ymd.year, ymd.month + 1, ymd.day); return true; } @@ -2290,7 +2291,7 @@ DEF_CONSOLE_CMD(ConNewGRFProfile) IConsolePrint(CC_DEBUG, "Started profiling for GRFID{} {}.", (started > 1) ? "s" : "", grfids); if (argc >= 3) { int days = std::max(atoi(argv[2]), 1); - _newgrf_profile_end_date = _date + days; + _newgrf_profile_end_date = TimerGameCalendar::date + days; char datestrbuf[32]{ 0 }; SetDParam(0, _newgrf_profile_end_date); diff --git a/src/core/random_func.cpp b/src/core/random_func.cpp index 93c2b06431..6fe3617815 100644 --- a/src/core/random_func.cpp +++ b/src/core/random_func.cpp @@ -17,7 +17,7 @@ #include "../network/network_internal.h" #include "../company_func.h" #include "../fileio_func.h" -#include "../date_func.h" +#include "../timer/timer_game_calendar.h" #endif /* RANDOM_DEBUG */ #include "../safeguards.h" @@ -72,7 +72,7 @@ void SetRandomSeed(uint32 seed) uint32 DoRandom(int line, const char *file) { if (_networking && (!_network_server || (NetworkClientSocket::IsValidID(0) && NetworkClientSocket::Get(0)->status != NetworkClientSocket::STATUS_INACTIVE))) { - Debug(random, 0, "{:08x}; {:02x}; {:04x}; {:02x}; {}:{}", _date, _date_fract, _frame_counter, (byte)_current_company, file, line); + Debug(random, 0, "{:08x}; {:02x}; {:04x}; {:02x}; {}:{}", TimerGameCalendar::date, TimerGameCalendar::date_fract, _frame_counter, (byte)_current_company, file, line); } return _random.Next(); diff --git a/src/crashlog.cpp b/src/crashlog.cpp index 5d26a47278..d00d9253a8 100644 --- a/src/crashlog.cpp +++ b/src/crashlog.cpp @@ -11,6 +11,7 @@ #include "crashlog.h" #include "gamelog.h" #include "date_func.h" +#include "timer/timer_game_calendar.h" #include "map_func.h" #include "rev.h" #include "strings_func.h" @@ -357,8 +358,8 @@ char *CrashLog::FillCrashLog(char *buffer, const char *last) const buffer += UTCTime::Format(buffer, last, "Crash at: %Y-%m-%d %H:%M:%S (UTC)\n"); YearMonthDay ymd; - ConvertDateToYMD(_date, &ymd); - buffer += seprintf(buffer, last, "In game date: %i-%02i-%02i (%i)\n\n", ymd.year, ymd.month + 1, ymd.day, _date_fract); + ConvertDateToYMD(TimerGameCalendar::date, &ymd); + buffer += seprintf(buffer, last, "In game date: %i-%02i-%02i (%i)\n\n", ymd.year, ymd.month + 1, ymd.day, TimerGameCalendar::date_fract); buffer = this->LogError(buffer, last, CrashLog::message.c_str()); buffer = this->LogOpenTTDVersion(buffer, last); diff --git a/src/currency.cpp b/src/currency.cpp index ca75f3d656..aef97552ec 100644 --- a/src/currency.cpp +++ b/src/currency.cpp @@ -13,7 +13,6 @@ #include "currency.h" #include "news_func.h" #include "settings_type.h" -#include "date_func.h" #include "string_type.h" #include "timer/timer.h" #include "timer/timer_game_calendar.h" @@ -129,8 +128,8 @@ uint64 GetMaskOfAllowedCurrencies() for (i = 0; i < CURRENCY_END; i++) { Year to_euro = _currency_specs[i].to_euro; - if (to_euro != CF_NOEURO && to_euro != CF_ISEURO && _cur_year >= to_euro) continue; - if (to_euro == CF_ISEURO && _cur_year < 2000) continue; + if (to_euro != CF_NOEURO && to_euro != CF_ISEURO && TimerGameCalendar::year >= to_euro) continue; + if (to_euro == CF_ISEURO && TimerGameCalendar::year < 2000) continue; SetBit(mask, i); } SetBit(mask, CURRENCY_CUSTOM); // always allow custom currency @@ -144,7 +143,7 @@ static IntervalTimer _check_switch_to_euro({TimerGameCalendar { if (_currency_specs[_settings_game.locale.currency].to_euro != CF_NOEURO && _currency_specs[_settings_game.locale.currency].to_euro != CF_ISEURO && - _cur_year >= _currency_specs[_settings_game.locale.currency].to_euro) { + TimerGameCalendar::year >= _currency_specs[_settings_game.locale.currency].to_euro) { _settings_game.locale.currency = 2; // this is the index of euro above. AddNewsItem(STR_NEWS_EURO_INTRODUCTION, NT_ECONOMY, NF_NORMAL); } diff --git a/src/date.cpp b/src/date.cpp index 23bf5552ff..818043306b 100644 --- a/src/date.cpp +++ b/src/date.cpp @@ -25,30 +25,8 @@ #include "safeguards.h" -Year _cur_year; ///< Current year, starting at 0 -Month _cur_month; ///< Current month (0..11) -Date _date; ///< Current date in days (day counter) -DateFract _date_fract; ///< Fractional part of the day. uint64 _tick_counter; ///< Ever incrementing tick counter for setting off various events -/** - * Set the date. - * @param date New date - * @param fract The number of ticks that have passed on this date. - */ -void SetDate(Date date, DateFract fract) -{ - assert(fract < DAY_TICKS); - - YearMonthDay ymd; - - _date = date; - _date_fract = fract; - ConvertDateToYMD(date, &ymd); - _cur_year = ymd.year; - _cur_month = ymd.month; -} - #define M(a, b) ((a << 5) | b) static const uint16 _month_date_from_year_day[] = { M( 0, 1), M( 0, 2), M( 0, 3), M( 0, 4), M( 0, 5), M( 0, 6), M( 0, 7), M( 0, 8), M( 0, 9), M( 0, 10), M( 0, 11), M( 0, 12), M( 0, 13), M( 0, 14), M( 0, 15), M( 0, 16), M( 0, 17), M( 0, 18), M( 0, 19), M( 0, 20), M( 0, 21), M( 0, 22), M( 0, 23), M( 0, 24), M( 0, 25), M( 0, 26), M( 0, 27), M( 0, 28), M( 0, 29), M( 0, 30), M( 0, 31), diff --git a/src/date_func.h b/src/date_func.h index e8ac6a7c77..d155ab1739 100644 --- a/src/date_func.h +++ b/src/date_func.h @@ -12,13 +12,8 @@ #include "date_type.h" -extern Year _cur_year; -extern Month _cur_month; -extern Date _date; -extern DateFract _date_fract; extern uint64 _tick_counter; -void SetDate(Date date, DateFract fract); void ConvertDateToYMD(Date date, YearMonthDay *ymd); Date ConvertYMDToDate(Year year, Month month, Day day); diff --git a/src/date_gui.cpp b/src/date_gui.cpp index 66c9a378a3..fe7b9e57c8 100644 --- a/src/date_gui.cpp +++ b/src/date_gui.cpp @@ -10,6 +10,7 @@ #include "stdafx.h" #include "strings_func.h" #include "date_func.h" +#include "timer/timer_game_calendar.h" #include "window_func.h" #include "window_gui.h" #include "date_gui.h" @@ -50,7 +51,7 @@ struct SetDateWindow : Window { this->parent = parent; this->InitNested(window_number); - if (initial_date == 0) initial_date = _date; + if (initial_date == 0) initial_date = TimerGameCalendar::date; ConvertDateToYMD(initial_date, &this->date); this->date.year = Clamp(this->date.year, min_year, max_year); } diff --git a/src/date_type.h b/src/date_type.h index c26844d589..2fbead2187 100644 --- a/src/date_type.h +++ b/src/date_type.h @@ -20,7 +20,7 @@ typedef uint8 Month; ///< Type for the month, note: 0 based, i.e. 0 = January, typedef uint8 Day; ///< Type for the day of the month, note: 1 based, first day of a month is 1. /** - * 1 day is 74 ticks; _date_fract used to be uint16 and incremented by 885. On + * 1 day is 74 ticks; TimerGameCalendar::date_fract used to be uint16 and incremented by 885. On * an overflow the new day begun and 65535 / 885 = 74. * 1 tick is approximately 27 ms. * 1 day is thus about 2 seconds (74 * 27 = 1998) on a machine that can run OpenTTD normally @@ -45,7 +45,7 @@ static const int INDUSTRY_CUT_TREE_TICKS = INDUSTRY_PRODUCE_TICKS * 2; ///< cyc * ORIGINAL_BASE_YEAR, ORIGINAL_MAX_YEAR and DAYS_TILL_ORIGINAL_BASE_YEAR are * primarily used for loading newgrf and savegame data and returning some * newgrf (callback) functions that were in the original (TTD) inherited - * format, where '_date == 0' meant that it was 1920-01-01. + * format, where 'TimerGameCalendar::date == 0' meant that it was 1920-01-01. */ /** The minimum starting year/base year of the original TTD */ @@ -77,7 +77,7 @@ static const Year ORIGINAL_MAX_YEAR = 2090; #define DAYS_TILL(year) (DAYS_IN_YEAR * (year) + LEAP_YEARS_TILL(year)) /** - * The offset in days from the '_date == 0' till + * The offset in days from the 'TimerGameCalendar::date == 0' till * 'ConvertYMDToDate(ORIGINAL_BASE_YEAR, 0, 1)' */ #define DAYS_TILL_ORIGINAL_BASE_YEAR DAYS_TILL(ORIGINAL_BASE_YEAR) diff --git a/src/disaster_vehicle.cpp b/src/disaster_vehicle.cpp index 528225cc1a..2cb981e89f 100644 --- a/src/disaster_vehicle.cpp +++ b/src/disaster_vehicle.cpp @@ -34,7 +34,6 @@ #include "town.h" #include "company_func.h" #include "strings_func.h" -#include "date_func.h" #include "viewport_func.h" #include "vehicle_func.h" #include "sound_func.h" @@ -923,7 +922,7 @@ static void DoDisaster() byte j = 0; for (size_t i = 0; i != lengthof(_disasters); i++) { - if (_cur_year >= _disasters[i].min_year && _cur_year < _disasters[i].max_year) buf[j++] = (byte)i; + if (TimerGameCalendar::year >= _disasters[i].min_year && TimerGameCalendar::year < _disasters[i].max_year) buf[j++] = (byte)i; } if (j == 0) return; diff --git a/src/economy.cpp b/src/economy.cpp index 6e5d135aca..49738746d8 100644 --- a/src/economy.cpp +++ b/src/economy.cpp @@ -29,7 +29,6 @@ #include "newgrf_roadstop.h" #include "object.h" #include "strings_func.h" -#include "date_func.h" #include "vehicle_func.h" #include "sound_func.h" #include "autoreplace_func.h" @@ -693,7 +692,7 @@ static void CompaniesGenStatistics() cur_company.Restore(); /* Only run the economic statics and update company stats every 3rd month (1st of quarter). */ - if (!HasBit(1 << 0 | 1 << 3 | 1 << 6 | 1 << 9, _cur_month)) return; + if (!HasBit(1 << 0 | 1 << 3 | 1 << 6 | 1 << 9, TimerGameCalendar::month)) return; for (Company *c : Company::Iterate()) { /* Drop the oldest history off the end */ @@ -737,7 +736,7 @@ bool AddInflation(bool check_year) * inflation doesn't add anything after that either; it even makes playing * it impossible due to the diverging cost and income rates. */ - if (check_year && (_cur_year < ORIGINAL_BASE_YEAR || _cur_year >= ORIGINAL_MAX_YEAR)) return true; + if (check_year && (TimerGameCalendar::year < ORIGINAL_BASE_YEAR || TimerGameCalendar::year >= ORIGINAL_MAX_YEAR)) return true; if (_economy.inflation_prices == MAX_INFLATION || _economy.inflation_payment == MAX_INFLATION) return true; @@ -846,8 +845,8 @@ static void CompaniesPayInterest() if (c->money < 0) { yearly_fee += -c->money *_economy.interest_rate / 100; } - Money up_to_previous_month = yearly_fee * _cur_month / 12; - Money up_to_this_month = yearly_fee * (_cur_month + 1) / 12; + Money up_to_previous_month = yearly_fee * TimerGameCalendar::month / 12; + Money up_to_this_month = yearly_fee * (TimerGameCalendar::month + 1) / 12; SubtractMoneyFromCompany(CommandCost(EXPENSES_LOAN_INTEREST, up_to_this_month - up_to_previous_month)); @@ -930,7 +929,7 @@ void StartupEconomy() if (_settings_game.economy.inflation) { /* Apply inflation that happened before our game start year. */ - int months = (std::min(_cur_year, ORIGINAL_MAX_YEAR) - ORIGINAL_BASE_YEAR) * 12; + int months = (std::min(TimerGameCalendar::year, ORIGINAL_MAX_YEAR) - ORIGINAL_BASE_YEAR) * 12; for (int i = 0; i < months; i++) { AddInflation(false); } @@ -1082,7 +1081,7 @@ static uint DeliverGoodsToIndustry(const Station *st, CargoID cargo_type, uint n uint amount = std::min(num_pieces, 0xFFFFu - ind->incoming_cargo_waiting[cargo_index]); ind->incoming_cargo_waiting[cargo_index] += amount; - ind->last_cargo_accepted_at[cargo_index] = _date; + ind->last_cargo_accepted_at[cargo_index] = TimerGameCalendar::date; num_pieces -= amount; accepted += amount; @@ -1778,7 +1777,7 @@ static void LoadUnloadVehicle(Vehicle *front) /* if last speed is 0, we treat that as if no vehicle has ever visited the station. */ ge->last_speed = std::min(t, 255); - ge->last_age = std::min(_cur_year - front->build_year, 255); + ge->last_age = std::min(TimerGameCalendar::year - front->build_year, 255); assert(v->cargo_cap >= v->cargo.StoredCount()); /* Capacity available for loading more cargo. */ @@ -2048,7 +2047,7 @@ CommandCost CmdBuyShareInCompany(DoCommandFlag flags, CompanyID target_company) if (c == nullptr || !_settings_game.economy.allow_shares || _current_company == target_company) return CMD_ERROR; /* Protect new companies from hostile takeovers */ - if (_cur_year - c->inaugurated_year < _settings_game.economy.min_years_for_shares) return_cmd_error(STR_ERROR_PROTECTED); + if (TimerGameCalendar::year - c->inaugurated_year < _settings_game.economy.min_years_for_shares) return_cmd_error(STR_ERROR_PROTECTED); /* Those lines are here for network-protection (clients can be slow) */ if (GetAmountOwnedBy(c, INVALID_OWNER) == 0) return cost; diff --git a/src/engine.cpp b/src/engine.cpp index 769d350c5c..393854546d 100644 --- a/src/engine.cpp +++ b/src/engine.cpp @@ -675,7 +675,7 @@ void StartupOneEngine(Engine *e, Date aging_date, uint32 seed) * of engines in early starting games. * Note: TTDP uses fixed 1922 */ e->intro_date = ei->base_intro <= ConvertYMDToDate(_settings_game.game_creation.starting_year + 2, 0, 1) ? ei->base_intro : (Date)GB(r, 0, 9) + ei->base_intro; - if (e->intro_date <= _date) { + if (e->intro_date <= TimerGameCalendar::date) { e->age = (aging_date - e->intro_date) >> 5; e->company_avail = MAX_UVALUE(CompanyMask); e->flags |= ENGINE_AVAILABLE; @@ -721,7 +721,7 @@ void StartupOneEngine(Engine *e, Date aging_date, uint32 seed) void StartupEngines() { /* Aging of vehicles stops, so account for that when starting late */ - const Date aging_date = std::min(_date, ConvertYMDToDate(_year_engine_aging_stops, 0, 1)); + const Date aging_date = std::min(TimerGameCalendar::date, ConvertYMDToDate(_year_engine_aging_stops, 0, 1)); uint32 seed = Random(); for (Engine *e : Engine::Iterate()) { @@ -883,11 +883,11 @@ static bool IsVehicleTypeDisabled(VehicleType type, bool ai) static IntervalTimer _engines_daily({TimerGameCalendar::DAY, TimerGameCalendar::Priority::ENGINE}, [](auto) { for (Company *c : Company::Iterate()) { - c->avail_railtypes = AddDateIntroducedRailTypes(c->avail_railtypes, _date); - c->avail_roadtypes = AddDateIntroducedRoadTypes(c->avail_roadtypes, _date); + c->avail_railtypes = AddDateIntroducedRailTypes(c->avail_railtypes, TimerGameCalendar::date); + c->avail_roadtypes = AddDateIntroducedRoadTypes(c->avail_roadtypes, TimerGameCalendar::date); } - if (_cur_year >= _year_engine_aging_stops) return; + if (TimerGameCalendar::year >= _year_engine_aging_stops) return; for (Engine *e : Engine::Iterate()) { EngineID i = e->index; @@ -1038,11 +1038,11 @@ static void NewVehicleAvailable(Engine *e) if (e->type == VEH_TRAIN) { /* maybe make another rail type available */ assert(e->u.rail.railtype < RAILTYPE_END); - for (Company *c : Company::Iterate()) c->avail_railtypes = AddDateIntroducedRailTypes(c->avail_railtypes | GetRailTypeInfo(e->u.rail.railtype)->introduces_railtypes, _date); + for (Company *c : Company::Iterate()) c->avail_railtypes = AddDateIntroducedRailTypes(c->avail_railtypes | GetRailTypeInfo(e->u.rail.railtype)->introduces_railtypes, TimerGameCalendar::date); } else if (e->type == VEH_ROAD) { /* maybe make another road type available */ assert(e->u.road.roadtype < ROADTYPE_END); - for (Company* c : Company::Iterate()) c->avail_roadtypes = AddDateIntroducedRoadTypes(c->avail_roadtypes | GetRoadTypeInfo(e->u.road.roadtype)->introduces_roadtypes, _date); + for (Company* c : Company::Iterate()) c->avail_roadtypes = AddDateIntroducedRoadTypes(c->avail_roadtypes | GetRoadTypeInfo(e->u.road.roadtype)->introduces_roadtypes, TimerGameCalendar::date); } /* Only broadcast event if AIs are able to build this vehicle type. */ @@ -1067,7 +1067,7 @@ static void NewVehicleAvailable(Engine *e) /** Monthly update of the availability, reliability, and preview offers of the engines. */ void EnginesMonthlyLoop() { - if (_cur_year < _year_engine_aging_stops) { + if (TimerGameCalendar::year < _year_engine_aging_stops) { bool refresh = false; for (Engine *e : Engine::Iterate()) { /* Age the vehicle */ @@ -1080,10 +1080,10 @@ void EnginesMonthlyLoop() /* Do not introduce invalid engines */ if (!e->IsEnabled()) continue; - if (!(e->flags & ENGINE_AVAILABLE) && _date >= (e->intro_date + DAYS_IN_YEAR)) { + if (!(e->flags & ENGINE_AVAILABLE) && TimerGameCalendar::date >= (e->intro_date + DAYS_IN_YEAR)) { /* Introduce it to all companies */ NewVehicleAvailable(e); - } else if (!(e->flags & (ENGINE_AVAILABLE | ENGINE_EXCLUSIVE_PREVIEW)) && _date >= e->intro_date) { + } else if (!(e->flags & (ENGINE_AVAILABLE | ENGINE_EXCLUSIVE_PREVIEW)) && TimerGameCalendar::date >= e->intro_date) { /* Introduction date has passed... * Check if it is allowed to build this vehicle type at all * based on the current game settings. If not, it does not diff --git a/src/genworld.cpp b/src/genworld.cpp index 4ae44b98eb..2a994b682b 100644 --- a/src/genworld.cpp +++ b/src/genworld.cpp @@ -17,6 +17,7 @@ #include "heightmap.h" #include "viewport_func.h" #include "date_func.h" +#include "timer/timer_game_calendar.h" #include "engine_func.h" #include "water.h" #include "video/video_driver.hpp" @@ -193,7 +194,7 @@ static void _GenerateWorld() if (_debug_desync_level > 0) { char name[MAX_PATH]; - seprintf(name, lastof(name), "dmp_cmds_%08x_%08x.sav", _settings_game.game_creation.generation_seed, _date); + seprintf(name, lastof(name), "dmp_cmds_%08x_%08x.sav", _settings_game.game_creation.generation_seed, TimerGameCalendar::date); SaveOrLoad(name, SLO_SAVE, DFT_GAME_FILE, AUTOSAVE_DIR, false); } } catch (AbortGenerateWorldSignal&) { diff --git a/src/goal_gui.cpp b/src/goal_gui.cpp index 1d81131321..bf7381c140 100644 --- a/src/goal_gui.cpp +++ b/src/goal_gui.cpp @@ -12,7 +12,6 @@ #include "town.h" #include "window_gui.h" #include "strings_func.h" -#include "date_func.h" #include "viewport_func.h" #include "gui.h" #include "goal_base.h" diff --git a/src/graph_gui.cpp b/src/graph_gui.cpp index 5ac49097bf..6dfc366f49 100644 --- a/src/graph_gui.cpp +++ b/src/graph_gui.cpp @@ -16,7 +16,7 @@ #include "cargotype.h" #include "strings_func.h" #include "window_func.h" -#include "date_func.h" +#include "timer/timer_game_calendar.h" #include "gfx_func.h" #include "core/geometry_func.hpp" #include "currency.h" @@ -581,8 +581,8 @@ public: nums = std::min(this->num_vert_lines, std::max(nums, c->num_valid_stat_ent)); } - int mo = (_cur_month / 3 - nums) * 3; - int yr = _cur_year; + int mo = (TimerGameCalendar::month / 3 - nums) * 3; + int yr = TimerGameCalendar::year; while (mo < 0) { yr--; mo += 12; diff --git a/src/highscore_gui.cpp b/src/highscore_gui.cpp index 8bc256067f..762aac2e11 100644 --- a/src/highscore_gui.cpp +++ b/src/highscore_gui.cpp @@ -24,7 +24,6 @@ #include "misc_cmd.h" #include "timer/timer.h" #include "timer/timer_game_calendar.h" -#include "date_func.h" #include "widgets/highscore_widget.h" @@ -260,7 +259,7 @@ static IntervalTimer _check_end_game({TimerGameCalendar::YEAR if (_settings_game.game_creation.ending_year == 0) return; /* Show the end-game chart at the end of the ending year (hence the + 1). */ - if (_cur_year == _settings_game.game_creation.ending_year + 1) { + if (TimerGameCalendar::year == _settings_game.game_creation.ending_year + 1) { ShowEndGameChart(); } }); diff --git a/src/industry_cmd.cpp b/src/industry_cmd.cpp index 2b6566a255..d67c3f1347 100644 --- a/src/industry_cmd.cpp +++ b/src/industry_cmd.cpp @@ -1796,11 +1796,11 @@ static void DoCreateNewIndustry(Industry *i, TileIndex tile, IndustryType type, i->counter = GB(r, 4, 12); i->random = initial_random_bits; i->was_cargo_delivered = false; - i->last_prod_year = _cur_year; + i->last_prod_year = TimerGameCalendar::year; i->founder = founder; i->ctlflags = INDCTL_NONE; - i->construction_date = _date; + i->construction_date = TimerGameCalendar::date; i->construction_type = (_game_mode == GM_EDITOR) ? ICT_SCENARIO_EDITOR : (_generating_world ? ICT_MAP_GENERATION : ICT_NORMAL_GAMEPLAY); @@ -2246,8 +2246,8 @@ static uint16 GetIndustryGamePlayProbability(IndustryType it, byte *min_number) const IndustrySpec *ind_spc = GetIndustrySpec(it); byte chance = ind_spc->appear_ingame[_settings_game.game_creation.landscape]; if (!ind_spc->enabled || ind_spc->layouts.empty() || - ((ind_spc->behaviour & INDUSTRYBEH_BEFORE_1950) && _cur_year > 1950) || - ((ind_spc->behaviour & INDUSTRYBEH_AFTER_1960) && _cur_year < 1960) || + ((ind_spc->behaviour & INDUSTRYBEH_BEFORE_1950) && TimerGameCalendar::year > 1950) || + ((ind_spc->behaviour & INDUSTRYBEH_AFTER_1960) && TimerGameCalendar::year < 1960) || (chance = GetIndustryProbabilityCallback(it, IACT_RANDOMCREATION, chance)) == 0) { *min_number = 0; return 0; @@ -2421,7 +2421,7 @@ static void UpdateIndustryStatistics(Industry *i) if (i->produced_cargo[j] != CT_INVALID) { byte pct = 0; if (i->this_month_production[j] != 0) { - i->last_prod_year = _cur_year; + i->last_prod_year = TimerGameCalendar::year; pct = std::min(i->this_month_transported[j] * 256 / i->this_month_production[j], 255); } i->last_month_pct_transported[j] = pct; @@ -2856,7 +2856,7 @@ static void ChangeIndustryProduction(Industry *i, bool monthly) if ((i->ctlflags & INDCTL_NO_PRODUCTION_INCREASE) && (mul > 0 || increment > 0)) return; if (!callback_enabled && (indspec->life_type & INDUSTRYLIFE_PROCESSING)) { - if ( (byte)(_cur_year - i->last_prod_year) >= 5 && Chance16(1, original_economy ? 2 : 180)) { + if ( (byte)(TimerGameCalendar::year - i->last_prod_year) >= 5 && Chance16(1, original_economy ? 2 : 180)) { closeit = true; } } diff --git a/src/landscape.cpp b/src/landscape.cpp index 3e81458e1e..653a9c1fc8 100644 --- a/src/landscape.cpp +++ b/src/landscape.cpp @@ -21,6 +21,7 @@ #include "genworld.h" #include "fios.h" #include "date_func.h" +#include "timer/timer_game_calendar.h" #include "water.h" #include "effectvehicle_func.h" #include "landscape_type.h" @@ -611,7 +612,7 @@ byte GetSnowLine() if (_snow_line == nullptr) return _settings_game.game_creation.snow_line_height; YearMonthDay ymd; - ConvertDateToYMD(_date, &ymd); + ConvertDateToYMD(TimerGameCalendar::date, &ymd); return _snow_line->table[ymd.month][ymd.day]; } diff --git a/src/linkgraph/linkgraph.cpp b/src/linkgraph/linkgraph.cpp index c84c62b7e6..f3b469e411 100644 --- a/src/linkgraph/linkgraph.cpp +++ b/src/linkgraph/linkgraph.cpp @@ -65,7 +65,7 @@ void LinkGraph::ShiftDates(int interval) void LinkGraph::Compress() { - this->last_compression = (_date + this->last_compression) / 2; + this->last_compression = (TimerGameCalendar::date + this->last_compression) / 2; for (NodeID node1 = 0; node1 < this->Size(); ++node1) { this->nodes[node1].supply /= 2; for (BaseEdge &edge : this->nodes[node1].edges) { @@ -89,8 +89,8 @@ void LinkGraph::Compress() */ void LinkGraph::Merge(LinkGraph *other) { - Date age = _date - this->last_compression + 1; - Date other_age = _date - other->last_compression + 1; + Date age = TimerGameCalendar::date - this->last_compression + 1; + Date other_age = TimerGameCalendar::date - other->last_compression + 1; NodeID first = this->Size(); for (NodeID node1 = 0; node1 < other->Size(); ++node1) { Station *st = Station::Get(other->nodes[node1].station); @@ -172,8 +172,8 @@ void LinkGraph::BaseNode::AddEdge(NodeID to, uint capacity, uint usage, uint32 t edge.capacity = capacity; edge.usage = usage; edge.travel_time_sum = static_cast(travel_time) * capacity; - if (mode & EUM_UNRESTRICTED) edge.last_unrestricted_update = _date; - if (mode & EUM_RESTRICTED) edge.last_restricted_update = _date; + if (mode & EUM_UNRESTRICTED) edge.last_unrestricted_update = TimerGameCalendar::date; + if (mode & EUM_RESTRICTED) edge.last_restricted_update = TimerGameCalendar::date; } /** @@ -239,8 +239,8 @@ void LinkGraph::BaseEdge::Update(uint capacity, uint usage, uint32 travel_time, } this->usage = std::max(this->usage, usage); } - if (mode & EUM_UNRESTRICTED) this->last_unrestricted_update = _date; - if (mode & EUM_RESTRICTED) this->last_restricted_update = _date; + if (mode & EUM_UNRESTRICTED) this->last_unrestricted_update = TimerGameCalendar::date; + if (mode & EUM_RESTRICTED) this->last_restricted_update = TimerGameCalendar::date; } /** diff --git a/src/linkgraph/linkgraph.h b/src/linkgraph/linkgraph.h index d9f8f9d9a7..41aa91b5a5 100644 --- a/src/linkgraph/linkgraph.h +++ b/src/linkgraph/linkgraph.h @@ -14,7 +14,7 @@ #include "../core/smallmap_type.hpp" #include "../station_base.h" #include "../cargotype.h" -#include "../date_func.h" +#include "../timer/timer_game_calendar.h" #include "../saveload/saveload.h" #include "linkgraph_type.h" #include @@ -106,7 +106,7 @@ public: void UpdateSupply(uint supply) { this->supply += supply; - this->last_update = _date; + this->last_update = TimerGameCalendar::date; } /** @@ -195,7 +195,7 @@ public: * Real constructor. * @param cargo Cargo the link graph is about. */ - LinkGraph(CargoID cargo) : cargo(cargo), last_compression(_date) {} + LinkGraph(CargoID cargo) : cargo(cargo), last_compression(TimerGameCalendar::date) {} void Init(uint size); void ShiftDates(int interval); @@ -249,7 +249,7 @@ public: */ inline uint Monthly(uint base) const { - return base * 30 / (_date - this->last_compression + 1); + return base * 30 / (TimerGameCalendar::date - this->last_compression + 1); } NodeID AddNode(const Station *st); diff --git a/src/linkgraph/linkgraphjob.cpp b/src/linkgraph/linkgraphjob.cpp index 6c5e889bc6..6551a9559e 100644 --- a/src/linkgraph/linkgraphjob.cpp +++ b/src/linkgraph/linkgraphjob.cpp @@ -37,7 +37,7 @@ LinkGraphJob::LinkGraphJob(const LinkGraph &orig) : * This is on purpose. */ link_graph(orig), settings(_settings_game.linkgraph), - join_date(_date + (_settings_game.linkgraph.recalc_time / SECONDS_PER_DAY)), + join_date(TimerGameCalendar::date + (_settings_game.linkgraph.recalc_time / SECONDS_PER_DAY)), job_completed(false), job_aborted(false) { diff --git a/src/linkgraph/linkgraphjob.h b/src/linkgraph/linkgraphjob.h index 5a25664ad2..6c6936dc1e 100644 --- a/src/linkgraph/linkgraphjob.h +++ b/src/linkgraph/linkgraphjob.h @@ -212,7 +212,7 @@ public: * Check if job is supposed to be finished. * @return True if job should be finished by now, false if not. */ - inline bool IsScheduledToBeJoined() const { return this->join_date <= _date; } + inline bool IsScheduledToBeJoined() const { return this->join_date <= TimerGameCalendar::date; } /** * Get the date when the job should be finished. diff --git a/src/linkgraph/linkgraphschedule.cpp b/src/linkgraph/linkgraphschedule.cpp index cdd057718b..ec30ce3eca 100644 --- a/src/linkgraph/linkgraphschedule.cpp +++ b/src/linkgraph/linkgraphschedule.cpp @@ -163,10 +163,10 @@ LinkGraphSchedule::~LinkGraphSchedule() } /** - * Pause the game if in 2 _date_fract ticks, we would do a join with the next + * Pause the game if in 2 TimerGameCalendar::date_fract ticks, we would do a join with the next * link graph job, but it is still running. - * The check is done 2 _date_fract ticks early instead of 1, as in multiplayer - * calls to DoCommandP are executed after a delay of 1 _date_fract tick. + * The check is done 2 TimerGameCalendar::date_fract ticks early instead of 1, as in multiplayer + * calls to DoCommandP are executed after a delay of 1 TimerGameCalendar::date_fract tick. * If we previously paused, unpause if the job is now ready to be joined with. */ void StateGameLoop_LinkGraphPauseControl() @@ -177,10 +177,10 @@ void StateGameLoop_LinkGraphPauseControl() Command::Post(PM_PAUSED_LINK_GRAPH, false); } } else if (_pause_mode == PM_UNPAUSED && - _date_fract == LinkGraphSchedule::SPAWN_JOIN_TICK - 2 && - _date % (_settings_game.linkgraph.recalc_interval / SECONDS_PER_DAY) == (_settings_game.linkgraph.recalc_interval / SECONDS_PER_DAY) / 2 && + TimerGameCalendar::date_fract == LinkGraphSchedule::SPAWN_JOIN_TICK - 2 && + TimerGameCalendar::date % (_settings_game.linkgraph.recalc_interval / SECONDS_PER_DAY) == (_settings_game.linkgraph.recalc_interval / SECONDS_PER_DAY) / 2 && LinkGraphSchedule::instance.IsJoinWithUnfinishedJobDue()) { - /* Perform check two _date_fract ticks before we would join, to make + /* Perform check two TimerGameCalendar::date_fract ticks before we would join, to make * sure it also works in multiplayer. */ Command::Post(PM_PAUSED_LINK_GRAPH, true); } @@ -204,8 +204,8 @@ void AfterLoad_LinkGraphPauseControl() */ void OnTick_LinkGraph() { - if (_date_fract != LinkGraphSchedule::SPAWN_JOIN_TICK) return; - Date offset = _date % (_settings_game.linkgraph.recalc_interval / SECONDS_PER_DAY); + if (TimerGameCalendar::date_fract != LinkGraphSchedule::SPAWN_JOIN_TICK) return; + Date offset = TimerGameCalendar::date % (_settings_game.linkgraph.recalc_interval / SECONDS_PER_DAY); if (offset == 0) { LinkGraphSchedule::instance.SpawnNext(); } else if (offset == (_settings_game.linkgraph.recalc_interval / SECONDS_PER_DAY) / 2) { diff --git a/src/misc.cpp b/src/misc.cpp index a9b3e19759..d95a20f950 100644 --- a/src/misc.cpp +++ b/src/misc.cpp @@ -73,7 +73,7 @@ void InitializeGame(uint size_x, uint size_y, bool reset_date, bool reset_settin _newgrf_profilers.clear(); if (reset_date) { - SetDate(ConvertYMDToDate(_settings_game.game_creation.starting_year, 0, 1), 0); + TimerGameCalendar::SetDate(ConvertYMDToDate(_settings_game.game_creation.starting_year, 0, 1), 0); InitializeOldNames(); } diff --git a/src/network/core/game_info.cpp b/src/network/core/game_info.cpp index 4cbcb31ba7..8ca1f1f1c1 100644 --- a/src/network/core/game_info.cpp +++ b/src/network/core/game_info.cpp @@ -14,6 +14,7 @@ #include "../../core/bitmath_func.hpp" #include "../../company_base.h" #include "../../date_func.h" +#include "../../timer/timer_game_calendar.h" #include "../../debug.h" #include "../../map_func.h" #include "../../game/game.hpp" @@ -149,7 +150,7 @@ const NetworkServerGameInfo *GetCurrentNetworkServerGameInfo() */ _network_game_info.companies_on = (byte)Company::GetNumItems(); _network_game_info.spectators_on = NetworkSpectatorCount(); - _network_game_info.game_date = _date; + _network_game_info.game_date = TimerGameCalendar::date; return &_network_game_info; } diff --git a/src/network/network.cpp b/src/network/network.cpp index 8acc740994..8e3b974a4d 100644 --- a/src/network/network.cpp +++ b/src/network/network.cpp @@ -11,7 +11,7 @@ #include "../strings_func.h" #include "../command_func.h" -#include "../date_func.h" +#include "../timer/timer_game_calendar.h" #include "network_admin.h" #include "network_client.h" #include "network_query.h" @@ -263,7 +263,7 @@ void NetworkTextMessage(NetworkAction action, TextColour colour, bool self_send, char *msg_ptr = message + Utf8Encode(message, _current_text_dir == TD_LTR ? CHAR_TD_LRM : CHAR_TD_RLM); GetString(msg_ptr, strid, lastof(message)); - Debug(desync, 1, "msg: {:08x}; {:02x}; {}", _date, _date_fract, message); + Debug(desync, 1, "msg: {:08x}; {:02x}; {}", TimerGameCalendar::date, TimerGameCalendar::date_fract, message); IConsolePrint(colour, message); NetworkAddChatMessage(colour, _settings_client.gui.network_chat_timeout, message); } @@ -1038,12 +1038,12 @@ void NetworkGameLoop() if (_network_server) { /* Log the sync state to check for in-syncedness of replays. */ - if (_date_fract == 0) { + if (TimerGameCalendar::date_fract == 0) { /* We don't want to log multiple times if paused. */ static Date last_log; - if (last_log != _date) { - Debug(desync, 1, "sync: {:08x}; {:02x}; {:08x}; {:08x}", _date, _date_fract, _random.state[0], _random.state[1]); - last_log = _date; + if (last_log != TimerGameCalendar::date) { + Debug(desync, 1, "sync: {:08x}; {:02x}; {:08x}; {:08x}", TimerGameCalendar::date, TimerGameCalendar::date_fract, _random.state[0], _random.state[1]); + last_log = TimerGameCalendar::date; } } @@ -1061,19 +1061,19 @@ void NetworkGameLoop() } while (f != nullptr && !feof(f)) { - if (_date == next_date && _date_fract == next_date_fract) { + if (TimerGameCalendar::date == next_date && TimerGameCalendar::date_fract == next_date_fract) { if (cp != nullptr) { NetworkSendCommand(cp->cmd, cp->err_msg, nullptr, cp->company, cp->data); - Debug(desync, 0, "Injecting: {:08x}; {:02x}; {:02x}; {:08x}; {:06x}; {} ({})", _date, _date_fract, (int)_current_company, cp->cmd, cp->tile, FormatArrayAsHex(cp->data), GetCommandName(cp->cmd)); + Debug(desync, 0, "Injecting: {:08x}; {:02x}; {:02x}; {:08x}; {:06x}; {} ({})", TimerGameCalendar::date, TimerGameCalendar::date_fract, (int)_current_company, cp->cmd, cp->tile, FormatArrayAsHex(cp->data), GetCommandName(cp->cmd)); delete cp; cp = nullptr; } if (check_sync_state) { if (sync_state[0] == _random.state[0] && sync_state[1] == _random.state[1]) { - Debug(desync, 0, "Sync check: {:08x}; {:02x}; match", _date, _date_fract); + Debug(desync, 0, "Sync check: {:08x}; {:02x}; match", TimerGameCalendar::date, TimerGameCalendar::date_fract); } else { Debug(desync, 0, "Sync check: {:08x}; {:02x}; mismatch expected {{{:08x}, {:08x}}}, got {{{:08x}, {:08x}}}", - _date, _date_fract, sync_state[0], sync_state[1], _random.state[0], _random.state[1]); + TimerGameCalendar::date, TimerGameCalendar::date_fract, sync_state[0], sync_state[1], _random.state[0], _random.state[1]); NOT_REACHED(); } check_sync_state = false; diff --git a/src/network/network_admin.cpp b/src/network/network_admin.cpp index 4a2baa3f23..eb48a482a4 100644 --- a/src/network/network_admin.cpp +++ b/src/network/network_admin.cpp @@ -10,6 +10,7 @@ #include "../stdafx.h" #include "../strings_func.h" #include "../date_func.h" +#include "../timer/timer_game_calendar.h" #include "core/game_info.h" #include "network_admin.h" #include "network_base.h" @@ -207,7 +208,7 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::SendDate() { Packet *p = new Packet(ADMIN_PACKET_SERVER_DATE); - p->Send_uint32(_date); + p->Send_uint32(TimerGameCalendar::date); this->SendPacket(p); return NETWORK_RECV_STATUS_OKAY; diff --git a/src/network/network_client.cpp b/src/network/network_client.cpp index 2912874560..3bfdaa118d 100644 --- a/src/network/network_client.cpp +++ b/src/network/network_client.cpp @@ -20,7 +20,7 @@ #include "../company_gui.h" #include "../company_cmd.h" #include "../core/random_func.hpp" -#include "../date_func.h" +#include "../timer/timer_game_calendar.h" #include "../gfx_func.h" #include "../error.h" #include "../rev.h" @@ -277,7 +277,7 @@ void ClientNetworkGameSocketHandler::ClientError(NetworkRecvStatus res) if (_sync_seed_1 != _random.state[0]) { #endif ShowNetworkError(STR_NETWORK_ERROR_DESYNC); - Debug(desync, 1, "sync_err: {:08x}; {:02x}", _date, _date_fract); + Debug(desync, 1, "sync_err: {:08x}; {:02x}", TimerGameCalendar::date, TimerGameCalendar::date_fract); Debug(net, 0, "Sync error detected"); my_client->ClientError(NETWORK_RECV_STATUS_DESYNC); return false; diff --git a/src/network/network_server.cpp b/src/network/network_server.cpp index 0d3a5aeaed..c98ff56d1d 100644 --- a/src/network/network_server.cpp +++ b/src/network/network_server.cpp @@ -9,7 +9,6 @@ #include "../stdafx.h" #include "../strings_func.h" -#include "../date_func.h" #include "core/game_info.h" #include "network_admin.h" #include "network_server.h" @@ -882,10 +881,10 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_JOIN(Packet *p) assert(NetworkClientInfo::CanAllocateItem()); NetworkClientInfo *ci = new NetworkClientInfo(this->client_id); this->SetInfo(ci); - ci->join_date = _date; + ci->join_date = TimerGameCalendar::date; ci->client_name = client_name; ci->client_playas = playas; - Debug(desync, 1, "client: {:08x}; {:02x}; {:02x}; {:02x}", _date, _date_fract, (int)ci->client_playas, (int)ci->index); + Debug(desync, 1, "client: {:08x}; {:02x}; {:02x}; {:02x}", TimerGameCalendar::date, TimerGameCalendar::date_fract, (int)ci->client_playas, (int)ci->index); /* Make sure companies to which people try to join are not autocleaned */ if (Company::IsValidID(playas)) _network_company_states[playas].months_empty = 0; @@ -1479,7 +1478,7 @@ void NetworkUpdateClientInfo(ClientID client_id) if (ci == nullptr) return; - Debug(desync, 1, "client: {:08x}; {:02x}; {:02x}; {:04x}", _date, _date_fract, (int)ci->client_playas, client_id); + Debug(desync, 1, "client: {:08x}; {:02x}; {:02x}; {:04x}", TimerGameCalendar::date, TimerGameCalendar::date_fract, (int)ci->client_playas, client_id); for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) { if (cs->status >= ServerNetworkGameSocketHandler::STATUS_AUTHORIZED) { @@ -1493,8 +1492,8 @@ void NetworkUpdateClientInfo(ClientID client_id) /** Check if we want to restart the map */ static void NetworkCheckRestartMap() { - if (_settings_client.network.restart_game_year != 0 && _cur_year >= _settings_client.network.restart_game_year) { - Debug(net, 3, "Auto-restarting map: year {} reached", _cur_year); + if (_settings_client.network.restart_game_year != 0 && TimerGameCalendar::year >= _settings_client.network.restart_game_year) { + Debug(net, 3, "Auto-restarting map: year {} reached", TimerGameCalendar::year); _settings_newgame.game_creation.generation_seed = GENERATE_NEW_SEED; switch(_file_to_saveload.abstract_ftype) { @@ -1829,7 +1828,7 @@ static IntervalTimer _network_monthly({TimerGameCalendar::MON NetworkAutoCleanCompanies(); NetworkAdminUpdate(ADMIN_FREQUENCY_MONTHLY); - if ((_cur_month % 3) == 0) NetworkAdminUpdate(ADMIN_FREQUENCY_QUARTERLY); + if ((TimerGameCalendar::month % 3) == 0) NetworkAdminUpdate(ADMIN_FREQUENCY_QUARTERLY); }); /** Daily "callback". Called whenever the date changes. */ @@ -1838,7 +1837,7 @@ static IntervalTimer _network_daily({TimerGameCalendar::DAY, if (!_network_server) return; NetworkAdminUpdate(ADMIN_FREQUENCY_DAILY); - if ((_date % 7) == 3) NetworkAdminUpdate(ADMIN_FREQUENCY_WEEKLY); + if ((TimerGameCalendar::date % 7) == 3) NetworkAdminUpdate(ADMIN_FREQUENCY_WEEKLY); }); /** diff --git a/src/newgrf.cpp b/src/newgrf.cpp index efdd9c357c..02e6356d76 100644 --- a/src/newgrf.cpp +++ b/src/newgrf.cpp @@ -6498,18 +6498,18 @@ bool GetGlobalVariable(byte param, uint32 *value, const GRFFile *grffile) { switch (param) { case 0x00: // current date - *value = std::max(_date - DAYS_TILL_ORIGINAL_BASE_YEAR, 0); + *value = std::max(TimerGameCalendar::date - DAYS_TILL_ORIGINAL_BASE_YEAR, 0); return true; case 0x01: // current year - *value = Clamp(_cur_year, ORIGINAL_BASE_YEAR, ORIGINAL_MAX_YEAR) - ORIGINAL_BASE_YEAR; + *value = Clamp(TimerGameCalendar::year, ORIGINAL_BASE_YEAR, ORIGINAL_MAX_YEAR) - ORIGINAL_BASE_YEAR; return true; case 0x02: { // detailed date information: month of year (bit 0-7), day of month (bit 8-12), leap year (bit 15), day of year (bit 16-24) YearMonthDay ymd; - ConvertDateToYMD(_date, &ymd); + ConvertDateToYMD(TimerGameCalendar::date, &ymd); Date start_of_year = ConvertYMDToDate(ymd.year, 0, 1); - *value = ymd.month | (ymd.day - 1) << 8 | (IsLeapYear(ymd.year) ? 1 << 15 : 0) | (_date - start_of_year) << 16; + *value = ymd.month | (ymd.day - 1) << 8 | (IsLeapYear(ymd.year) ? 1 << 15 : 0) | (TimerGameCalendar::date - start_of_year) << 16; return true; } @@ -6522,7 +6522,7 @@ bool GetGlobalVariable(byte param, uint32 *value, const GRFFile *grffile) return true; case 0x09: // date fraction - *value = _date_fract * 885; + *value = TimerGameCalendar::date_fract * 885; return true; case 0x0A: // animation counter @@ -6615,11 +6615,11 @@ bool GetGlobalVariable(byte param, uint32 *value, const GRFFile *grffile) return true; case 0x23: // long format date - *value = _date; + *value = TimerGameCalendar::date; return true; case 0x24: // long format year - *value = _cur_year; + *value = TimerGameCalendar::year; return true; default: return false; @@ -9939,16 +9939,16 @@ void LoadNewGRF(uint load_index, uint num_baseset) * so all NewGRFs are loaded equally. For this we use the * start date of the game and we set the counters, etc. to * 0 so they're the same too. */ - Date date = _date; - Year year = _cur_year; - DateFract date_fract = _date_fract; + Date date = TimerGameCalendar::date; + Year year = TimerGameCalendar::year; + DateFract date_fract = TimerGameCalendar::date_fract; uint64 tick_counter = _tick_counter; byte display_opt = _display_opt; if (_networking) { - _cur_year = _settings_game.game_creation.starting_year; - _date = ConvertYMDToDate(_cur_year, 0, 1); - _date_fract = 0; + TimerGameCalendar::year = _settings_game.game_creation.starting_year; + TimerGameCalendar::date = ConvertYMDToDate(TimerGameCalendar::year, 0, 1); + TimerGameCalendar::date_fract = 0; _tick_counter = 0; _display_opt = 0; } @@ -10043,9 +10043,9 @@ void LoadNewGRF(uint load_index, uint num_baseset) AfterLoadGRFs(); /* Now revert back to the original situation */ - _cur_year = year; - _date = date; - _date_fract = date_fract; + TimerGameCalendar::year = year; + TimerGameCalendar::date = date; + TimerGameCalendar::date_fract = date_fract; _tick_counter = tick_counter; _display_opt = display_opt; } diff --git a/src/newgrf_airport.cpp b/src/newgrf_airport.cpp index 3e81b68c68..b5e0b40a53 100644 --- a/src/newgrf_airport.cpp +++ b/src/newgrf_airport.cpp @@ -9,7 +9,7 @@ #include "stdafx.h" #include "debug.h" -#include "date_func.h" +#include "timer/timer_game_calendar.h" #include "newgrf_spritegroup.h" #include "newgrf_text.h" #include "station_base.h" @@ -124,9 +124,9 @@ AirportSpec AirportSpec::specs[NUM_AIRPORTS]; ///< Airport specifications. bool AirportSpec::IsAvailable() const { if (!this->enabled) return false; - if (_cur_year < this->min_year) return false; + if (TimerGameCalendar::year < this->min_year) return false; if (_settings_game.station.never_expire_airports) return true; - return _cur_year <= this->max_year; + return TimerGameCalendar::year <= this->max_year; } /** diff --git a/src/newgrf_engine.cpp b/src/newgrf_engine.cpp index 6fb9b1eb4d..63a195f52f 100644 --- a/src/newgrf_engine.cpp +++ b/src/newgrf_engine.cpp @@ -14,7 +14,7 @@ #include "company_func.h" #include "newgrf_cargo.h" #include "newgrf_spritegroup.h" -#include "date_func.h" +#include "timer/timer_game_calendar.h" #include "vehicle_func.h" #include "core/random_func.hpp" #include "aircraft.h" @@ -971,11 +971,11 @@ static uint32 VehicleGetVariable(Vehicle *v, const VehicleScopeResolver *object, } } case 0x48: return Engine::Get(this->self_type)->flags; // Vehicle Type Info - case 0x49: return _cur_year; // 'Long' format build year - case 0x4B: return _date; // Long date of last service - case 0x92: return Clamp(_date - DAYS_TILL_ORIGINAL_BASE_YEAR, 0, 0xFFFF); // Date of last service - case 0x93: return GB(Clamp(_date - DAYS_TILL_ORIGINAL_BASE_YEAR, 0, 0xFFFF), 8, 8); - case 0xC4: return Clamp(_cur_year, ORIGINAL_BASE_YEAR, ORIGINAL_MAX_YEAR) - ORIGINAL_BASE_YEAR; // Build year + case 0x49: return TimerGameCalendar::year; // 'Long' format build year + case 0x4B: return TimerGameCalendar::date; // Long date of last service + case 0x92: return Clamp(TimerGameCalendar::date - DAYS_TILL_ORIGINAL_BASE_YEAR, 0, 0xFFFF); // Date of last service + case 0x93: return GB(Clamp(TimerGameCalendar::date - DAYS_TILL_ORIGINAL_BASE_YEAR, 0, 0xFFFF), 8, 8); + case 0xC4: return Clamp(TimerGameCalendar::year, ORIGINAL_BASE_YEAR, ORIGINAL_MAX_YEAR) - ORIGINAL_BASE_YEAR; // Build year case 0xC6: return Engine::Get(this->self_type)->grf_prop.local_id; case 0xC7: return GB(Engine::Get(this->self_type)->grf_prop.local_id, 8, 8); case 0xDA: return INVALID_VEHICLE; // Next vehicle diff --git a/src/newgrf_object.cpp b/src/newgrf_object.cpp index 2595fcfc2c..076c89ca15 100644 --- a/src/newgrf_object.cpp +++ b/src/newgrf_object.cpp @@ -17,6 +17,7 @@ #include "newgrf_sound.h" #include "object_base.h" #include "object_map.h" +#include "timer/timer_game_calendar.h" #include "tile_cmd.h" #include "town.h" #include "water.h" @@ -82,7 +83,7 @@ bool ObjectSpec::IsEverAvailable() const */ bool ObjectSpec::WasEverAvailable() const { - return this->IsEverAvailable() && _date > this->introduction_date; + return this->IsEverAvailable() && TimerGameCalendar::date > this->introduction_date; } /** @@ -92,7 +93,7 @@ bool ObjectSpec::WasEverAvailable() const bool ObjectSpec::IsAvailable() const { return this->WasEverAvailable() && - (_date < this->end_of_life_date || this->end_of_life_date < this->introduction_date + 365); + (TimerGameCalendar::date < this->end_of_life_date || this->end_of_life_date < this->introduction_date + 365); } /** @@ -276,7 +277,7 @@ static uint32 GetCountAndDistanceOfClosestInstance(byte local_id, uint32 grfid, break; /* Construction date */ - case 0x42: return _date; + case 0x42: return TimerGameCalendar::date; /* Object founder information */ case 0x44: return _current_company; diff --git a/src/newgrf_profiling.cpp b/src/newgrf_profiling.cpp index 451af9a18e..88b9e64b61 100644 --- a/src/newgrf_profiling.cpp +++ b/src/newgrf_profiling.cpp @@ -166,7 +166,7 @@ uint32 NewGRFProfiler::FinishAll() */ static IntervalTimer _check_profiling_finished({TimerGameCalendar::DAY, TimerGameCalendar::Priority::NONE}, [](auto) { - if (_newgrf_profilers.empty() || _newgrf_profile_end_date > _date) return; + if (_newgrf_profilers.empty() || _newgrf_profile_end_date > TimerGameCalendar::date) return; NewGRFProfiler::FinishAll(); }); diff --git a/src/newgrf_railtype.cpp b/src/newgrf_railtype.cpp index c6e2b1c40d..848d51f230 100644 --- a/src/newgrf_railtype.cpp +++ b/src/newgrf_railtype.cpp @@ -10,7 +10,7 @@ #include "stdafx.h" #include "debug.h" #include "newgrf_railtype.h" -#include "date_func.h" +#include "timer/timer_game_calendar.h" #include "depot_base.h" #include "town.h" @@ -29,7 +29,7 @@ case 0x40: return 0; case 0x41: return 0; case 0x42: return 0; - case 0x43: return _date; + case 0x43: return TimerGameCalendar::date; case 0x44: return HZB_TOWN_EDGE; } } @@ -40,7 +40,7 @@ case 0x42: return IsLevelCrossingTile(this->tile) && IsCrossingBarred(this->tile); case 0x43: if (IsRailDepotTile(this->tile)) return Depot::GetByTile(this->tile)->build_date; - return _date; + return TimerGameCalendar::date; case 0x44: { const Town *t = nullptr; if (IsRailDepotTile(this->tile)) { diff --git a/src/newgrf_roadstop.cpp b/src/newgrf_roadstop.cpp index 76b901d8f7..a311ee2f79 100644 --- a/src/newgrf_roadstop.cpp +++ b/src/newgrf_roadstop.cpp @@ -19,7 +19,7 @@ #include "company_func.h" #include "road.h" #include "window_type.h" -#include "date_func.h" +#include "timer/timer_game_calendar.h" #include "town.h" #include "viewport_func.h" #include "newgrf_animation_base.h" @@ -176,7 +176,7 @@ uint32 RoadStopScopeResolver::GetVariable(byte variable, uint32 parameter, bool case 0xF0: return this->st == nullptr ? 0 : this->st->facilities; // facilities - case 0xFA: return Clamp((this->st == nullptr ? _date : this->st->build_date) - DAYS_TILL_ORIGINAL_BASE_YEAR, 0, 65535); // build date + case 0xFA: return Clamp((this->st == nullptr ? TimerGameCalendar::date : this->st->build_date) - DAYS_TILL_ORIGINAL_BASE_YEAR, 0, 65535); // build date } if (this->st != nullptr) return this->st->GetNewGRFVariable(this->ro, variable, parameter, available); diff --git a/src/newgrf_roadtype.cpp b/src/newgrf_roadtype.cpp index a0cab4b15d..ecd1ce54e5 100644 --- a/src/newgrf_roadtype.cpp +++ b/src/newgrf_roadtype.cpp @@ -10,7 +10,7 @@ #include "stdafx.h" #include "debug.h" #include "newgrf_roadtype.h" -#include "date_func.h" +#include "timer/timer_game_calendar.h" #include "depot_base.h" #include "town.h" @@ -29,7 +29,7 @@ case 0x40: return 0; case 0x41: return 0; case 0x42: return 0; - case 0x43: return _date; + case 0x43: return TimerGameCalendar::date; case 0x44: return HZB_TOWN_EDGE; } } @@ -40,7 +40,7 @@ case 0x42: return IsLevelCrossingTile(this->tile) && IsCrossingBarred(this->tile); case 0x43: if (IsRoadDepotTile(this->tile)) return Depot::GetByTile(this->tile)->build_date; - return _date; + return TimerGameCalendar::date; case 0x44: { const Town *t = nullptr; if (IsRoadDepotTile(this->tile)) { diff --git a/src/newgrf_station.cpp b/src/newgrf_station.cpp index 671104fe23..ba6ee47fad 100644 --- a/src/newgrf_station.cpp +++ b/src/newgrf_station.cpp @@ -23,6 +23,7 @@ #include "tunnelbridge_map.h" #include "newgrf_animation_base.h" #include "newgrf_class_func.h" +#include "timer/timer_game_calendar.h" #include "safeguards.h" @@ -293,7 +294,7 @@ TownScopeResolver *StationResolverObject::GetTown() } break; - case 0xFA: return Clamp(_date - DAYS_TILL_ORIGINAL_BASE_YEAR, 0, 65535); // Build date, clamped to a 16 bit value + case 0xFA: return Clamp(TimerGameCalendar::date - DAYS_TILL_ORIGINAL_BASE_YEAR, 0, 65535); // Build date, clamped to a 16 bit value } *available = false; diff --git a/src/news_gui.cpp b/src/news_gui.cpp index 5b098ac47f..18d73ac9d9 100644 --- a/src/news_gui.cpp +++ b/src/news_gui.cpp @@ -13,6 +13,7 @@ #include "strings_func.h" #include "window_func.h" #include "date_func.h" +#include "timer/timer_game_calendar.h" #include "vehicle_base.h" #include "vehicle_func.h" #include "vehicle_gui.h" @@ -686,7 +687,7 @@ static void MoveToNextTickerItem() const NewsType type = ni->type; /* check the date, don't show too old items */ - if (_date - _news_type_data[type].age > ni->date) continue; + if (TimerGameCalendar::date - _news_type_data[type].age > ni->date) continue; switch (_news_type_data[type].GetDisplay()) { default: NOT_REACHED(); @@ -723,7 +724,7 @@ static void MoveToNextNewsItem() const NewsType type = ni->type; /* check the date, don't show too old items */ - if (_date - _news_type_data[type].age > ni->date) continue; + if (TimerGameCalendar::date - _news_type_data[type].age > ni->date) continue; switch (_news_type_data[type].GetDisplay()) { default: NOT_REACHED(); @@ -800,10 +801,10 @@ static void DeleteNewsItem(NewsItem *ni) * @see NewsSubtype */ NewsItem::NewsItem(StringID string_id, NewsType type, NewsFlag flags, NewsReferenceType reftype1, uint32 ref1, NewsReferenceType reftype2, uint32 ref2, const NewsAllocatedData *data) : - string_id(string_id), date(_date), type(type), flags(flags), reftype1(reftype1), reftype2(reftype2), ref1(ref1), ref2(ref2), data(data) + string_id(string_id), date(TimerGameCalendar::date), type(type), flags(flags), reftype1(reftype1), reftype2(reftype2), ref1(ref1), ref2(ref2), data(data) { /* show this news message in colour? */ - if (_cur_year >= _settings_client.gui.coloured_news_year) this->flags |= NF_INCOLOUR; + if (TimerGameCalendar::year >= _settings_client.gui.coloured_news_year) this->flags |= NF_INCOLOUR; CopyOutDParam(this->params, 0, lengthof(this->params)); } @@ -983,7 +984,7 @@ static void RemoveOldNewsItems() NewsItem *next; for (NewsItem *cur = _oldest_news; _total_news > MIN_NEWS_AMOUNT && cur != nullptr; cur = next) { next = cur->next; - if (_date - _news_type_data[cur->type].age * _settings_client.gui.news_message_timeout > cur->date) DeleteNewsItem(cur); + if (TimerGameCalendar::date - _news_type_data[cur->type].age * _settings_client.gui.news_message_timeout > cur->date) DeleteNewsItem(cur); } } @@ -1009,9 +1010,9 @@ void NewsLoop() static byte _last_clean_month = 0; - if (_last_clean_month != _cur_month) { + if (_last_clean_month != TimerGameCalendar::month) { RemoveOldNewsItems(); - _last_clean_month = _cur_month; + _last_clean_month = TimerGameCalendar::month; } if (ReadyForNextTickerItem()) MoveToNextTickerItem(); diff --git a/src/object_cmd.cpp b/src/object_cmd.cpp index 7748605186..f0f37f52f6 100644 --- a/src/object_cmd.cpp +++ b/src/object_cmd.cpp @@ -29,7 +29,7 @@ #include "object_base.h" #include "newgrf_config.h" #include "newgrf_object.h" -#include "date_func.h" +#include "timer/timer_game_calendar.h" #include "newgrf_debug.h" #include "vehicle_func.h" #include "station_func.h" @@ -92,7 +92,7 @@ void BuildObject(ObjectType type, TileIndex tile, CompanyID owner, Town *town, u o->type = type; o->location = ta; o->town = town == nullptr ? CalcClosestTownFromTile(tile) : town; - o->build_date = _date; + o->build_date = TimerGameCalendar::date; o->view = view; /* If nothing owns the object, the colour will be random. Otherwise diff --git a/src/openttd.cpp b/src/openttd.cpp index 3c498049f7..ffd5ceca9c 100644 --- a/src/openttd.cpp +++ b/src/openttd.cpp @@ -39,7 +39,6 @@ #include "genworld.h" #include "progress.h" #include "strings_func.h" -#include "date_func.h" #include "vehicle_func.h" #include "gamelog.h" #include "animated_tile_func.h" @@ -852,7 +851,7 @@ static void OnStartScenario() /* Make sure all industries were built "this year", to avoid too early closures. (#9918) */ for (Industry *i : Industry::Iterate()) { - i->last_prod_year = _cur_year; + i->last_prod_year = TimerGameCalendar::year; } } @@ -1106,7 +1105,7 @@ void SwitchToMode(SwitchMode new_mode) case SM_LOAD_SCENARIO: { // Load scenario from scenario editor if (SafeLoad(_file_to_saveload.name, _file_to_saveload.file_op, _file_to_saveload.detail_ftype, GM_EDITOR, NO_DIRECTORY)) { SetLocalCompany(OWNER_NONE); - _settings_newgame.game_creation.starting_year = _cur_year; + _settings_newgame.game_creation.starting_year = TimerGameCalendar::year; /* Cancel the saveload pausing */ Command::Post(PM_PAUSED_SAVELOAD, false); } else { @@ -1390,10 +1389,10 @@ void StateGameLoop() CallWindowGameTickEvent(); NewsLoop(); } else { - if (_debug_desync_level > 2 && _date_fract == 0 && (_date & 0x1F) == 0) { + if (_debug_desync_level > 2 && TimerGameCalendar::date_fract == 0 && (TimerGameCalendar::date & 0x1F) == 0) { /* Save the desync savegame if needed. */ char name[MAX_PATH]; - seprintf(name, lastof(name), "dmp_cmds_%08x_%08x.sav", _settings_game.game_creation.generation_seed, _date); + seprintf(name, lastof(name), "dmp_cmds_%08x_%08x.sav", _settings_game.game_creation.generation_seed, TimerGameCalendar::date); SaveOrLoad(name, SLO_SAVE, DFT_GAME_FILE, AUTOSAVE_DIR, false); } @@ -1432,7 +1431,7 @@ void StateGameLoop() static IntervalTimer _autosave_interval({TimerGameCalendar::MONTH, TimerGameCalendar::Priority::AUTOSAVE}, [](auto) { if (_settings_client.gui.autosave == 0) return; - if ((_cur_month % _autosave_months[_settings_client.gui.autosave]) != 0) return; + if ((TimerGameCalendar::month % _autosave_months[_settings_client.gui.autosave]) != 0) return; _do_autosave = true; SetWindowDirty(WC_STATUS_BAR, 0); diff --git a/src/rail.cpp b/src/rail.cpp index dd7550d7d3..0978d6b143 100644 --- a/src/rail.cpp +++ b/src/rail.cpp @@ -10,7 +10,7 @@ #include "stdafx.h" #include "station_map.h" #include "tunnelbridge_map.h" -#include "date_func.h" +#include "timer/timer_game_calendar.h" #include "company_func.h" #include "company_base.h" #include "engine_base.h" @@ -256,7 +256,7 @@ RailTypes GetCompanyRailtypes(CompanyID company, bool introduces) const EngineInfo *ei = &e->info; if (HasBit(ei->climates, _settings_game.game_creation.landscape) && - (HasBit(e->company_avail, company) || _date >= e->intro_date + DAYS_IN_YEAR)) { + (HasBit(e->company_avail, company) || TimerGameCalendar::date >= e->intro_date + DAYS_IN_YEAR)) { const RailVehicleInfo *rvi = &e->u.rail; if (rvi->railveh_type != RAILVEH_WAGON) { @@ -270,7 +270,7 @@ RailTypes GetCompanyRailtypes(CompanyID company, bool introduces) } } - if (introduces) return AddDateIntroducedRailTypes(rts, _date); + if (introduces) return AddDateIntroducedRailTypes(rts, TimerGameCalendar::date); return rts; } diff --git a/src/rail_cmd.cpp b/src/rail_cmd.cpp index d6c8489b52..a2c97af8b7 100644 --- a/src/rail_cmd.cpp +++ b/src/rail_cmd.cpp @@ -26,7 +26,7 @@ #include "pbs.h" #include "company_base.h" #include "core/backup_type.hpp" -#include "date_func.h" +#include "timer/timer_game_calendar.h" #include "strings_func.h" #include "company_gui.h" #include "object_map.h" @@ -997,7 +997,7 @@ CommandCost CmdBuildTrainDepot(DoCommandFlag flags, TileIndex tile, RailType rai if (flags & DC_EXEC) { Depot *d = new Depot(tile); - d->build_date = _date; + d->build_date = TimerGameCalendar::date; MakeRailDepot(tile, _current_company, d->index, dir, railtype); MarkTileDirtyByTile(tile); diff --git a/src/rail_gui.cpp b/src/rail_gui.cpp index fa639344c7..885fb80c8e 100644 --- a/src/rail_gui.cpp +++ b/src/rail_gui.cpp @@ -19,7 +19,6 @@ #include "company_base.h" #include "strings_func.h" #include "window_func.h" -#include "date_func.h" #include "sound_func.h" #include "company_func.h" #include "widgets/dropdown_type.h" @@ -250,7 +249,7 @@ static void GenericPlaceSignals(TileIndex tile) Command::Post(_convert_signal_button ? STR_ERROR_SIGNAL_CAN_T_CONVERT_SIGNALS_HERE : STR_ERROR_CAN_T_BUILD_SIGNALS_HERE, CcPlaySound_CONSTRUCTION_RAIL, tile, track, _cur_signal_type, _cur_signal_variant, _convert_signal_button, false, _ctrl_pressed, cycle_start, SIGTYPE_LAST, 0, 0); } else { - SignalVariant sigvar = _cur_year < _settings_client.gui.semaphore_build_before ? SIG_SEMAPHORE : SIG_ELECTRIC; + SignalVariant sigvar = TimerGameCalendar::year < _settings_client.gui.semaphore_build_before ? SIG_SEMAPHORE : SIG_ELECTRIC; Command::Post(STR_ERROR_CAN_T_BUILD_SIGNALS_HERE, CcPlaySound_CONSTRUCTION_RAIL, tile, track, _settings_client.gui.default_signal_type, sigvar, false, false, _ctrl_pressed, cycle_start, SIGTYPE_LAST, 0, 0); @@ -399,7 +398,7 @@ static void HandleAutoSignalPlacement() } else { bool sig_gui = FindWindowById(WC_BUILD_SIGNAL, 0) != nullptr; SignalType sigtype = sig_gui ? _cur_signal_type : _settings_client.gui.default_signal_type; - SignalVariant sigvar = sig_gui ? _cur_signal_variant : (_cur_year < _settings_client.gui.semaphore_build_before ? SIG_SEMAPHORE : SIG_ELECTRIC); + SignalVariant sigvar = sig_gui ? _cur_signal_variant : (TimerGameCalendar::year < _settings_client.gui.semaphore_build_before ? SIG_SEMAPHORE : SIG_ELECTRIC); Command::Post(STR_ERROR_CAN_T_BUILD_SIGNALS_HERE, CcPlaySound_CONSTRUCTION_RAIL, TileVirtXY(_thd.selstart.x, _thd.selstart.y), TileVirtXY(_thd.selend.x, _thd.selend.y), track, sigtype, sigvar, false, _ctrl_pressed, !_settings_client.gui.drag_signals_fixed_distance, _settings_client.gui.drag_signals_density); } @@ -2195,7 +2194,7 @@ static void SetDefaultRailGui() */ void ResetSignalVariant(int32 new_value) { - SignalVariant new_variant = (_cur_year < _settings_client.gui.semaphore_build_before ? SIG_SEMAPHORE : SIG_ELECTRIC); + SignalVariant new_variant = (TimerGameCalendar::year < _settings_client.gui.semaphore_build_before ? SIG_SEMAPHORE : SIG_ELECTRIC); if (new_variant != _cur_signal_variant) { Window *w = FindWindowById(WC_BUILD_SIGNAL, 0); @@ -2209,7 +2208,7 @@ void ResetSignalVariant(int32 new_value) static IntervalTimer _check_reset_signal({TimerGameCalendar::YEAR, TimerGameCalendar::Priority::NONE}, [](auto) { - if (_cur_year != _settings_client.gui.semaphore_build_before) return; + if (TimerGameCalendar::year != _settings_client.gui.semaphore_build_before) return; ResetSignalVariant(); }); diff --git a/src/road.cpp b/src/road.cpp index 5c5429bdbf..97c6639115 100644 --- a/src/road.cpp +++ b/src/road.cpp @@ -15,7 +15,7 @@ #include "company_func.h" #include "company_base.h" #include "engine_base.h" -#include "date_func.h" +#include "timer/timer_game_calendar.h" #include "landscape.h" #include "road.h" #include "road_func.h" @@ -194,7 +194,7 @@ RoadTypes GetCompanyRoadTypes(CompanyID company, bool introduces) const EngineInfo *ei = &e->info; if (HasBit(ei->climates, _settings_game.game_creation.landscape) && - (HasBit(e->company_avail, company) || _date >= e->intro_date + DAYS_IN_YEAR)) { + (HasBit(e->company_avail, company) || TimerGameCalendar::date >= e->intro_date + DAYS_IN_YEAR)) { const RoadVehicleInfo *rvi = &e->u.road; assert(rvi->roadtype < ROADTYPE_END); if (introduces) { @@ -205,7 +205,7 @@ RoadTypes GetCompanyRoadTypes(CompanyID company, bool introduces) } } - if (introduces) return AddDateIntroducedRoadTypes(rts, _date); + if (introduces) return AddDateIntroducedRoadTypes(rts, TimerGameCalendar::date); return rts; } diff --git a/src/road_cmd.cpp b/src/road_cmd.cpp index 2e25302b4c..6766a299f4 100644 --- a/src/road_cmd.cpp +++ b/src/road_cmd.cpp @@ -33,7 +33,7 @@ #include "newgrf_debug.h" #include "newgrf_railtype.h" #include "newgrf_roadtype.h" -#include "date_func.h" +#include "timer/timer_game_calendar.h" #include "genworld.h" #include "company_gui.h" #include "road_func.h" @@ -1171,7 +1171,7 @@ CommandCost CmdBuildRoadDepot(DoCommandFlag flags, TileIndex tile, RoadType rt, if (flags & DC_EXEC) { Depot *dep = new Depot(tile); - dep->build_date = _date; + dep->build_date = TimerGameCalendar::date; /* A road depot has two road bits. */ UpdateCompanyRoadInfrastructure(rt, _current_company, ROAD_DEPOT_TRACKBIT_FACTOR); diff --git a/src/road_gui.cpp b/src/road_gui.cpp index a955fa27d7..f46679994e 100644 --- a/src/road_gui.cpp +++ b/src/road_gui.cpp @@ -30,7 +30,6 @@ #include "engine_base.h" #include "strings_func.h" #include "core/geometry_func.hpp" -#include "date_func.h" #include "station_cmd.h" #include "road_cmd.h" #include "tunnelbridge_cmd.h" @@ -1875,7 +1874,7 @@ DropDownList GetRoadTypeDropDownList(RoadTramTypes rtts, bool for_replacement, b DropDownList GetScenRoadTypeDropDownList(RoadTramTypes rtts) { RoadTypes avail_roadtypes = GetRoadTypes(false); - avail_roadtypes = AddDateIntroducedRoadTypes(avail_roadtypes, _date); + avail_roadtypes = AddDateIntroducedRoadTypes(avail_roadtypes, TimerGameCalendar::date); RoadTypes used_roadtypes = GetRoadTypes(true); /* Filter listed road types */ diff --git a/src/roadveh_cmd.cpp b/src/roadveh_cmd.cpp index 68059ed0d5..791e768f5a 100644 --- a/src/roadveh_cmd.cpp +++ b/src/roadveh_cmd.cpp @@ -19,7 +19,7 @@ #include "pathfinder/yapf/yapf.h" #include "strings_func.h" #include "tunnelbridge_map.h" -#include "date_func.h" +#include "timer/timer_game_calendar.h" #include "vehicle_func.h" #include "sound_func.h" #include "ai/ai.hpp" @@ -298,8 +298,8 @@ CommandCost CmdBuildRoadVehicle(DoCommandFlag flags, TileIndex tile, const Engin v->SetServiceInterval(Company::Get(v->owner)->settings.vehicle.servint_roadveh); - v->date_of_last_service = _date; - v->build_year = _cur_year; + v->date_of_last_service = TimerGameCalendar::date; + v->build_year = TimerGameCalendar::year; v->sprite_cache.sprite_seq.Set(SPR_IMG_QUERY); v->random_bits = VehicleRandomBits(); diff --git a/src/saveload/afterload.cpp b/src/saveload/afterload.cpp index 86d98f0607..0efc40f5c7 100644 --- a/src/saveload/afterload.cpp +++ b/src/saveload/afterload.cpp @@ -260,7 +260,7 @@ static void InitializeWindowsAndCaches() * accordingly if it is not the case. No need to set it on companies that are not been used already, * thus the MIN_YEAR (which is really nothing more than Zero, initialized value) test */ if (_file_to_saveload.abstract_ftype == FT_SCENARIO && c->inaugurated_year != MIN_YEAR) { - c->inaugurated_year = _cur_year; + c->inaugurated_year = TimerGameCalendar::year; } } @@ -748,12 +748,12 @@ bool AfterLoadGame() default: break; } - /* The value of _date_fract got divided, so make sure that old games are converted correctly. */ - if (IsSavegameVersionBefore(SLV_11, 1) || (IsSavegameVersionBefore(SLV_147) && _date_fract > DAY_TICKS)) _date_fract /= 885; + /* The value of TimerGameCalendar::date_fract got divided, so make sure that old games are converted correctly. */ + if (IsSavegameVersionBefore(SLV_11, 1) || (IsSavegameVersionBefore(SLV_147) && TimerGameCalendar::date_fract > DAY_TICKS)) TimerGameCalendar::date_fract /= 885; /* Update current year * must be done before loading sprites as some newgrfs check it */ - SetDate(_date, _date_fract); + TimerGameCalendar::SetDate(TimerGameCalendar::date, TimerGameCalendar::date_fract); /* * Force the old behaviour for compatibility reasons with old savegames. As new @@ -1444,8 +1444,8 @@ bool AfterLoadGame() /* Time starts at 0 instead of 1920. * Account for this in older games by adding an offset */ if (IsSavegameVersionBefore(SLV_31)) { - _date += DAYS_TILL_ORIGINAL_BASE_YEAR; - _cur_year += ORIGINAL_BASE_YEAR; + TimerGameCalendar::date += DAYS_TILL_ORIGINAL_BASE_YEAR; + TimerGameCalendar::year += ORIGINAL_BASE_YEAR; for (Station *st : Station::Iterate()) st->build_date += DAYS_TILL_ORIGINAL_BASE_YEAR; for (Waypoint *wp : Waypoint::Iterate()) wp->build_date += DAYS_TILL_ORIGINAL_BASE_YEAR; @@ -1960,7 +1960,7 @@ bool AfterLoadGame() /* Replace "house construction year" with "house age" */ if (IsTileType(t, MP_HOUSE) && IsHouseCompleted(t)) { - t.m5() = Clamp(_cur_year - (t.m5() + ORIGINAL_BASE_YEAR), 0, 0xFF); + t.m5() = Clamp(TimerGameCalendar::year - (t.m5() + ORIGINAL_BASE_YEAR), 0, 0xFF); } } } @@ -2108,7 +2108,7 @@ bool AfterLoadGame() o->location.tile = (TileIndex)t; o->location.w = size; o->location.h = size; - o->build_date = _date; + o->build_date = TimerGameCalendar::date; o->town = type == OBJECT_STATUE ? Town::Get(t.m2()) : CalcClosestTownFromTile(t, UINT_MAX); t.m2() = o->index; Object::IncTypeCount(type); @@ -2437,7 +2437,7 @@ bool AfterLoadGame() } if (IsSavegameVersionBefore(SLV_142)) { - for (Depot *d : Depot::Iterate()) d->build_date = _date; + for (Depot *d : Depot::Iterate()) d->build_date = TimerGameCalendar::date; } /* In old versions it was possible to remove an airport while a plane was diff --git a/src/saveload/misc_sl.cpp b/src/saveload/misc_sl.cpp index 7fdfd5aa2d..6f82033658 100644 --- a/src/saveload/misc_sl.cpp +++ b/src/saveload/misc_sl.cpp @@ -13,6 +13,7 @@ #include "compat/misc_sl_compat.h" #include "../date_func.h" +#include "../timer/timer_game_calendar.h" #include "../zoom_func.h" #include "../window_gui.h" #include "../window_func.h" @@ -72,9 +73,9 @@ byte _age_cargo_skip_counter; ///< Skip aging of cargo? Used before savegame ver extern TimeoutTimer _new_competitor_timeout; static const SaveLoad _date_desc[] = { - SLEG_CONDVAR("date", _date, SLE_FILE_U16 | SLE_VAR_I32, SL_MIN_VERSION, SLV_31), - SLEG_CONDVAR("date", _date, SLE_INT32, SLV_31, SL_MAX_VERSION), - SLEG_VAR("date_fract", _date_fract, SLE_UINT16), + SLEG_CONDVAR("date", TimerGameCalendar::date, SLE_FILE_U16 | SLE_VAR_I32, SL_MIN_VERSION, SLV_31), + SLEG_CONDVAR("date", TimerGameCalendar::date, SLE_INT32, SLV_31, SL_MAX_VERSION), + SLEG_VAR("date_fract", TimerGameCalendar::date_fract, SLE_UINT16), SLEG_CONDVAR("tick_counter", _tick_counter, SLE_FILE_U16 | SLE_VAR_U64, SL_MIN_VERSION, SLV_U64_TICK_COUNTER), SLEG_CONDVAR("tick_counter", _tick_counter, SLE_UINT64, SLV_U64_TICK_COUNTER, SL_MAX_VERSION), SLEG_CONDVAR("age_cargo_skip_counter", _age_cargo_skip_counter, SLE_UINT8, SL_MIN_VERSION, SLV_162), diff --git a/src/saveload/oldloader_sl.cpp b/src/saveload/oldloader_sl.cpp index 783ef54f01..b7c151c79d 100644 --- a/src/saveload/oldloader_sl.cpp +++ b/src/saveload/oldloader_sl.cpp @@ -21,6 +21,7 @@ #include "../debug.h" #include "../depot_base.h" #include "../date_func.h" +#include "../timer/timer_game_calendar.h" #include "../vehicle_func.h" #include "../effectvehicle_base.h" #include "../engine_func.h" @@ -398,7 +399,7 @@ static bool FixTTOEngines() for (uint i = 0; i < lengthof(_orig_aircraft_vehicle_info); i++, j++) new (GetTempDataEngine(j)) Engine(VEH_AIRCRAFT, i); } - Date aging_date = std::min(_date + DAYS_TILL_ORIGINAL_BASE_YEAR, ConvertYMDToDate(2050, 0, 1)); + Date aging_date = std::min(TimerGameCalendar::date + DAYS_TILL_ORIGINAL_BASE_YEAR, ConvertYMDToDate(2050, 0, 1)); for (EngineID i = 0; i < 256; i++) { int oi = ttd_to_tto[i]; @@ -406,17 +407,17 @@ static bool FixTTOEngines() if (oi == 255) { /* Default engine is used */ - _date += DAYS_TILL_ORIGINAL_BASE_YEAR; + TimerGameCalendar::date += DAYS_TILL_ORIGINAL_BASE_YEAR; StartupOneEngine(e, aging_date, 0); CalcEngineReliability(e, false); e->intro_date -= DAYS_TILL_ORIGINAL_BASE_YEAR; - _date -= DAYS_TILL_ORIGINAL_BASE_YEAR; + TimerGameCalendar::date -= DAYS_TILL_ORIGINAL_BASE_YEAR; /* Make sure for example monorail and maglev are available when they should be */ - if (_date >= e->intro_date && HasBit(e->info.climates, 0)) { + if (TimerGameCalendar::date >= e->intro_date && HasBit(e->info.climates, 0)) { e->flags |= ENGINE_AVAILABLE; e->company_avail = MAX_UVALUE(CompanyMask); - e->age = _date > e->intro_date ? (_date - e->intro_date) / 30 : 0; + e->age = TimerGameCalendar::date > e->intro_date ? (TimerGameCalendar::date - e->intro_date) / 30 : 0; } } else { /* Using data from TTO savegame */ @@ -846,7 +847,7 @@ static bool LoadOldIndustry(LoadgameState *ls, int num) if (i->type == 0x0A) i->type = 0x12; // Iron Ore Mine has different ID YearMonthDay ymd; - ConvertDateToYMD(_date, &ymd); + ConvertDateToYMD(TimerGameCalendar::date, &ymd); i->last_prod_year = ymd.year; i->random_colour = RemapTTOColour(i->random_colour); @@ -1580,8 +1581,8 @@ extern uint8 _old_units; static const OldChunks main_chunk[] = { OCL_ASSERT( OC_TTD, 0 ), OCL_ASSERT( OC_TTO, 0 ), - OCL_VAR ( OC_FILE_U16 | OC_VAR_U32, 1, &_date ), - OCL_VAR ( OC_UINT16, 1, &_date_fract ), + OCL_VAR ( OC_FILE_U16 | OC_VAR_U32, 1, &TimerGameCalendar::date ), + OCL_VAR ( OC_UINT16, 1, &TimerGameCalendar::date_fract ), OCL_NULL( 600 ), ///< TextEffects OCL_VAR ( OC_UINT32, 2, &_random.state ), diff --git a/src/saveload/saveload.cpp b/src/saveload/saveload.cpp index 3681054f69..b9945597c6 100644 --- a/src/saveload/saveload.cpp +++ b/src/saveload/saveload.cpp @@ -3281,7 +3281,7 @@ SaveOrLoadResult SaveOrLoad(const std::string &filename, SaveLoadOperation fop, } if (fop == SLO_SAVE) { // SAVE game - Debug(desync, 1, "save: {:08x}; {:02x}; {}", _date, _date_fract, filename); + Debug(desync, 1, "save: {:08x}; {:02x}; {}", TimerGameCalendar::date, TimerGameCalendar::date_fract, filename); if (_network_server || !_settings_client.gui.threaded_saves) threaded = false; return DoSave(new FileWriter(fh), threaded); @@ -3359,7 +3359,7 @@ void GenerateDefaultSaveName(char *buf, const char *last) case 2: SetDParam(1, STR_JUST_DATE_ISO); break; default: NOT_REACHED(); } - SetDParam(2, _date); + SetDParam(2, TimerGameCalendar::date); /* Get the correct string (special string for when there's not company) */ GetString(buf, !Company::IsValidID(cid) ? STR_SAVEGAME_NAME_SPECTATOR : STR_SAVEGAME_NAME_DEFAULT, last); diff --git a/src/script/api/script_bridge.cpp b/src/script/api/script_bridge.cpp index 1ec873204e..939641ad94 100644 --- a/src/script/api/script_bridge.cpp +++ b/src/script/api/script_bridge.cpp @@ -13,17 +13,17 @@ #include "../script_instance.hpp" #include "../../bridge_map.h" #include "../../strings_func.h" -#include "../../date_func.h" #include "../../landscape_cmd.h" #include "../../road_cmd.h" #include "../../tunnelbridge_cmd.h" +#include "../../timer/timer_game_calendar.h" #include "table/strings.h" #include "../../safeguards.h" /* static */ bool ScriptBridge::IsValidBridge(BridgeID bridge_id) { - return bridge_id < MAX_BRIDGES && ::GetBridgeSpec(bridge_id)->avail_year <= _cur_year; + return bridge_id < MAX_BRIDGES && ::GetBridgeSpec(bridge_id)->avail_year <= TimerGameCalendar::year; } /* static */ bool ScriptBridge::IsBridgeTile(TileIndex tile) diff --git a/src/script/api/script_date.cpp b/src/script/api/script_date.cpp index 27289d75d0..c6a3438300 100644 --- a/src/script/api/script_date.cpp +++ b/src/script/api/script_date.cpp @@ -10,6 +10,7 @@ #include "../../stdafx.h" #include "script_date.hpp" #include "../../date_func.h" +#include "../../timer/timer_game_calendar.h" #include @@ -22,7 +23,7 @@ /* static */ ScriptDate::Date ScriptDate::GetCurrentDate() { - return (ScriptDate::Date)_date; + return (ScriptDate::Date)TimerGameCalendar::date; } /* static */ SQInteger ScriptDate::GetYear(ScriptDate::Date date) diff --git a/src/ship_cmd.cpp b/src/ship_cmd.cpp index 3dba2259c1..6b9b955a86 100644 --- a/src/ship_cmd.cpp +++ b/src/ship_cmd.cpp @@ -22,7 +22,7 @@ #include "spritecache.h" #include "strings_func.h" #include "window_func.h" -#include "date_func.h" +#include "timer/timer_game_calendar.h" #include "vehicle_func.h" #include "sound_func.h" #include "ai/ai.hpp" @@ -891,8 +891,8 @@ CommandCost CmdBuildShip(DoCommandFlag flags, TileIndex tile, const Engine *e, V v->state = TRACK_BIT_DEPOT; v->SetServiceInterval(Company::Get(_current_company)->settings.vehicle.servint_ships); - v->date_of_last_service = _date; - v->build_year = _cur_year; + v->date_of_last_service = TimerGameCalendar::date; + v->build_year = TimerGameCalendar::year; v->sprite_cache.sprite_seq.Set(SPR_IMG_QUERY); v->random_bits = VehicleRandomBits(); diff --git a/src/station.cpp b/src/station.cpp index 700ca7241d..02388b6384 100644 --- a/src/station.cpp +++ b/src/station.cpp @@ -13,7 +13,6 @@ #include "roadveh.h" #include "viewport_func.h" #include "viewport_kdtree.h" -#include "date_func.h" #include "command_func.h" #include "news_func.h" #include "aircraft.h" @@ -234,7 +233,7 @@ void Station::AddFacility(StationFacility new_facility_bit, TileIndex facil_xy) } this->facilities |= new_facility_bit; this->owner = _current_company; - this->build_date = _date; + this->build_date = TimerGameCalendar::date; } /** diff --git a/src/station_cmd.cpp b/src/station_cmd.cpp index 478b08a0fe..f0e78f68bf 100644 --- a/src/station_cmd.cpp +++ b/src/station_cmd.cpp @@ -3807,9 +3807,9 @@ void DeleteStaleLinks(Station *from) for (Edge &edge : (*lg)[ge.node].edges) { Station *to = Station::Get((*lg)[edge.dest_node].station); assert(to->goods[c].node == edge.dest_node); - assert(_date >= edge.LastUpdate()); + assert(TimerGameCalendar::date >= edge.LastUpdate()); uint timeout = LinkGraph::MIN_TIMEOUT_DISTANCE + (DistanceManhattan(from->xy, to->xy) >> 3); - if ((uint)(_date - edge.LastUpdate()) > timeout) { + if ((uint)(TimerGameCalendar::date - edge.LastUpdate()) > timeout) { bool updated = false; if (auto_distributed) { @@ -3837,11 +3837,11 @@ void DeleteStaleLinks(Station *from) while (iter != vehicles.end()) { Vehicle *v = *iter; /* Do not refresh links of vehicles that have been stopped in depot for a long time. */ - if (!v->IsStoppedInDepot() || static_cast(_date - v->date_of_last_service) <= + if (!v->IsStoppedInDepot() || static_cast(TimerGameCalendar::date - v->date_of_last_service) <= LinkGraph::STALE_LINK_DEPOT_TIMEOUT) { LinkRefresher::Run(v, false); // Don't allow merging. Otherwise lg might get deleted. } - if (edge.LastUpdate() == _date) { + if (edge.LastUpdate() == TimerGameCalendar::date) { updated = true; break; } @@ -3864,19 +3864,19 @@ void DeleteStaleLinks(Station *from) ge.flows.DeleteFlows(to->index); RerouteCargo(from, c, to->index, from->index); } - } else if (edge.last_unrestricted_update != INVALID_DATE && (uint)(_date - edge.last_unrestricted_update) > timeout) { + } else if (edge.last_unrestricted_update != INVALID_DATE && (uint)(TimerGameCalendar::date - edge.last_unrestricted_update) > timeout) { edge.Restrict(); ge.flows.RestrictFlows(to->index); RerouteCargo(from, c, to->index, from->index); - } else if (edge.last_restricted_update != INVALID_DATE && (uint)(_date - edge.last_restricted_update) > timeout) { + } else if (edge.last_restricted_update != INVALID_DATE && (uint)(TimerGameCalendar::date - edge.last_restricted_update) > timeout) { edge.Release(); } } /* Remove dead edges. */ for (NodeID r : to_remove) (*lg)[ge.node].RemoveEdge(r); - assert(_date >= lg->LastCompression()); - if ((uint)(_date - lg->LastCompression()) > LinkGraph::COMPRESSION_INTERVAL) { + assert(TimerGameCalendar::date >= lg->LastCompression()); + if ((uint)(TimerGameCalendar::date - lg->LastCompression()) > LinkGraph::COMPRESSION_INTERVAL) { lg->Compress(); } } @@ -4304,7 +4304,7 @@ void BuildOilRig(TileIndex tile) st->airport.Add(tile); st->ship_station.Add(tile); st->facilities = FACIL_AIRPORT | FACIL_DOCK; - st->build_date = _date; + st->build_date = TimerGameCalendar::date; UpdateStationDockingTiles(st); st->rect.BeforeAddTile(tile, StationRect::ADD_FORCE); diff --git a/src/statusbar_gui.cpp b/src/statusbar_gui.cpp index ef5d16c488..ad9710c66a 100644 --- a/src/statusbar_gui.cpp +++ b/src/statusbar_gui.cpp @@ -9,7 +9,6 @@ #include "stdafx.h" #include "core/backup_type.hpp" -#include "date_func.h" #include "gfx_func.h" #include "news_func.h" #include "company_func.h" @@ -138,7 +137,7 @@ struct StatusBarWindow : Window { switch (widget) { case WID_S_LEFT: /* Draw the date */ - SetDParam(0, _date); + SetDParam(0, TimerGameCalendar::date); DrawString(tr, STR_WHITE_DATE_LONG, TC_FROMSTRING, SA_HOR_CENTER); break; diff --git a/src/story.cpp b/src/story.cpp index de04e69dba..c986ad52e3 100644 --- a/src/story.cpp +++ b/src/story.cpp @@ -14,7 +14,7 @@ #include "company_base.h" #include "company_func.h" #include "string_func.h" -#include "date_func.h" +#include "timer/timer_game_calendar.h" #include "tile_map.h" #include "goal_type.h" #include "goal_base.h" @@ -218,7 +218,7 @@ std::tuple CmdCreateStoryPage(DoCommandFlag flags, Com StoryPage *s = new StoryPage(); s->sort_value = _story_page_next_sort_value; - s->date = _date; + s->date = TimerGameCalendar::date; s->company = company; if (text.empty()) { s->title = nullptr; diff --git a/src/story_gui.cpp b/src/story_gui.cpp index ac4ab8519f..5635f8c18e 100644 --- a/src/story_gui.cpp +++ b/src/story_gui.cpp @@ -10,7 +10,6 @@ #include "stdafx.h" #include "window_gui.h" #include "strings_func.h" -#include "date_func.h" #include "gui.h" #include "story_base.h" #include "core/geometry_func.hpp" diff --git a/src/subsidy_gui.cpp b/src/subsidy_gui.cpp index 3c265644d1..a5a2125880 100644 --- a/src/subsidy_gui.cpp +++ b/src/subsidy_gui.cpp @@ -13,6 +13,7 @@ #include "window_gui.h" #include "strings_func.h" #include "date_func.h" +#include "timer/timer_game_calendar.h" #include "viewport_func.h" #include "gui.h" #include "subsidy_func.h" @@ -143,7 +144,7 @@ struct SubsidyListWindow : Window { if (widget != WID_SUL_PANEL) return; YearMonthDay ymd; - ConvertDateToYMD(_date, &ymd); + ConvertDateToYMD(TimerGameCalendar::date, &ymd); Rect tr = r.Shrink(WidgetDimensions::scaled.framerect); @@ -160,7 +161,7 @@ struct SubsidyListWindow : Window { if (IsInsideMM(pos, 0, cap)) { /* Displays the two offered towns */ SetupSubsidyDecodeParam(s, SubsidyDecodeParamType::Gui); - SetDParam(7, _date - ymd.day + s->remaining * 32); + SetDParam(7, TimerGameCalendar::date - ymd.day + s->remaining * 32); DrawString(tr.left, tr.right, tr.top + pos * FONT_HEIGHT_NORMAL, STR_SUBSIDIES_OFFERED_FROM_TO); } pos++; @@ -184,7 +185,7 @@ struct SubsidyListWindow : Window { if (IsInsideMM(pos, 0, cap)) { SetupSubsidyDecodeParam(s, SubsidyDecodeParamType::Gui); SetDParam(7, s->awarded); - SetDParam(8, _date - ymd.day + s->remaining * 32); + SetDParam(8, TimerGameCalendar::date - ymd.day + s->remaining * 32); /* Displays the two connected stations */ DrawString(tr.left, tr.right, tr.top + pos * FONT_HEIGHT_NORMAL, STR_SUBSIDIES_SUBSIDISED_FROM_TO); diff --git a/src/timer/timer_game_calendar.cpp b/src/timer/timer_game_calendar.cpp index 5d080b6237..bc44c13169 100644 --- a/src/timer/timer_game_calendar.cpp +++ b/src/timer/timer_game_calendar.cpp @@ -20,6 +20,29 @@ #include "safeguards.h" +Year TimerGameCalendar::year = {}; +Month TimerGameCalendar::month = {}; +Date TimerGameCalendar::date = {}; +DateFract TimerGameCalendar::date_fract = {}; + +/** + * Set the date. + * @param date New date + * @param fract The number of ticks that have passed on this date. + */ +/* static */ void TimerGameCalendar::SetDate(Date date, DateFract fract) +{ + assert(fract < DAY_TICKS); + + YearMonthDay ymd; + + TimerGameCalendar::date = date; + TimerGameCalendar::date_fract = fract; + ConvertDateToYMD(date, &ymd); + TimerGameCalendar::year = ymd.year; + TimerGameCalendar::month = ymd.month; +} + template<> void IntervalTimer::Elapsed(TimerGameCalendar::TElapsed trigger) { @@ -48,25 +71,25 @@ void TimerManager::Elapsed(TimerGameCalendar::TElapsed delta) if (_game_mode == GM_MENU) return; - _date_fract++; - if (_date_fract < DAY_TICKS) return; - _date_fract = 0; + TimerGameCalendar::date_fract++; + if (TimerGameCalendar::date_fract < DAY_TICKS) return; + TimerGameCalendar::date_fract = 0; /* increase day counter */ - _date++; + TimerGameCalendar::date++; YearMonthDay ymd; - ConvertDateToYMD(_date, &ymd); + ConvertDateToYMD(TimerGameCalendar::date, &ymd); /* check if we entered a new month? */ - bool new_month = ymd.month != _cur_month; + bool new_month = ymd.month != TimerGameCalendar::month; /* check if we entered a new year? */ - bool new_year = ymd.year != _cur_year; + bool new_year = ymd.year != TimerGameCalendar::year; /* update internal variables before calling the daily/monthly/yearly loops */ - _cur_month = ymd.month; - _cur_year = ymd.year; + TimerGameCalendar::month = ymd.month; + TimerGameCalendar::year = ymd.year; /* Make a temporary copy of the timers, as a timer's callback might add/remove other timers. */ auto timers = TimerManager::GetTimers(); @@ -88,12 +111,12 @@ void TimerManager::Elapsed(TimerGameCalendar::TElapsed delta) } /* check if we reached the maximum year, decrement dates by a year */ - if (_cur_year == MAX_YEAR + 1) { + if (TimerGameCalendar::year == MAX_YEAR + 1) { int days_this_year; - _cur_year--; - days_this_year = IsLeapYear(_cur_year) ? DAYS_IN_LEAP_YEAR : DAYS_IN_YEAR; - _date -= days_this_year; + TimerGameCalendar::year--; + days_this_year = IsLeapYear(TimerGameCalendar::year) ? DAYS_IN_LEAP_YEAR : DAYS_IN_YEAR; + TimerGameCalendar::date -= days_this_year; for (Vehicle *v : Vehicle::Iterate()) v->ShiftDates(-days_this_year); for (LinkGraph *lg : LinkGraph::Iterate()) lg->ShiftDates(-days_this_year); } diff --git a/src/timer/timer_game_calendar.h b/src/timer/timer_game_calendar.h index 76de11216b..b8b31789ed 100644 --- a/src/timer/timer_game_calendar.h +++ b/src/timer/timer_game_calendar.h @@ -10,6 +10,8 @@ #ifndef TIMER_GAME_CALENDAR_H #define TIMER_GAME_CALENDAR_H +#include "../date_type.h" + /** * Timer that is increased every 27ms, and counts towards ticks / days / months / years. * @@ -72,6 +74,13 @@ public: using TElapsed = uint; struct TStorage { }; + + static void SetDate(Date date, DateFract fract); + + static Year year; ///< Current year, starting at 0. + static Month month; ///< Current month (0..11). + static Date date; ///< Current date in days (day counter). + static DateFract date_fract; ///< Fractional part of the day. }; #endif /* TIMER_GAME_CALENDAR_H */ diff --git a/src/timetable_cmd.cpp b/src/timetable_cmd.cpp index 436948922f..343b6b658a 100644 --- a/src/timetable_cmd.cpp +++ b/src/timetable_cmd.cpp @@ -10,7 +10,7 @@ #include "stdafx.h" #include "command_func.h" #include "company_func.h" -#include "date_func.h" +#include "timer/timer_game_calendar.h" #include "window_func.h" #include "vehicle_base.h" #include "timetable_cmd.h" @@ -304,8 +304,8 @@ CommandCost CmdSetTimetableStart(DoCommandFlag flags, VehicleID veh_id, bool tim /* Don't let a timetable start more than 15 years into the future or 1 year in the past. */ if (start_date < 0 || start_date > MAX_DAY) return CMD_ERROR; - if (start_date - _date > MAX_TIMETABLE_START_YEARS * DAYS_IN_LEAP_YEAR) return CMD_ERROR; - if (_date - start_date > DAYS_IN_LEAP_YEAR) return CMD_ERROR; + if (start_date - TimerGameCalendar::date > MAX_TIMETABLE_START_YEARS * DAYS_IN_LEAP_YEAR) return CMD_ERROR; + if (TimerGameCalendar::date - start_date > DAYS_IN_LEAP_YEAR) return CMD_ERROR; if (timetable_all && !v->orders->IsCompleteTimetable()) return CommandCost(STR_ERROR_TIMETABLE_INCOMPLETE); if (timetable_all && start_date + total_duration / DAY_TICKS > MAX_DAY) return CMD_ERROR; @@ -426,7 +426,7 @@ void UpdateVehicleTimetable(Vehicle *v, bool travelling) just_started = !HasBit(v->vehicle_flags, VF_TIMETABLE_STARTED); if (v->timetable_start != 0) { - v->lateness_counter = (_date - v->timetable_start) * DAY_TICKS + _date_fract; + v->lateness_counter = (TimerGameCalendar::date - v->timetable_start) * DAY_TICKS + TimerGameCalendar::date_fract; v->timetable_start = 0; } diff --git a/src/timetable_gui.cpp b/src/timetable_gui.cpp index 228fabd4cd..e43302f810 100644 --- a/src/timetable_gui.cpp +++ b/src/timetable_gui.cpp @@ -18,7 +18,7 @@ #include "string_func.h" #include "gfx_func.h" #include "company_func.h" -#include "date_func.h" +#include "timer/timer_game_calendar.h" #include "date_gui.h" #include "vehicle_gui.h" #include "settings_type.h" @@ -185,7 +185,7 @@ struct TimetableWindow : Window { assert(HasBit(v->vehicle_flags, VF_TIMETABLE_STARTED)); bool travelling = (!v->current_order.IsType(OT_LOADING) || v->current_order.GetNonStopType() == ONSF_STOP_EVERYWHERE); - Ticks start_time = _date_fract - v->current_order_time; + Ticks start_time = TimerGameCalendar::date_fract - v->current_order_time; FillTimetableArrivalDepartureTable(v, v->cur_real_order_index % v->GetNumOrders(), travelling, table, start_time); @@ -474,7 +474,7 @@ struct TimetableWindow : Window { } /* Now actually draw the arrival time. */ - SetDParam(0, _date + (arr_dep[i / 2].arrival + this_offset) / DAY_TICKS); + SetDParam(0, TimerGameCalendar::date + (arr_dep[i / 2].arrival + this_offset) / DAY_TICKS); DrawString(time.left, time.right, tr.top, STR_JUST_DATE_TINY, colour); } } else { @@ -482,7 +482,7 @@ struct TimetableWindow : Window { if (arr_dep[i / 2].departure != INVALID_TICKS) { DrawString(abbr.left, abbr.right, tr.top, STR_TIMETABLE_DEPARTURE_ABBREVIATION, i == selected ? TC_WHITE : TC_BLACK); TextColour colour = show_late ? TC_RED : (i == selected ? TC_WHITE : TC_BLACK); - SetDParam(0, _date + (arr_dep[i / 2].departure + offset) / DAY_TICKS); + SetDParam(0, TimerGameCalendar::date + (arr_dep[i / 2].departure + offset) / DAY_TICKS); DrawString(time.left, time.right, tr.top, STR_JUST_DATE_TINY, colour); } } @@ -572,7 +572,7 @@ struct TimetableWindow : Window { } case WID_VT_START_DATE: // Change the date that the timetable starts. - ShowSetDateWindow(this, v->index, _date, _cur_year, _cur_year + MAX_TIMETABLE_START_YEARS, ChangeTimetableStartCallback, reinterpret_cast(static_cast(_ctrl_pressed))); + ShowSetDateWindow(this, v->index, TimerGameCalendar::date, TimerGameCalendar::year, TimerGameCalendar::year + MAX_TIMETABLE_START_YEARS, ChangeTimetableStartCallback, reinterpret_cast(static_cast(_ctrl_pressed))); break; case WID_VT_CHANGE_TIME: { // "Wait For" button. diff --git a/src/toolbar_gui.cpp b/src/toolbar_gui.cpp index 157a09b59e..fd202e91d1 100644 --- a/src/toolbar_gui.cpp +++ b/src/toolbar_gui.cpp @@ -1149,8 +1149,8 @@ void SetStartingYear(Year year) _settings_game.game_creation.starting_year = Clamp(year, MIN_YEAR, MAX_YEAR); Date new_date = ConvertYMDToDate(_settings_game.game_creation.starting_year, 0, 1); /* If you open a savegame as scenario there may already be link graphs.*/ - LinkGraphSchedule::instance.ShiftDates(new_date - _date); - SetDate(new_date, 0); + LinkGraphSchedule::instance.ShiftDates(new_date - TimerGameCalendar::date); + TimerGameCalendar::SetDate(new_date, 0); } /** diff --git a/src/town_cmd.cpp b/src/town_cmd.cpp index 730a417e04..0b7e1f9142 100644 --- a/src/town_cmd.cpp +++ b/src/town_cmd.cpp @@ -873,7 +873,7 @@ RoadType GetTownRoadType(const Town *t) if (!HasBit(rti->flags, ROTF_TOWN_BUILD)) continue; /* Not yet introduced at this date. */ - if (IsInsideMM(rti->introduction_date, 0, MAX_DAY) && rti->introduction_date > _date) continue; + if (IsInsideMM(rti->introduction_date, 0, MAX_DAY) && rti->introduction_date > TimerGameCalendar::date) continue; if (best != nullptr) { if ((rti->max_speed == 0 ? assume_max_speed : rti->max_speed) < (best->max_speed == 0 ? assume_max_speed : best->max_speed)) continue; @@ -2632,7 +2632,7 @@ static bool BuildTownHouse(Town *t, TileIndex tile) continue; } - if (_cur_year < hs->min_year || _cur_year > hs->max_year) continue; + if (TimerGameCalendar::year < hs->min_year || TimerGameCalendar::year > hs->max_year) continue; /* Special houses that there can be only one of. */ uint oneof = 0; diff --git a/src/train_cmd.cpp b/src/train_cmd.cpp index 1edc7231aa..21f33b3a5c 100644 --- a/src/train_cmd.cpp +++ b/src/train_cmd.cpp @@ -36,6 +36,7 @@ #include "framerate_type.h" #include "train_cmd.h" #include "misc_cmd.h" +#include "timer/timer_game_calendar.h" #include "table/strings.h" #include "table/train_sprites.h" @@ -651,8 +652,8 @@ static CommandCost CmdBuildRailWagon(DoCommandFlag flags, TileIndex tile, const v->railtype = rvi->railtype; - v->date_of_last_service = _date; - v->build_year = _cur_year; + v->date_of_last_service = TimerGameCalendar::date; + v->build_year = TimerGameCalendar::year; v->sprite_cache.sprite_seq.Set(SPR_IMG_QUERY); v->random_bits = VehicleRandomBits(); @@ -781,8 +782,8 @@ CommandCost CmdBuildRailVehicle(DoCommandFlag flags, TileIndex tile, const Engin v->railtype = rvi->railtype; v->SetServiceInterval(Company::Get(_current_company)->settings.vehicle.servint_trains); - v->date_of_last_service = _date; - v->build_year = _cur_year; + v->date_of_last_service = TimerGameCalendar::date; + v->build_year = TimerGameCalendar::year; v->sprite_cache.sprite_seq.Set(SPR_IMG_QUERY); v->random_bits = VehicleRandomBits(); diff --git a/src/tunnelbridge_cmd.cpp b/src/tunnelbridge_cmd.cpp index fef709f890..0ccb488052 100644 --- a/src/tunnelbridge_cmd.cpp +++ b/src/tunnelbridge_cmd.cpp @@ -24,7 +24,7 @@ #include "autoslope.h" #include "tunnelbridge_map.h" #include "strings_func.h" -#include "date_func.h" +#include "timer/timer_game_calendar.h" #include "clear_func.h" #include "vehicle_func.h" #include "sound_func.h" @@ -206,7 +206,7 @@ CommandCost CheckBridgeAvailability(BridgeType bridge_type, uint bridge_len, DoC if (bridge_type >= MAX_BRIDGES) return CMD_ERROR; const BridgeSpec *b = GetBridgeSpec(bridge_type); - if (b->avail_year > _cur_year) return CMD_ERROR; + if (b->avail_year > TimerGameCalendar::year) return CMD_ERROR; uint max = std::min(b->max_length, _settings_game.construction.max_bridge_length); diff --git a/src/vehicle.cpp b/src/vehicle.cpp index a6b5960a64..5187d2b985 100644 --- a/src/vehicle.cpp +++ b/src/vehicle.cpp @@ -168,7 +168,7 @@ void VehicleServiceInDepot(Vehicle *v) SetWindowDirty(WC_VEHICLE_DETAILS, v->index); // ensure that last service date and reliability are updated do { - v->date_of_last_service = _date; + v->date_of_last_service = TimerGameCalendar::date; v->breakdowns_since_last_service = 0; v->reliability = v->GetEngine()->reliability; /* Prevent vehicles from breaking down directly after exiting the depot. */ @@ -194,7 +194,7 @@ bool Vehicle::NeedsServicing() const const Company *c = Company::Get(this->owner); if (this->ServiceIntervalIsPercent() ? (this->reliability >= this->GetEngine()->reliability * (100 - this->GetServiceInterval()) / 100) : - (this->date_of_last_service + this->GetServiceInterval() >= _date)) { + (this->date_of_last_service + this->GetServiceInterval() >= TimerGameCalendar::date)) { return false; } @@ -920,15 +920,15 @@ void VehicleEnteredDepotThisTick(Vehicle *v) /** * Increases the day counter for all vehicles and calls 1-day and 32-day handlers. - * Each tick, it processes vehicles with "index % DAY_TICKS == _date_fract", + * Each tick, it processes vehicles with "index % DAY_TICKS == TimerGameCalendar::date_fract", * so each day, all vehicles are processes in DAY_TICKS steps. */ static void RunVehicleDayProc() { if (_game_mode != GM_NORMAL) return; - /* Run the day_proc for every DAY_TICKS vehicle starting at _date_fract. */ - for (size_t i = _date_fract; i < Vehicle::GetPoolSize(); i += DAY_TICKS) { + /* Run the day_proc for every DAY_TICKS vehicle starting at TimerGameCalendar::date_fract. */ + for (size_t i = TimerGameCalendar::date_fract; i < Vehicle::GetPoolSize(); i += DAY_TICKS) { Vehicle *v = Vehicle::Get(i); if (v == nullptr) continue; diff --git a/src/water_cmd.cpp b/src/water_cmd.cpp index bc719df099..2004f26d53 100644 --- a/src/water_cmd.cpp +++ b/src/water_cmd.cpp @@ -32,7 +32,7 @@ #include "game/game.hpp" #include "core/random_func.hpp" #include "core/backup_type.hpp" -#include "date_func.h" +#include "timer/timer_game_calendar.h" #include "company_base.h" #include "company_gui.h" #include "newgrf_generic.h" @@ -134,7 +134,7 @@ CommandCost CmdBuildShipDepot(DoCommandFlag flags, TileIndex tile, Axis axis) if (flags & DC_EXEC) { Depot *depot = new Depot(tile); - depot->build_date = _date; + depot->build_date = TimerGameCalendar::date; uint new_water_infra = 2 * LOCK_DEPOT_TILE_FACTOR; /* Update infrastructure counts after the tile clears earlier. diff --git a/src/waypoint_cmd.cpp b/src/waypoint_cmd.cpp index 40402ef86b..35bcf978d8 100644 --- a/src/waypoint_cmd.cpp +++ b/src/waypoint_cmd.cpp @@ -19,7 +19,7 @@ #include "viewport_func.h" #include "viewport_kdtree.h" #include "window_func.h" -#include "date_func.h" +#include "timer/timer_game_calendar.h" #include "vehicle_func.h" #include "string_func.h" #include "company_func.h" @@ -248,7 +248,7 @@ CommandCost CmdBuildRailWaypoint(DoCommandFlag flags, TileIndex start_tile, Axis wp->delete_ctr = 0; wp->facilities |= FACIL_TRAIN; - wp->build_date = _date; + wp->build_date = TimerGameCalendar::date; wp->string_id = STR_SV_STNAME_WAYPOINT; wp->train_station = new_location; @@ -329,7 +329,7 @@ CommandCost CmdBuildBuoy(DoCommandFlag flags, TileIndex tile) wp->facilities |= FACIL_DOCK; wp->owner = OWNER_NONE; - wp->build_date = _date; + wp->build_date = TimerGameCalendar::date; if (wp->town == nullptr) MakeDefaultName(wp); From 31ad9908316ec561584ebfa036eb7a8bf2f682e4 Mon Sep 17 00:00:00 2001 From: Patric Stout Date: Mon, 24 Apr 2023 18:55:40 +0200 Subject: [PATCH 14/27] Codechange: move tick-counter into TimerGameTick (#10712) --- src/date.cpp | 2 -- src/date_func.h | 2 -- src/gamelog.cpp | 3 ++- src/genworld.cpp | 4 ++-- src/industry_cmd.cpp | 21 +++++++++++---------- src/landscape.cpp | 3 ++- src/misc.cpp | 3 ++- src/newgrf.cpp | 9 +++++---- src/newgrf_animation_base.h | 4 ++-- src/newgrf_profiling.cpp | 8 ++++---- src/saveload/afterload.cpp | 2 +- src/saveload/misc_sl.cpp | 4 ++-- src/saveload/oldloader_sl.cpp | 2 +- src/saveload/saveload.h | 2 +- src/station_cmd.cpp | 13 ++++++++----- src/timer/timer_game_calendar.cpp | 2 -- src/timer/timer_game_tick.cpp | 4 ++++ src/timer/timer_game_tick.h | 2 ++ src/town_cmd.cpp | 6 +++--- src/tree_cmd.cpp | 8 ++++---- src/vehicle.cpp | 5 +++-- src/vehicle_base.h | 2 +- 22 files changed, 60 insertions(+), 51 deletions(-) diff --git a/src/date.cpp b/src/date.cpp index 818043306b..f715402263 100644 --- a/src/date.cpp +++ b/src/date.cpp @@ -25,8 +25,6 @@ #include "safeguards.h" -uint64 _tick_counter; ///< Ever incrementing tick counter for setting off various events - #define M(a, b) ((a << 5) | b) static const uint16 _month_date_from_year_day[] = { M( 0, 1), M( 0, 2), M( 0, 3), M( 0, 4), M( 0, 5), M( 0, 6), M( 0, 7), M( 0, 8), M( 0, 9), M( 0, 10), M( 0, 11), M( 0, 12), M( 0, 13), M( 0, 14), M( 0, 15), M( 0, 16), M( 0, 17), M( 0, 18), M( 0, 19), M( 0, 20), M( 0, 21), M( 0, 22), M( 0, 23), M( 0, 24), M( 0, 25), M( 0, 26), M( 0, 27), M( 0, 28), M( 0, 29), M( 0, 30), M( 0, 31), diff --git a/src/date_func.h b/src/date_func.h index d155ab1739..f74f99b112 100644 --- a/src/date_func.h +++ b/src/date_func.h @@ -12,8 +12,6 @@ #include "date_type.h" -extern uint64 _tick_counter; - void ConvertDateToYMD(Date date, YearMonthDay *ymd); Date ConvertYMDToDate(Year year, Month month, Day day); diff --git a/src/gamelog.cpp b/src/gamelog.cpp index 0346134c19..84013e205a 100644 --- a/src/gamelog.cpp +++ b/src/gamelog.cpp @@ -15,6 +15,7 @@ #include "console_func.h" #include "debug.h" #include "date_func.h" +#include "timer/timer_game_tick.h" #include "rev.h" #include @@ -387,7 +388,7 @@ static LoggedChange *GamelogChange(GamelogChangeType ct) _current_action = &_gamelog_action[_gamelog_actions++]; _current_action->at = _gamelog_action_type; - _current_action->tick = _tick_counter; + _current_action->tick = TimerGameTick::counter; _current_action->change = nullptr; _current_action->changes = 0; } diff --git a/src/genworld.cpp b/src/genworld.cpp index 2a994b682b..2fd6fc6cb9 100644 --- a/src/genworld.cpp +++ b/src/genworld.cpp @@ -16,8 +16,8 @@ #include "network/network.h" #include "heightmap.h" #include "viewport_func.h" -#include "date_func.h" #include "timer/timer_game_calendar.h" +#include "timer/timer_game_tick.h" #include "engine_func.h" #include "water.h" #include "video/video_driver.hpp" @@ -154,7 +154,7 @@ static void _GenerateWorld() SetGeneratingWorldProgress(GWP_RUNTILELOOP, 0x500); for (i = 0; i < 0x500; i++) { RunTileLoop(); - _tick_counter++; + TimerGameTick::counter++; IncreaseGeneratingWorldProgress(GWP_RUNTILELOOP); } diff --git a/src/industry_cmd.cpp b/src/industry_cmd.cpp index d67c3f1347..080690f8b9 100644 --- a/src/industry_cmd.cpp +++ b/src/industry_cmd.cpp @@ -46,6 +46,7 @@ #include "terraform_cmd.h" #include "timer/timer.h" #include "timer/timer_game_calendar.h" +#include "timer/timer_game_tick.h" #include "table/strings.h" #include "table/industry_land.h" @@ -661,7 +662,7 @@ static void AnimateOilWell(TileIndex tile, IndustryGfx gfx) static void AnimateMineTower(TileIndex tile) { - int state = _tick_counter & 0x7FF; + int state = TimerGameTick::counter & 0x7FF; if ((state -= 0x400) < 0) return; @@ -702,36 +703,36 @@ static void AnimateTile_Industry(TileIndex tile) switch (gfx) { case GFX_SUGAR_MINE_SIEVE: - if ((_tick_counter & 1) == 0) AnimateSugarSieve(tile); + if ((TimerGameTick::counter & 1) == 0) AnimateSugarSieve(tile); break; case GFX_TOFFEE_QUARY: - if ((_tick_counter & 3) == 0) AnimateToffeeQuarry(tile); + if ((TimerGameTick::counter & 3) == 0) AnimateToffeeQuarry(tile); break; case GFX_BUBBLE_CATCHER: - if ((_tick_counter & 1) == 0) AnimateBubbleCatcher(tile); + if ((TimerGameTick::counter & 1) == 0) AnimateBubbleCatcher(tile); break; case GFX_POWERPLANT_SPARKS: - if ((_tick_counter & 3) == 0) AnimatePowerPlantSparks(tile); + if ((TimerGameTick::counter & 3) == 0) AnimatePowerPlantSparks(tile); break; case GFX_TOY_FACTORY: - if ((_tick_counter & 1) == 0) AnimateToyFactory(tile); + if ((TimerGameTick::counter & 1) == 0) AnimateToyFactory(tile); break; case GFX_PLASTIC_FOUNTAIN_ANIMATED_1: case GFX_PLASTIC_FOUNTAIN_ANIMATED_2: case GFX_PLASTIC_FOUNTAIN_ANIMATED_3: case GFX_PLASTIC_FOUNTAIN_ANIMATED_4: case GFX_PLASTIC_FOUNTAIN_ANIMATED_5: case GFX_PLASTIC_FOUNTAIN_ANIMATED_6: case GFX_PLASTIC_FOUNTAIN_ANIMATED_7: case GFX_PLASTIC_FOUNTAIN_ANIMATED_8: - if ((_tick_counter & 3) == 0) AnimatePlasticFountain(tile, gfx); + if ((TimerGameTick::counter & 3) == 0) AnimatePlasticFountain(tile, gfx); break; case GFX_OILWELL_ANIMATED_1: case GFX_OILWELL_ANIMATED_2: case GFX_OILWELL_ANIMATED_3: - if ((_tick_counter & 7) == 0) AnimateOilWell(tile, gfx); + if ((TimerGameTick::counter & 7) == 0) AnimateOilWell(tile, gfx); break; case GFX_COAL_MINE_TOWER_ANIMATED: @@ -879,7 +880,7 @@ static void TileLoop_Industry(TileIndex tile) case GFX_COAL_MINE_TOWER_NOT_ANIMATED: case GFX_COPPER_MINE_TOWER_NOT_ANIMATED: case GFX_GOLD_MINE_TOWER_NOT_ANIMATED: - if (!(_tick_counter & 0x400) && Chance16(1, 2)) { + if (!(TimerGameTick::counter & 0x400) && Chance16(1, 2)) { switch (gfx) { case GFX_COAL_MINE_TOWER_NOT_ANIMATED: gfx = GFX_COAL_MINE_TOWER_ANIMATED; break; case GFX_COPPER_MINE_TOWER_NOT_ANIMATED: gfx = GFX_COPPER_MINE_TOWER_ANIMATED; break; @@ -902,7 +903,7 @@ static void TileLoop_Industry(TileIndex tile) case GFX_COAL_MINE_TOWER_ANIMATED: case GFX_COPPER_MINE_TOWER_ANIMATED: case GFX_GOLD_MINE_TOWER_ANIMATED: - if (!(_tick_counter & 0x400)) { + if (!(TimerGameTick::counter & 0x400)) { switch (gfx) { case GFX_COAL_MINE_TOWER_ANIMATED: gfx = GFX_COAL_MINE_TOWER_NOT_ANIMATED; break; case GFX_COPPER_MINE_TOWER_ANIMATED: gfx = GFX_COPPER_MINE_TOWER_NOT_ANIMATED; break; diff --git a/src/landscape.cpp b/src/landscape.cpp index 653a9c1fc8..ff3dd5bdcc 100644 --- a/src/landscape.cpp +++ b/src/landscape.cpp @@ -22,6 +22,7 @@ #include "fios.h" #include "date_func.h" #include "timer/timer_game_calendar.h" +#include "timer/timer_game_tick.h" #include "water.h" #include "effectvehicle_func.h" #include "landscape_type.h" @@ -780,7 +781,7 @@ void RunTileLoop() assert(tile != 0); /* Manually update tile 0 every 256 ticks - the LFSR never iterates over it itself. */ - if (_tick_counter % 256 == 0) { + if (TimerGameTick::counter % 256 == 0) { _tile_type_procs[GetTileType(0)]->tile_loop_proc(0); count--; } diff --git a/src/misc.cpp b/src/misc.cpp index d95a20f950..408f294ee9 100644 --- a/src/misc.cpp +++ b/src/misc.cpp @@ -16,6 +16,7 @@ #include "newgrf_house.h" #include "economy_func.h" #include "date_func.h" +#include "timer/timer_game_tick.h" #include "texteff.hpp" #include "gfx_func.h" #include "gamelog.h" @@ -65,7 +66,7 @@ void InitializeGame(uint size_x, uint size_y, bool reset_date, bool reset_settin _pause_mode = PM_UNPAUSED; _game_speed = 100; - _tick_counter = 0; + TimerGameTick::counter = 0; _cur_tileloop_tile = 1; _thd.redsq = INVALID_TILE; if (reset_settings) MakeNewgameSettingsLive(); diff --git a/src/newgrf.cpp b/src/newgrf.cpp index 02e6356d76..0b7ebca4be 100644 --- a/src/newgrf.cpp +++ b/src/newgrf.cpp @@ -38,6 +38,7 @@ #include "fios.h" #include "strings_func.h" #include "date_func.h" +#include "timer/timer_game_tick.h" #include "string_func.h" #include "network/core/config.h" #include @@ -6526,7 +6527,7 @@ bool GetGlobalVariable(byte param, uint32 *value, const GRFFile *grffile) return true; case 0x0A: // animation counter - *value = GB(_tick_counter, 0, 16); + *value = GB(TimerGameTick::counter, 0, 16); return true; case 0x0B: { // TTDPatch version @@ -9942,14 +9943,14 @@ void LoadNewGRF(uint load_index, uint num_baseset) Date date = TimerGameCalendar::date; Year year = TimerGameCalendar::year; DateFract date_fract = TimerGameCalendar::date_fract; - uint64 tick_counter = _tick_counter; + uint64 tick_counter = TimerGameTick::counter; byte display_opt = _display_opt; if (_networking) { TimerGameCalendar::year = _settings_game.game_creation.starting_year; TimerGameCalendar::date = ConvertYMDToDate(TimerGameCalendar::year, 0, 1); TimerGameCalendar::date_fract = 0; - _tick_counter = 0; + TimerGameTick::counter = 0; _display_opt = 0; } @@ -10046,6 +10047,6 @@ void LoadNewGRF(uint load_index, uint num_baseset) TimerGameCalendar::year = year; TimerGameCalendar::date = date; TimerGameCalendar::date_fract = date_fract; - _tick_counter = tick_counter; + TimerGameTick::counter = tick_counter; _display_opt = display_opt; } diff --git a/src/newgrf_animation_base.h b/src/newgrf_animation_base.h index 8df0228408..92502069f9 100644 --- a/src/newgrf_animation_base.h +++ b/src/newgrf_animation_base.h @@ -11,7 +11,7 @@ #include "animated_tile_func.h" #include "core/random_func.hpp" -#include "date_func.h" +#include "timer/timer_game_tick.h" #include "viewport_func.h" #include "newgrf_animation_type.h" #include "newgrf_callbacks.h" @@ -60,7 +60,7 @@ struct AnimationBase { * increasing this value by one doubles the wait. 0 is the minimum value * allowed for animation_speed, which corresponds to 30ms, and 16 is the * maximum, corresponding to around 33 minutes. */ - if (_tick_counter % (1ULL << animation_speed) != 0) return; + if (TimerGameTick::counter % (1ULL << animation_speed) != 0) return; uint8 frame = Tframehelper::Get(obj, tile); uint8 num_frames = spec->animation.frames; diff --git a/src/newgrf_profiling.cpp b/src/newgrf_profiling.cpp index 88b9e64b61..d02ba6dcc7 100644 --- a/src/newgrf_profiling.cpp +++ b/src/newgrf_profiling.cpp @@ -8,7 +8,6 @@ /** @file newgrf_profiling.cpp Profiling of NewGRF action 2 handling. */ #include "newgrf_profiling.h" -#include "date_func.h" #include "fileio_func.h" #include "string_func.h" #include "console_func.h" @@ -16,6 +15,7 @@ #include "walltime_func.h" #include "timer/timer.h" #include "timer/timer_game_calendar.h" +#include "timer/timer_game_tick.h" #include @@ -50,7 +50,7 @@ void NewGRFProfiler::BeginResolve(const ResolverObject &resolver) this->cur_call.root_sprite = resolver.root_spritegroup->nfo_line; this->cur_call.subs = 0; this->cur_call.time = (uint32)time_point_cast(high_resolution_clock::now()).time_since_epoch().count(); - this->cur_call.tick = _tick_counter; + this->cur_call.tick = TimerGameTick::counter; this->cur_call.cb = resolver.callback; this->cur_call.feat = resolver.GetFeature(); this->cur_call.item = resolver.GetDebugID(); @@ -89,7 +89,7 @@ void NewGRFProfiler::Start() { this->Abort(); this->active = true; - this->start_tick = _tick_counter; + this->start_tick = TimerGameTick::counter; } uint32 NewGRFProfiler::Finish() @@ -148,7 +148,7 @@ uint32 NewGRFProfiler::FinishAll() for (NewGRFProfiler &pr : _newgrf_profilers) { if (pr.active) { total_microseconds += pr.Finish(); - max_ticks = std::max(max_ticks, _tick_counter - pr.start_tick); + max_ticks = std::max(max_ticks, TimerGameTick::counter - pr.start_tick); } } diff --git a/src/saveload/afterload.cpp b/src/saveload/afterload.cpp index 0efc40f5c7..7e7f3ffe64 100644 --- a/src/saveload/afterload.cpp +++ b/src/saveload/afterload.cpp @@ -3192,7 +3192,7 @@ bool AfterLoadGame() /* Use current order time to approximate last loading time */ if (IsSavegameVersionBefore(SLV_LAST_LOADING_TICK)) { for (Vehicle *v : Vehicle::Iterate()) { - v->last_loading_tick = std::max(_tick_counter, static_cast(v->current_order_time)) - v->current_order_time; + v->last_loading_tick = std::max(TimerGameTick::counter, static_cast(v->current_order_time)) - v->current_order_time; } } diff --git a/src/saveload/misc_sl.cpp b/src/saveload/misc_sl.cpp index 6f82033658..3caa0fbab1 100644 --- a/src/saveload/misc_sl.cpp +++ b/src/saveload/misc_sl.cpp @@ -76,8 +76,8 @@ static const SaveLoad _date_desc[] = { SLEG_CONDVAR("date", TimerGameCalendar::date, SLE_FILE_U16 | SLE_VAR_I32, SL_MIN_VERSION, SLV_31), SLEG_CONDVAR("date", TimerGameCalendar::date, SLE_INT32, SLV_31, SL_MAX_VERSION), SLEG_VAR("date_fract", TimerGameCalendar::date_fract, SLE_UINT16), - SLEG_CONDVAR("tick_counter", _tick_counter, SLE_FILE_U16 | SLE_VAR_U64, SL_MIN_VERSION, SLV_U64_TICK_COUNTER), - SLEG_CONDVAR("tick_counter", _tick_counter, SLE_UINT64, SLV_U64_TICK_COUNTER, SL_MAX_VERSION), + SLEG_CONDVAR("tick_counter", TimerGameTick::counter, SLE_FILE_U16 | SLE_VAR_U64, SL_MIN_VERSION, SLV_U64_TICK_COUNTER), + SLEG_CONDVAR("tick_counter", TimerGameTick::counter, SLE_UINT64, SLV_U64_TICK_COUNTER, SL_MAX_VERSION), SLEG_CONDVAR("age_cargo_skip_counter", _age_cargo_skip_counter, SLE_UINT8, SL_MIN_VERSION, SLV_162), SLEG_CONDVAR("cur_tileloop_tile", _cur_tileloop_tile, SLE_FILE_U16 | SLE_VAR_U32, SL_MIN_VERSION, SLV_6), SLEG_CONDVAR("cur_tileloop_tile", _cur_tileloop_tile, SLE_UINT32, SLV_6, SL_MAX_VERSION), diff --git a/src/saveload/oldloader_sl.cpp b/src/saveload/oldloader_sl.cpp index b7c151c79d..393ef1f593 100644 --- a/src/saveload/oldloader_sl.cpp +++ b/src/saveload/oldloader_sl.cpp @@ -1617,7 +1617,7 @@ static const OldChunks main_chunk[] = { OCL_NULL( 2 ), ///< land_code, no longer in use OCL_VAR ( OC_FILE_U16 | OC_VAR_U8, 1, &_age_cargo_skip_counter ), - OCL_VAR ( OC_FILE_U16 | OC_VAR_U64, 1, &_tick_counter ), + OCL_VAR ( OC_FILE_U16 | OC_VAR_U64, 1, &TimerGameTick::counter ), OCL_VAR ( OC_TILE, 1, &_cur_tileloop_tile ), OCL_ASSERT( OC_TTO, 0x3A2E ), diff --git a/src/saveload/saveload.h b/src/saveload/saveload.h index 24c3ca5b27..3c406c767b 100644 --- a/src/saveload/saveload.h +++ b/src/saveload/saveload.h @@ -341,7 +341,7 @@ enum SaveLoadVersion : uint16 { SLV_DOCK_DOCKINGTILES, ///< 298 PR#9578 All tiles around docks may be docking tiles. SLV_REPAIR_OBJECT_DOCKING_TILES, ///< 299 PR#9594 v12.0 Fixing issue with docking tiles overlapping objects. - SLV_U64_TICK_COUNTER, ///< 300 PR#10035 Make _tick_counter 64bit to avoid wrapping. + SLV_U64_TICK_COUNTER, ///< 300 PR#10035 Make tick counter 64bit to avoid wrapping. SLV_LAST_LOADING_TICK, ///< 301 PR#9693 Store tick of last loading for vehicles. SLV_MULTITRACK_LEVEL_CROSSINGS, ///< 302 PR#9931 v13.0 Multi-track level crossings. SLV_NEWGRF_ROAD_STOPS, ///< 303 PR#10144 NewGRF road stops. diff --git a/src/station_cmd.cpp b/src/station_cmd.cpp index f0e78f68bf..2e9ad663d4 100644 --- a/src/station_cmd.cpp +++ b/src/station_cmd.cpp @@ -62,6 +62,7 @@ #include "newgrf_roadstop.h" #include "timer/timer.h" #include "timer/timer_game_calendar.h" +#include "timer/timer_game_tick.h" #include "table/strings.h" @@ -3979,16 +3980,18 @@ void OnTick_Station() StationHandleSmallTick(st); /* Clean up the link graph about once a week. */ - if (Station::IsExpected(st) && (_tick_counter + st->index) % STATION_LINKGRAPH_TICKS == 0) { + if (Station::IsExpected(st) && (TimerGameTick::counter + st->index) % STATION_LINKGRAPH_TICKS == 0) { DeleteStaleLinks(Station::From(st)); }; - /* Run STATION_ACCEPTANCE_TICKS = 250 tick interval trigger for station animation. - * Station index is included so that triggers are not all done - * at the same time. */ - if ((_tick_counter + st->index) % STATION_ACCEPTANCE_TICKS == 0) { + /* Spread out big-tick over STATION_ACCEPTANCE_TICKS ticks. */ + if ((TimerGameTick::counter + st->index) % STATION_ACCEPTANCE_TICKS == 0) { /* Stop processing this station if it was deleted */ if (!StationHandleBigTick(st)) continue; + } + + /* Spread out station animation over STATION_ACCEPTANCE_TICKS ticks. */ + if ((TimerGameTick::counter + st->index) % STATION_ACCEPTANCE_TICKS == 0) { TriggerStationAnimation(st, st->xy, SAT_250_TICKS); TriggerRoadStopAnimation(st, st->xy, SAT_250_TICKS); if (Station::IsExpected(st)) AirportAnimationTrigger(Station::From(st), AAT_STATION_250_TICKS); diff --git a/src/timer/timer_game_calendar.cpp b/src/timer/timer_game_calendar.cpp index bc44c13169..97546b710f 100644 --- a/src/timer/timer_game_calendar.cpp +++ b/src/timer/timer_game_calendar.cpp @@ -67,8 +67,6 @@ void TimerManager::Elapsed(TimerGameCalendar::TElapsed delta) { assert(delta == 1); - _tick_counter++; - if (_game_mode == GM_MENU) return; TimerGameCalendar::date_fract++; diff --git a/src/timer/timer_game_tick.cpp b/src/timer/timer_game_tick.cpp index 75ed88d63d..88ef701157 100644 --- a/src/timer/timer_game_tick.cpp +++ b/src/timer/timer_game_tick.cpp @@ -16,6 +16,8 @@ #include "safeguards.h" +uint64 TimerGameTick::counter = 0; + template<> void IntervalTimer::Elapsed(TimerGameTick::TElapsed delta) { @@ -51,6 +53,8 @@ void TimeoutTimer::Elapsed(TimerGameTick::TElapsed delta) template<> void TimerManager::Elapsed(TimerGameTick::TElapsed delta) { + TimerGameTick::counter++; + for (auto timer : TimerManager::GetTimers()) { timer->Elapsed(delta); } diff --git a/src/timer/timer_game_tick.h b/src/timer/timer_game_tick.h index 6a48a35bfd..0356b1b311 100644 --- a/src/timer/timer_game_tick.h +++ b/src/timer/timer_game_tick.h @@ -29,6 +29,8 @@ public: struct TStorage { uint elapsed; }; + + static uint64 counter; ///< Monotonic counter, in ticks, since start of game. }; #endif /* TIMER_GAME_TICK_H */ diff --git a/src/town_cmd.cpp b/src/town_cmd.cpp index 0b7e1f9142..5f84fbf4f3 100644 --- a/src/town_cmd.cpp +++ b/src/town_cmd.cpp @@ -34,7 +34,6 @@ #include "newgrf_cargo.h" #include "cheat_type.h" #include "animated_tile_func.h" -#include "date_func.h" #include "subsidy_func.h" #include "core/pool_func.hpp" #include "town.h" @@ -54,6 +53,7 @@ #include "tunnelbridge_cmd.h" #include "timer/timer.h" #include "timer/timer_game_calendar.h" +#include "timer/timer_game_tick.h" #include "table/strings.h" #include "table/town_land.h" @@ -345,7 +345,7 @@ static void AnimateTile_Town(TileIndex tile) return; } - if (_tick_counter & 3) return; + if (TimerGameTick::counter & 3) return; /* If the house is not one with a lift anymore, then stop this animating. * Not exactly sure when this happens, but probably when a house changes. @@ -597,7 +597,7 @@ static void TileLoop_Town(TileIndex tile) /* Binomial distribution per tick, by a series of coin flips */ /* Reduce generation rate to a 1/4, using tile bits to spread out distribution. * As tick counter is incremented by 256 between each call, we ignore the lower 8 bits. */ - if (GB(_tick_counter, 8, 2) == GB(tile, 0, 2)) { + if (GB(TimerGameTick::counter, 8, 2) == GB(tile, 0, 2)) { /* Make a bitmask with up to 32 bits set, one for each potential pax */ int genmax = (hs->population + 7) / 8; uint32 genmask = (genmax >= 32) ? 0xFFFFFFFF : ((1 << genmax) - 1); diff --git a/src/tree_cmd.cpp b/src/tree_cmd.cpp index 0186b35e75..a3838fbf6e 100644 --- a/src/tree_cmd.cpp +++ b/src/tree_cmd.cpp @@ -22,7 +22,7 @@ #include "company_base.h" #include "core/random_func.hpp" #include "newgrf_generic.h" -#include "date_func.h" +#include "timer/timer_game_tick.h" #include "tree_cmd.h" #include "landscape_cmd.h" @@ -707,11 +707,11 @@ static void TileLoop_Trees(TileIndex tile) AmbientSoundEffect(tile); - /* _tick_counter is incremented by 256 between each call, so ignore lower 8 bits. + /* TimerGameTick::counter is incremented by 256 between each call, so ignore lower 8 bits. * Also, we use a simple hash to spread the updates evenly over the map. * 11 and 9 are just some co-prime numbers for better spread. */ - uint32 cycle = 11 * TileX(tile) + 9 * TileY(tile) + (_tick_counter >> 8); + uint32 cycle = 11 * TileX(tile) + 9 * TileY(tile) + (TimerGameTick::counter >> 8); /* Handle growth of grass (under trees/on MP_TREES tiles) at every 8th processings, like it's done for grass on MP_CLEAR tiles. */ if ((cycle & 7) == 7 && GetTreeGround(tile) == TREE_GROUND_GRASS) { @@ -841,7 +841,7 @@ void OnTick_Trees() * this is the maximum number of ticks that are skipped. Number of ticks to skip is * inversely proportional to map size, so that is handled to create a mask. */ int skip = Map::ScaleBySize(16); - if (skip < 16 && (_tick_counter & (16 / skip - 1)) != 0) return; + if (skip < 16 && (TimerGameTick::counter & (16 / skip - 1)) != 0) return; /* place a tree at a random rainforest spot */ if (_settings_game.game_creation.landscape == LT_TROPIC) { diff --git a/src/vehicle.cpp b/src/vehicle.cpp index 5187d2b985..20a401576b 100644 --- a/src/vehicle.cpp +++ b/src/vehicle.cpp @@ -58,6 +58,7 @@ #include "newgrf_roadstop.h" #include "timer/timer.h" #include "timer/timer_game_calendar.h" +#include "timer/timer_game_tick.h" #include "table/strings.h" @@ -2116,7 +2117,7 @@ void Vehicle::BeginLoading() { assert(IsTileType(this->tile, MP_STATION) || this->type == VEH_SHIP); - Ticks travel_time = _tick_counter - this->last_loading_tick; + Ticks travel_time = TimerGameTick::counter - this->last_loading_tick; if (this->current_order.IsType(OT_GOTO_STATION) && this->current_order.GetDestination() == this->last_station_visited) { this->DeleteUnreachedImplicitOrders(); @@ -2281,7 +2282,7 @@ void Vehicle::LeaveStation() /* if the vehicle could load here or could stop with cargo loaded set the last loading station */ this->last_loading_station = this->last_station_visited; - this->last_loading_tick = _tick_counter; + this->last_loading_tick = TimerGameTick::counter; } else { /* if the vehicle couldn't load and had to unload or transfer everything * set the last loading station to invalid as it will leave empty. */ diff --git a/src/vehicle_base.h b/src/vehicle_base.h index 5d2ebba7fa..613e9b1877 100644 --- a/src/vehicle_base.h +++ b/src/vehicle_base.h @@ -332,7 +332,7 @@ public: StationID last_station_visited; ///< The last station we stopped at. StationID last_loading_station; ///< Last station the vehicle has stopped at and could possibly leave from with any cargo loaded. - uint64_t last_loading_tick; ///< Last time (relative to _tick_counter) the vehicle has stopped at a station and could possibly leave with any cargo loaded. + uint64_t last_loading_tick; ///< Last time (based on TimerGameTick counter) the vehicle has stopped at a station and could possibly leave with any cargo loaded. CargoID cargo_type; ///< type of cargo this vehicle is carrying byte cargo_subtype; ///< Used for livery refits (NewGRF variations) From 2f495c015ac9d4cf3a6a3881577fd5a3867701e7 Mon Sep 17 00:00:00 2001 From: Tyler Trahan Date: Mon, 24 Apr 2023 13:33:03 -0400 Subject: [PATCH 15/27] Fix 7c6bf97: Don't change date and shift dates in the wrong order (#10711) --- src/cheat_gui.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/cheat_gui.cpp b/src/cheat_gui.cpp index 48a2fd5073..07863ee84c 100644 --- a/src/cheat_gui.cpp +++ b/src/cheat_gui.cpp @@ -112,13 +112,13 @@ static int32 ClickChangeDateCheat(int32 new_value, int32 change_direction) ConvertDateToYMD(TimerGameCalendar::date, &ymd); Date new_date = ConvertYMDToDate(new_value, ymd.month, ymd.day); - /* Change the date. */ - TimerGameCalendar::SetDate(new_date, TimerGameCalendar::date_fract); - - /* Shift cached dates. */ + /* Shift cached dates before we change the date. */ for (auto v : Vehicle::Iterate()) v->ShiftDates(new_date - TimerGameCalendar::date); LinkGraphSchedule::instance.ShiftDates(new_date - TimerGameCalendar::date); + /* Now it's safe to actually change the date. */ + TimerGameCalendar::SetDate(new_date, TimerGameCalendar::date_fract); + EnginesMonthlyLoop(); SetWindowDirty(WC_STATUS_BAR, 0); InvalidateWindowClassesData(WC_BUILD_STATION, 0); From 1c76e0904dac4e7096bca02330b713a73c609c49 Mon Sep 17 00:00:00 2001 From: Patric Stout Date: Mon, 24 Apr 2023 20:33:39 +0200 Subject: [PATCH 16/27] Codechange: revive STR_TINY_BLACK_COMMA from its coma (#10714) --- src/build_vehicle_gui.cpp | 4 ++-- src/lang/afrikaans.txt | 2 +- src/lang/arabic_egypt.txt | 2 +- src/lang/basque.txt | 2 +- src/lang/belarusian.txt | 2 +- src/lang/brazilian_portuguese.txt | 2 +- src/lang/bulgarian.txt | 2 +- src/lang/catalan.txt | 2 +- src/lang/chuvash.txt | 2 +- src/lang/croatian.txt | 2 +- src/lang/czech.txt | 2 +- src/lang/danish.txt | 2 +- src/lang/dutch.txt | 2 +- src/lang/english.txt | 2 +- src/lang/english_AU.txt | 2 +- src/lang/english_US.txt | 2 +- src/lang/esperanto.txt | 2 +- src/lang/estonian.txt | 2 +- src/lang/faroese.txt | 2 +- src/lang/finnish.txt | 2 +- src/lang/french.txt | 2 +- src/lang/frisian.txt | 2 +- src/lang/gaelic.txt | 2 +- src/lang/galician.txt | 2 +- src/lang/german.txt | 2 +- src/lang/greek.txt | 2 +- src/lang/hebrew.txt | 2 +- src/lang/hindi.txt | 2 +- src/lang/hungarian.txt | 2 +- src/lang/icelandic.txt | 2 +- src/lang/ido.txt | 2 +- src/lang/indonesian.txt | 2 +- src/lang/irish.txt | 2 +- src/lang/italian.txt | 2 +- src/lang/japanese.txt | 2 +- src/lang/korean.txt | 2 +- src/lang/latin.txt | 2 +- src/lang/latvian.txt | 2 +- src/lang/lithuanian.txt | 2 +- src/lang/luxembourgish.txt | 2 +- src/lang/macedonian.txt | 2 +- src/lang/malay.txt | 2 +- src/lang/maltese.txt | 2 +- src/lang/marathi.txt | 2 +- src/lang/norwegian_bokmal.txt | 2 +- src/lang/norwegian_nynorsk.txt | 2 +- src/lang/persian.txt | 2 +- src/lang/polish.txt | 2 +- src/lang/portuguese.txt | 2 +- src/lang/romanian.txt | 2 +- src/lang/russian.txt | 2 +- src/lang/serbian.txt | 2 +- src/lang/simplified_chinese.txt | 2 +- src/lang/slovak.txt | 2 +- src/lang/slovenian.txt | 2 +- src/lang/spanish.txt | 2 +- src/lang/spanish_MX.txt | 2 +- src/lang/swedish.txt | 2 +- src/lang/tamil.txt | 2 +- src/lang/thai.txt | 2 +- src/lang/traditional_chinese.txt | 2 +- src/lang/turkish.txt | 2 +- src/lang/ukrainian.txt | 2 +- src/lang/urdu.txt | 2 +- src/lang/vietnamese.txt | 2 +- src/lang/welsh.txt | 2 +- 66 files changed, 67 insertions(+), 67 deletions(-) diff --git a/src/build_vehicle_gui.cpp b/src/build_vehicle_gui.cpp index c4fbae295e..d63a3558d0 100644 --- a/src/build_vehicle_gui.cpp +++ b/src/build_vehicle_gui.cpp @@ -1011,7 +1011,7 @@ void DrawEngineList(VehicleType type, const Rect &r, const GUIEngineList &eng_li if (show_count) { replace_icon = GetSpriteSize(SPR_GROUP_REPLACE_ACTIVE); SetDParamMaxDigits(0, 3, FS_SMALL); - count_width = GetStringBoundingBox(STR_TINY_BLACK_COMA).width; + count_width = GetStringBoundingBox(STR_TINY_BLACK_COMMA).width; } Rect tr = ir.Indent(circle_width + WidgetDimensions::scaled.hsep_normal + sprite_width + WidgetDimensions::scaled.hsep_wide, rtl); // Name position @@ -1050,7 +1050,7 @@ void DrawEngineList(VehicleType type, const Rect &r, const GUIEngineList &eng_li DrawVehicleEngine(r.left, r.right, sprite_x, y + sprite_y_offset, item.engine_id, (show_count && num_engines == 0) ? PALETTE_CRASH : GetEnginePalette(item.engine_id, _local_company), EIT_PURCHASE); if (show_count) { SetDParam(0, num_engines); - DrawString(cr.left, cr.right, y + small_text_y_offset, STR_TINY_BLACK_COMA, TC_FROMSTRING, SA_RIGHT | SA_FORCE); + DrawString(cr.left, cr.right, y + small_text_y_offset, STR_TINY_BLACK_COMMA, TC_FROMSTRING, SA_RIGHT | SA_FORCE); if (EngineHasReplacementForCompany(Company::Get(_local_company), item.engine_id, selected_group)) DrawSprite(SPR_GROUP_REPLACE_ACTIVE, num_engines == 0 ? PALETTE_CRASH : PAL_NONE, rr.left, y + replace_icon_y_offset); } if (has_variants) { diff --git a/src/lang/afrikaans.txt b/src/lang/afrikaans.txt index 0d5f48bf65..bf58be2f68 100644 --- a/src/lang/afrikaans.txt +++ b/src/lang/afrikaans.txt @@ -5229,7 +5229,7 @@ STR_JUST_BIG_RAW_STRING :{BIG_FONT}{STRI # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/arabic_egypt.txt b/src/lang/arabic_egypt.txt index d632dde908..db0c27e3dd 100644 --- a/src/lang/arabic_egypt.txt +++ b/src/lang/arabic_egypt.txt @@ -4927,7 +4927,7 @@ STR_JUST_BIG_RAW_STRING :{BIG_FONT}{STRI # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/basque.txt b/src/lang/basque.txt index 89f49b2b64..9b732bb855 100644 --- a/src/lang/basque.txt +++ b/src/lang/basque.txt @@ -4961,7 +4961,7 @@ STR_JUST_BIG_RAW_STRING :{BIG_FONT}{STRI # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/belarusian.txt b/src/lang/belarusian.txt index 0d5f4554ad..5a74a01ace 100644 --- a/src/lang/belarusian.txt +++ b/src/lang/belarusian.txt @@ -5701,7 +5701,7 @@ STR_JUST_BIG_RAW_STRING :{BIG_FONT}{STRI # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/brazilian_portuguese.txt b/src/lang/brazilian_portuguese.txt index d01ad1f1e7..05dd6fc6f3 100644 --- a/src/lang/brazilian_portuguese.txt +++ b/src/lang/brazilian_portuguese.txt @@ -5602,7 +5602,7 @@ STR_JUST_BIG_RAW_STRING :{BIG_FONT}{STRI # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/bulgarian.txt b/src/lang/bulgarian.txt index fd653c5818..0ec3a15f13 100644 --- a/src/lang/bulgarian.txt +++ b/src/lang/bulgarian.txt @@ -5050,7 +5050,7 @@ STR_JUST_BIG_RAW_STRING :{BIG_FONT}{STRI # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/catalan.txt b/src/lang/catalan.txt index eac967f762..f9696bf7cf 100644 --- a/src/lang/catalan.txt +++ b/src/lang/catalan.txt @@ -5602,7 +5602,7 @@ STR_JUST_BIG_RAW_STRING :{BIG_FONT}{STRI # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/chuvash.txt b/src/lang/chuvash.txt index 378e0e7cc7..09a719bf4d 100644 --- a/src/lang/chuvash.txt +++ b/src/lang/chuvash.txt @@ -1821,7 +1821,7 @@ STR_JUST_RAW_STRING :{STRING} # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/croatian.txt b/src/lang/croatian.txt index 0f181c624f..9bc3f38d08 100644 --- a/src/lang/croatian.txt +++ b/src/lang/croatian.txt @@ -5455,7 +5455,7 @@ STR_JUST_BIG_RAW_STRING :{BIG_FONT}{STRI # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/czech.txt b/src/lang/czech.txt index 64f1342c0b..17509f4bd8 100644 --- a/src/lang/czech.txt +++ b/src/lang/czech.txt @@ -5815,7 +5815,7 @@ STR_JUST_BIG_RAW_STRING :{BIG_FONT}{STRI # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/danish.txt b/src/lang/danish.txt index 19f447f4fc..db0b5e0866 100644 --- a/src/lang/danish.txt +++ b/src/lang/danish.txt @@ -5601,7 +5601,7 @@ STR_JUST_BIG_RAW_STRING :{BIG_FONT}{STRI # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/dutch.txt b/src/lang/dutch.txt index fb7cbc72de..75e041b55c 100644 --- a/src/lang/dutch.txt +++ b/src/lang/dutch.txt @@ -5606,7 +5606,7 @@ STR_JUST_BIG_RAW_STRING :{BIG_FONT}{STRI # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/english.txt b/src/lang/english.txt index b12b339f9a..ec9d72dc5d 100644 --- a/src/lang/english.txt +++ b/src/lang/english.txt @@ -5607,7 +5607,7 @@ STR_JUST_BIG_RAW_STRING :{BIG_FONT}{RAW_ # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/english_AU.txt b/src/lang/english_AU.txt index 0cab037e5a..cd7312addb 100644 --- a/src/lang/english_AU.txt +++ b/src/lang/english_AU.txt @@ -5607,7 +5607,7 @@ STR_JUST_BIG_RAW_STRING :{BIG_FONT}{STRI # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/english_US.txt b/src/lang/english_US.txt index b99660e710..155810f55a 100644 --- a/src/lang/english_US.txt +++ b/src/lang/english_US.txt @@ -5607,7 +5607,7 @@ STR_JUST_BIG_RAW_STRING :{BIG_FONT}{STRI # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/esperanto.txt b/src/lang/esperanto.txt index 439231b78c..bafdcb85c7 100644 --- a/src/lang/esperanto.txt +++ b/src/lang/esperanto.txt @@ -4461,7 +4461,7 @@ STR_JUST_BIG_RAW_STRING :{BIG_FONT}{STRI # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/estonian.txt b/src/lang/estonian.txt index 2ae60e435c..7ee4b4fbaf 100644 --- a/src/lang/estonian.txt +++ b/src/lang/estonian.txt @@ -5639,7 +5639,7 @@ STR_JUST_BIG_RAW_STRING :{BIG_FONT}{STRI # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/faroese.txt b/src/lang/faroese.txt index fc2f86ae28..093bb895a9 100644 --- a/src/lang/faroese.txt +++ b/src/lang/faroese.txt @@ -4603,7 +4603,7 @@ STR_JUST_RAW_STRING :{STRING} # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/finnish.txt b/src/lang/finnish.txt index f90c989494..cc50f5b1a1 100644 --- a/src/lang/finnish.txt +++ b/src/lang/finnish.txt @@ -5606,7 +5606,7 @@ STR_JUST_BIG_RAW_STRING :{BIG_FONT}{STRI # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/french.txt b/src/lang/french.txt index 3d2fc3e413..c82717ff41 100644 --- a/src/lang/french.txt +++ b/src/lang/french.txt @@ -5607,7 +5607,7 @@ STR_JUST_BIG_RAW_STRING :{BIG_FONT}{STRI # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/frisian.txt b/src/lang/frisian.txt index d84d8cb866..b45ead94bb 100644 --- a/src/lang/frisian.txt +++ b/src/lang/frisian.txt @@ -4798,7 +4798,7 @@ STR_JUST_BIG_RAW_STRING :{BIG_FONT}{STRI # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/gaelic.txt b/src/lang/gaelic.txt index 8da18cc02e..c55c2100d1 100644 --- a/src/lang/gaelic.txt +++ b/src/lang/gaelic.txt @@ -5520,7 +5520,7 @@ STR_JUST_BIG_RAW_STRING :{BIG_FONT}{STRI # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/galician.txt b/src/lang/galician.txt index 351b206d26..6d16900508 100644 --- a/src/lang/galician.txt +++ b/src/lang/galician.txt @@ -5608,7 +5608,7 @@ STR_JUST_BIG_RAW_STRING :{BIG_FONT}{STRI # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/german.txt b/src/lang/german.txt index da807a6473..2d92843a6e 100644 --- a/src/lang/german.txt +++ b/src/lang/german.txt @@ -5597,7 +5597,7 @@ STR_JUST_BIG_RAW_STRING :{BIG_FONT}{STRI # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/greek.txt b/src/lang/greek.txt index 0ec59002c9..e0ddb756ad 100644 --- a/src/lang/greek.txt +++ b/src/lang/greek.txt @@ -5687,7 +5687,7 @@ STR_JUST_BIG_RAW_STRING :{BIG_FONT}{STRI # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/hebrew.txt b/src/lang/hebrew.txt index a567be6133..b7d193dd7d 100644 --- a/src/lang/hebrew.txt +++ b/src/lang/hebrew.txt @@ -5278,7 +5278,7 @@ STR_JUST_BIG_RAW_STRING :{BIG_FONT}{STRI # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/hindi.txt b/src/lang/hindi.txt index 387093a538..1ea63d23dc 100644 --- a/src/lang/hindi.txt +++ b/src/lang/hindi.txt @@ -1518,7 +1518,7 @@ STR_JUST_BIG_RAW_STRING :{BIG_FONT}{STRI # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/hungarian.txt b/src/lang/hungarian.txt index 538343553f..96bae4af2a 100644 --- a/src/lang/hungarian.txt +++ b/src/lang/hungarian.txt @@ -5676,7 +5676,7 @@ STR_JUST_BIG_RAW_STRING :{BIG_FONT}{STRI # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/icelandic.txt b/src/lang/icelandic.txt index b44b3b8d16..6ba3e68ea0 100644 --- a/src/lang/icelandic.txt +++ b/src/lang/icelandic.txt @@ -4846,7 +4846,7 @@ STR_JUST_RAW_STRING :{STRING} # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/ido.txt b/src/lang/ido.txt index 297233d123..237753a0a1 100644 --- a/src/lang/ido.txt +++ b/src/lang/ido.txt @@ -1696,7 +1696,7 @@ STR_JUST_RAW_STRING :{STRING} # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/indonesian.txt b/src/lang/indonesian.txt index 4528fb3c5a..d2bbb2dab3 100644 --- a/src/lang/indonesian.txt +++ b/src/lang/indonesian.txt @@ -5571,7 +5571,7 @@ STR_JUST_BIG_RAW_STRING :{BIG_FONT}{STRI # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/irish.txt b/src/lang/irish.txt index bf2411ab3c..1b35e6a89e 100644 --- a/src/lang/irish.txt +++ b/src/lang/irish.txt @@ -5480,7 +5480,7 @@ STR_JUST_BIG_RAW_STRING :{BIG_FONT}{STRI # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/italian.txt b/src/lang/italian.txt index b7f01771e4..a7995cc936 100644 --- a/src/lang/italian.txt +++ b/src/lang/italian.txt @@ -5648,7 +5648,7 @@ STR_JUST_BIG_RAW_STRING :{BIG_FONT}{STRI # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/japanese.txt b/src/lang/japanese.txt index 1033f065e8..e4a0d2e6fd 100644 --- a/src/lang/japanese.txt +++ b/src/lang/japanese.txt @@ -5595,7 +5595,7 @@ STR_JUST_BIG_RAW_STRING :{BIG_FONT}{STRI # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/korean.txt b/src/lang/korean.txt index eeeea82408..b065aaf7fe 100644 --- a/src/lang/korean.txt +++ b/src/lang/korean.txt @@ -5608,7 +5608,7 @@ STR_JUST_BIG_RAW_STRING :{BIG_FONT}{STRI # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/latin.txt b/src/lang/latin.txt index 967083a7f1..14d8e6904c 100644 --- a/src/lang/latin.txt +++ b/src/lang/latin.txt @@ -5472,7 +5472,7 @@ STR_JUST_BIG_RAW_STRING :{BIG_FONT}{STRI # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/latvian.txt b/src/lang/latvian.txt index 740b6a7a6b..253fbff1a0 100644 --- a/src/lang/latvian.txt +++ b/src/lang/latvian.txt @@ -5588,7 +5588,7 @@ STR_JUST_BIG_RAW_STRING :{BIG_FONT}{STRI # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/lithuanian.txt b/src/lang/lithuanian.txt index bf0eefea0d..b25b0c4bbf 100644 --- a/src/lang/lithuanian.txt +++ b/src/lang/lithuanian.txt @@ -6045,7 +6045,7 @@ STR_JUST_BIG_RAW_STRING :{BIG_FONT}{STRI # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/luxembourgish.txt b/src/lang/luxembourgish.txt index 9c08da2187..a4ad44de64 100644 --- a/src/lang/luxembourgish.txt +++ b/src/lang/luxembourgish.txt @@ -5581,7 +5581,7 @@ STR_JUST_BIG_RAW_STRING :{BIG_FONT}{STRI # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/macedonian.txt b/src/lang/macedonian.txt index ac3b40b60f..c6064c65dc 100644 --- a/src/lang/macedonian.txt +++ b/src/lang/macedonian.txt @@ -2240,7 +2240,7 @@ STR_JUST_RAW_STRING :{STRING} # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/malay.txt b/src/lang/malay.txt index 14cc903a8b..ab2a36db3a 100644 --- a/src/lang/malay.txt +++ b/src/lang/malay.txt @@ -4753,7 +4753,7 @@ STR_JUST_RAW_STRING :{STRING} # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/maltese.txt b/src/lang/maltese.txt index d7af4d76b5..20bca7ea89 100644 --- a/src/lang/maltese.txt +++ b/src/lang/maltese.txt @@ -1739,7 +1739,7 @@ STR_JUST_RAW_STRING :{STRING} # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/marathi.txt b/src/lang/marathi.txt index f4799eb7c9..679d7d56b7 100644 --- a/src/lang/marathi.txt +++ b/src/lang/marathi.txt @@ -2113,7 +2113,7 @@ STR_JUST_RAW_STRING :{STRING} # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/norwegian_bokmal.txt b/src/lang/norwegian_bokmal.txt index 563fa80774..b02d7b25f8 100644 --- a/src/lang/norwegian_bokmal.txt +++ b/src/lang/norwegian_bokmal.txt @@ -5502,7 +5502,7 @@ STR_JUST_BIG_RAW_STRING :{BIG_FONT}{STRI # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/norwegian_nynorsk.txt b/src/lang/norwegian_nynorsk.txt index 8d69c390f5..baf7ad2a2c 100644 --- a/src/lang/norwegian_nynorsk.txt +++ b/src/lang/norwegian_nynorsk.txt @@ -4990,7 +4990,7 @@ STR_JUST_BIG_RAW_STRING :{BIG_FONT}{STRI # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/persian.txt b/src/lang/persian.txt index 4f88d8ae87..cdb62ffcdd 100644 --- a/src/lang/persian.txt +++ b/src/lang/persian.txt @@ -4290,7 +4290,7 @@ STR_JUST_BIG_RAW_STRING :{BIG_FONT}{STRI # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/polish.txt b/src/lang/polish.txt index 6dbbbbb604..e8d6dbd421 100644 --- a/src/lang/polish.txt +++ b/src/lang/polish.txt @@ -6024,7 +6024,7 @@ STR_JUST_BIG_RAW_STRING :{BIG_FONT}{STRI # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/portuguese.txt b/src/lang/portuguese.txt index 2e75bb44b2..e21f560e00 100644 --- a/src/lang/portuguese.txt +++ b/src/lang/portuguese.txt @@ -5607,7 +5607,7 @@ STR_JUST_BIG_RAW_STRING :{BIG_FONT}{STRI # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/romanian.txt b/src/lang/romanian.txt index 8b96a026c0..b954a2313a 100644 --- a/src/lang/romanian.txt +++ b/src/lang/romanian.txt @@ -5594,7 +5594,7 @@ STR_JUST_BIG_RAW_STRING :{BIG_FONT}{STRI # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/russian.txt b/src/lang/russian.txt index 8523941347..1b2e61a71b 100644 --- a/src/lang/russian.txt +++ b/src/lang/russian.txt @@ -5831,7 +5831,7 @@ STR_JUST_BIG_RAW_STRING :{BIG_FONT}{STRI # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/serbian.txt b/src/lang/serbian.txt index 928fc41c31..029dc38ad3 100644 --- a/src/lang/serbian.txt +++ b/src/lang/serbian.txt @@ -5782,7 +5782,7 @@ STR_JUST_BIG_RAW_STRING :{BIG_FONT}{STRI # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/simplified_chinese.txt b/src/lang/simplified_chinese.txt index 4a977e293f..3456f9a67c 100644 --- a/src/lang/simplified_chinese.txt +++ b/src/lang/simplified_chinese.txt @@ -5591,7 +5591,7 @@ STR_JUST_BIG_RAW_STRING :{BIG_FONT}{STRI # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/slovak.txt b/src/lang/slovak.txt index 82f2920048..9e7317fb5d 100644 --- a/src/lang/slovak.txt +++ b/src/lang/slovak.txt @@ -5670,7 +5670,7 @@ STR_JUST_BIG_RAW_STRING :{BIG_FONT}{STRI # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/slovenian.txt b/src/lang/slovenian.txt index 4e200cb91b..f2843a6ace 100644 --- a/src/lang/slovenian.txt +++ b/src/lang/slovenian.txt @@ -5291,7 +5291,7 @@ STR_JUST_BIG_RAW_STRING :{BIG_FONT}{STRI # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/spanish.txt b/src/lang/spanish.txt index 92df45c636..1051b74fed 100644 --- a/src/lang/spanish.txt +++ b/src/lang/spanish.txt @@ -5578,7 +5578,7 @@ STR_JUST_BIG_RAW_STRING :{BIG_FONT}{STRI # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/spanish_MX.txt b/src/lang/spanish_MX.txt index 0fa8e683bb..a25ec4a60c 100644 --- a/src/lang/spanish_MX.txt +++ b/src/lang/spanish_MX.txt @@ -5581,7 +5581,7 @@ STR_JUST_BIG_RAW_STRING :{BIG_FONT}{STRI # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/swedish.txt b/src/lang/swedish.txt index 2f5f480dc2..c641d67bcb 100644 --- a/src/lang/swedish.txt +++ b/src/lang/swedish.txt @@ -5595,7 +5595,7 @@ STR_JUST_BIG_RAW_STRING :{BIG_FONT}{STRI # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/tamil.txt b/src/lang/tamil.txt index 7f1fec6d7b..6177cb032d 100644 --- a/src/lang/tamil.txt +++ b/src/lang/tamil.txt @@ -5068,7 +5068,7 @@ STR_JUST_BIG_RAW_STRING :{BIG_FONT}{STRI # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/thai.txt b/src/lang/thai.txt index fcdc273c0d..47ef4e9b4e 100644 --- a/src/lang/thai.txt +++ b/src/lang/thai.txt @@ -5205,7 +5205,7 @@ STR_JUST_BIG_RAW_STRING :{BIG_FONT}{STRI # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/traditional_chinese.txt b/src/lang/traditional_chinese.txt index 96ab183b87..f0c499408b 100644 --- a/src/lang/traditional_chinese.txt +++ b/src/lang/traditional_chinese.txt @@ -5595,7 +5595,7 @@ STR_JUST_BIG_RAW_STRING :{BIG_FONT}{STRI # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/turkish.txt b/src/lang/turkish.txt index e06cdd0856..4e8d9f7d8e 100644 --- a/src/lang/turkish.txt +++ b/src/lang/turkish.txt @@ -5618,7 +5618,7 @@ STR_JUST_BIG_RAW_STRING :{BIG_FONT}{STRI # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/ukrainian.txt b/src/lang/ukrainian.txt index 0a0ad48013..6e6d17d7bf 100644 --- a/src/lang/ukrainian.txt +++ b/src/lang/ukrainian.txt @@ -5741,7 +5741,7 @@ STR_JUST_BIG_RAW_STRING :{BIG_FONT}{STRI # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/urdu.txt b/src/lang/urdu.txt index 9421f86052..4469fcb764 100644 --- a/src/lang/urdu.txt +++ b/src/lang/urdu.txt @@ -3180,7 +3180,7 @@ STR_JUST_RAW_STRING :{STRING} # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/vietnamese.txt b/src/lang/vietnamese.txt index 0ab7cc6bc3..b5bb6898dd 100644 --- a/src/lang/vietnamese.txt +++ b/src/lang/vietnamese.txt @@ -5606,7 +5606,7 @@ STR_JUST_BIG_RAW_STRING :{BIG_FONT}{STRI # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} diff --git a/src/lang/welsh.txt b/src/lang/welsh.txt index 7f47899011..a201c79111 100644 --- a/src/lang/welsh.txt +++ b/src/lang/welsh.txt @@ -5114,7 +5114,7 @@ STR_JUST_BIG_RAW_STRING :{BIG_FONT}{STRI # Slightly 'raw' stringcodes with colour or size STR_BLACK_COMMA :{BLACK}{COMMA} -STR_TINY_BLACK_COMA :{TINY_FONT}{BLACK}{COMMA} +STR_TINY_BLACK_COMMA :{TINY_FONT}{BLACK}{COMMA} STR_TINY_COMMA :{TINY_FONT}{COMMA} STR_BLUE_COMMA :{BLUE}{COMMA} STR_RED_COMMA :{RED}{COMMA} From 27e9a799886171b7e360cde52a2c680995e2713a Mon Sep 17 00:00:00 2001 From: translators Date: Mon, 24 Apr 2023 18:40:29 +0000 Subject: [PATCH 17/27] Update: Translations from eints finnish: 2 changes by hpiirai portuguese: 1 change by azulcosta --- src/lang/finnish.txt | 3 ++- src/lang/portuguese.txt | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/lang/finnish.txt b/src/lang/finnish.txt index cc50f5b1a1..bcdf3c2df4 100644 --- a/src/lang/finnish.txt +++ b/src/lang/finnish.txt @@ -1712,7 +1712,7 @@ STR_CONFIG_SETTING_SCRIPT_MAX_MEMORY_HELPTEXT :Kuinka paljon m STR_CONFIG_SETTING_SCRIPT_MAX_MEMORY_VALUE :{COMMA} MiB STR_CONFIG_SETTING_SERVINT_ISPERCENT :Huoltovälit ovat prosentteina: {STRING} -STR_CONFIG_SETTING_SERVINT_ISPERCENT_HELPTEXT :Määritä, aiheuttaako edellisestä huollosta kulunut aika vai luotettavuuden laskeminen kulkuneuvon huoltamisen +STR_CONFIG_SETTING_SERVINT_ISPERCENT_HELPTEXT :Kun tämä on valittuna, kulkuneuvot yrittävät mennä huoltoon niiden luotettavuuden laskettua annetun prosenttiosuuden verran enimmäisluotettavuudesta.{}{}Jos esimerkiksi kulkuneuvon enimmäisluotettavuus on 90 % ja huoltoväli 20 %, kulkuneuvo pyrkii huoltoon luotettavuuden laskettua 72 %:iin. STR_CONFIG_SETTING_SERVINT_TRAINS :Junien oletushuoltoväli: {STRING} STR_CONFIG_SETTING_SERVINT_TRAINS_HELPTEXT :Määritä oletushuoltoväli uusille junille, mikäli kulkuneuvolle ei ole määritelty erillistä huoltoväliä @@ -5110,6 +5110,7 @@ STR_ERROR_NO_BUOY :{WHITE}Poijua e STR_ERROR_CAN_T_TIMETABLE_VEHICLE :{WHITE}Ei voi asettaa aikataulua. STR_ERROR_TIMETABLE_ONLY_WAIT_AT_STATIONS :{WHITE}Kulkuneuvo voi odottaa vain asemalla STR_ERROR_TIMETABLE_NOT_STOPPING_HERE :{WHITE}Tämä kulkuneuvo ei pysähdy tällä asemalla +STR_ERROR_TIMETABLE_INCOMPLETE :{WHITE}… aikataulu on puutteellinen # Sign related errors STR_ERROR_TOO_MANY_SIGNS :{WHITE}... liian monta kylttiä. diff --git a/src/lang/portuguese.txt b/src/lang/portuguese.txt index e21f560e00..8c90122a3a 100644 --- a/src/lang/portuguese.txt +++ b/src/lang/portuguese.txt @@ -5111,6 +5111,7 @@ STR_ERROR_NO_BUOY :{WHITE}Não exi STR_ERROR_CAN_T_TIMETABLE_VEHICLE :{WHITE}Impossível programar veículo... STR_ERROR_TIMETABLE_ONLY_WAIT_AT_STATIONS :{WHITE}Veículos apenas podem esperar em estações. STR_ERROR_TIMETABLE_NOT_STOPPING_HERE :{WHITE}Este veículo não pára nesta estação. +STR_ERROR_TIMETABLE_INCOMPLETE :{WHITE}... horário incompleto # Sign related errors STR_ERROR_TOO_MANY_SIGNS :{WHITE}... demasiados sinais From 37392935ddd78f3c6f940e58e28be00e979e2628 Mon Sep 17 00:00:00 2001 From: Jonathan G Rennison Date: Mon, 24 Apr 2023 19:55:16 +0100 Subject: [PATCH 18/27] Fix #10707: Incorrect type of days_in_transit in CargoPacket constructor (#10715) --- src/cargopacket.cpp | 2 +- src/cargopacket.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cargopacket.cpp b/src/cargopacket.cpp index 848cae1c84..e79de1e14b 100644 --- a/src/cargopacket.cpp +++ b/src/cargopacket.cpp @@ -68,7 +68,7 @@ CargoPacket::CargoPacket(StationID source, TileIndex source_xy, uint16 count, So * @note We have to zero memory ourselves here because we are using a 'new' * that, in contrary to all other pools, does not memset to 0. */ -CargoPacket::CargoPacket(uint16 count, byte days_in_transit, StationID source, TileIndex source_xy, TileIndex loaded_at_xy, Money feeder_share, SourceType source_type, SourceID source_id) : +CargoPacket::CargoPacket(uint16 count, uint16 days_in_transit, StationID source, TileIndex source_xy, TileIndex loaded_at_xy, Money feeder_share, SourceType source_type, SourceID source_id) : feeder_share(feeder_share), count(count), days_in_transit(days_in_transit), diff --git a/src/cargopacket.h b/src/cargopacket.h index 384e3785c7..9aacfed57c 100644 --- a/src/cargopacket.h +++ b/src/cargopacket.h @@ -66,7 +66,7 @@ public: CargoPacket(); CargoPacket(StationID source, TileIndex source_xy, uint16 count, SourceType source_type, SourceID source_id); - CargoPacket(uint16 count, byte days_in_transit, StationID source, TileIndex source_xy, TileIndex loaded_at_xy, Money feeder_share = 0, SourceType source_type = SourceType::Industry, SourceID source_id = INVALID_SOURCE); + CargoPacket(uint16 count, uint16 days_in_transit, StationID source, TileIndex source_xy, TileIndex loaded_at_xy, Money feeder_share = 0, SourceType source_type = SourceType::Industry, SourceID source_id = INVALID_SOURCE); /** Destroy the packet. */ ~CargoPacket() { } From 6830e5f5f709217a83fabb2421e7996f6d4ea577 Mon Sep 17 00:00:00 2001 From: Tyler Trahan Date: Mon, 24 Apr 2023 15:58:48 -0400 Subject: [PATCH 19/27] Cleanup: Don't use a magic number when closing processing industries (#10710) --- src/industry.h | 2 ++ src/industry_cmd.cpp | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/industry.h b/src/industry.h index fd0d5ef9e9..cb8abea42e 100644 --- a/src/industry.h +++ b/src/industry.h @@ -21,6 +21,8 @@ typedef Pool IndustryPool; extern IndustryPool _industry_pool; +static const Year PROCESSING_INDUSTRY_ABANDONMENT_YEARS = 5; ///< If a processing industry doesn't produce for this many consecutive years, it may close. + /** * Production level maximum, minimum and default values. * It is not a value been really used in order to change, but rather an indicator diff --git a/src/industry_cmd.cpp b/src/industry_cmd.cpp index 080690f8b9..ba9309e9ae 100644 --- a/src/industry_cmd.cpp +++ b/src/industry_cmd.cpp @@ -2857,7 +2857,7 @@ static void ChangeIndustryProduction(Industry *i, bool monthly) if ((i->ctlflags & INDCTL_NO_PRODUCTION_INCREASE) && (mul > 0 || increment > 0)) return; if (!callback_enabled && (indspec->life_type & INDUSTRYLIFE_PROCESSING)) { - if ( (byte)(TimerGameCalendar::year - i->last_prod_year) >= 5 && Chance16(1, original_economy ? 2 : 180)) { + if (TimerGameCalendar::year - i->last_prod_year >= PROCESSING_INDUSTRY_ABANDONMENT_YEARS && Chance16(1, original_economy ? 2 : 180)) { closeit = true; } } From 55d981aec3ec68c72f897bff7fa155c1c92de73d Mon Sep 17 00:00:00 2001 From: Peter Nelson Date: Wed, 19 Apr 2023 13:23:46 +0100 Subject: [PATCH 20/27] Add: Helper to update widget vertical size. This avoids directly setting min_y outside widget code. --- src/widget.cpp | 12 ++++++++++++ src/widget_type.h | 2 ++ 2 files changed, 14 insertions(+) diff --git a/src/widget.cpp b/src/widget.cpp index 1c590e3d3f..796291cde5 100644 --- a/src/widget.cpp +++ b/src/widget.cpp @@ -1134,6 +1134,18 @@ void NWidgetResizeBase::SetResize(uint resize_x, uint resize_y) this->resize_y = resize_y; } +/** + * Set absolute (post-scaling) minimal size of the widget. + * @param min_y Vertical minimal size of the widget. + * @return true iff the widget minimum size has changed. + */ +bool NWidgetResizeBase::UpdateVerticalSize(uint min_y) +{ + if (min_y == this->min_y) return false; + this->min_y = min_y; + return true; +} + void NWidgetResizeBase::AssignSizePosition(SizingType sizing, uint x, uint y, uint given_width, uint given_height, bool rtl) { this->StoreSizePosition(sizing, x, y, given_width, given_height); diff --git a/src/widget_type.h b/src/widget_type.h index 078aa49b10..0133bc5174 100644 --- a/src/widget_type.h +++ b/src/widget_type.h @@ -263,6 +263,8 @@ public: void SetFill(uint fill_x, uint fill_y); void SetResize(uint resize_x, uint resize_y); + bool UpdateVerticalSize(uint min_y); + void AssignSizePosition(SizingType sizing, uint x, uint y, uint given_width, uint given_height, bool rtl) override; uint min_x; ///< Minimal horizontal size of only this widget. From e8df28d7f332150f611a1eda1217f4d8c95bc926 Mon Sep 17 00:00:00 2001 From: Peter Nelson Date: Tue, 25 Apr 2023 09:13:33 +0100 Subject: [PATCH 21/27] Add: parameter for ReInit() to reposition window to default. --- src/window.cpp | 9 ++++++++- src/window_gui.h | 2 +- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/src/window.cpp b/src/window.cpp index e8bbfbf5d6..16a43e0fdd 100644 --- a/src/window.cpp +++ b/src/window.cpp @@ -1010,9 +1010,10 @@ void Window::SetDirty() const * Re-initialize a window, and optionally change its size. * @param rx Horizontal resize of the window. * @param ry Vertical resize of the window. + * @param reposition If set, reposition the window to default location. * @note For just resizing the window, use #ResizeWindow instead. */ -void Window::ReInit(int rx, int ry) +void Window::ReInit(int rx, int ry, bool reposition) { this->SetDirty(); // Mark whole current window as dirty. @@ -1039,6 +1040,12 @@ void Window::ReInit(int rx, int ry) if (this->resize.step_width > 1) dx -= dx % (int)this->resize.step_width; if (this->resize.step_height > 1) dy -= dy % (int)this->resize.step_height; + if (reposition) { + Point pt = this->OnInitialPosition(this->nested_root->smallest_x, this->nested_root->smallest_y, window_number); + this->InitializePositionSize(pt.x, pt.y, this->nested_root->smallest_x, this->nested_root->smallest_y); + this->FindWindowPlacementAndResize(this->window_desc->GetDefaultWidth(), this->window_desc->GetDefaultHeight()); + } + ResizeWindow(this, dx, dy); /* ResizeWindow() does this->SetDirty() already, no need to do it again here. */ } diff --git a/src/window_gui.h b/src/window_gui.h index c9825ab686..c94af5d84b 100644 --- a/src/window_gui.h +++ b/src/window_gui.h @@ -449,7 +449,7 @@ public: static void DeleteClosedWindows(); void SetDirty() const; - void ReInit(int rx = 0, int ry = 0); + void ReInit(int rx = 0, int ry = 0, bool reposition = false); /** Is window shaded currently? */ inline bool IsShaded() const From 9aee502838cfd4c8b501bdc67bddf9f2b21c6ca3 Mon Sep 17 00:00:00 2001 From: Peter Nelson Date: Wed, 19 Apr 2023 01:43:11 +0100 Subject: [PATCH 22/27] Change: Size Game Options description widgets after initial sizing. Trying to update text widgets with free flowing multiline text during UpdateWidgetSize(), as the final width is not yet known and so the calculated height being incorrect, usually resulting in one or more empty text lines. The solution is to update the widget heights afterwards during OnResize(), at which point the final widths are known. The window is then resized if needed. (Note this technique needs more attention if width can also change.) --- src/settings_gui.cpp | 61 ++++++++++++++++++++++++-------------------- 1 file changed, 34 insertions(+), 27 deletions(-) diff --git a/src/settings_gui.cpp b/src/settings_gui.cpp index f5f1002164..a138b45f5a 100644 --- a/src/settings_gui.cpp +++ b/src/settings_gui.cpp @@ -347,17 +347,40 @@ struct GameOptionsWindow : Window { } } + void OnResize() override + { + bool changed = false; + + NWidgetResizeBase *wid = this->GetWidget(WID_GO_BASE_GRF_DESCRIPTION); + int y = 0; + for (int i = 0; i < BaseGraphics::GetNumSets(); i++) { + SetDParamStr(0, BaseGraphics::GetSet(i)->GetDescription(GetCurrentLanguageIsoCode())); + y = std::max(y, GetStringHeight(STR_BLACK_RAW_STRING, wid->current_x)); + } + changed |= wid->UpdateVerticalSize(y); + + wid = this->GetWidget(WID_GO_BASE_SFX_DESCRIPTION); + y = 0; + for (int i = 0; i < BaseSounds::GetNumSets(); i++) { + SetDParamStr(0, BaseSounds::GetSet(i)->GetDescription(GetCurrentLanguageIsoCode())); + y = std::max(y, GetStringHeight(STR_BLACK_RAW_STRING, wid->current_x)); + } + changed |= wid->UpdateVerticalSize(y); + + wid = this->GetWidget(WID_GO_BASE_MUSIC_DESCRIPTION); + y = 0; + for (int i = 0; i < BaseMusic::GetNumSets(); i++) { + SetDParamStr(0, BaseMusic::GetSet(i)->GetDescription(GetCurrentLanguageIsoCode())); + y = std::max(y, GetStringHeight(STR_BLACK_RAW_STRING, wid->current_x)); + } + changed |= wid->UpdateVerticalSize(y); + + if (changed) this->ReInit(0, 0, true); + } + void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override { switch (widget) { - case WID_GO_BASE_GRF_DESCRIPTION: - /* Find the biggest description for the default size. */ - for (int i = 0; i < BaseGraphics::GetNumSets(); i++) { - SetDParamStr(0, BaseGraphics::GetSet(i)->GetDescription(GetCurrentLanguageIsoCode())); - size->height = std::max(size->height, (uint)GetStringHeight(STR_BLACK_RAW_STRING, size->width)); - } - break; - case WID_GO_BASE_GRF_STATUS: /* Find the biggest description for the default size. */ for (int i = 0; i < BaseGraphics::GetNumSets(); i++) { @@ -369,22 +392,6 @@ struct GameOptionsWindow : Window { } break; - case WID_GO_BASE_SFX_DESCRIPTION: - /* Find the biggest description for the default size. */ - for (int i = 0; i < BaseSounds::GetNumSets(); i++) { - SetDParamStr(0, BaseSounds::GetSet(i)->GetDescription(GetCurrentLanguageIsoCode())); - size->height = std::max(size->height, (uint)GetStringHeight(STR_BLACK_RAW_STRING, size->width)); - } - break; - - case WID_GO_BASE_MUSIC_DESCRIPTION: - /* Find the biggest description for the default size. */ - for (int i = 0; i < BaseMusic::GetNumSets(); i++) { - SetDParamStr(0, BaseMusic::GetSet(i)->GetDescription(GetCurrentLanguageIsoCode())); - size->height = std::max(size->height, (uint)GetStringHeight(STR_BLACK_RAW_STRING, size->width)); - } - break; - case WID_GO_BASE_MUSIC_STATUS: /* Find the biggest description for the default size. */ for (int i = 0; i < BaseMusic::GetNumSets(); i++) { @@ -736,7 +743,7 @@ static const NWidgetPart _nested_game_options_widgets[] = { NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_GO_BASE_GRF_DROPDOWN), SetMinimalSize(150, 12), SetDataTip(STR_BLACK_RAW_STRING, STR_GAME_OPTIONS_BASE_GRF_TOOLTIP), NWidget(WWT_TEXT, COLOUR_GREY, WID_GO_BASE_GRF_STATUS), SetMinimalSize(150, 12), SetDataTip(STR_EMPTY, STR_NULL), SetFill(1, 0), EndContainer(), - NWidget(WWT_TEXT, COLOUR_GREY, WID_GO_BASE_GRF_DESCRIPTION), SetMinimalSize(330, 0), SetDataTip(STR_EMPTY, STR_GAME_OPTIONS_BASE_GRF_DESCRIPTION_TOOLTIP), SetFill(1, 0), SetPadding(6, 0, 6, 0), + NWidget(WWT_EMPTY, INVALID_COLOUR, WID_GO_BASE_GRF_DESCRIPTION), SetMinimalSize(330, 0), SetMinimalTextLines(1, 0), SetDataTip(STR_NULL, STR_GAME_OPTIONS_BASE_GRF_DESCRIPTION_TOOLTIP), SetFill(1, 0), SetPadding(6, 0, 6, 0), NWidget(NWID_HORIZONTAL, NC_EQUALSIZE), SetPIP(7, 0, 7), NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_GO_BASE_GRF_TEXTFILE + TFT_README), SetFill(1, 0), SetResize(1, 0), SetDataTip(STR_TEXTFILE_VIEW_README, STR_NULL), NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_GO_BASE_GRF_TEXTFILE + TFT_CHANGELOG), SetFill(1, 0), SetResize(1, 0), SetDataTip(STR_TEXTFILE_VIEW_CHANGELOG, STR_NULL), @@ -750,7 +757,7 @@ static const NWidgetPart _nested_game_options_widgets[] = { NWidget(NWID_SPACER), SetMinimalSize(150, 12), SetFill(1, 0), NWidget(WWT_EMPTY, COLOUR_GREY, WID_GO_BASE_SFX_VOLUME), SetMinimalSize(67, 12), SetFill(0, 0), SetDataTip(0x0, STR_MUSIC_TOOLTIP_DRAG_SLIDERS_TO_SET_MUSIC), EndContainer(), - NWidget(WWT_TEXT, COLOUR_GREY, WID_GO_BASE_SFX_DESCRIPTION), SetMinimalSize(330, 0), SetDataTip(STR_EMPTY, STR_GAME_OPTIONS_BASE_SFX_DESCRIPTION_TOOLTIP), SetFill(1, 0), SetPadding(6, 0, 6, 0), + NWidget(WWT_EMPTY, INVALID_COLOUR, WID_GO_BASE_SFX_DESCRIPTION), SetMinimalSize(330, 0), SetMinimalTextLines(1, 0), SetDataTip(STR_NULL, STR_GAME_OPTIONS_BASE_SFX_DESCRIPTION_TOOLTIP), SetFill(1, 0), SetPadding(6, 0, 6, 0), NWidget(NWID_HORIZONTAL, NC_EQUALSIZE), SetPIP(7, 0, 7), NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_GO_BASE_SFX_TEXTFILE + TFT_README), SetFill(1, 0), SetResize(1, 0), SetDataTip(STR_TEXTFILE_VIEW_README, STR_NULL), NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_GO_BASE_SFX_TEXTFILE + TFT_CHANGELOG), SetFill(1, 0), SetResize(1, 0), SetDataTip(STR_TEXTFILE_VIEW_CHANGELOG, STR_NULL), @@ -765,7 +772,7 @@ static const NWidgetPart _nested_game_options_widgets[] = { NWidget(WWT_EMPTY, COLOUR_GREY, WID_GO_BASE_MUSIC_VOLUME), SetMinimalSize(67, 12), SetFill(0, 0), SetDataTip(0x0, STR_MUSIC_TOOLTIP_DRAG_SLIDERS_TO_SET_MUSIC), EndContainer(), NWidget(NWID_HORIZONTAL), SetPIP(0, 30, 7), - NWidget(WWT_TEXT, COLOUR_GREY, WID_GO_BASE_MUSIC_DESCRIPTION), SetMinimalSize(330, 0), SetDataTip(STR_EMPTY, STR_GAME_OPTIONS_BASE_MUSIC_DESCRIPTION_TOOLTIP), SetFill(1, 0), SetPadding(6, 0, 6, 0), + NWidget(WWT_EMPTY, INVALID_COLOUR, WID_GO_BASE_MUSIC_DESCRIPTION), SetMinimalSize(330, 0), SetMinimalTextLines(1, 0), SetDataTip(STR_NULL, STR_GAME_OPTIONS_BASE_MUSIC_DESCRIPTION_TOOLTIP), SetFill(1, 0), SetPadding(6, 0, 6, 0), NWidget(NWID_VERTICAL), SetPIP(0, 0, 0), NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_GO_BASE_MUSIC_JUKEBOX), SetMinimalSize(22, 22), SetDataTip(SPR_IMG_MUSIC, STR_TOOLBAR_TOOLTIP_SHOW_SOUND_MUSIC_WINDOW), SetPadding(6, 0, 6, 0), EndContainer(), From b8f0513a72016f2c08b13d7c713039c20046f22b Mon Sep 17 00:00:00 2001 From: Peter Nelson Date: Wed, 19 Apr 2023 01:50:36 +0100 Subject: [PATCH 23/27] Change: Draw and size video driver info like base set info. This allows very long video driver information strings to wrap instead of making the game options window very wide. --- src/settings_gui.cpp | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/src/settings_gui.cpp b/src/settings_gui.cpp index a138b45f5a..31a79b8331 100644 --- a/src/settings_gui.cpp +++ b/src/settings_gui.cpp @@ -298,7 +298,6 @@ struct GameOptionsWindow : Window { case WID_GO_BASE_SFX_DROPDOWN: SetDParamStr(0, BaseSounds::GetUsedSet()->name); break; case WID_GO_BASE_MUSIC_DROPDOWN: SetDParamStr(0, BaseMusic::GetUsedSet()->name); break; case WID_GO_BASE_MUSIC_STATUS: SetDParam(0, BaseMusic::GetUsedSet()->GetNumInvalid()); break; - case WID_GO_VIDEO_DRIVER_INFO: SetDParamStr(0, VideoDriver::GetInstance()->GetInfoString()); break; case WID_GO_REFRESH_RATE_DROPDOWN: SetDParam(0, _settings_client.gui.refresh_rate); break; case WID_GO_RESOLUTION_DROPDOWN: { auto current_resolution = GetCurrentResolutionIndex(); @@ -337,6 +336,11 @@ struct GameOptionsWindow : Window { DrawSliderWidget(r, MIN_INTERFACE_SCALE, MAX_INTERFACE_SCALE, this->gui_scale, _scale_labels); break; + case WID_GO_VIDEO_DRIVER_INFO: + SetDParamStr(0, VideoDriver::GetInstance()->GetInfoString()); + DrawStringMultiLine(r, STR_GAME_OPTIONS_VIDEO_DRIVER_INFO); + break; + case WID_GO_BASE_SFX_VOLUME: DrawSliderWidget(r, 0, INT8_MAX, _settings_client.music.effect_vol, {}); break; @@ -375,6 +379,11 @@ struct GameOptionsWindow : Window { } changed |= wid->UpdateVerticalSize(y); + wid = this->GetWidget(WID_GO_VIDEO_DRIVER_INFO); + SetDParamStr(0, VideoDriver::GetInstance()->GetInfoString()); + y = GetStringHeight(STR_GAME_OPTIONS_VIDEO_DRIVER_INFO, wid->current_x); + changed |= wid->UpdateVerticalSize(y); + if (changed) this->ReInit(0, 0, true); } @@ -732,7 +741,7 @@ static const NWidgetPart _nested_game_options_widgets[] = { EndContainer(), #endif NWidget(NWID_HORIZONTAL), - NWidget(WWT_TEXT, COLOUR_GREY, WID_GO_VIDEO_DRIVER_INFO), SetMinimalSize(0, 12), SetFill(1, 0), SetDataTip(STR_GAME_OPTIONS_VIDEO_DRIVER_INFO, STR_NULL), + NWidget(WWT_EMPTY, INVALID_COLOUR, WID_GO_VIDEO_DRIVER_INFO), SetMinimalTextLines(1, 0), SetFill(1, 0), EndContainer(), EndContainer(), EndContainer(), From 43c65a3fec37baabee10186f0e250d5268a8e1ea Mon Sep 17 00:00:00 2001 From: Rubidium Date: Tue, 18 Apr 2023 22:21:17 +0200 Subject: [PATCH 24/27] Codechange: use std::string for base media filename/warning storage --- src/base_media_base.h | 23 +++++++++-------------- src/base_media_func.h | 18 +++++++++--------- src/fileio.cpp | 2 +- src/fileio_func.h | 2 +- src/gfxinit.cpp | 16 ++++++++-------- src/music.cpp | 12 ++++++------ src/music/midifile.cpp | 6 +++--- src/sound.cpp | 4 ++-- 8 files changed, 39 insertions(+), 44 deletions(-) diff --git a/src/base_media_base.h b/src/base_media_base.h index 9a9d6ff48a..84c12d0858 100644 --- a/src/base_media_base.h +++ b/src/base_media_base.h @@ -31,9 +31,9 @@ struct MD5File { CR_NO_FILE, ///< The file did not exist }; - const char *filename; ///< filename + std::string filename; ///< filename uint8 hash[16]; ///< md5 sum of the file - const char *missing_warning; ///< warning when this file is missing + std::string missing_warning; ///< warning when this file is missing ChecksumResult check_result; ///< cached result of md5 check ChecksumResult CheckMD5(Subdirectory subdir, size_t max_size) const; @@ -73,11 +73,6 @@ struct BaseSet { /** Free everything we allocated */ ~BaseSet() { - for (uint i = 0; i < NUM_FILES; i++) { - free(this->files[i].filename); - free(this->files[i].missing_warning); - } - delete this->next; } @@ -100,7 +95,7 @@ struct BaseSet { return Tnum_files - this->valid_files; } - bool FillSetDetails(IniFile *ini, const char *path, const char *full_filename, bool allow_empty_filename = true); + bool FillSetDetails(IniFile *ini, const std::string &path, const std::string &full_filename, bool allow_empty_filename = true); /** * Get the description for the given ISO code. @@ -147,7 +142,7 @@ struct BaseSet { const char *GetTextfile(TextfileType type) const { for (uint i = 0; i < NUM_FILES; i++) { - const char *textfile = ::GetTextfile(type, BASESET_DIR, this->files[i].filename); + const char *textfile = ::GetTextfile(type, BASESET_DIR, this->files[i].filename.c_str()); if (textfile != nullptr) { return textfile; } @@ -249,7 +244,7 @@ struct GraphicsSet : BaseSet { PaletteType palette; ///< Palette of this graphics set BlitterType blitter; ///< Blitter of this graphics set - bool FillSetDetails(struct IniFile *ini, const char *path, const char *full_filename); + bool FillSetDetails(struct IniFile *ini, const std::string &path, const std::string &full_filename); static MD5File::ChecksumResult CheckMD5(const MD5File *file, Subdirectory subdir); }; @@ -279,8 +274,8 @@ static const uint NUM_SONGS_AVAILABLE = 1 + NUM_SONG_CLASSES * NUM_SONGS_CLASS; static const uint NUM_SONGS_PLAYLIST = 32; /* Functions to read DOS music CAT files, similar to but not quite the same as sound effect CAT files */ -char *GetMusicCatEntryName(const char *filename, size_t entrynum); -byte *GetMusicCatEntryData(const char *filename, size_t entrynum, size_t &entrylen); +char *GetMusicCatEntryName(const std::string &filename, size_t entrynum); +byte *GetMusicCatEntryData(const std::string &filename, size_t entrynum, size_t &entrylen); enum MusicTrackType { MTT_STANDARDMIDI, ///< Standard MIDI file @@ -291,7 +286,7 @@ enum MusicTrackType { struct MusicSongInfo { std::string songname; ///< name of song displayed in UI byte tracknr; ///< track number of song displayed in UI - const char *filename; ///< file on disk containing song (when used in MusicSet class, this pointer is owned by MD5File object for the file) + std::string filename; ///< file on disk containing song (when used in MusicSet class) MusicTrackType filetype; ///< decoder required for song file int cat_index; ///< entry index in CAT file, for filetype==MTT_MPSMIDI bool loop; ///< song should play in a tight loop if possible, never ending @@ -306,7 +301,7 @@ struct MusicSet : BaseSet { /** Number of valid songs in set. */ byte num_available; - bool FillSetDetails(struct IniFile *ini, const char *path, const char *full_filename); + bool FillSetDetails(struct IniFile *ini, const std::string &path, const std::string &full_filename); }; /** All data/functions related with replacing the base music */ diff --git a/src/base_media_func.h b/src/base_media_func.h index d2c8bcdcd9..b1300567d4 100644 --- a/src/base_media_func.h +++ b/src/base_media_func.h @@ -38,7 +38,7 @@ extern void CheckExternalFiles(); * @return true if loading was successful. */ template -bool BaseSet::FillSetDetails(IniFile *ini, const char *path, const char *full_filename, bool allow_empty_filename) +bool BaseSet::FillSetDetails(IniFile *ini, const std::string &path, const std::string &full_filename, bool allow_empty_filename) { IniGroup *metadata = ini->GetGroup("metadata"); IniItem *item; @@ -81,15 +81,15 @@ bool BaseSet::FillSetDetails(IniFile *ini, const } if (!item->value.has_value()) { - file->filename = nullptr; + file->filename.clear(); /* If we list no file, that file must be valid */ this->valid_files++; this->found_files++; continue; } - const char *filename = item->value->c_str(); - file->filename = str_fmt("%s%s", path, filename); + const std::string &filename = item->value.value(); + file->filename = path + filename; /* Then find the MD5 checksum */ item = md5s->GetItem(filename, false); @@ -122,9 +122,9 @@ bool BaseSet::FillSetDetails(IniFile *ini, const if (item == nullptr) item = origin->GetItem("default", false); if (item == nullptr || !item->value.has_value()) { Debug(grf, 1, "No origin warning message specified for: {}", filename); - file->missing_warning = stredup(""); + file->missing_warning.clear(); } else { - file->missing_warning = stredup(item->value->c_str()); + file->missing_warning = item->value.value(); } file->check_result = T::CheckMD5(file, BASESET_DIR); @@ -169,7 +169,7 @@ bool BaseMedia::AddFile(const std::string &filename, size_t basepath_ path.clear(); } - if (set->FillSetDetails(ini, path.c_str(), filename.c_str())) { + if (set->FillSetDetails(ini, path, filename)) { Tbase_set *duplicate = nullptr; for (Tbase_set *c = BaseMedia::available_sets; c != nullptr; c = c->next) { if (c->name == set->name || c->shortname == set->shortname) { @@ -282,7 +282,7 @@ template const char *TryGetBaseSetFile(const ContentInfo *ci, if (s->GetNumMissing() != 0) continue; if (s->shortname != ci->unique_id) continue; - if (!md5sum) return s->files[0].filename; + if (!md5sum) return s->files[0].filename.c_str(); byte md5[16]; memset(md5, 0, sizeof(md5)); @@ -291,7 +291,7 @@ template const char *TryGetBaseSetFile(const ContentInfo *ci, md5[j] ^= s->files[i].hash[j]; } } - if (memcmp(md5, ci->md5sum, sizeof(md5)) == 0) return s->files[0].filename; + if (memcmp(md5, ci->md5sum, sizeof(md5)) == 0) return s->files[0].filename.c_str(); } return nullptr; } diff --git a/src/fileio.cpp b/src/fileio.cpp index ee12b25639..04f6408664 100644 --- a/src/fileio.cpp +++ b/src/fileio.cpp @@ -140,7 +140,7 @@ void FioFCloseFile(FILE *f) * @param filename Filename to look for. * @return String containing the path if the path was found, else an empty string. */ -std::string FioFindFullPath(Subdirectory subdir, const char *filename) +std::string FioFindFullPath(Subdirectory subdir, const std::string &filename) { assert(subdir < NUM_SUBDIRS); diff --git a/src/fileio_func.h b/src/fileio_func.h index 3556849a0f..c6d2a8ef0e 100644 --- a/src/fileio_func.h +++ b/src/fileio_func.h @@ -18,7 +18,7 @@ void FioFCloseFile(FILE *f); FILE *FioFOpenFile(const std::string &filename, const char *mode, Subdirectory subdir, size_t *filesize = nullptr); bool FioCheckFileExists(const std::string &filename, Subdirectory subdir); -std::string FioFindFullPath(Subdirectory subdir, const char *filename); +std::string FioFindFullPath(Subdirectory subdir, const std::string &filename); std::string FioGetDirectory(Searchpath sp, Subdirectory subdir); std::string FioFindDirectory(Subdirectory subdir); void FioCreateDirectory(const std::string &name); diff --git a/src/gfxinit.cpp b/src/gfxinit.cpp index 2028eaf901..b4c1655b32 100644 --- a/src/gfxinit.cpp +++ b/src/gfxinit.cpp @@ -42,7 +42,7 @@ static const SpriteID * const _landscape_spriteindexes[] = { * @param needs_palette_remap Whether the colours in the GRF file need a palette remap. * @return The number of loaded sprites. */ -static uint LoadGrfFile(const char *filename, uint load_index, bool needs_palette_remap) +static uint LoadGrfFile(const std::string &filename, uint load_index, bool needs_palette_remap) { uint load_index_org = load_index; uint sprite_id = 0; @@ -52,7 +52,7 @@ static uint LoadGrfFile(const char *filename, uint load_index, bool needs_palett Debug(sprite, 2, "Reading grf-file '{}'", filename); byte container_ver = file.GetContainerVersion(); - if (container_ver == 0) usererror("Base grf '%s' is corrupt", filename); + if (container_ver == 0) usererror("Base grf '%s' is corrupt", filename.c_str()); ReadGRFSpriteOffsets(file); if (container_ver >= 2) { /* Read compression. */ @@ -79,7 +79,7 @@ static uint LoadGrfFile(const char *filename, uint load_index, bool needs_palett * @param needs_palette_remap Whether the colours in the GRF file need a palette remap. * @return The number of loaded sprites. */ -static void LoadGrfFileIndexed(const char *filename, const SpriteID *index_tbl, bool needs_palette_remap) +static void LoadGrfFileIndexed(const std::string &filename, const SpriteID *index_tbl, bool needs_palette_remap) { uint start; uint sprite_id = 0; @@ -89,7 +89,7 @@ static void LoadGrfFileIndexed(const char *filename, const SpriteID *index_tbl, Debug(sprite, 2, "Reading indexed grf-file '{}'", filename); byte container_ver = file.GetContainerVersion(); - if (container_ver == 0) usererror("Base grf '%s' is corrupt", filename); + if (container_ver == 0) usererror("Base grf '%s' is corrupt", filename.c_str()); ReadGRFSpriteOffsets(file); if (container_ver >= 2) { /* Read compression. */ @@ -137,7 +137,7 @@ void CheckExternalFiles() add_pos += seprintf(add_pos, last, "Trying to load graphics set '%s', but it is incomplete. The game will probably not run correctly until you properly install this set or select another one. See section 4.1 of README.md.\n\nThe following files are corrupted or missing:\n", used_set->name.c_str()); for (uint i = 0; i < GraphicsSet::NUM_FILES; i++) { MD5File::ChecksumResult res = GraphicsSet::CheckMD5(&used_set->files[i], BASESET_DIR); - if (res != MD5File::CR_MATCH) add_pos += seprintf(add_pos, last, "\t%s is %s (%s)\n", used_set->files[i].filename, res == MD5File::CR_MISMATCH ? "corrupt" : "missing", used_set->files[i].missing_warning); + if (res != MD5File::CR_MATCH) add_pos += seprintf(add_pos, last, "\t%s is %s (%s)\n", used_set->files[i].filename.c_str(), res == MD5File::CR_MISMATCH ? "corrupt" : "missing", used_set->files[i].missing_warning.c_str()); } add_pos += seprintf(add_pos, last, "\n"); } @@ -149,7 +149,7 @@ void CheckExternalFiles() static_assert(SoundsSet::NUM_FILES == 1); /* No need to loop each file, as long as there is only a single * sound file. */ - add_pos += seprintf(add_pos, last, "\t%s is %s (%s)\n", sounds_set->files->filename, SoundsSet::CheckMD5(sounds_set->files, BASESET_DIR) == MD5File::CR_MISMATCH ? "corrupt" : "missing", sounds_set->files->missing_warning); + add_pos += seprintf(add_pos, last, "\t%s is %s (%s)\n", sounds_set->files->filename.c_str(), SoundsSet::CheckMD5(sounds_set->files, BASESET_DIR) == MD5File::CR_MISMATCH ? "corrupt" : "missing", sounds_set->files->missing_warning.c_str()); } if (add_pos != error_msg) ShowInfoI(error_msg); @@ -201,7 +201,7 @@ static void LoadSpriteTables() ClrBit(master->flags, GCF_INIT_ONLY); /* Baseset extra graphics */ - GRFConfig *extra = new GRFConfig(used_set->files[GFT_EXTRA].filename); + GRFConfig *extra = new GRFConfig(used_set->files[GFT_EXTRA].filename.c_str()); /* We know the palette of the base set, so if the base NewGRF is not * setting one, use the palette of the base set and not the global @@ -355,7 +355,7 @@ void GfxLoadSprites() UpdateCursorSize(); } -bool GraphicsSet::FillSetDetails(IniFile *ini, const char *path, const char *full_filename) +bool GraphicsSet::FillSetDetails(IniFile *ini, const std::string &path, const std::string &full_filename) { bool ret = this->BaseSet::FillSetDetails(ini, path, full_filename, false); if (ret) { diff --git a/src/music.cpp b/src/music.cpp index d7fbd4b6b0..9c4392be4a 100644 --- a/src/music.cpp +++ b/src/music.cpp @@ -25,7 +25,7 @@ * @return Pointer to string, caller is responsible for freeing memory, * nullptr if entrynum does not exist. */ -char *GetMusicCatEntryName(const char *filename, size_t entrynum) +char *GetMusicCatEntryName(const std::string &filename, size_t entrynum) { if (!FioCheckFileExists(filename, BASESET_DIR)) return nullptr; @@ -52,7 +52,7 @@ char *GetMusicCatEntryName(const char *filename, size_t entrynum) * @return Pointer to buffer with data read, caller is responsible for freeind memory, * nullptr if entrynum does not exist. */ -byte *GetMusicCatEntryData(const char *filename, size_t entrynum, size_t &entrylen) +byte *GetMusicCatEntryData(const std::string &filename, size_t entrynum, size_t &entrylen) { entrylen = 0; if (!FioCheckFileExists(filename, BASESET_DIR)) return nullptr; @@ -116,7 +116,7 @@ template return BaseMedia::used_set != nullptr; } -bool MusicSet::FillSetDetails(IniFile *ini, const char *path, const char *full_filename) +bool MusicSet::FillSetDetails(IniFile *ini, const std::string &path, const std::string &full_filename) { bool ret = this->BaseSet::FillSetDetails(ini, path, full_filename); if (ret) { @@ -126,8 +126,8 @@ bool MusicSet::FillSetDetails(IniFile *ini, const char *path, const char *full_f IniGroup *timingtrim = ini->GetGroup("timingtrim"); uint tracknr = 1; for (uint i = 0; i < lengthof(this->songinfo); i++) { - const char *filename = this->files[i].filename; - if (names == nullptr || StrEmpty(filename) || this->files[i].check_result == MD5File::CR_NO_FILE) { + const std::string &filename = this->files[i].filename; + if (filename.empty() || this->files[i].check_result == MD5File::CR_NO_FILE) { continue; } @@ -149,7 +149,7 @@ bool MusicSet::FillSetDetails(IniFile *ini, const char *path, const char *full_f this->songinfo[i].filetype = MTT_STANDARDMIDI; } - const char *trimmed_filename = filename; + const char *trimmed_filename = filename.c_str(); /* As we possibly add a path to the filename and we compare * on the filename with the path as in the .obm, we need to * keep stripping path elements until we find a match. */ diff --git a/src/music/midifile.cpp b/src/music/midifile.cpp index 8f12aae1e3..894de4f072 100644 --- a/src/music/midifile.cpp +++ b/src/music/midifile.cpp @@ -849,7 +849,7 @@ bool MidiFile::LoadSong(const MusicSongInfo &song) { switch (song.filetype) { case MTT_STANDARDMIDI: - return this->LoadFile(song.filename); + return this->LoadFile(song.filename.c_str()); case MTT_MPSMIDI: { size_t songdatalen = 0; @@ -1060,9 +1060,9 @@ std::string MidiFile::GetSMFFile(const MusicSongInfo &song) char basename[MAX_PATH]; { - const char *fnstart = strrchr(song.filename, PATHSEPCHAR); + const char *fnstart = strrchr(song.filename.c_str(), PATHSEPCHAR); if (fnstart == nullptr) { - fnstart = song.filename; + fnstart = song.filename.c_str(); } else { fnstart++; } diff --git a/src/sound.cpp b/src/sound.cpp index 2c77e0fed8..0fa435c26c 100644 --- a/src/sound.cpp +++ b/src/sound.cpp @@ -23,7 +23,7 @@ static SoundEntry _original_sounds[ORIGINAL_SAMPLE_COUNT]; -static void OpenBankFile(const char *filename) +static void OpenBankFile(const std::string &filename) { /** * The sound file for the original sounds, i.e. those not defined/overridden by a NewGRF. @@ -34,7 +34,7 @@ static void OpenBankFile(const char *filename) memset(_original_sounds, 0, sizeof(_original_sounds)); /* If there is no sound file (nosound set), don't load anything */ - if (filename == nullptr) return; + if (filename.empty()) return; original_sound_file.reset(new RandomAccessFile(filename, BASESET_DIR)); size_t pos = original_sound_file->GetPos(); From f74e26ca7eb823ed1c82c578bbdbd8374e47bebf Mon Sep 17 00:00:00 2001 From: Rubidium Date: Wed, 19 Apr 2023 22:47:36 +0200 Subject: [PATCH 25/27] 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) From 5794590b361fafb297e7c770492b774a0e7c6e1b Mon Sep 17 00:00:00 2001 From: translators Date: Tue, 25 Apr 2023 18:41:18 +0000 Subject: [PATCH 26/27] Update: Translations from eints vietnamese: 1 change by KhoiCanDev polish: 7 changes by pAter-exe --- src/lang/polish.txt | 8 +++++++- src/lang/vietnamese.txt | 1 + 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/src/lang/polish.txt b/src/lang/polish.txt index e8d6dbd421..0df0f9c208 100644 --- a/src/lang/polish.txt +++ b/src/lang/polish.txt @@ -2092,7 +2092,7 @@ STR_CONFIG_SETTING_SCRIPT_MAX_MEMORY_HELPTEXT :Ilość pamięc STR_CONFIG_SETTING_SCRIPT_MAX_MEMORY_VALUE :{COMMA} MiB STR_CONFIG_SETTING_SERVINT_ISPERCENT :Okres między serwisowaniami w procentach: {STRING} -STR_CONFIG_SETTING_SERVINT_ISPERCENT_HELPTEXT :Wybierz, czy serwisowanie pojazdów odbywa się na podstawie czasu od ostatniego serwisu, czy sprawności malejącej o pewien procent maksymalnej sprawności +STR_CONFIG_SETTING_SERVINT_ISPERCENT_HELPTEXT :Kiedy włączone, pojazdy podejmują próbę serwisowania, gdy ich niezawodność spadnie o dany procent maksymalnej niezawodności.{}{}Na przykład, jeśli maksymalna niezawodność pojazdu wynosi 90%, a interwał serwisowy wynosi 20%, pojazd podejmie próbę serwisowania, gdy osiągnie 72% niezawodności. STR_CONFIG_SETTING_SERVINT_TRAINS :Domyślny interwał serwisowania pociągów: {STRING} STR_CONFIG_SETTING_SERVINT_TRAINS_HELPTEXT :Ustaw domyślny okres serwisowania dla nowych pojazdów kolejowych, jeśli takowy nie istnieje dla określonego pojazdu @@ -2306,6 +2306,10 @@ STR_CONFIG_SETTING_LARGER_TOWNS_DISABLED :Żadne STR_CONFIG_SETTING_CITY_SIZE_MULTIPLIER :Początkowy mnożnik rozmiarów metropolii: {STRING} STR_CONFIG_SETTING_CITY_SIZE_MULTIPLIER_HELPTEXT :Średni rozmiar metropolii w porównaniu do normalnych miast na początku gry +STR_CONFIG_SETTING_LINKGRAPH_RECALC_INTERVAL :Aktualizuj graf dystrybucji co {STRING}{NBSP}sekund{P 0:2 ę y ""} +STR_CONFIG_SETTING_LINKGRAPH_RECALC_INTERVAL_HELPTEXT :Czas pomiędzy kolejnymi przeliczeniami grafu połączeń. Każde przeliczenie oblicza plany dla jednego komponentu grafu. Wartość X dla tego ustawienia nie oznacza, że cały graf będzie aktualizowany co X sekund. Aktualizowane będą tylko niektóre komponenty. Im mniejszą wartość ustawisz, tym więcej czasu będzie potrzebował procesor, aby wykonać obliczenia. Im większą wartość ustawisz, tym więcej czasu upłynie, zanim rozpocznie się dystrybucja ładunków po nowych trasach. +STR_CONFIG_SETTING_LINKGRAPH_RECALC_TIME :Przeznacz {STRING}{NBSP}sekund{P 0:2 ę y ""} na przeliczenie grafu dystrybucji +STR_CONFIG_SETTING_LINKGRAPH_RECALC_TIME_HELPTEXT :Czas potrzebny na każde przeliczenie komponentu grafu połączeń. Po rozpoczęciu przeliczania, tworzony jest wątek, który może działać przez podaną liczbę sekund. Im mniejszą wartość ustawisz, tym większe prawdopodobieństwo, że wątek nie zostanie ukończony w wyznaczonym czasie. Wtedy gra zatrzymuje się do czasu jego zakończenia („lag”). Im większą wartość ustawisz, tym dłużej będzie trwała aktualizacja dystrybucji, gdy zmienią się trasy. STR_CONFIG_SETTING_DISTRIBUTION_PAX :Tryb dystrybucji dla pasażerów: {STRING} STR_CONFIG_SETTING_DISTRIBUTION_PAX_HELPTEXT :Tryb „symetryczny” oznacza, że mniej więcej tyle samo pasażerów będzie podróżować ze stacji A do stacji B, co z B do A. Tryb „asymetryczny” oznacza, że w obu kierunkach może podróżować różna liczba pasażerów. Tryb „ręczny” oznacza, że dla pasażerów nie będzie przeprowadzana dystrybucja automatyczna. @@ -4974,6 +4978,7 @@ STR_AI_CONFIG_RANDOM_AI :Losowe SI STR_AI_CONFIG_NONE :(brak) STR_AI_CONFIG_NAME_VERSION :{STRING} {YELLOW}v{NUM} STR_AI_CONFIG_MAX_COMPETITORS :{LTBLUE}Maksymalna liczba przeciwników: {ORANGE}{COMMA} +STR_AI_CONFIG_COMPETITORS_INTERVAL :{LTBLUE}Odstęp czasowy pomiędzy uruchamianiem rywali: {ORANGE}{COMMA} minut{P a y ""} STR_AI_CONFIG_MOVE_UP :{BLACK}Przesuń w górę STR_AI_CONFIG_MOVE_UP_TOOLTIP :{BLACK}Przesuń wybraną SI w górę listy @@ -5491,6 +5496,7 @@ STR_ERROR_NO_BUOY :{WHITE}Brak boi STR_ERROR_CAN_T_TIMETABLE_VEHICLE :{WHITE}Nie można wyznaczyć rozkładu jazdy pojazdu... STR_ERROR_TIMETABLE_ONLY_WAIT_AT_STATIONS :{WHITE}Pojazdy mogą czekać tylko na stacjach STR_ERROR_TIMETABLE_NOT_STOPPING_HERE :{WHITE}Ten pojazd nie zatrzymuje się na tej stacji. +STR_ERROR_TIMETABLE_INCOMPLETE :{WHITE}... rozkład jazdy jest niekompletny # Sign related errors STR_ERROR_TOO_MANY_SIGNS :{WHITE}... zbyt wiele napisów diff --git a/src/lang/vietnamese.txt b/src/lang/vietnamese.txt index b5bb6898dd..c1dbc0354e 100644 --- a/src/lang/vietnamese.txt +++ b/src/lang/vietnamese.txt @@ -5110,6 +5110,7 @@ STR_ERROR_NO_BUOY :{WHITE}Không c STR_ERROR_CAN_T_TIMETABLE_VEHICLE :{WHITE}Không thể lập lịch trình cho phương tiện... STR_ERROR_TIMETABLE_ONLY_WAIT_AT_STATIONS :{WHITE}Phương tiện chỉ có thể chờ ở nhà ga, bến, cảng. STR_ERROR_TIMETABLE_NOT_STOPPING_HERE :{WHITE}Phương tiện này không dừng lại tại ga, bến này theo lộ trình. +STR_ERROR_TIMETABLE_INCOMPLETE :{WHITE}... lịch trình chưa hoàn thiện # Sign related errors STR_ERROR_TOO_MANY_SIGNS :{WHITE}... quá nhiều biển hiệu From 1697dff74402a54e4e0de22595a300e8457ea2b0 Mon Sep 17 00:00:00 2001 From: PeterN Date: Tue, 25 Apr 2023 20:34:10 +0100 Subject: [PATCH 27/27] Change: Hide all variants from UI when (display) parent is hidden. (#10708) --- src/autoreplace_gui.cpp | 2 +- src/build_vehicle_gui.cpp | 8 ++++---- src/engine.cpp | 24 ++++++++++++++++++++++++ src/engine_base.h | 12 ++++++++++++ 4 files changed, 41 insertions(+), 5 deletions(-) diff --git a/src/autoreplace_gui.cpp b/src/autoreplace_gui.cpp index be339cc4a7..c7c8603dc1 100644 --- a/src/autoreplace_gui.cpp +++ b/src/autoreplace_gui.cpp @@ -148,7 +148,7 @@ class ReplaceVehicleWindow : public Window { GUIEngineList list; for (const Engine *e : Engine::IterateType(type)) { - if (!draw_left && !this->show_hidden_engines && e->IsHidden(_local_company)) continue; + if (!draw_left && !this->show_hidden_engines && e->IsVariantHidden(_local_company)) continue; EngineID eid = e->index; switch (type) { case VEH_TRAIN: diff --git a/src/build_vehicle_gui.cpp b/src/build_vehicle_gui.cpp index d63a3558d0..8202891d32 100644 --- a/src/build_vehicle_gui.cpp +++ b/src/build_vehicle_gui.cpp @@ -1349,7 +1349,7 @@ struct BuildVehicleWindow : Window { * and if not, reset selection to INVALID_ENGINE. This could be the case * when engines become obsolete and are removed */ for (const Engine *e : Engine::IterateType(VEH_TRAIN)) { - if (!this->show_hidden_engines && e->IsHidden(_local_company)) continue; + if (!this->show_hidden_engines && e->IsVariantHidden(_local_company)) continue; EngineID eid = e->index; const RailVehicleInfo *rvi = &e->u.rail; @@ -1400,7 +1400,7 @@ struct BuildVehicleWindow : Window { this->eng_list.clear(); for (const Engine *e : Engine::IterateType(VEH_ROAD)) { - if (!this->show_hidden_engines && e->IsHidden(_local_company)) continue; + if (!this->show_hidden_engines && e->IsVariantHidden(_local_company)) continue; EngineID eid = e->index; if (!IsEngineBuildable(eid, VEH_ROAD, _local_company)) continue; if (this->filter.roadtype != INVALID_ROADTYPE && !HasPowerOnRoad(e->u.road.roadtype, this->filter.roadtype)) continue; @@ -1419,7 +1419,7 @@ struct BuildVehicleWindow : Window { this->eng_list.clear(); for (const Engine *e : Engine::IterateType(VEH_SHIP)) { - if (!this->show_hidden_engines && e->IsHidden(_local_company)) continue; + if (!this->show_hidden_engines && e->IsVariantHidden(_local_company)) continue; EngineID eid = e->index; if (!IsEngineBuildable(eid, VEH_SHIP, _local_company)) continue; this->eng_list.emplace_back(eid, e->info.variant_id, e->display_flags, 0); @@ -1443,7 +1443,7 @@ struct BuildVehicleWindow : Window { * and if not, reset selection to INVALID_ENGINE. This could be the case * when planes become obsolete and are removed */ for (const Engine *e : Engine::IterateType(VEH_AIRCRAFT)) { - if (!this->show_hidden_engines && e->IsHidden(_local_company)) continue; + if (!this->show_hidden_engines && e->IsVariantHidden(_local_company)) continue; EngineID eid = e->index; if (!IsEngineBuildable(eid, VEH_AIRCRAFT, _local_company)) continue; /* First VEH_END window_numbers are fake to allow a window open for all different types at once */ diff --git a/src/engine.cpp b/src/engine.cpp index 393854546d..3f028bd784 100644 --- a/src/engine.cpp +++ b/src/engine.cpp @@ -475,6 +475,30 @@ StringID Engine::GetAircraftTypeText() const } } +/** + * Check whether the engine variant chain is hidden in the GUI for the given company. + * @param c Company to check. + * @return \c true iff the engine variant chain is hidden in the GUI for the given company. + */ +bool Engine::IsVariantHidden(CompanyID c) const +{ + /* In case company is spectator. */ + if (c >= MAX_COMPANIES) return false; + + /* Shortcut if this engine is explicitly hidden. */ + if (this->IsHidden(c)) return true; + + /* Check for hidden parent variants. This is a bit convoluted as we must check hidden status of + * the last display variant rather than the actual parent variant. */ + const Engine *re = this; + const Engine *ve = re->GetDisplayVariant(); + while (!(ve->IsHidden(c)) && re->info.variant_id != INVALID_ENGINE && re->info.variant_id != re->index) { + re = Engine::Get(re->info.variant_id); + ve = re->GetDisplayVariant(); + } + return ve->IsHidden(c); +} + /** * Initializes the #EngineOverrideManager with the default engines. */ diff --git a/src/engine_base.h b/src/engine_base.h index 14af402021..c6c62091b7 100644 --- a/src/engine_base.h +++ b/src/engine_base.h @@ -137,6 +137,18 @@ struct Engine : EnginePool::PoolItem<&_engine_pool> { return c < MAX_COMPANIES && HasBit(this->company_hidden, c); } + /** + * Get the last display variant for an engine. + * @return Engine's last display variant or engine itself if no last display variant is set. + */ + const Engine *GetDisplayVariant() const + { + if (this->display_last_variant == this->index || this->display_last_variant == INVALID_ENGINE) return this; + return Engine::Get(this->display_last_variant); + } + + bool IsVariantHidden(CompanyID c) const; + /** * Check if the engine is a ground vehicle. * @return True iff the engine is a train or a road vehicle.