From 4635d0968f2cf35f0fa5a7ddadbcf86a0edf7a7b Mon Sep 17 00:00:00 2001 From: frosch Date: Sun, 16 Mar 2025 14:10:55 +0100 Subject: [PATCH] Codechange: Replace C-style casts with static_cast/reinterpret_cast/constructors. Generated using: clang-tidy-19 -p build --checks -*,google-readability-casting --fix --fix-errors src/*.cpp src/*/*.cpp src/*/*/*.cpp git restore src/3rdparty --- src/ai/ai_core.cpp | 8 +- src/ai/ai_gui.cpp | 18 +-- src/ai/ai_info.cpp | 4 +- src/aircraft_cmd.cpp | 4 +- src/airport.cpp | 2 +- src/airport_gui.cpp | 8 +- src/autoreplace.cpp | 8 +- src/autoreplace_cmd.cpp | 6 +- src/autoreplace_gui.cpp | 4 +- src/blitter/32bpp_anim.cpp | 58 ++++----- src/blitter/32bpp_anim_sse2.cpp | 4 +- src/blitter/32bpp_anim_sse4.cpp | 88 ++++++------- src/blitter/32bpp_base.cpp | 26 ++-- src/blitter/32bpp_optimized.cpp | 36 +++--- src/blitter/32bpp_simple.cpp | 10 +- src/blitter/32bpp_sse2.cpp | 8 +- src/blitter/40bpp_anim.cpp | 62 +++++----- src/blitter/8bpp_base.cpp | 28 ++--- src/blitter/8bpp_optimized.cpp | 6 +- src/blitter/8bpp_simple.cpp | 4 +- src/bridge_gui.cpp | 10 +- src/build_vehicle_gui.cpp | 8 +- src/cheat_gui.cpp | 10 +- src/clear_cmd.cpp | 2 +- src/company_cmd.cpp | 24 ++-- src/company_gui.cpp | 18 +-- src/console_cmds.cpp | 40 +++--- src/console_gui.cpp | 2 +- src/depot_gui.cpp | 10 +- src/disaster_vehicle.cpp | 24 ++-- src/dock_gui.cpp | 2 +- src/dropdown.cpp | 4 +- src/economy.cpp | 10 +- src/elrail.cpp | 8 +- src/engine.cpp | 6 +- src/fontcache/freetypefontcache.cpp | 14 +-- src/framerate_gui.cpp | 34 ++--- src/game/game_gui.cpp | 8 +- src/game/game_info.cpp | 2 +- src/game/game_text.cpp | 4 +- src/gamelog.cpp | 4 +- src/genworld_gui.cpp | 10 +- src/gfx.cpp | 24 ++-- src/gfx_layout.cpp | 4 +- src/gfx_layout_fallback.cpp | 2 +- src/gfx_layout_icu.cpp | 4 +- src/goal.cpp | 6 +- src/goal_gui.cpp | 4 +- src/graph_gui.cpp | 14 +-- src/ground_vehicle.cpp | 4 +- src/group_cmd.cpp | 2 +- src/group_gui.cpp | 6 +- src/heightmap.cpp | 14 +-- src/hotkeys.cpp | 2 +- src/industry_cmd.cpp | 12 +- src/industry_gui.cpp | 12 +- src/intro_gui.cpp | 6 +- src/landscape.cpp | 28 ++--- src/league_gui.cpp | 2 +- src/linkgraph/linkgraph_gui.cpp | 14 +-- src/linkgraph/refresh.cpp | 2 +- src/main_gui.cpp | 8 +- src/map.cpp | 4 +- src/misc_cmd.cpp | 8 +- src/misc_gui.cpp | 2 +- src/mixer.cpp | 14 +-- src/music/dmusic.cpp | 8 +- src/music/midifile.cpp | 18 +-- src/music/win32_m.cpp | 2 +- src/music_gui.cpp | 16 +-- src/network/core/address.cpp | 36 +++--- src/network/core/network_game_info.cpp | 8 +- src/network/core/os_abstraction.cpp | 4 +- src/network/core/packet.cpp | 30 ++--- src/network/core/tcp_admin.cpp | 10 +- src/network/core/tcp_connect.cpp | 6 +- src/network/core/tcp_content.cpp | 2 +- src/network/core/tcp_coordinator.cpp | 2 +- src/network/core/tcp_game.cpp | 2 +- src/network/core/tcp_turn.cpp | 2 +- src/network/core/udp.cpp | 8 +- src/network/network.cpp | 6 +- src/network/network_admin.cpp | 12 +- src/network/network_chat_gui.cpp | 6 +- src/network/network_client.cpp | 30 ++--- src/network/network_command.cpp | 10 +- src/network/network_content.cpp | 34 ++--- src/network/network_content_gui.cpp | 8 +- src/network/network_coordinator.cpp | 4 +- src/network/network_gui.cpp | 14 +-- src/network/network_query.cpp | 2 +- src/network/network_server.cpp | 30 ++--- src/newgrf.cpp | 62 +++++----- src/newgrf_airport.cpp | 2 +- src/newgrf_airporttiles.cpp | 2 +- src/newgrf_commons.cpp | 4 +- src/newgrf_debug_gui.cpp | 18 +-- src/newgrf_engine.cpp | 8 +- src/newgrf_generic.cpp | 2 +- src/newgrf_gui.cpp | 8 +- src/newgrf_house.cpp | 8 +- src/newgrf_industries.cpp | 4 +- src/newgrf_industrytiles.cpp | 4 +- src/newgrf_profiling.cpp | 6 +- src/newgrf_roadstop.cpp | 2 +- src/newgrf_sound.cpp | 2 +- src/newgrf_spritegroup.cpp | 2 +- src/newgrf_station.cpp | 14 +-- src/newgrf_text.cpp | 10 +- src/object_cmd.cpp | 2 +- src/order_cmd.cpp | 42 +++---- src/order_gui.cpp | 24 ++-- src/os/macosx/string_osx.cpp | 4 +- src/os/unix/font_unix.cpp | 12 +- src/os/windows/font_win32.cpp | 6 +- src/os/windows/string_uniscribe.cpp | 6 +- src/os/windows/win32.cpp | 6 +- src/palette.cpp | 8 +- src/pathfinder/yapf/yapf_road.cpp | 6 +- src/pathfinder/yapf/yapf_ship.cpp | 6 +- src/pbs.cpp | 4 +- src/rail_cmd.cpp | 38 +++--- src/rail_gui.cpp | 8 +- src/road_cmd.cpp | 12 +- src/road_gui.cpp | 12 +- src/roadstop.cpp | 2 +- src/roadveh_cmd.cpp | 38 +++--- src/saveload/afterload.cpp | 46 +++---- src/saveload/ai_sl.cpp | 2 +- src/saveload/company_sl.cpp | 2 +- src/saveload/game_sl.cpp | 2 +- src/saveload/gamelog_sl.cpp | 6 +- src/saveload/industry_sl.cpp | 2 +- src/saveload/linkgraph_sl.cpp | 2 +- src/saveload/newgrf_sl.cpp | 2 +- src/saveload/oldloader.cpp | 32 ++--- src/saveload/oldloader_sl.cpp | 8 +- src/saveload/order_sl.cpp | 2 +- src/saveload/randomizer_sl.cpp | 2 +- src/saveload/saveload.cpp | 150 +++++++++++------------ src/saveload/settings_sl.cpp | 2 +- src/saveload/vehicle_sl.cpp | 2 +- src/saveload/waypoint_sl.cpp | 2 +- src/screenshot.cpp | 8 +- src/screenshot_bmp.cpp | 2 +- src/screenshot_png.cpp | 2 +- src/script/api/script_airport.cpp | 8 +- src/script/api/script_basestation.cpp | 2 +- src/script/api/script_bridge.cpp | 8 +- src/script/api/script_cargo.cpp | 8 +- src/script/api/script_client.cpp | 4 +- src/script/api/script_company.cpp | 18 +-- src/script/api/script_date.cpp | 2 +- src/script/api/script_engine.cpp | 18 +-- src/script/api/script_enginelist.cpp | 2 +- src/script/api/script_error.cpp | 2 +- src/script/api/script_event.cpp | 8 +- src/script/api/script_event_types.cpp | 2 +- src/script/api/script_game.cpp | 2 +- src/script/api/script_goal.cpp | 6 +- src/script/api/script_group.cpp | 14 +-- src/script/api/script_industry.cpp | 10 +- src/script/api/script_industrytype.cpp | 2 +- src/script/api/script_infrastructure.cpp | 12 +- src/script/api/script_league.cpp | 4 +- src/script/api/script_news.cpp | 2 +- src/script/api/script_object.cpp | 4 +- src/script/api/script_order.cpp | 40 +++--- src/script/api/script_priorityqueue.cpp | 2 +- src/script/api/script_rail.cpp | 78 ++++++------ src/script/api/script_road.cpp | 36 +++--- src/script/api/script_station.cpp | 4 +- src/script/api/script_story_page.cpp | 26 ++-- src/script/api/script_subsidy.cpp | 2 +- src/script/api/script_text.cpp | 4 +- src/script/api/script_tile.cpp | 26 ++-- src/script/api/script_tilelist.cpp | 4 +- src/script/api/script_town.cpp | 10 +- src/script/api/script_vehicle.cpp | 2 +- src/script/api/script_vehiclelist.cpp | 2 +- src/script/api/script_window.cpp | 14 +-- src/script/script_gui.cpp | 14 +-- src/script/script_info.cpp | 4 +- src/script/script_instance.cpp | 6 +- src/script/squirrel.cpp | 24 ++-- src/script/squirrel_std.cpp | 2 +- src/settingentry_gui.cpp | 2 +- src/settings.cpp | 38 +++--- src/settings_gui.cpp | 24 ++-- src/settings_table.cpp | 2 +- src/ship_cmd.cpp | 4 +- src/signal.cpp | 4 +- src/signs_gui.cpp | 2 +- src/smallmap_gui.cpp | 30 ++--- src/sound.cpp | 2 +- src/spritecache.cpp | 8 +- src/station_cmd.cpp | 34 ++--- src/station_gui.cpp | 10 +- src/story.cpp | 10 +- src/story_gui.cpp | 12 +- src/strgen/strgen.cpp | 10 +- src/strgen/strgen_base.cpp | 20 +-- src/string.cpp | 10 +- src/strings.cpp | 40 +++--- src/terraform_cmd.cpp | 4 +- src/textbuf.cpp | 12 +- src/textfile_gui.cpp | 2 +- src/tgp.cpp | 46 +++---- src/timetable_cmd.cpp | 6 +- src/timetable_gui.cpp | 10 +- src/toolbar_gui.cpp | 44 +++---- src/town_cmd.cpp | 22 ++-- src/town_gui.cpp | 8 +- src/townname.cpp | 4 +- src/train_cmd.cpp | 18 +-- src/train_gui.cpp | 8 +- src/transparency_gui.cpp | 10 +- src/tree_cmd.cpp | 6 +- src/tree_gui.cpp | 6 +- src/tunnelbridge_cmd.cpp | 24 ++-- src/vehicle.cpp | 26 ++-- src/vehicle_cmd.cpp | 2 +- src/vehicle_gui.cpp | 10 +- src/video/opengl.cpp | 36 +++--- src/viewport.cpp | 52 ++++---- src/viewport_sprite_sorter_sse4.cpp | 8 +- src/water_cmd.cpp | 2 +- src/waypoint_cmd.cpp | 4 +- src/widget.cpp | 20 +-- src/window.cpp | 36 +++--- 230 files changed, 1475 insertions(+), 1475 deletions(-) diff --git a/src/ai/ai_core.cpp b/src/ai/ai_core.cpp index 122c4fb83c..c02bdfeb4d 100644 --- a/src/ai/ai_core.cpp +++ b/src/ai/ai_core.cpp @@ -84,16 +84,16 @@ Backup cur_company(_current_company); for (const Company *c : Company::Iterate()) { if (c->is_ai) { - PerformanceMeasurer framerate((PerformanceElement)(PFE_AI0 + c->index)); + PerformanceMeasurer framerate(static_cast(PFE_AI0 + c->index)); cur_company.Change(c->index); c->ai_instance->GameLoop(); /* Occasionally collect garbage; every 255 ticks do one company. * Effectively collecting garbage once every two months per AI. */ - if ((AI::frame_counter & 255) == 0 && (CompanyID)GB(AI::frame_counter, 8, 4) == c->index) { + if ((AI::frame_counter & 255) == 0 && CompanyID(GB(AI::frame_counter, 8, 4)) == c->index) { c->ai_instance->CollectGarbage(); } } else { - PerformanceMeasurer::SetInactive((PerformanceElement)(PFE_AI0 + c->index)); + PerformanceMeasurer::SetInactive(static_cast(PFE_AI0 + c->index)); } } cur_company.Restore(); @@ -107,7 +107,7 @@ /* static */ void AI::Stop(CompanyID company) { if (_networking && !_network_server) return; - PerformanceMeasurer::SetInactive((PerformanceElement)(PFE_AI0 + company)); + PerformanceMeasurer::SetInactive(static_cast(PFE_AI0 + company)); Backup cur_company(_current_company, company); Company *c = Company::Get(company); diff --git a/src/ai/ai_gui.cpp b/src/ai/ai_gui.cpp index 8c0e13babc..ff32de4b51 100644 --- a/src/ai/ai_gui.cpp +++ b/src/ai/ai_gui.cpp @@ -217,7 +217,7 @@ struct AIConfigWindow : public Window { if (widget >= WID_AIC_TEXTFILE && widget < WID_AIC_TEXTFILE + TFT_CONTENT_END) { if (this->selected_slot == CompanyID::Invalid() || AIConfig::GetConfig(this->selected_slot) == nullptr) return; - ShowScriptTextfileWindow((TextfileType)(widget - WID_AIC_TEXTFILE), this->selected_slot); + ShowScriptTextfileWindow(static_cast(widget - WID_AIC_TEXTFILE), this->selected_slot); return; } @@ -249,14 +249,14 @@ struct AIConfigWindow : public Window { } case WID_AIC_LIST: { // Select a slot - this->selected_slot = (CompanyID)this->vscroll->GetScrolledRowFromWidget(pt.y, this, widget); + this->selected_slot = CompanyID(this->vscroll->GetScrolledRowFromWidget(pt.y, this, widget)); this->InvalidateData(); - if (click_count > 1 && IsEditable(this->selected_slot)) ShowScriptListWindow((CompanyID)this->selected_slot, _ctrl_pressed); + if (click_count > 1 && IsEditable(this->selected_slot)) ShowScriptListWindow(CompanyID(this->selected_slot), _ctrl_pressed); break; } case WID_AIC_MOVE_UP: - if (IsEditable(this->selected_slot) && IsEditable((CompanyID)(this->selected_slot - 1))) { + if (IsEditable(this->selected_slot) && IsEditable(CompanyID(this->selected_slot - 1))) { Swap(GetGameSettings().ai_config[this->selected_slot], GetGameSettings().ai_config[this->selected_slot - 1]); this->selected_slot = CompanyID(this->selected_slot - 1); this->vscroll->ScrollTowards(this->selected_slot.base()); @@ -265,7 +265,7 @@ struct AIConfigWindow : public Window { break; case WID_AIC_MOVE_DOWN: - if (IsEditable(this->selected_slot) && IsEditable((CompanyID)(this->selected_slot + 1))) { + if (IsEditable(this->selected_slot) && IsEditable(CompanyID(this->selected_slot + 1))) { Swap(GetGameSettings().ai_config[this->selected_slot], GetGameSettings().ai_config[this->selected_slot + 1]); ++this->selected_slot; this->vscroll->ScrollTowards(this->selected_slot.base()); @@ -281,11 +281,11 @@ struct AIConfigWindow : public Window { } case WID_AIC_CHANGE: // choose other AI - if (IsEditable(this->selected_slot)) ShowScriptListWindow((CompanyID)this->selected_slot, _ctrl_pressed); + if (IsEditable(this->selected_slot)) ShowScriptListWindow(CompanyID(this->selected_slot), _ctrl_pressed); break; case WID_AIC_CONFIGURE: // change the settings for an AI - ShowScriptSettingsWindow((CompanyID)this->selected_slot); + ShowScriptSettingsWindow(CompanyID(this->selected_slot)); break; case WID_AIC_CONTENT_DOWNLOAD: @@ -319,8 +319,8 @@ struct AIConfigWindow : public Window { this->SetWidgetDisabledState(WID_AIC_INCREASE_INTERVAL, GetGameSettings().difficulty.competitors_interval == MAX_COMPETITORS_INTERVAL); this->SetWidgetDisabledState(WID_AIC_CHANGE, !IsEditable(this->selected_slot)); this->SetWidgetDisabledState(WID_AIC_CONFIGURE, this->selected_slot == CompanyID::Invalid() || config->GetConfigList()->empty()); - this->SetWidgetDisabledState(WID_AIC_MOVE_UP, !IsEditable(this->selected_slot) || !IsEditable((CompanyID)(this->selected_slot - 1))); - this->SetWidgetDisabledState(WID_AIC_MOVE_DOWN, !IsEditable(this->selected_slot) || !IsEditable((CompanyID)(this->selected_slot + 1))); + this->SetWidgetDisabledState(WID_AIC_MOVE_UP, !IsEditable(this->selected_slot) || !IsEditable(CompanyID(this->selected_slot - 1))); + this->SetWidgetDisabledState(WID_AIC_MOVE_DOWN, !IsEditable(this->selected_slot) || !IsEditable(CompanyID(this->selected_slot + 1))); this->SetWidgetDisabledState(WID_AIC_OPEN_URL, this->selected_slot == CompanyID::Invalid() || config->GetInfo() == nullptr || config->GetInfo()->GetURL().empty()); for (TextfileType tft = TFT_CONTENT_BEGIN; tft < TFT_CONTENT_END; tft++) { diff --git a/src/ai/ai_info.cpp b/src/ai/ai_info.cpp index 79d5ca96dd..7c52e62de4 100644 --- a/src/ai/ai_info.cpp +++ b/src/ai/ai_info.cpp @@ -59,7 +59,7 @@ template <> SQInteger PushClassName(HSQUIRRELVM vm) { sq /* Get the AIInfo */ SQUserPointer instance = nullptr; if (SQ_FAILED(sq_getinstanceup(vm, 2, &instance, nullptr)) || instance == nullptr) return sq_throwerror(vm, "Pass an instance of a child class of AIInfo to RegisterAI"); - AIInfo *info = (AIInfo *)instance; + AIInfo *info = static_cast(instance); SQInteger res = ScriptInfo::Constructor(vm, info); if (res != 0) return res; @@ -98,7 +98,7 @@ template <> SQInteger PushClassName(HSQUIRRELVM vm) { sq /* Get the AIInfo */ SQUserPointer instance; sq_getinstanceup(vm, 2, &instance, nullptr); - AIInfo *info = (AIInfo *)instance; + AIInfo *info = static_cast(instance); info->api_version = *std::rbegin(AIInfo::ApiVersions); SQInteger res = ScriptInfo::Constructor(vm, info); diff --git a/src/aircraft_cmd.cpp b/src/aircraft_cmd.cpp index bbde5c95c6..81524f0d47 100644 --- a/src/aircraft_cmd.cpp +++ b/src/aircraft_cmd.cpp @@ -670,7 +670,7 @@ static int UpdateAircraftSpeed(Aircraft *v, uint speed_limit = SPEED_LIMIT_NONE, speed_limit = v->vcache.cached_max_speed; } - v->subspeed = (t = v->subspeed) + (uint8_t)spd; + v->subspeed = (t = v->subspeed) + static_cast(spd); /* Aircraft's current speed is used twice so that very fast planes are * forced to slow down rapidly in the short distance needed. The magic @@ -697,7 +697,7 @@ static int UpdateAircraftSpeed(Aircraft *v, uint speed_limit = SPEED_LIMIT_NONE, spd = v->GetOldAdvanceSpeed(spd); spd += v->progress; - v->progress = (uint8_t)spd; + v->progress = static_cast(spd); return spd >> 8; } diff --git a/src/airport.cpp b/src/airport.cpp index d835d15c49..45a44b0b50 100644 --- a/src/airport.cpp +++ b/src/airport.cpp @@ -81,7 +81,7 @@ AirportMovingData RotateAirportMovingData(const AirportMovingData *orig, Directi { AirportMovingData amd; amd.flags = orig->flags; - amd.direction = ChangeDir(orig->direction, (DirDiff)rotation); + amd.direction = ChangeDir(orig->direction, static_cast(rotation)); switch (rotation) { case DIR_N: amd.x = orig->x; diff --git a/src/airport_gui.cpp b/src/airport_gui.cpp index a0e750e9d1..98a36b7e15 100644 --- a/src/airport_gui.cpp +++ b/src/airport_gui.cpp @@ -264,7 +264,7 @@ public: this->OnInvalidateData(); /* Ensure airport class is valid (changing NewGRFs). */ - _selected_airport_class = Clamp(_selected_airport_class, APC_BEGIN, (AirportClassID)(AirportClass::GetClassCount() - 1)); + _selected_airport_class = Clamp(_selected_airport_class, APC_BEGIN, static_cast(AirportClass::GetClassCount() - 1)); const AirportClass *ac = AirportClass::Get(_selected_airport_class); this->vscroll->SetCount(ac->GetSpecCount()); @@ -425,7 +425,7 @@ public: if (_selected_airport_index != -1) { const AirportSpec *as = AirportClass::Get(_selected_airport_class)->GetSpec(_selected_airport_index); - int rad = _settings_game.station.modified_catchment ? as->catchment : (uint)CA_UNMODIFIED; + int rad = _settings_game.station.modified_catchment ? as->catchment : CA_UNMODIFIED; /* only show the station (airport) noise, if the noise option is activated */ if (_settings_game.economy.station_noise_level) { @@ -482,7 +482,7 @@ public: this->SetWidgetDisabledState(WID_AP_LAYOUT_DECREASE, _selected_airport_layout == 0); this->SetWidgetDisabledState(WID_AP_LAYOUT_INCREASE, _selected_airport_layout + 1U >= as->layouts.size()); - int rad = _settings_game.station.modified_catchment ? as->catchment : (uint)CA_UNMODIFIED; + int rad = _settings_game.station.modified_catchment ? as->catchment : CA_UNMODIFIED; if (_settings_client.gui.station_show_coverage) SetTileSelectBigSize(-rad, -rad, 2 * rad, 2 * rad); } } @@ -562,7 +562,7 @@ public: void OnDropdownSelect(WidgetID widget, int index) override { if (widget == WID_AP_CLASS_DROPDOWN) { - _selected_airport_class = (AirportClassID)index; + _selected_airport_class = static_cast(index); this->vscroll->SetCount(AirportClass::Get(_selected_airport_class)->GetSpecCount()); this->SelectFirstAvailableAirport(false); } diff --git a/src/autoreplace.cpp b/src/autoreplace.cpp index 865266ecd4..b50cc89b96 100644 --- a/src/autoreplace.cpp +++ b/src/autoreplace.cpp @@ -26,7 +26,7 @@ INSTANTIATE_POOL_METHODS(EngineRenew) */ static EngineRenew *GetEngineReplacement(EngineRenewList erl, EngineID engine, GroupID group) { - EngineRenew *er = (EngineRenew *)erl; + EngineRenew *er = static_cast(erl); while (er != nullptr) { if (er->from == engine && GroupIsInGroup(group, er->group_id)) return er; @@ -42,7 +42,7 @@ static EngineRenew *GetEngineReplacement(EngineRenewList erl, EngineID engine, G */ void RemoveAllEngineReplacement(EngineRenewList *erl) { - EngineRenew *er = (EngineRenew *)(*erl); + EngineRenew *er = static_cast(*erl); EngineRenew *next; while (er != nullptr) { @@ -126,7 +126,7 @@ CommandCost AddEngineReplacement(EngineRenewList *erl, EngineID old_engine, Engi */ CommandCost RemoveEngineReplacement(EngineRenewList *erl, EngineID engine, GroupID group, DoCommandFlags flags) { - EngineRenew *er = (EngineRenew *)(*erl); + EngineRenew *er = static_cast(*erl); EngineRenew *prev = nullptr; while (er != nullptr) { @@ -134,7 +134,7 @@ CommandCost RemoveEngineReplacement(EngineRenewList *erl, EngineID engine, Group if (flags.Test(DoCommandFlag::Execute)) { if (prev == nullptr) { // First element /* The second becomes the new first element */ - *erl = (EngineRenewList)er->next; + *erl = static_cast(er->next); } else { /* Cut this element out */ prev->next = er->next; diff --git a/src/autoreplace_cmd.cpp b/src/autoreplace_cmd.cpp index b51ce3519e..abb15fe487 100644 --- a/src/autoreplace_cmd.cpp +++ b/src/autoreplace_cmd.cpp @@ -457,7 +457,7 @@ static CommandCost ReplaceFreeUnit(Vehicle **single_unit, DoCommandFlags flags, Train *old_v = Train::From(*single_unit); assert(!old_v->IsArticulatedPart() && !old_v->IsRearDualheaded()); - CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES, (Money)0); + CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES, Money(0)); /* Build and refit replacement vehicle */ Vehicle *new_v = nullptr; @@ -524,7 +524,7 @@ static CommandCost ReplaceChain(Vehicle **chain, DoCommandFlags flags, bool wago Vehicle *old_head = *chain; assert(old_head->IsPrimaryVehicle()); - CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES, (Money)0); + CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES, Money(0)); if (old_head->type == VEH_TRAIN) { /* Store the length of the old vehicle chain, rounded up to whole tiles */ @@ -771,7 +771,7 @@ CommandCost CmdAutoreplaceVehicle(DoCommandFlags flags, VehicleID veh_id) w = (!free_wagon && w->type == VEH_TRAIN ? Train::From(w)->GetNextUnit() : nullptr); } - CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES, (Money)0); + CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES, Money(0)); bool nothing_to_do = true; if (any_replacements) { diff --git a/src/autoreplace_gui.cpp b/src/autoreplace_gui.cpp index 214d222eec..0570859e94 100644 --- a/src/autoreplace_gui.cpp +++ b/src/autoreplace_gui.cpp @@ -634,7 +634,7 @@ public: break; case WID_RV_RAIL_TYPE_DROPDOWN: { - RailType temp = (RailType)index; + RailType temp = static_cast(index); if (temp == this->sel_railtype) return; // we didn't select a new one. No need to change anything this->sel_railtype = temp; this->OnRailRoadTypeChange(); @@ -642,7 +642,7 @@ public: } case WID_RV_ROAD_TYPE_DROPDOWN: { - RoadType temp = (RoadType)index; + RoadType temp = static_cast(index); if (temp == this->sel_roadtype) return; // we didn't select a new one. No need to change anything this->sel_roadtype = temp; this->OnRailRoadTypeChange(); diff --git a/src/blitter/32bpp_anim.cpp b/src/blitter/32bpp_anim.cpp index 6635d34d0f..25874b98b5 100644 --- a/src/blitter/32bpp_anim.cpp +++ b/src/blitter/32bpp_anim.cpp @@ -23,18 +23,18 @@ static FBlitter_32bppAnim iFBlitter_32bppAnim; template inline void Blitter_32bppAnim::Draw(const Blitter::BlitterParams *bp, ZoomLevel zoom) { - const SpriteData *src = (const SpriteData *)bp->sprite; + const SpriteData *src = static_cast(bp->sprite); - const Colour *src_px = (const Colour *)(src->data + src->offset[zoom][0]); - const uint16_t *src_n = (const uint16_t *)(src->data + src->offset[zoom][1]); + const Colour *src_px = reinterpret_cast(src->data + src->offset[zoom][0]); + const uint16_t *src_n = reinterpret_cast(src->data + src->offset[zoom][1]); for (uint i = bp->skip_top; i != 0; i--) { - src_px = (const Colour *)((const uint8_t *)src_px + *(const uint32_t *)src_px); - src_n = (const uint16_t *)((const uint8_t *)src_n + *(const uint32_t *)src_n); + src_px = reinterpret_cast(reinterpret_cast(src_px) + *reinterpret_cast(src_px)); + src_n = reinterpret_cast(reinterpret_cast(src_n) + *reinterpret_cast(src_n)); } - Colour *dst = (Colour *)bp->dst + bp->top * bp->pitch + bp->left; - uint16_t *anim = this->anim_buf + this->ScreenToAnimOffset((uint32_t *)bp->dst) + bp->top * this->anim_buf_pitch + bp->left; + Colour *dst = static_cast(bp->dst) + bp->top * bp->pitch + bp->left; + uint16_t *anim = this->anim_buf + this->ScreenToAnimOffset(static_cast(bp->dst)) + bp->top * this->anim_buf_pitch + bp->left; const uint8_t *remap = bp->remap; // store so we don't have to access it via bp every time @@ -42,10 +42,10 @@ inline void Blitter_32bppAnim::Draw(const Blitter::BlitterParams *bp, ZoomLevel Colour *dst_ln = dst + bp->pitch; uint16_t *anim_ln = anim + this->anim_buf_pitch; - const Colour *src_px_ln = (const Colour *)((const uint8_t *)src_px + *(const uint32_t *)src_px); + const Colour *src_px_ln = reinterpret_cast(reinterpret_cast(src_px) + *reinterpret_cast(src_px)); src_px++; - const uint16_t *src_n_ln = (const uint16_t *)((const uint8_t *)src_n + *(const uint32_t *)src_n); + const uint16_t *src_n_ln = reinterpret_cast(reinterpret_cast(src_n) + *reinterpret_cast(src_n)); src_n += 2; Colour *dst_end = dst + bp->skip_left; @@ -70,7 +70,7 @@ inline void Blitter_32bppAnim::Draw(const Blitter::BlitterParams *bp, ZoomLevel dst = dst_end - bp->skip_left; dst_end = dst + bp->width; - n = std::min(n - d, (uint)bp->width); + n = std::min(n - d, static_cast(bp->width)); goto draw; } dst += n; @@ -288,8 +288,8 @@ void Blitter_32bppAnim::DrawColourMappingRect(void *dst, int width, int height, return; } - Colour *udst = (Colour *)dst; - uint16_t *anim = this->anim_buf + this->ScreenToAnimOffset((uint32_t *)dst); + Colour *udst = static_cast(dst); + uint16_t *anim = this->anim_buf + this->ScreenToAnimOffset(static_cast(dst)); if (pal == PALETTE_TO_TRANSPARENT) { do { @@ -323,12 +323,12 @@ void Blitter_32bppAnim::DrawColourMappingRect(void *dst, int width, int height, void Blitter_32bppAnim::SetPixel(void *video, int x, int y, uint8_t colour) { - *((Colour *)video + x + y * _screen.pitch) = LookupColourInPalette(colour); + *(static_cast(video) + x + y * _screen.pitch) = LookupColourInPalette(colour); /* Set the colour in the anim-buffer too, if we are rendering to the screen */ if (_screen_disable_anim) return; - this->anim_buf[this->ScreenToAnimOffset((uint32_t *)video) + x + y * this->anim_buf_pitch] = colour | (DEFAULT_BRIGHTNESS << 8); + this->anim_buf[this->ScreenToAnimOffset(static_cast(video)) + x + y * this->anim_buf_pitch] = colour | (DEFAULT_BRIGHTNESS << 8); } void Blitter_32bppAnim::DrawLine(void *video, int x, int y, int x2, int y2, int screen_width, int screen_height, uint8_t colour, int width, int dash) @@ -337,13 +337,13 @@ void Blitter_32bppAnim::DrawLine(void *video, int x, int y, int x2, int y2, int if (_screen_disable_anim) { this->DrawLineGeneric(x, y, x2, y2, screen_width, screen_height, width, dash, [&](int x, int y) { - *((Colour *)video + x + y * _screen.pitch) = c; + *(static_cast(video) + x + y * _screen.pitch) = c; }); } else { - uint16_t * const offset_anim_buf = this->anim_buf + this->ScreenToAnimOffset((uint32_t *)video); + uint16_t * const offset_anim_buf = this->anim_buf + this->ScreenToAnimOffset(static_cast(video)); const uint16_t anim_colour = colour | (DEFAULT_BRIGHTNESS << 8); this->DrawLineGeneric(x, y, x2, y2, screen_width, screen_height, width, dash, [&](int x, int y) { - *((Colour *)video + x + y * _screen.pitch) = c; + *(static_cast(video) + x + y * _screen.pitch) = c; offset_anim_buf[x + y * this->anim_buf_pitch] = anim_colour; }); } @@ -358,10 +358,10 @@ void Blitter_32bppAnim::DrawRect(void *video, int width, int height, uint8_t col } Colour colour32 = LookupColourInPalette(colour); - uint16_t *anim_line = this->ScreenToAnimOffset((uint32_t *)video) + this->anim_buf; + uint16_t *anim_line = this->ScreenToAnimOffset(static_cast(video)) + this->anim_buf; do { - Colour *dst = (Colour *)video; + Colour *dst = static_cast(video); uint16_t *anim = anim_line; for (int i = width; i > 0; i--) { @@ -371,7 +371,7 @@ void Blitter_32bppAnim::DrawRect(void *video, int width, int height, uint8_t col dst++; anim++; } - video = (uint32_t *)video + _screen.pitch; + video = static_cast(video) + _screen.pitch; anim_line += this->anim_buf_pitch; } while (--height); } @@ -380,9 +380,9 @@ void Blitter_32bppAnim::CopyFromBuffer(void *video, const void *src, int width, { assert(!_screen_disable_anim); assert(video >= _screen.dst_ptr && video <= (uint32_t *)_screen.dst_ptr + _screen.width + _screen.height * _screen.pitch); - Colour *dst = (Colour *)video; - const uint32_t *usrc = (const uint32_t *)src; - uint16_t *anim_line = this->ScreenToAnimOffset((uint32_t *)video) + this->anim_buf; + Colour *dst = static_cast(video); + const uint32_t *usrc = static_cast(src); + uint16_t *anim_line = this->ScreenToAnimOffset(static_cast(video)) + this->anim_buf; for (; height > 0; height--) { /* We need to keep those for palette animation. */ @@ -394,7 +394,7 @@ void Blitter_32bppAnim::CopyFromBuffer(void *video, const void *src, int width, dst += _screen.pitch; /* Copy back the anim-buffer */ memcpy(anim_line, usrc, width * sizeof(uint16_t)); - usrc = (const uint32_t *)&((const uint16_t *)usrc)[width]; + usrc = reinterpret_cast(&(reinterpret_cast(usrc))[width]); anim_line += this->anim_buf_pitch; /* Okay, it is *very* likely that the image we stored is using @@ -420,12 +420,12 @@ void Blitter_32bppAnim::CopyToBuffer(const void *video, void *dst, int width, in { assert(!_screen_disable_anim); assert(video >= _screen.dst_ptr && video <= (uint32_t *)_screen.dst_ptr + _screen.width + _screen.height * _screen.pitch); - uint32_t *udst = (uint32_t *)dst; - const uint32_t *src = (const uint32_t *)video; + uint32_t *udst = static_cast(dst); + const uint32_t *src = static_cast(video); if (this->anim_buf == nullptr) return; - const uint16_t *anim_line = this->ScreenToAnimOffset((const uint32_t *)video) + this->anim_buf; + const uint16_t *anim_line = this->ScreenToAnimOffset(static_cast(video)) + this->anim_buf; for (; height > 0; height--) { memcpy(udst, src, width * sizeof(uint32_t)); @@ -433,7 +433,7 @@ void Blitter_32bppAnim::CopyToBuffer(const void *video, void *dst, int width, in udst += width; /* Copy the anim-buffer */ memcpy(udst, anim_line, width * sizeof(uint16_t)); - udst = (uint32_t *)&((uint16_t *)udst)[width]; + udst = reinterpret_cast(&(reinterpret_cast(udst))[width]); anim_line += this->anim_buf_pitch; } } @@ -505,7 +505,7 @@ void Blitter_32bppAnim::PaletteAnimate(const Palette &palette) assert(this->palette.first_dirty == PALETTE_ANIM_START || this->palette.first_dirty == 0); const uint16_t *anim = this->anim_buf; - Colour *dst = (Colour *)_screen.dst_ptr; + Colour *dst = static_cast(_screen.dst_ptr); /* Let's walk the anim buffer and try to find the pixels */ const int width = this->anim_buf_width; diff --git a/src/blitter/32bpp_anim_sse2.cpp b/src/blitter/32bpp_anim_sse2.cpp index 14e9856a53..879a93f0f7 100644 --- a/src/blitter/32bpp_anim_sse2.cpp +++ b/src/blitter/32bpp_anim_sse2.cpp @@ -31,7 +31,7 @@ void Blitter_32bppSSE2_Anim::PaletteAnimate(const Palette &palette) assert(this->palette.first_dirty == PALETTE_ANIM_START || this->palette.first_dirty == 0); const uint16_t *anim = this->anim_buf; - Colour *dst = (Colour *)_screen.dst_ptr; + Colour *dst = static_cast(_screen.dst_ptr); bool screen_dirty = false; @@ -47,7 +47,7 @@ void Blitter_32bppSSE2_Anim::PaletteAnimate(const Palette &palette) const uint16_t *next_anim_ln = anim + anim_pitch; int x = width; while (x > 0) { - __m128i data = _mm_load_si128((const __m128i *) anim); + __m128i data = _mm_load_si128(reinterpret_cast(anim)); /* low bytes only, shifted into high positions */ __m128i colour_data = _mm_and_si128(data, colour_mask); diff --git a/src/blitter/32bpp_anim_sse4.cpp b/src/blitter/32bpp_anim_sse4.cpp index e4a961e0c2..b4ae6ab6da 100644 --- a/src/blitter/32bpp_anim_sse4.cpp +++ b/src/blitter/32bpp_anim_sse4.cpp @@ -34,15 +34,15 @@ GNU_TARGET("sse4.1") inline void Blitter_32bppSSE4_Anim::Draw(const BlitterParams *bp, ZoomLevel zoom) { const uint8_t * const remap = bp->remap; - Colour *dst_line = (Colour *) bp->dst + bp->top * bp->pitch + bp->left; - uint16_t *anim_line = this->anim_buf + this->ScreenToAnimOffset((uint32_t *)bp->dst) + bp->top * this->anim_buf_pitch + bp->left; + Colour *dst_line = static_cast(bp->dst) + bp->top * bp->pitch + bp->left; + uint16_t *anim_line = this->anim_buf + this->ScreenToAnimOffset(static_cast(bp->dst)) + bp->top * this->anim_buf_pitch + bp->left; int effective_width = bp->width; /* Find where to start reading in the source sprite. */ - const Blitter_32bppSSE_Base::SpriteData * const sd = (const Blitter_32bppSSE_Base::SpriteData *) bp->sprite; + const Blitter_32bppSSE_Base::SpriteData * const sd = static_cast(bp->sprite); const SpriteInfo * const si = &sd->infos[zoom]; - const MapValue *src_mv_line = (const MapValue *) &sd->data[si->mv_offset] + bp->skip_top * si->sprite_width; - const Colour *src_rgba_line = (const Colour *) ((const uint8_t *) &sd->data[si->sprite_offset] + bp->skip_top * si->sprite_line_size); + const MapValue *src_mv_line = reinterpret_cast(&sd->data[si->mv_offset]) + bp->skip_top * si->sprite_width; + const Colour *src_rgba_line = reinterpret_cast(&sd->data[si->sprite_offset] + bp->skip_top * si->sprite_line_size); if (read_mode != RM_WITH_MARGIN) { src_rgba_line += bp->skip_left; @@ -69,8 +69,8 @@ inline void Blitter_32bppSSE4_Anim::Draw(const BlitterParams *bp, ZoomLevel zoom dst += src_rgba_line[0].data; if (mode != BlitterMode::Transparent) src_mv += src_rgba_line[0].data; const int width_diff = si->sprite_width - bp->width; - effective_width = bp->width - (int) src_rgba_line[0].data; - const int delta_diff = (int) src_rgba_line[1].data - width_diff; + effective_width = bp->width - static_cast(src_rgba_line[0].data); + const int delta_diff = static_cast(src_rgba_line[1].data) - width_diff; const int new_width = effective_width - delta_diff; effective_width = delta_diff > 0 ? new_width : effective_width; if (effective_width <= 0) goto next_line; @@ -79,10 +79,10 @@ inline void Blitter_32bppSSE4_Anim::Draw(const BlitterParams *bp, ZoomLevel zoom switch (mode) { default: if (!translucent) { - for (uint x = (uint) effective_width; x > 0; x--) { + for (uint x = static_cast(effective_width); x > 0; x--) { if (src->a) { if (animated) { - *anim = *(const uint16_t*) src_mv; + *anim = *reinterpret_cast(src_mv); *dst = (src_mv->m >= PALETTE_ANIM_START) ? AdjustBrightneSSE(this->LookupColourInPalette(src_mv->m), src_mv->v) : src->data; } else { *anim = 0; @@ -97,22 +97,22 @@ inline void Blitter_32bppSSE4_Anim::Draw(const BlitterParams *bp, ZoomLevel zoom break; } - for (uint x = (uint) effective_width/2; x != 0; x--) { - uint32_t mvX2 = *((uint32_t *) const_cast(src_mv)); - __m128i srcABCD = _mm_loadl_epi64((const __m128i*) src); - __m128i dstABCD = _mm_loadl_epi64((__m128i*) dst); + for (uint x = static_cast(effective_width)/2; x != 0; x--) { + uint32_t mvX2 = *(reinterpret_cast(const_cast(src_mv))); + __m128i srcABCD = _mm_loadl_epi64(reinterpret_cast(src)); + __m128i dstABCD = _mm_loadl_epi64(reinterpret_cast<__m128i*>(dst)); if (animated) { /* Remap colours. */ const uint8_t m0 = mvX2; if (m0 >= PALETTE_ANIM_START) { const Colour c0 = (this->LookupColourInPalette(m0).data & 0x00FFFFFF) | (src[0].data & 0xFF000000); - InsertFirstUint32(AdjustBrightneSSE(c0, (uint8_t) (mvX2 >> 8)).data, srcABCD); + InsertFirstUint32(AdjustBrightneSSE(c0, static_cast(mvX2 >> 8)).data, srcABCD); } const uint8_t m1 = mvX2 >> 16; if (m1 >= PALETTE_ANIM_START) { const Colour c1 = (this->LookupColourInPalette(m1).data & 0x00FFFFFF) | (src[1].data & 0xFF000000); - InsertSecondUint32(AdjustBrightneSSE(c1, (uint8_t) (mvX2 >> 24)).data, srcABCD); + InsertSecondUint32(AdjustBrightneSSE(c1, static_cast(mvX2 >> 24)).data, srcABCD); } /* Update anim buffer. */ @@ -121,23 +121,23 @@ inline void Blitter_32bppSSE4_Anim::Draw(const BlitterParams *bp, ZoomLevel zoom uint32_t anim01 = 0; if (a0 == 255) { if (a1 == 255) { - *(uint32_t*) anim = mvX2; + *reinterpret_cast(anim) = mvX2; goto bmno_full_opacity; } - anim01 = (uint16_t) mvX2; + anim01 = static_cast(mvX2); } else if (a0 == 0) { if (a1 == 0) { goto bmno_full_transparency; } else { - if (a1 == 255) anim[1] = (uint16_t) (mvX2 >> 16); + if (a1 == 255) anim[1] = static_cast(mvX2 >> 16); goto bmno_alpha_blend; } } if (a1 > 0) { if (a1 == 255) anim01 |= mvX2 & 0xFFFF0000; - *(uint32_t*) anim = anim01; + *reinterpret_cast(anim) = anim01; } else { - anim[0] = (uint16_t) anim01; + anim[0] = static_cast(anim01); } } else { if (src[0].a) anim[0] = 0; @@ -148,7 +148,7 @@ inline void Blitter_32bppSSE4_Anim::Draw(const BlitterParams *bp, ZoomLevel zoom bmno_alpha_blend: srcABCD = AlphaBlendTwoPixels(srcABCD, dstABCD, a_cm, pack_low_cm, a_am); bmno_full_opacity: - _mm_storel_epi64((__m128i *) dst, srcABCD); + _mm_storel_epi64(reinterpret_cast<__m128i *>(dst), srcABCD); bmno_full_transparency: src_mv += 2; src += 2; @@ -160,7 +160,7 @@ bmno_full_transparency: if (src->a == 0) { /* Complete transparency. */ } else if (src->a == 255) { - *anim = *(const uint16_t*) src_mv; + *anim = *reinterpret_cast(src_mv); *dst = (src_mv->m >= PALETTE_ANIM_START) ? AdjustBrightneSSE(LookupColourInPalette(src_mv->m), src_mv->v) : *src; } else { *anim = 0; @@ -179,15 +179,15 @@ bmno_full_transparency: break; case BlitterMode::ColourRemap: - for (uint x = (uint) effective_width / 2; x != 0; x--) { - uint32_t mvX2 = *((uint32_t *) const_cast(src_mv)); - __m128i srcABCD = _mm_loadl_epi64((const __m128i*) src); - __m128i dstABCD = _mm_loadl_epi64((__m128i*) dst); + for (uint x = static_cast(effective_width) / 2; x != 0; x--) { + uint32_t mvX2 = *(reinterpret_cast(const_cast(src_mv))); + __m128i srcABCD = _mm_loadl_epi64(reinterpret_cast(src)); + __m128i dstABCD = _mm_loadl_epi64(reinterpret_cast<__m128i*>(dst)); /* Remap colours. */ - const uint m0 = (uint8_t) mvX2; + const uint m0 = static_cast(mvX2); const uint r0 = remap[m0]; - const uint m1 = (uint8_t) (mvX2 >> 16); + const uint m1 = static_cast(mvX2 >> 16); const uint r1 = remap[m1]; if (mvX2 & 0x00FF00FF) { #define CMOV_REMAP(m_colour, m_colour_init, m_src, m_m) \ @@ -209,7 +209,7 @@ bmno_full_transparency: CMOV_REMAP(c0, animated ? dsts : 0, srcs, mvX2); remapped_src = c0.data; CMOV_REMAP(c1, animated ? dsts >> 32 : 0, srcs >> 32, mvX2 >> 16); - remapped_src |= (uint64_t) c1.data << 32; + remapped_src |= static_cast(c1.data) << 32; srcABCD = _mm_cvtsi64_si128(remapped_src); #else Colour remapped_src[2]; @@ -231,7 +231,7 @@ bmno_full_transparency: if (a0 == 255) { anim01 |= r0; if (a1 == 255) { - *(uint32_t*) anim = anim01 | (r1 << 16); + *reinterpret_cast(anim) = anim01 | (r1 << 16); goto bmcr_full_opacity; } } else if (a0 == 0) { @@ -246,9 +246,9 @@ bmno_full_transparency: } if (a1 > 0) { if (a1 == 255) anim01 |= r1 << 16; - *(uint32_t*) anim = anim01; + *reinterpret_cast(anim) = anim01; } else { - anim[0] = (uint16_t) anim01; + anim[0] = static_cast(anim01); } } else { if (src[0].a) anim[0] = 0; @@ -259,7 +259,7 @@ bmno_full_transparency: bmcr_alpha_blend: srcABCD = AlphaBlendTwoPixels(srcABCD, dstABCD, a_cm, pack_low_cm, a_am); bmcr_full_opacity: - _mm_storel_epi64((__m128i *) dst, srcABCD); + _mm_storel_epi64(reinterpret_cast<__m128i *>(dst), srcABCD); bmcr_full_transparency: src_mv += 2; dst += 2; @@ -273,7 +273,7 @@ bmcr_full_transparency: if (src->a == 0) break; if (src_mv->m) { const uint r = remap[src_mv->m]; - *anim = (animated && src->a == 255) ? r | ((uint16_t) src_mv->v << 8 ) : 0; + *anim = (animated && src->a == 255) ? r | (static_cast(src_mv->v) << 8 ) : 0; if (r != 0) { Colour remapped_colour = AdjustBrightneSSE(this->LookupColourInPalette(r), src_mv->v); if (src->a == 255) { @@ -299,10 +299,10 @@ bmcr_alpha_blend_single: case BlitterMode::Transparent: /* Make the current colour a bit more black, so it looks like this image is transparent. */ - for (uint x = (uint) bp->width / 2; x > 0; x--) { - __m128i srcABCD = _mm_loadl_epi64((const __m128i*) src); - __m128i dstABCD = _mm_loadl_epi64((__m128i*) dst); - _mm_storel_epi64((__m128i *) dst, DarkenTwoPixels(srcABCD, dstABCD, a_cm, tr_nom_base)); + for (uint x = static_cast(bp->width) / 2; x > 0; x--) { + __m128i srcABCD = _mm_loadl_epi64(reinterpret_cast(src)); + __m128i dstABCD = _mm_loadl_epi64(reinterpret_cast<__m128i*>(dst)); + _mm_storel_epi64(reinterpret_cast<__m128i *>(dst), DarkenTwoPixels(srcABCD, dstABCD, a_cm, tr_nom_base)); src += 2; dst += 2; anim += 2; @@ -320,7 +320,7 @@ bmcr_alpha_blend_single: case BlitterMode::TransparentRemap: /* Apply custom transparency remap. */ - for (uint x = (uint) bp->width; x > 0; x--) { + for (uint x = static_cast(bp->width); x > 0; x--) { if (src->a != 0) { *dst = this->LookupColourInPalette(remap[GetNearestColourIndex(*dst)]); *anim = 0; @@ -334,7 +334,7 @@ bmcr_alpha_blend_single: case BlitterMode::CrashRemap: - for (uint x = (uint) bp->width; x > 0; x--) { + for (uint x = static_cast(bp->width); x > 0; x--) { if (src_mv->m == 0) { if (src->a != 0) { uint8_t g = MakeDark(src->r, src->g, src->b); @@ -353,7 +353,7 @@ bmcr_alpha_blend_single: break; case BlitterMode::BlackRemap: - for (uint x = (uint) bp->width; x > 0; x--) { + for (uint x = static_cast(bp->width); x > 0; x--) { if (src->a != 0) { *dst = Colour(0, 0, 0); *anim = 0; @@ -368,7 +368,7 @@ bmcr_alpha_blend_single: next_line: if (mode != BlitterMode::Transparent && mode != BlitterMode::TransparentRemap) src_mv_line += si->sprite_width; - src_rgba_line = (const Colour*) ((const uint8_t*) src_rgba_line + si->sprite_line_size); + src_rgba_line = reinterpret_cast(reinterpret_cast(src_rgba_line) + si->sprite_line_size); dst_line += bp->pitch; anim_line += this->anim_buf_pitch; } @@ -390,12 +390,12 @@ void Blitter_32bppSSE4_Anim::Draw(Blitter::BlitterParams *bp, BlitterMode mode, return; } - const Blitter_32bppSSE_Base::SpriteFlags sprite_flags = ((const Blitter_32bppSSE_Base::SpriteData *) bp->sprite)->flags; + const Blitter_32bppSSE_Base::SpriteFlags sprite_flags = (static_cast(bp->sprite))->flags; switch (mode) { default: { bm_normal: if (bp->skip_left != 0 || bp->width <= MARGIN_NORMAL_THRESHOLD) { - const BlockType bt_last = (BlockType) (bp->width & 1); + const BlockType bt_last = static_cast(bp->width & 1); if (bt_last == BT_EVEN) { if (sprite_flags & SF_NO_ANIM) Draw(bp, zoom); else Draw(bp, zoom); diff --git a/src/blitter/32bpp_base.cpp b/src/blitter/32bpp_base.cpp index 58acafc35a..cc00bc5c34 100644 --- a/src/blitter/32bpp_base.cpp +++ b/src/blitter/32bpp_base.cpp @@ -15,19 +15,19 @@ void *Blitter_32bppBase::MoveTo(void *video, int x, int y) { - return (uint32_t *)video + x + y * _screen.pitch; + return static_cast(video) + x + y * _screen.pitch; } void Blitter_32bppBase::SetPixel(void *video, int x, int y, uint8_t colour) { - *((Colour *)video + x + y * _screen.pitch) = LookupColourInPalette(colour); + *(static_cast(video) + x + y * _screen.pitch) = LookupColourInPalette(colour); } void Blitter_32bppBase::DrawLine(void *video, int x, int y, int x2, int y2, int screen_width, int screen_height, uint8_t colour, int width, int dash) { const Colour c = LookupColourInPalette(colour); this->DrawLineGeneric(x, y, x2, y2, screen_width, screen_height, width, dash, [=](int x, int y) { - *((Colour *)video + x + y * _screen.pitch) = c; + *(static_cast(video) + x + y * _screen.pitch) = c; }); } @@ -36,19 +36,19 @@ void Blitter_32bppBase::DrawRect(void *video, int width, int height, uint8_t col Colour colour32 = LookupColourInPalette(colour); do { - Colour *dst = (Colour *)video; + Colour *dst = static_cast(video); for (int i = width; i > 0; i--) { *dst = colour32; dst++; } - video = (uint32_t *)video + _screen.pitch; + video = static_cast(video) + _screen.pitch; } while (--height); } void Blitter_32bppBase::CopyFromBuffer(void *video, const void *src, int width, int height) { - uint32_t *dst = (uint32_t *)video; - const uint32_t *usrc = (const uint32_t *)src; + uint32_t *dst = static_cast(video); + const uint32_t *usrc = static_cast(src); for (; height > 0; height--) { memcpy(dst, usrc, width * sizeof(uint32_t)); @@ -59,8 +59,8 @@ void Blitter_32bppBase::CopyFromBuffer(void *video, const void *src, int width, void Blitter_32bppBase::CopyToBuffer(const void *video, void *dst, int width, int height) { - uint32_t *udst = (uint32_t *)dst; - const uint32_t *src = (const uint32_t *)video; + uint32_t *udst = static_cast(dst); + const uint32_t *src = static_cast(video); for (; height > 0; height--) { memcpy(udst, src, width * sizeof(uint32_t)); @@ -71,8 +71,8 @@ void Blitter_32bppBase::CopyToBuffer(const void *video, void *dst, int width, in void Blitter_32bppBase::CopyImageToBuffer(const void *video, void *dst, int width, int height, int dst_pitch) { - uint32_t *udst = (uint32_t *)dst; - const uint32_t *src = (const uint32_t *)video; + uint32_t *udst = static_cast(dst); + const uint32_t *src = static_cast(video); for (; height > 0; height--) { memcpy(udst, src, width * sizeof(uint32_t)); @@ -88,7 +88,7 @@ void Blitter_32bppBase::ScrollBuffer(void *video, int &left, int &top, int &widt if (scroll_y > 0) { /* Calculate pointers */ - dst = (uint32_t *)video + left + (top + height - 1) * _screen.pitch; + dst = static_cast(video) + left + (top + height - 1) * _screen.pitch; src = dst - scroll_y * _screen.pitch; /* Decrease height and increase top */ @@ -113,7 +113,7 @@ void Blitter_32bppBase::ScrollBuffer(void *video, int &left, int &top, int &widt } } else { /* Calculate pointers */ - dst = (uint32_t *)video + left + top * _screen.pitch; + dst = static_cast(video) + left + top * _screen.pitch; src = dst - scroll_y * _screen.pitch; /* Decrease height. (scroll_y is <=0). */ diff --git a/src/blitter/32bpp_optimized.cpp b/src/blitter/32bpp_optimized.cpp index eebdece030..33135f8002 100644 --- a/src/blitter/32bpp_optimized.cpp +++ b/src/blitter/32bpp_optimized.cpp @@ -28,24 +28,24 @@ static FBlitter_32bppOptimized iFBlitter_32bppOptimized; template inline void Blitter_32bppOptimized::Draw(const Blitter::BlitterParams *bp, ZoomLevel zoom) { - const SpriteData *src = (const SpriteData *)bp->sprite; + const SpriteData *src = static_cast(bp->sprite); /* src_px : each line begins with uint32_t n = 'number of bytes in this line', * then n times is the Colour struct for this line */ - const Colour *src_px = (const Colour *)(src->data + src->offset[zoom][0]); + const Colour *src_px = reinterpret_cast(src->data + src->offset[zoom][0]); /* src_n : each line begins with uint32_t n = 'number of bytes in this line', * then interleaved stream of 'm' and 'n' channels. 'm' is remap, * 'n' is number of bytes with the same alpha channel class */ - const uint16_t *src_n = (const uint16_t *)(src->data + src->offset[zoom][1]); + const uint16_t *src_n = reinterpret_cast(src->data + src->offset[zoom][1]); /* skip upper lines in src_px and src_n */ for (uint i = bp->skip_top; i != 0; i--) { - src_px = (const Colour *)((const uint8_t *)src_px + *(const uint32_t *)src_px); - src_n = (const uint16_t *)((const uint8_t *)src_n + *(const uint32_t *)src_n); + src_px = reinterpret_cast(reinterpret_cast(src_px) + *reinterpret_cast(src_px)); + src_n = reinterpret_cast(reinterpret_cast(src_n) + *reinterpret_cast(src_n)); } /* skip lines in dst */ - Colour *dst = (Colour *)bp->dst + bp->top * bp->pitch + bp->left; + Colour *dst = static_cast(bp->dst) + bp->top * bp->pitch + bp->left; /* store so we don't have to access it via bp every time (compiler assumes pointer aliasing) */ const uint8_t *remap = bp->remap; @@ -55,11 +55,11 @@ inline void Blitter_32bppOptimized::Draw(const Blitter::BlitterParams *bp, ZoomL Colour *dst_ln = dst + bp->pitch; /* next src line begins here */ - const Colour *src_px_ln = (const Colour *)((const uint8_t *)src_px + *(const uint32_t *)src_px); + const Colour *src_px_ln = reinterpret_cast(reinterpret_cast(src_px) + *reinterpret_cast(src_px)); src_px++; /* next src_n line begins here */ - const uint16_t *src_n_ln = (const uint16_t *)((const uint8_t *)src_n + *(const uint32_t *)src_n); + const uint16_t *src_n_ln = reinterpret_cast(reinterpret_cast(src_n) + *reinterpret_cast(src_n)); src_n += 2; /* we will end this line when we reach this point */ @@ -84,7 +84,7 @@ inline void Blitter_32bppOptimized::Draw(const Blitter::BlitterParams *bp, ZoomL dst = dst_end - bp->skip_left; dst_end = dst + bp->width; - n = std::min(n - d, (uint)bp->width); + n = std::min(n - d, static_cast(bp->width)); goto draw; } dst += n; @@ -330,8 +330,8 @@ template Sprite *Blitter_32bppOptimized::EncodeInternal(const for (uint y = src_orig->height; y > 0; y--) { /* Index 0 of dst_px and dst_n is left as space to save the length of the row to be filled later. */ - Colour *dst_px = (Colour *)&dst_px_ln[1]; - uint16_t *dst_n = (uint16_t *)&dst_n_ln[1]; + Colour *dst_px = reinterpret_cast(&dst_px_ln[1]); + uint16_t *dst_n = reinterpret_cast(&dst_n_ln[1]); uint16_t *dst_len = dst_n++; @@ -395,14 +395,14 @@ template Sprite *Blitter_32bppOptimized::EncodeInternal(const *dst_len = len; } - dst_px = (Colour *)AlignPtr(dst_px, 4); - dst_n = (uint16_t *)AlignPtr(dst_n, 4); + dst_px = static_cast(AlignPtr(dst_px, 4)); + dst_n = static_cast(AlignPtr(dst_n, 4)); - *dst_px_ln = (uint8_t *)dst_px - (uint8_t *)dst_px_ln; - *dst_n_ln = (uint8_t *)dst_n - (uint8_t *)dst_n_ln; + *dst_px_ln = reinterpret_cast(dst_px) - reinterpret_cast(dst_px_ln); + *dst_n_ln = reinterpret_cast(dst_n) - reinterpret_cast(dst_n_ln); - dst_px_ln = (uint32_t *)dst_px; - dst_n_ln = (uint32_t *)dst_n; + dst_px_ln = reinterpret_cast(dst_px); + dst_n_ln = reinterpret_cast(dst_n); } lengths[z][0] = reinterpret_cast(dst_px_ln) - reinterpret_cast(dst_px_orig[z].get()); // all are aligned to 4B boundary @@ -421,7 +421,7 @@ template Sprite *Blitter_32bppOptimized::EncodeInternal(const dest_sprite->x_offs = sprite[ZOOM_LVL_MIN].x_offs; dest_sprite->y_offs = sprite[ZOOM_LVL_MIN].y_offs; - SpriteData *dst = (SpriteData *)dest_sprite->data; + SpriteData *dst = reinterpret_cast(dest_sprite->data); memset(dst, 0, sizeof(*dst)); for (ZoomLevel z = zoom_min; z <= zoom_max; z++) { diff --git a/src/blitter/32bpp_simple.cpp b/src/blitter/32bpp_simple.cpp index e55aadb6dc..ed69d7b55a 100644 --- a/src/blitter/32bpp_simple.cpp +++ b/src/blitter/32bpp_simple.cpp @@ -25,8 +25,8 @@ void Blitter_32bppSimple::Draw(Blitter::BlitterParams *bp, BlitterMode mode, Zoo Colour *dst, *dst_line; /* Find where to start reading in the source sprite */ - src_line = (const Blitter_32bppSimple::Pixel *)bp->sprite + (bp->skip_top * bp->sprite_width + bp->skip_left) * ScaleByZoom(1, zoom); - dst_line = (Colour *)bp->dst + bp->top * bp->pitch + bp->left; + src_line = static_cast(bp->sprite) + (bp->skip_top * bp->sprite_width + bp->skip_left) * ScaleByZoom(1, zoom); + dst_line = static_cast(bp->dst) + bp->top * bp->pitch + bp->left; for (int y = 0; y < bp->height; y++) { dst = dst_line; @@ -89,7 +89,7 @@ void Blitter_32bppSimple::Draw(Blitter::BlitterParams *bp, BlitterMode mode, Zoo void Blitter_32bppSimple::DrawColourMappingRect(void *dst, int width, int height, PaletteID pal) { - Colour *udst = (Colour *)dst; + Colour *udst = static_cast(dst); if (pal == PALETTE_TO_TRANSPARENT) { do { @@ -125,8 +125,8 @@ Sprite *Blitter_32bppSimple::Encode(const SpriteLoader::SpriteCollection &sprite dest_sprite->x_offs = sprite[ZOOM_LVL_MIN].x_offs; dest_sprite->y_offs = sprite[ZOOM_LVL_MIN].y_offs; - dst = (Blitter_32bppSimple::Pixel *)dest_sprite->data; - SpriteLoader::CommonPixel *src = (SpriteLoader::CommonPixel *)sprite[ZOOM_LVL_MIN].data; + dst = reinterpret_cast(dest_sprite->data); + SpriteLoader::CommonPixel *src = sprite[ZOOM_LVL_MIN].data; for (int i = 0; i < sprite[ZOOM_LVL_MIN].height * sprite[ZOOM_LVL_MIN].width; i++) { if (src->m == 0) { diff --git a/src/blitter/32bpp_sse2.cpp b/src/blitter/32bpp_sse2.cpp index 5defef274f..56cf96276f 100644 --- a/src/blitter/32bpp_sse2.cpp +++ b/src/blitter/32bpp_sse2.cpp @@ -65,8 +65,8 @@ Sprite *Blitter_32bppSSE_Base::Encode(const SpriteLoader::SpriteCollection &spri for (ZoomLevel z = zoom_min; z <= zoom_max; z++) { const SpriteLoader::Sprite *src_sprite = &sprite[z]; const SpriteLoader::CommonPixel *src = (const SpriteLoader::CommonPixel *) src_sprite->data; - Colour *dst_rgba_line = (Colour *) &dst_sprite->data[sizeof(SpriteData) + sd.infos[z].sprite_offset]; - MapValue *dst_mv = (MapValue *) &dst_sprite->data[sizeof(SpriteData) + sd.infos[z].mv_offset]; + Colour *dst_rgba_line = reinterpret_cast(&dst_sprite->data[sizeof(SpriteData) + sd.infos[z].sprite_offset]); + MapValue *dst_mv = reinterpret_cast(&dst_sprite->data[sizeof(SpriteData) + sd.infos[z].mv_offset]); for (uint y = src_sprite->height; y != 0; y--) { Colour *dst_rgba = dst_rgba_line + META_LENGTH; for (uint x = src_sprite->width; x != 0; x--) { @@ -96,7 +96,7 @@ Sprite *Blitter_32bppSSE_Base::Encode(const SpriteLoader::SpriteCollection &spri } } else { dst_rgba->data = 0; - *(uint16_t*) dst_mv = 0; + *reinterpret_cast(dst_mv) = 0; } dst_rgba++; dst_mv++; @@ -114,7 +114,7 @@ Sprite *Blitter_32bppSSE_Base::Encode(const SpriteLoader::SpriteCollection &spri (*dst_rgba_line).data = nb_pix_transp; Colour *nb_right = dst_rgba_line + 1; - dst_rgba_line = (Colour*) ((uint8_t*) dst_rgba_line + sd.infos[z].sprite_line_size); + dst_rgba_line = reinterpret_cast(reinterpret_cast(dst_rgba_line) + sd.infos[z].sprite_line_size); /* Count the number of transparent pixels from the right. */ dst_rgba = dst_rgba_line - 1; diff --git a/src/blitter/40bpp_anim.cpp b/src/blitter/40bpp_anim.cpp index 866389644a..97300175d9 100644 --- a/src/blitter/40bpp_anim.cpp +++ b/src/blitter/40bpp_anim.cpp @@ -33,9 +33,9 @@ void Blitter_40bppAnim::SetPixel(void *video, int x, int y, uint8_t colour) Blitter_32bppOptimized::SetPixel(video, x, y, colour); } else { size_t y_offset = static_cast(y) * _screen.pitch; - *((Colour *)video + x + y_offset) = _black_colour; + *(static_cast(video) + x + y_offset) = _black_colour; - VideoDriver::GetInstance()->GetAnimBuffer()[((uint32_t *)video - (uint32_t *)_screen.dst_ptr) + x + y_offset] = colour; + VideoDriver::GetInstance()->GetAnimBuffer()[(static_cast(video) - static_cast(_screen.dst_ptr)) + x + y_offset] = colour; } } @@ -48,10 +48,10 @@ void Blitter_40bppAnim::DrawRect(void *video, int width, int height, uint8_t col } assert(VideoDriver::GetInstance()->GetAnimBuffer() != nullptr); - uint8_t *anim_line = ((uint32_t *)video - (uint32_t *)_screen.dst_ptr) + VideoDriver::GetInstance()->GetAnimBuffer(); + uint8_t *anim_line = (static_cast(video) - static_cast(_screen.dst_ptr)) + VideoDriver::GetInstance()->GetAnimBuffer(); do { - Colour *dst = (Colour *)video; + Colour *dst = static_cast(video); uint8_t *anim = anim_line; for (int i = width; i > 0; i--) { @@ -60,7 +60,7 @@ void Blitter_40bppAnim::DrawRect(void *video, int width, int height, uint8_t col dst++; anim++; } - video = (uint32_t *)video + _screen.pitch; + video = static_cast(video) + _screen.pitch; anim_line += _screen.pitch; } while (--height); } @@ -74,10 +74,10 @@ void Blitter_40bppAnim::DrawLine(void *video, int x, int y, int x2, int y2, int } assert(VideoDriver::GetInstance()->GetAnimBuffer() != nullptr); - uint8_t *anim = ((uint32_t *)video - (uint32_t *)_screen.dst_ptr) + VideoDriver::GetInstance()->GetAnimBuffer(); + uint8_t *anim = (static_cast(video) - static_cast(_screen.dst_ptr)) + VideoDriver::GetInstance()->GetAnimBuffer(); this->DrawLineGeneric(x, y, x2, y2, screen_width, screen_height, width, dash, [=](int x, int y) { - *((Colour *)video + x + y * _screen.pitch) = _black_colour; + *(static_cast(video) + x + y * _screen.pitch) = _black_colour; *(anim + x + y * _screen.pitch) = colour; }); } @@ -92,26 +92,26 @@ void Blitter_40bppAnim::DrawLine(void *video, int x, int y, int x2, int y2, int template inline void Blitter_40bppAnim::Draw(const Blitter::BlitterParams *bp, ZoomLevel zoom) { - const SpriteData *src = (const SpriteData *)bp->sprite; + const SpriteData *src = static_cast(bp->sprite); /* src_px : each line begins with uint32_t n = 'number of bytes in this line', * then n times is the Colour struct for this line */ - const Colour *src_px = (const Colour *)(src->data + src->offset[zoom][0]); + const Colour *src_px = reinterpret_cast(src->data + src->offset[zoom][0]); /* src_n : each line begins with uint32_t n = 'number of bytes in this line', * then interleaved stream of 'm' and 'n' channels. 'm' is remap, * 'n' is number of bytes with the same alpha channel class */ - const uint16_t *src_n = (const uint16_t *)(src->data + src->offset[zoom][1]); + const uint16_t *src_n = reinterpret_cast(src->data + src->offset[zoom][1]); /* skip upper lines in src_px and src_n */ for (uint i = bp->skip_top; i != 0; i--) { - src_px = (const Colour *)((const uint8_t *)src_px + *(const uint32_t *)src_px); - src_n = (const uint16_t *)((const uint8_t *)src_n + *(const uint32_t *)src_n); + src_px = reinterpret_cast(reinterpret_cast(src_px) + *reinterpret_cast(src_px)); + src_n = reinterpret_cast(reinterpret_cast(src_n) + *reinterpret_cast(src_n)); } /* skip lines in dst */ - Colour *dst = (Colour *)bp->dst + bp->top * bp->pitch + bp->left; + Colour *dst = static_cast(bp->dst) + bp->top * bp->pitch + bp->left; assert(VideoDriver::GetInstance()->GetAnimBuffer() != nullptr); - uint8_t *anim = VideoDriver::GetInstance()->GetAnimBuffer() + ((uint32_t *)bp->dst - (uint32_t *)_screen.dst_ptr) + bp->top * bp->pitch + bp->left; + uint8_t *anim = VideoDriver::GetInstance()->GetAnimBuffer() + (static_cast(bp->dst) - static_cast(_screen.dst_ptr)) + bp->top * bp->pitch + bp->left; /* store so we don't have to access it via bp every time (compiler assumes pointer aliasing) */ const uint8_t *remap = bp->remap; @@ -122,11 +122,11 @@ inline void Blitter_40bppAnim::Draw(const Blitter::BlitterParams *bp, ZoomLevel uint8_t *anim_ln = anim + bp->pitch; /* next src line begins here */ - const Colour *src_px_ln = (const Colour *)((const uint8_t *)src_px + *(const uint32_t *)src_px); + const Colour *src_px_ln = reinterpret_cast(reinterpret_cast(src_px) + *reinterpret_cast(src_px)); src_px++; /* next src_n line begins here */ - const uint16_t *src_n_ln = (const uint16_t *)((const uint8_t *)src_n + *(const uint32_t *)src_n); + const uint16_t *src_n_ln = reinterpret_cast(reinterpret_cast(src_n) + *reinterpret_cast(src_n)); src_n += 2; /* we will end this line when we reach this point */ @@ -153,7 +153,7 @@ inline void Blitter_40bppAnim::Draw(const Blitter::BlitterParams *bp, ZoomLevel dst = dst_end - bp->skip_left; dst_end = dst + bp->width; - n = std::min(n - d, (uint)bp->width); + n = std::min(n - d, static_cast(bp->width)); goto draw; } dst += n; @@ -168,7 +168,7 @@ inline void Blitter_40bppAnim::Draw(const Blitter::BlitterParams *bp, ZoomLevel dst_end += bp->width; while (dst < dst_end) { - n = std::min(*src_n++, (uint)(dst_end - dst)); + n = std::min(*src_n++, static_cast(dst_end - dst)); if (src_px->a == 0) { anim += n; @@ -356,8 +356,8 @@ void Blitter_40bppAnim::DrawColourMappingRect(void *dst, int width, int height, return; } - Colour *udst = (Colour *)dst; - uint8_t *anim = VideoDriver::GetInstance()->GetAnimBuffer() + ((uint32_t *)dst - (uint32_t *)_screen.dst_ptr); + Colour *udst = static_cast(dst); + uint8_t *anim = VideoDriver::GetInstance()->GetAnimBuffer() + (static_cast(dst) - static_cast(_screen.dst_ptr)); if (pal == PALETTE_TO_TRANSPARENT) { /* If the anim buffer contains a color value, the image composition will @@ -407,12 +407,12 @@ void Blitter_40bppAnim::CopyFromBuffer(void *video, const void *src, int width, { assert(!_screen_disable_anim); assert(video >= _screen.dst_ptr && video <= (uint32_t *)_screen.dst_ptr + _screen.width + _screen.height * _screen.pitch); - uint32_t *dst = (uint32_t *)video; - const uint32_t *usrc = (const uint32_t *)src; + uint32_t *dst = static_cast(video); + const uint32_t *usrc = static_cast(src); uint8_t *anim_buf = VideoDriver::GetInstance()->GetAnimBuffer(); if (anim_buf == nullptr) return; - uint8_t *anim_line = ((uint32_t *)video - (uint32_t *)_screen.dst_ptr) + anim_buf; + uint8_t *anim_line = (static_cast(video) - static_cast(_screen.dst_ptr)) + anim_buf; for (; height > 0; height--) { memcpy(dst, usrc, width * sizeof(uint32_t)); @@ -420,7 +420,7 @@ void Blitter_40bppAnim::CopyFromBuffer(void *video, const void *src, int width, dst += _screen.pitch; /* Copy back the anim-buffer */ memcpy(anim_line, usrc, width * sizeof(uint8_t)); - usrc = (const uint32_t *)((const uint8_t *)usrc + width); + usrc = reinterpret_cast(reinterpret_cast(usrc) + width); anim_line += _screen.pitch; } } @@ -429,12 +429,12 @@ void Blitter_40bppAnim::CopyToBuffer(const void *video, void *dst, int width, in { assert(!_screen_disable_anim); assert(video >= _screen.dst_ptr && video <= (uint32_t *)_screen.dst_ptr + _screen.width + _screen.height * _screen.pitch); - uint32_t *udst = (uint32_t *)dst; - const uint32_t *src = (const uint32_t *)video; + uint32_t *udst = static_cast(dst); + const uint32_t *src = static_cast(video); uint8_t *anim_buf = VideoDriver::GetInstance()->GetAnimBuffer(); if (anim_buf == nullptr) return; - const uint8_t *anim_line = ((const uint32_t *)video - (uint32_t *)_screen.dst_ptr) + anim_buf; + const uint8_t *anim_line = (static_cast(video) - static_cast(_screen.dst_ptr)) + anim_buf; for (; height > 0; height--) { memcpy(udst, src, width * sizeof(uint32_t)); @@ -442,7 +442,7 @@ void Blitter_40bppAnim::CopyToBuffer(const void *video, void *dst, int width, in udst += width; /* Copy the anim-buffer */ memcpy(udst, anim_line, width * sizeof(uint8_t)); - udst = (uint32_t *)((uint8_t *)udst + width); + udst = reinterpret_cast(reinterpret_cast(udst) + width); anim_line += _screen.pitch; } } @@ -455,9 +455,9 @@ void Blitter_40bppAnim::CopyImageToBuffer(const void *video, void *dst, int widt return; } - uint32_t *udst = (uint32_t *)dst; - const uint32_t *src = (const uint32_t *)video; - const uint8_t *anim_line = ((const uint32_t *)video - (uint32_t *)_screen.dst_ptr) + anim_buf; + uint32_t *udst = static_cast(dst); + const uint32_t *src = static_cast(video); + const uint8_t *anim_line = (static_cast(video) - static_cast(_screen.dst_ptr)) + anim_buf; for (; height > 0; height--) { for (int x = 0; x < width; x++) { diff --git a/src/blitter/8bpp_base.cpp b/src/blitter/8bpp_base.cpp index a936138a1a..847063322e 100644 --- a/src/blitter/8bpp_base.cpp +++ b/src/blitter/8bpp_base.cpp @@ -19,25 +19,25 @@ void Blitter_8bppBase::DrawColourMappingRect(void *dst, int width, int height, P const uint8_t *ctab = GetNonSprite(pal, SpriteType::Recolour) + 1; do { - for (int i = 0; i != width; i++) *((uint8_t *)dst + i) = ctab[((uint8_t *)dst)[i]]; - dst = (uint8_t *)dst + _screen.pitch; + for (int i = 0; i != width; i++) *(static_cast(dst) + i) = ctab[(static_cast(dst))[i]]; + dst = static_cast(dst) + _screen.pitch; } while (--height); } void *Blitter_8bppBase::MoveTo(void *video, int x, int y) { - return (uint8_t *)video + x + y * _screen.pitch; + return static_cast(video) + x + y * _screen.pitch; } void Blitter_8bppBase::SetPixel(void *video, int x, int y, uint8_t colour) { - *((uint8_t *)video + x + y * _screen.pitch) = colour; + *(static_cast(video) + x + y * _screen.pitch) = colour; } void Blitter_8bppBase::DrawLine(void *video, int x, int y, int x2, int y2, int screen_width, int screen_height, uint8_t colour, int width, int dash) { this->DrawLineGeneric(x, y, x2, y2, screen_width, screen_height, width, dash, [=](int x, int y) { - *((uint8_t *)video + x + y * _screen.pitch) = colour; + *(static_cast(video) + x + y * _screen.pitch) = colour; }); } @@ -45,14 +45,14 @@ void Blitter_8bppBase::DrawRect(void *video, int width, int height, uint8_t colo { do { memset(video, colour, width); - video = (uint8_t *)video + _screen.pitch; + video = static_cast(video) + _screen.pitch; } while (--height); } void Blitter_8bppBase::CopyFromBuffer(void *video, const void *src, int width, int height) { - uint8_t *dst = (uint8_t *)video; - const uint8_t *usrc = (const uint8_t *)src; + uint8_t *dst = static_cast(video); + const uint8_t *usrc = static_cast(src); for (; height > 0; height--) { memcpy(dst, usrc, width * sizeof(uint8_t)); @@ -63,8 +63,8 @@ void Blitter_8bppBase::CopyFromBuffer(void *video, const void *src, int width, i void Blitter_8bppBase::CopyToBuffer(const void *video, void *dst, int width, int height) { - uint8_t *udst = (uint8_t *)dst; - const uint8_t *src = (const uint8_t *)video; + uint8_t *udst = static_cast(dst); + const uint8_t *src = static_cast(video); for (; height > 0; height--) { memcpy(udst, src, width * sizeof(uint8_t)); @@ -75,8 +75,8 @@ void Blitter_8bppBase::CopyToBuffer(const void *video, void *dst, int width, int void Blitter_8bppBase::CopyImageToBuffer(const void *video, void *dst, int width, int height, int dst_pitch) { - uint8_t *udst = (uint8_t *)dst; - const uint8_t *src = (const uint8_t *)video; + uint8_t *udst = static_cast(dst); + const uint8_t *src = static_cast(video); for (; height > 0; height--) { memcpy(udst, src, width * sizeof(uint8_t)); @@ -92,7 +92,7 @@ void Blitter_8bppBase::ScrollBuffer(void *video, int &left, int &top, int &width if (scroll_y > 0) { /* Calculate pointers */ - dst = (uint8_t *)video + left + (top + height - 1) * _screen.pitch; + dst = static_cast(video) + left + (top + height - 1) * _screen.pitch; src = dst - scroll_y * _screen.pitch; /* Decrease height and increase top */ @@ -117,7 +117,7 @@ void Blitter_8bppBase::ScrollBuffer(void *video, int &left, int &top, int &width } } else { /* Calculate pointers */ - dst = (uint8_t *)video + left + top * _screen.pitch; + dst = static_cast(video) + left + top * _screen.pitch; src = dst - scroll_y * _screen.pitch; /* Decrease height. (scroll_y is <=0). */ diff --git a/src/blitter/8bpp_optimized.cpp b/src/blitter/8bpp_optimized.cpp index 775fad8253..bf0941ea46 100644 --- a/src/blitter/8bpp_optimized.cpp +++ b/src/blitter/8bpp_optimized.cpp @@ -22,12 +22,12 @@ static FBlitter_8bppOptimized iFBlitter_8bppOptimized; void Blitter_8bppOptimized::Draw(Blitter::BlitterParams *bp, BlitterMode mode, ZoomLevel zoom) { /* Find the offset of this zoom-level */ - const SpriteData *sprite_src = (const SpriteData *)bp->sprite; + const SpriteData *sprite_src = static_cast(bp->sprite); uint offset = sprite_src->offset[zoom]; /* Find where to start reading in the source sprite */ const uint8_t *src = sprite_src->data + offset; - uint8_t *dst_line = (uint8_t *)bp->dst + bp->top * bp->pitch + bp->left; + uint8_t *dst_line = static_cast(bp->dst) + bp->top * bp->pitch + bp->left; /* Skip over the top lines in the source image */ for (int y = 0; y < bp->skip_top; y++) { @@ -212,7 +212,7 @@ Sprite *Blitter_8bppOptimized::Encode(const SpriteLoader::SpriteCollection &spri } } - uint size = dst - (uint8_t *)temp_dst; + uint size = dst - reinterpret_cast(temp_dst); /* Safety check, to make sure we guessed the size correctly */ assert(size < memory); diff --git a/src/blitter/8bpp_simple.cpp b/src/blitter/8bpp_simple.cpp index 9451dcd944..0506f020d4 100644 --- a/src/blitter/8bpp_simple.cpp +++ b/src/blitter/8bpp_simple.cpp @@ -22,8 +22,8 @@ void Blitter_8bppSimple::Draw(Blitter::BlitterParams *bp, BlitterMode mode, Zoom uint8_t *dst, *dst_line; /* Find where to start reading in the source sprite */ - src_line = (const uint8_t *)bp->sprite + (bp->skip_top * bp->sprite_width + bp->skip_left) * ScaleByZoom(1, zoom); - dst_line = (uint8_t *)bp->dst + bp->top * bp->pitch + bp->left; + src_line = static_cast(bp->sprite) + (bp->skip_top * bp->sprite_width + bp->skip_left) * ScaleByZoom(1, zoom); + dst_line = static_cast(bp->dst) + bp->top * bp->pitch + bp->left; for (int y = 0; y < bp->height; y++) { dst = dst_line; diff --git a/src/bridge_gui.cpp b/src/bridge_gui.cpp index acfda71049..9bb5d38862 100644 --- a/src/bridge_gui.cpp +++ b/src/bridge_gui.cpp @@ -399,10 +399,10 @@ void ShowBuildBridgeWindow(TileIndex start, TileIndex end, TransportType transpo road_rt = GetRoadTypeRoad(start); tram_rt = GetRoadTypeTram(start); } - if (RoadTypeIsRoad((RoadType)road_rail_type)) { - road_rt = (RoadType)road_rail_type; + if (RoadTypeIsRoad(static_cast(road_rail_type))) { + road_rt = static_cast(road_rail_type); } else { - tram_rt = (RoadType)road_rail_type; + tram_rt = static_cast(road_rail_type); } if (road_rt != INVALID_ROADTYPE) infra_cost += (bridge_len + 2) * 2 * RoadBuildCost(road_rt); @@ -410,7 +410,7 @@ void ShowBuildBridgeWindow(TileIndex start, TileIndex end, TransportType transpo break; } - case TRANSPORT_RAIL: infra_cost = (bridge_len + 2) * RailBuildCost((RailType)road_rail_type); break; + case TRANSPORT_RAIL: infra_cost = (bridge_len + 2) * RailBuildCost(static_cast(road_rail_type)); break; default: break; } @@ -426,7 +426,7 @@ void ShowBuildBridgeWindow(TileIndex start, TileIndex end, TransportType transpo item.spec = GetBridgeSpec(brd_type); /* Add to terraforming & bulldozing costs the cost of the * bridge itself (not computed with DoCommandFlag::QueryCost) */ - item.cost = ret.GetCost() + (((int64_t)tot_bridgedata_len * _price[PR_BUILD_BRIDGE] * item.spec->price) >> 8) + infra_cost; + item.cost = ret.GetCost() + ((static_cast(tot_bridgedata_len) * _price[PR_BUILD_BRIDGE] * item.spec->price) >> 8) + infra_cost; any_available = true; } } diff --git a/src/build_vehicle_gui.cpp b/src/build_vehicle_gui.cpp index 9414dc118e..fc230d6171 100644 --- a/src/build_vehicle_gui.cpp +++ b/src/build_vehicle_gui.cpp @@ -293,8 +293,8 @@ static bool EnginePowerVsRunningCostSorter(const GUIEngineListItem &a, const GUI /* Using double for more precision when comparing close values. * This shouldn't have any major effects in performance nor in keeping * the game in sync between players since it's used in GUI only in client side */ - double v_a = (double)p_a / (double)r_a; - double v_b = (double)p_b / (double)r_b; + double v_a = static_cast(p_a) / (double)r_a; + double v_b = static_cast(p_b) / (double)r_b; /* Use EngineID to sort if both have same power/running cost, * since we want consistent sorting. * Also if both have no power then sort with reverse of running cost to simulate @@ -1168,7 +1168,7 @@ struct BuildVehicleWindow : Window { { this->vehicle_type = type; this->listview_mode = tile == INVALID_TILE; - this->window_number = this->listview_mode ? (int)type : tile.base(); + this->window_number = this->listview_mode ? static_cast(type) : tile.base(); this->sort_criteria = _engine_sort_last_criteria[type]; this->descending_sort_order = _engine_sort_last_order[type]; @@ -1901,7 +1901,7 @@ void ShowBuildVehicleWindow(TileIndex tile, VehicleType type) * so if tile == INVALID_TILE (Available XXX Window), use 'type' as unique number. * As it always is a low value, it won't collide with any real tile * number. */ - uint num = (tile == INVALID_TILE) ? (int)type : tile.base(); + uint num = (tile == INVALID_TILE) ? static_cast(type) : tile.base(); assert(IsCompanyBuildableVehicleType(type)); diff --git a/src/cheat_gui.cpp b/src/cheat_gui.cpp index 0b56ca159b..dab333181b 100644 --- a/src/cheat_gui.cpp +++ b/src/cheat_gui.cpp @@ -72,9 +72,9 @@ static int32_t ClickMoneyCheat(int32_t, int32_t change_direction) */ static int32_t ClickChangeCompanyCheat(int32_t new_value, int32_t change_direction) { - while ((uint)new_value < Company::GetPoolSize()) { - if (Company::IsValidID((CompanyID)new_value)) { - SetLocalCompany((CompanyID)new_value); + while (static_cast(new_value) < Company::GetPoolSize()) { + if (Company::IsValidID(CompanyID(new_value))) { + SetLocalCompany(CompanyID(new_value)); return _local_company.base(); } new_value += change_direction; @@ -150,7 +150,7 @@ static int32_t ClickChangeMaxHlCheat(int32_t new_value, int32_t) /* Check if at least one mountain on the map is higher than the new value. * If yes, disallow the change. */ for (const auto t : Map::Iterate()) { - if ((int32_t)TileHeight(t) > new_value) { + if (static_cast(TileHeight(t)) > new_value) { ShowErrorMessage(GetEncodedString(STR_CONFIG_SETTING_TOO_HIGH_MOUNTAIN), {}, WL_ERROR); /* Return old, unchanged value */ return _settings_game.construction.map_height_limit; @@ -283,7 +283,7 @@ struct CheatWindow : Window { std::string str; switch (ce->type) { case SLE_BOOL: { - bool on = (*(bool*)ce->variable); + bool on = (*static_cast(ce->variable)); DrawBoolButton(button_left, y + button_y_offset, on, true); str = GetString(ce->str, on ? STR_CONFIG_SETTING_ON : STR_CONFIG_SETTING_OFF); diff --git a/src/clear_cmd.cpp b/src/clear_cmd.cpp index f0d6b27021..b0ced69449 100644 --- a/src/clear_cmd.cpp +++ b/src/clear_cmd.cpp @@ -336,7 +336,7 @@ void GenerateClearTile() MarkTileDirtyByTile(tile); do { if (--j == 0) goto get_out; - tile_new = tile + TileOffsByDiagDir((DiagDirection)GB(Random(), 0, 2)); + tile_new = tile + TileOffsByDiagDir(static_cast(GB(Random(), 0, 2))); } while (!IsTileType(tile_new, MP_CLEAR) || IsClearGround(tile_new, CLEAR_DESERT)); tile = tile_new; } diff --git a/src/company_cmd.cpp b/src/company_cmd.cpp index df8d3bd187..a9c7af9efc 100644 --- a/src/company_cmd.cpp +++ b/src/company_cmd.cpp @@ -67,10 +67,10 @@ Company::Company(StringID name_1, bool is_ai) { this->name_1 = name_1; this->is_ai = is_ai; - this->terraform_limit = (uint32_t)_settings_game.construction.terraform_frame_burst << 16; - this->clear_limit = (uint32_t)_settings_game.construction.clear_frame_burst << 16; - this->tree_limit = (uint32_t)_settings_game.construction.tree_frame_burst << 16; - this->build_object_limit = (uint32_t)_settings_game.construction.build_object_frame_burst << 16; + this->terraform_limit = static_cast(_settings_game.construction.terraform_frame_burst) << 16; + this->clear_limit = static_cast(_settings_game.construction.clear_frame_burst) << 16; + this->tree_limit = static_cast(_settings_game.construction.tree_frame_burst) << 16; + this->build_object_limit = static_cast(_settings_game.construction.build_object_frame_burst) << 16; InvalidateWindowData(WC_PERFORMANCE_DETAIL, 0, CompanyID::Invalid()); } @@ -89,8 +89,8 @@ Company::~Company() */ void Company::PostDestructor(size_t index) { - InvalidateWindowData(WC_GRAPH_LEGEND, 0, (int)index); - InvalidateWindowData(WC_PERFORMANCE_DETAIL, 0, (int)index); + InvalidateWindowData(WC_GRAPH_LEGEND, 0, static_cast(index)); + InvalidateWindowData(WC_PERFORMANCE_DETAIL, 0, static_cast(index)); InvalidateWindowData(WC_COMPANY_LEAGUE, 0, 0); InvalidateWindowData(WC_LINKGRAPH_LEGEND, 0); /* If the currently shown error message has this company in it, then close it. */ @@ -147,8 +147,8 @@ void SetLocalCompany(CompanyID new_company) */ TextColour GetDrawStringCompanyColour(CompanyID company) { - if (!Company::IsValidID(company)) return (TextColour)GetColourGradient(COLOUR_WHITE, SHADE_NORMAL) | TC_IS_PALETTE_COLOUR; - return (TextColour)GetColourGradient(_company_colours[company], SHADE_NORMAL) | TC_IS_PALETTE_COLOUR; + if (!Company::IsValidID(company)) return static_cast(GetColourGradient(COLOUR_WHITE, SHADE_NORMAL)) | TC_IS_PALETTE_COLOUR; + return static_cast(GetColourGradient(_company_colours[company], SHADE_NORMAL)) | TC_IS_PALETTE_COLOUR; } /** @@ -172,7 +172,7 @@ static bool IsValidCompanyManagerFace(CompanyManagerFace cmf) { if (!AreCompanyManagerFaceBitsValid(cmf, CMFV_GEN_ETHN, GE_WM)) return false; - GenderEthnicity ge = (GenderEthnicity)GetCompanyManagerFaceBits(cmf, CMFV_GEN_ETHN, GE_WM); + GenderEthnicity ge = static_cast(GetCompanyManagerFaceBits(cmf, CMFV_GEN_ETHN, GE_WM)); bool has_moustache = !HasBit(ge, GENDER_FEMALE) && GetCompanyManagerFaceBits(cmf, CMFV_HAS_MOUSTACHE, ge) != 0; bool has_tie_earring = !HasBit(ge, GENDER_FEMALE) || GetCompanyManagerFaceBits(cmf, CMFV_HAS_TIE_EARRING, ge) != 0; bool has_glasses = GetCompanyManagerFaceBits(cmf, CMFV_HAS_GLASSES, ge) != 0; @@ -605,7 +605,7 @@ Company *DoStartupNewCompany(bool is_ai, CompanyID company = CompanyID::Invalid( if (_company_manager_face != 0 && !is_ai && !_networking) { c->face = _company_manager_face; } else { - RandomCompanyManagerFaceBits(c->face, (GenderEthnicity)Random(), false, _random); + RandomCompanyManagerFaceBits(c->face, static_cast(Random()), false, _random); } SetDefaultCompanySettings(c->index); @@ -840,7 +840,7 @@ void CompanyAdminUpdate(const Company *company) */ void CompanyAdminRemove(CompanyID company_id, CompanyRemoveReason reason) { - if (_network_server) NetworkAdminCompanyRemove(company_id, (AdminCompanyRemoveReason)reason); + if (_network_server) NetworkAdminCompanyRemove(company_id, static_cast(reason)); } /** @@ -949,7 +949,7 @@ CommandCost CmdCompanyCtrl(DoCommandFlags flags, CompanyCtrlAction cca, CompanyI delete c; AI::BroadcastNewEvent(new ScriptEventCompanyBankrupt(c_index)); Game::NewEvent(new ScriptEventCompanyBankrupt(c_index)); - CompanyAdminRemove(c_index, (CompanyRemoveReason)reason); + CompanyAdminRemove(c_index, reason); if (StoryPage::GetNumItems() == 0 || Goal::GetNumItems() == 0) InvalidateWindowData(WC_MAIN_TOOLBAR, 0); InvalidateWindowData(WC_CLIENT_LIST, 0); diff --git a/src/company_gui.cpp b/src/company_gui.cpp index 85573b9771..5060eadcc6 100644 --- a/src/company_gui.cpp +++ b/src/company_gui.cpp @@ -664,7 +664,7 @@ private: this->groups.clear(); if (this->livery_class >= LC_GROUP_RAIL) { - VehicleType vtype = (VehicleType)(this->livery_class - LC_GROUP_RAIL); + VehicleType vtype = static_cast(this->livery_class - LC_GROUP_RAIL); BuildGuiGroupList(this->groups, false, owner, vtype); } @@ -681,7 +681,7 @@ private: } } } else { - this->rows = (uint)this->groups.size(); + this->rows = static_cast(this->groups.size()); } this->vscroll->SetCount(this->rows); @@ -759,7 +759,7 @@ public: case WID_SCL_MATRIX: { /* 11 items in the default rail class */ this->square = GetSpriteSize(SPR_SQUARE); - this->line_height = std::max(this->square.height, (uint)GetCharacterHeight(FS_NORMAL)) + padding.height; + this->line_height = std::max(this->square.height, static_cast(GetCharacterHeight(FS_NORMAL))) + padding.height; size.height = 5 * this->line_height; resize.width = 1; @@ -906,7 +906,7 @@ public: if (this->vscroll->GetCount() == 0) { const StringID empty_labels[] = { STR_LIVERY_TRAIN_GROUP_EMPTY, STR_LIVERY_ROAD_VEHICLE_GROUP_EMPTY, STR_LIVERY_SHIP_GROUP_EMPTY, STR_LIVERY_AIRCRAFT_GROUP_EMPTY }; - VehicleType vtype = (VehicleType)(this->livery_class - LC_GROUP_RAIL); + VehicleType vtype = static_cast(this->livery_class - LC_GROUP_RAIL); DrawString(ir.left, ir.right, y + text_offs, empty_labels[vtype], TC_BLACK); } } @@ -926,7 +926,7 @@ public: case WID_SCL_GROUPS_SHIP: case WID_SCL_GROUPS_AIRCRAFT: this->RaiseWidget(WID_SCL_CLASS_GENERAL + this->livery_class); - this->livery_class = (LiveryClass)(widget - WID_SCL_CLASS_GENERAL); + this->livery_class = static_cast(widget - WID_SCL_CLASS_GENERAL); this->LowerWidget(WID_SCL_CLASS_GENERAL + this->livery_class); /* Select the first item in the list */ @@ -965,7 +965,7 @@ public: uint row = this->vscroll->GetScrolledRowFromWidget(pt.y, this, widget); if (row >= this->rows) return; - LiveryScheme j = (LiveryScheme)row; + LiveryScheme j = static_cast(row); for (LiveryScheme scheme = LS_BEGIN; scheme <= j && scheme < LS_END; scheme++) { if (_livery_class[scheme] != this->livery_class || !HasBit(_loaded_newgrf_features.used_liveries, scheme)) j++; @@ -1120,7 +1120,7 @@ void ShowCompanyLiveryWindow(CompanyID company, GroupID group) */ void DrawCompanyManagerFace(CompanyManagerFace cmf, Colours colour, const Rect &r) { - GenderEthnicity ge = (GenderEthnicity)GetCompanyManagerFaceBits(cmf, CMFV_GEN_ETHN, GE_WM); + GenderEthnicity ge = static_cast(GetCompanyManagerFaceBits(cmf, CMFV_GEN_ETHN, GE_WM)); /* Determine offset from centre of drawing rect. */ Dimension d = GetSpriteSize(SPR_GRADIENT); @@ -1352,7 +1352,7 @@ class SelectCompanyManagerFaceWindow : public Window void UpdateData() { - this->ge = (GenderEthnicity)GB(this->face, _cmf_info[CMFV_GEN_ETHN].offset, _cmf_info[CMFV_GEN_ETHN].length); // get the gender and ethnicity + this->ge = static_cast(GB(this->face, _cmf_info[CMFV_GEN_ETHN].offset, _cmf_info[CMFV_GEN_ETHN].length)); // get the gender and ethnicity this->is_female = HasBit(this->ge, GENDER_FEMALE); // get the gender: 0 == male and 1 == female this->is_moust_male = !is_female && GetCompanyManagerFaceBits(this->face, CMFV_HAS_MOUSTACHE, this->ge) != 0; // is a male face with moustache @@ -2222,7 +2222,7 @@ struct CompanyWindow : Window reinit |= this->GetWidget(WID_C_SELECT_HOSTILE_TAKEOVER)->SetDisplayedPlane((local || _local_company == COMPANY_SPECTATOR || !c->is_ai || _networking) ? SZSP_NONE : 0); /* Multiplayer buttons. */ - reinit |= this->GetWidget(WID_C_SELECT_MULTIPLAYER)->SetDisplayedPlane((!_networking || !NetworkCanJoinCompany(c->index) || _local_company == c->index) ? (int)SZSP_NONE : 0); + reinit |= this->GetWidget(WID_C_SELECT_MULTIPLAYER)->SetDisplayedPlane((!_networking || !NetworkCanJoinCompany(c->index) || _local_company == c->index) ? static_cast(SZSP_NONE) : 0); this->SetWidgetDisabledState(WID_C_COMPANY_JOIN, c->is_ai); diff --git a/src/console_cmds.cpp b/src/console_cmds.cpp index 54d2616066..f6f4fe2f57 100644 --- a/src/console_cmds.cpp +++ b/src/console_cmds.cpp @@ -283,7 +283,7 @@ DEF_CONSOLE_CMD(ConResetTile) if (argc == 2) { uint32_t result; if (GetArgumentInteger(&result, argv[1])) { - DoClearSquare((TileIndex)result); + DoClearSquare(TileIndex(result)); return true; } } @@ -382,7 +382,7 @@ DEF_CONSOLE_CMD(ConScrollToTile) IConsolePrint(CC_ERROR, "Tile does not exist."); return true; } - ScrollMainWindowToTile((TileIndex)result, instant); + ScrollMainWindowToTile(TileIndex(result), instant); return true; } break; @@ -666,7 +666,7 @@ static bool ConKickOrBan(const char *argv, bool ban, const std::string &reason) uint n; if (strchr(argv, '.') == nullptr && strchr(argv, ':') == nullptr) { // banning with ID - ClientID client_id = (ClientID)atoi(argv); + ClientID client_id = static_cast(atoi(argv)); /* Don't kill the server, or the client doing the rcon. The latter can't be kicked because * kicking frees closes and subsequently free the connection related instances, which we @@ -903,7 +903,7 @@ DEF_CONSOLE_CMD(ConClientNickChange) return true; } - ClientID client_id = (ClientID)atoi(argv[1]); + ClientID client_id = static_cast(atoi(argv[1])); if (client_id == CLIENT_ID_SERVER) { IConsolePrint(CC_ERROR, "Please use the command 'name' to change your own name!"); @@ -937,7 +937,7 @@ DEF_CONSOLE_CMD(ConJoinCompany) return true; } - CompanyID company_id = (CompanyID)(atoi(argv[1]) <= MAX_COMPANIES ? atoi(argv[1]) - 1 : atoi(argv[1])); + CompanyID company_id = CompanyID(atoi(argv[1]) <= MAX_COMPANIES ? atoi(argv[1]) - 1 : atoi(argv[1])); const NetworkClientInfo *info = NetworkClientInfo::GetByClientID(_network_own_client_id); if (info == nullptr) { @@ -984,8 +984,8 @@ DEF_CONSOLE_CMD(ConMoveClient) return true; } - const NetworkClientInfo *ci = NetworkClientInfo::GetByClientID((ClientID)atoi(argv[1])); - CompanyID company_id = (CompanyID)(atoi(argv[2]) <= MAX_COMPANIES ? atoi(argv[2]) - 1 : atoi(argv[2])); + const NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(static_cast(atoi(argv[1]))); + CompanyID company_id = CompanyID(atoi(argv[2]) <= MAX_COMPANIES ? atoi(argv[2]) - 1 : atoi(argv[2])); /* check the client exists */ if (ci == nullptr) { @@ -1029,7 +1029,7 @@ DEF_CONSOLE_CMD(ConResetCompany) if (argc != 2) return false; - CompanyID index = (CompanyID)(atoi(argv[1]) - 1); + CompanyID index = CompanyID(atoi(argv[1]) - 1); /* Check valid range */ if (!Company::IsValidID(index)) { @@ -1081,7 +1081,7 @@ DEF_CONSOLE_CMD(ConNetworkReconnect) return true; } - CompanyID playas = (argc >= 2) ? (CompanyID)atoi(argv[1]) : COMPANY_SPECTATOR; + CompanyID playas = (argc >= 2) ? CompanyID(atoi(argv[1])) : COMPANY_SPECTATOR; switch (playas.base()) { case 0: playas = COMPANY_NEW_COMPANY; break; case COMPANY_SPECTATOR.base(): /* nothing to do */ break; @@ -1263,7 +1263,7 @@ DEF_CONSOLE_CMD(ConEchoC) } if (argc < 3) return false; - IConsolePrint((TextColour)Clamp(atoi(argv[1]), TC_BEGIN, TC_END - 1), argv[2]); + IConsolePrint(static_cast(Clamp(atoi(argv[1]), TC_BEGIN, TC_END - 1)), argv[2]); return true; } @@ -1423,7 +1423,7 @@ DEF_CONSOLE_CMD(ConStartAI) n++; } - AIConfig *config = AIConfig::GetConfig((CompanyID)n); + AIConfig *config = AIConfig::GetConfig(CompanyID(n)); if (argc >= 2) { config->Change(argv[1], -1, false); @@ -1474,7 +1474,7 @@ DEF_CONSOLE_CMD(ConReloadAI) return true; } - CompanyID company_id = (CompanyID)(atoi(argv[1]) - 1); + CompanyID company_id = CompanyID(atoi(argv[1]) - 1); if (!Company::IsValidID(company_id)) { IConsolePrint(CC_ERROR, "Unknown company. Company range is between 1 and {}.", MAX_COMPANIES); return true; @@ -1512,7 +1512,7 @@ DEF_CONSOLE_CMD(ConStopAI) return true; } - CompanyID company_id = (CompanyID)(atoi(argv[1]) - 1); + CompanyID company_id = CompanyID(atoi(argv[1]) - 1); if (!Company::IsValidID(company_id)) { IConsolePrint(CC_ERROR, "Unknown company. Company range is between 1 and {}.", MAX_COMPANIES); return true; @@ -1915,7 +1915,7 @@ DEF_CONSOLE_CMD(ConSayCompany) if (argc != 3) return false; - CompanyID company_id = (CompanyID)(atoi(argv[1]) - 1); + CompanyID company_id = CompanyID(atoi(argv[1]) - 1); if (!Company::IsValidID(company_id)) { IConsolePrint(CC_DEFAULT, "Unknown company. Company range is between 1 and {}.", MAX_COMPANIES); return true; @@ -2185,7 +2185,7 @@ DEF_CONSOLE_CMD(ConContent) * good for 70% of the consumed bandwidth of BaNaNaS. */ IConsolePrint(CC_ERROR, "'select all' is no longer supported since 1.11."); } else { - _network_content_client.Select((ContentID)atoi(argv[2])); + _network_content_client.Select(static_cast(atoi(argv[2]))); } return true; } @@ -2198,7 +2198,7 @@ DEF_CONSOLE_CMD(ConContent) if (StrEqualsIgnoreCase(argv[2], "all")) { _network_content_client.UnselectAll(); } else { - _network_content_client.Unselect((ContentID)atoi(argv[2])); + _network_content_client.Unselect(static_cast(atoi(argv[2]))); } return true; } @@ -2468,7 +2468,7 @@ DEF_CONSOLE_CMD(ConNewGRFProfile) if (StrStartsWithIgnoreCase(argv[1], "sel") && argc >= 3) { for (size_t argnum = 2; argnum < argc; ++argnum) { int grfnum = atoi(argv[argnum]); - if (grfnum < 1 || grfnum > (int)files.size()) { // safe cast, files.size() should not be larger than a few hundred in the most extreme cases + if (grfnum < 1 || grfnum > static_cast(files.size())) { // safe cast, files.size() should not be larger than a few hundred in the most extreme cases IConsolePrint(CC_WARNING, "GRF number {} out of range, not added.", grfnum); continue; } @@ -2490,7 +2490,7 @@ DEF_CONSOLE_CMD(ConNewGRFProfile) break; } int grfnum = atoi(argv[argnum]); - if (grfnum < 1 || grfnum > (int)files.size()) { + if (grfnum < 1 || grfnum > static_cast(files.size())) { IConsolePrint(CC_WARNING, "GRF number {} out of range, not removing.", grfnum); continue; } @@ -2623,7 +2623,7 @@ static void ConDumpRoadTypes() grfs.emplace(grfid, grf); } IConsolePrint(CC_DEFAULT, " {:02d} {} {}, Flags: {}{}{}{}{}, GRF: {:08X}, {}", - (uint)rt, + static_cast(rt), RoadTypeIsTram(rt) ? "Tram" : "Road", FormatLabel(rti->label), rti->flags.Test(RoadTypeFlag::Catenary) ? 'c' : '-', @@ -2661,7 +2661,7 @@ static void ConDumpRailTypes() grfs.emplace(grfid, grf); } IConsolePrint(CC_DEFAULT, " {:02d} {}, Flags: {}{}{}{}{}{}, GRF: {:08X}, {}", - (uint)rt, + static_cast(rt), FormatLabel(rti->label), rti->flags.Test(RailTypeFlag::Catenary) ? 'c' : '-', rti->flags.Test(RailTypeFlag::NoLevelCrossing) ? 'l' : '-', diff --git a/src/console_gui.cpp b/src/console_gui.cpp index 597f65a939..d5c0a96c98 100644 --- a/src/console_gui.cpp +++ b/src/console_gui.cpp @@ -204,7 +204,7 @@ struct IConsoleWindow : Window /* If the text is longer than the window, don't show the starting ']' */ int delta = this->width - WidgetDimensions::scaled.frametext.right - cursor_width - this->line_offset - _iconsole_cmdline.pixels - ICON_RIGHT_BORDERWIDTH; if (delta > 0) { - DrawString(WidgetDimensions::scaled.frametext.left, right, this->height - this->line_height, "]", (TextColour)CC_COMMAND, SA_LEFT | SA_FORCE); + DrawString(WidgetDimensions::scaled.frametext.left, right, this->height - this->line_height, "]", CC_COMMAND, SA_LEFT | SA_FORCE); delta = 0; } diff --git a/src/depot_gui.cpp b/src/depot_gui.cpp index 3eadefbad9..322dfa4adf 100644 --- a/src/depot_gui.cpp +++ b/src/depot_gui.cpp @@ -189,7 +189,7 @@ static void InitBlocksizeForVehicles(VehicleType type, EngineImageType image_typ } if (y > max_height) max_height = y; if (-x_offs > max_extend_left) max_extend_left = -x_offs; - if ((int)x + x_offs > max_extend_right) max_extend_right = x + x_offs; + if (static_cast(x) + x_offs > max_extend_right) max_extend_right = x + x_offs; } int min_extend = ScaleSpriteTrad(16); @@ -407,7 +407,7 @@ struct DepotWindow : Window { /* Draw all vehicles in the current row */ const Vehicle *v = this->vehicle_list[num]; this->DrawVehicleInDepot(v, cell); - cell = cell.Translate(rtl ? -(int)this->resize.step_width : (int)this->resize.step_width, 0); + cell = cell.Translate(rtl ? -static_cast(this->resize.step_width) : static_cast(this->resize.step_width), 0); } } @@ -480,7 +480,7 @@ struct DepotWindow : Window { /* Skip vehicles that are scrolled off the list */ if (this->type == VEH_TRAIN) x += this->hscroll->GetPosition(); } else { - pos -= (uint)this->vehicle_list.size(); + pos -= static_cast(this->vehicle_list.size()); *veh = this->wagon_list[pos]; /* free wagons don't have an initial loco. */ x -= ScaleSpriteTrad(VEHICLEINFO_FULL_VEHICLE_WIDTH); @@ -505,7 +505,7 @@ struct DepotWindow : Window { case VEH_SHIP: case VEH_AIRCRAFT: - if (xm <= this->flag_size.width && ym >= (uint)(GetCharacterHeight(FS_NORMAL) + WidgetDimensions::scaled.vsep_normal)) return MODE_START_STOP; + if (xm <= this->flag_size.width && ym >= static_cast(GetCharacterHeight(FS_NORMAL) + WidgetDimensions::scaled.vsep_normal)) return MODE_START_STOP; break; default: NOT_REACHED(); @@ -740,7 +740,7 @@ struct DepotWindow : Window { /* Always make it longer than the longest train, so you can attach vehicles at the end, and also see the next vertical tile separator line */ this->hscroll->SetCount(max_width + ScaleSpriteTrad(2 * VEHICLEINFO_FULL_VEHICLE_WIDTH + 1)); } else { - this->vscroll->SetCount(CeilDiv((uint)this->vehicle_list.size(), this->num_columns)); + this->vscroll->SetCount(CeilDiv(static_cast(this->vehicle_list.size()), this->num_columns)); } /* Setup disabled buttons. */ diff --git a/src/disaster_vehicle.cpp b/src/disaster_vehicle.cpp index acced3ef5a..dc2603fc84 100644 --- a/src/disaster_vehicle.cpp +++ b/src/disaster_vehicle.cpp @@ -250,7 +250,7 @@ static bool DisasterTick_Zeppeliner(DisasterVehicle *v) } } - if (v->y_pos >= (int)((Map::SizeY() + 9) * TILE_SIZE - 1)) { + if (v->y_pos >= static_cast((Map::SizeY() + 9) * TILE_SIZE - 1)) { delete v; return false; } @@ -320,7 +320,7 @@ static bool DisasterTick_Ufo(DisasterVehicle *v) /* Fly around randomly */ int x = TileX(v->dest_tile) * TILE_SIZE; int y = TileY(v->dest_tile) * TILE_SIZE; - if (Delta(x, v->x_pos) + Delta(y, v->y_pos) >= (int)TILE_SIZE) { + if (Delta(x, v->x_pos) + Delta(y, v->y_pos) >= static_cast(TILE_SIZE)) { v->direction = GetDirectionTowards(v, x, y); GetNewVehiclePosResult gp = GetNewVehiclePos(v); v->UpdatePosition(gp.x, gp.y, GetAircraftFlightLevel(v)); @@ -436,7 +436,7 @@ static bool DisasterTick_Aircraft(DisasterVehicle *v, uint16_t image_override, b GetNewVehiclePosResult gp = GetNewVehiclePos(v); v->UpdatePosition(gp.x, gp.y, GetAircraftFlightLevel(v)); - if ((leave_at_top && gp.x < (-10 * (int)TILE_SIZE)) || (!leave_at_top && gp.x > (int)(Map::SizeX() * TILE_SIZE + 9 * TILE_SIZE) - 1)) { + if ((leave_at_top && gp.x < (-10 * static_cast(TILE_SIZE))) || (!leave_at_top && gp.x > static_cast(Map::SizeX() * TILE_SIZE + 9 * TILE_SIZE) - 1)) { delete v; return false; } @@ -471,7 +471,7 @@ static bool DisasterTick_Aircraft(DisasterVehicle *v, uint16_t image_override, b int x = v->x_pos + ((leave_at_top ? -15 : 15) * TILE_SIZE); int y = v->y_pos; - if ((uint)x > Map::MaxX() * TILE_SIZE - 1) return true; + if (static_cast(x) > Map::MaxX() * TILE_SIZE - 1) return true; TileIndex tile = TileVirtXY(x, y); if (!IsTileType(tile, MP_INDUSTRY)) return true; @@ -551,7 +551,7 @@ static bool DisasterTick_Big_Ufo(DisasterVehicle *v) for (Vehicle *target : Vehicle::Iterate()) { if (target->IsGroundVehicle()) { - if (Delta(target->x_pos, v->x_pos) + Delta(target->y_pos, v->y_pos) <= 12 * (int)TILE_SIZE) { + if (Delta(target->x_pos, v->x_pos) + Delta(target->y_pos, v->y_pos) <= 12 * static_cast(TILE_SIZE)) { target->breakdown_ctr = 5; target->breakdown_delay = 0xF0; } @@ -565,13 +565,13 @@ static bool DisasterTick_Big_Ufo(DisasterVehicle *v) delete v; return false; } - DisasterVehicle *u = new DisasterVehicle(-6 * (int)TILE_SIZE, v->y_pos, DIR_SW, ST_BIG_UFO_DESTROYER, v->index); - DisasterVehicle *w = new DisasterVehicle(-6 * (int)TILE_SIZE, v->y_pos, DIR_SW, ST_BIG_UFO_DESTROYER_SHADOW); + DisasterVehicle *u = new DisasterVehicle(-6 * static_cast(TILE_SIZE), v->y_pos, DIR_SW, ST_BIG_UFO_DESTROYER, v->index); + DisasterVehicle *w = new DisasterVehicle(-6 * static_cast(TILE_SIZE), v->y_pos, DIR_SW, ST_BIG_UFO_DESTROYER_SHADOW); u->SetNext(w); } else if (v->state == 0) { int x = TileX(v->dest_tile) * TILE_SIZE; int y = TileY(v->dest_tile) * TILE_SIZE; - if (Delta(x, v->x_pos) + Delta(y, v->y_pos) >= (int)TILE_SIZE) { + if (Delta(x, v->x_pos) + Delta(y, v->y_pos) >= static_cast(TILE_SIZE)) { v->direction = GetDirectionTowards(v, x, y); GetNewVehiclePosResult gp = GetNewVehiclePos(v); v->UpdatePosition(gp.x, gp.y, GetAircraftFlightLevel(v)); @@ -628,14 +628,14 @@ static bool DisasterTick_Big_Ufo_Destroyer(DisasterVehicle *v) GetNewVehiclePosResult gp = GetNewVehiclePos(v); v->UpdatePosition(gp.x, gp.y, GetAircraftFlightLevel(v)); - if (gp.x > (int)(Map::SizeX() * TILE_SIZE + 9 * TILE_SIZE) - 1) { + if (gp.x > static_cast(Map::SizeX() * TILE_SIZE + 9 * TILE_SIZE) - 1) { delete v; return false; } if (v->state == 0) { Vehicle *u = Vehicle::Get(v->big_ufo_destroyer_target); - if (Delta(v->x_pos, u->x_pos) > (int)TILE_SIZE) return true; + if (Delta(v->x_pos, u->x_pos) > static_cast(TILE_SIZE)) return true; v->state = 1; CreateEffectVehicleRel(u, 0, 7, 8, EV_EXPLOSION_LARGE); @@ -806,7 +806,7 @@ static void Disaster_Helicopter_Init() if (found == nullptr) return; - int x = -16 * (int)TILE_SIZE; + int x = -16 * static_cast(TILE_SIZE); int y = TileY(found->location.tile) * TILE_SIZE + 37; DisasterVehicle *v = new DisasterVehicle(x, y, DIR_SW, ST_HELICOPTER); @@ -888,7 +888,7 @@ static void Disaster_CoalMine_Init() { TileIndex tile = i->location.tile; - TileIndexDiff step = TileOffsByDiagDir((DiagDirection)GB(Random(), 0, 2)); + TileIndexDiff step = TileOffsByDiagDir(static_cast(GB(Random(), 0, 2))); for (uint n = 0; n < 30; n++) { DisasterClearSquare(tile); diff --git a/src/dock_gui.cpp b/src/dock_gui.cpp index 2175713df5..10e2f015a3 100644 --- a/src/dock_gui.cpp +++ b/src/dock_gui.cpp @@ -189,7 +189,7 @@ struct BuildDocksToolbarWindow : Window { default: return; } - this->last_clicked_widget = (DockToolbarWidgets)widget; + this->last_clicked_widget = static_cast(widget); } void OnPlaceObject([[maybe_unused]] Point pt, TileIndex tile) override diff --git a/src/dropdown.cpp b/src/dropdown.cpp index 64eb8e724c..2f21650e85 100644 --- a/src/dropdown.cpp +++ b/src/dropdown.cpp @@ -154,7 +154,7 @@ struct DropdownWindow : Window { if (desired.height < available_height) return; /* If the dropdown doesn't fully fit, we a need a dropdown. */ - uint avg_height = list.height / (uint)this->list.size(); + uint avg_height = list.height / static_cast(this->list.size()); uint rows = std::max((available_height - WidgetDimensions::scaled.dropdownlist.Vertical()) / avg_height, 1U); desired.width = std::max(list.width, desired.width - NWidgetScrollbar::GetVerticalDimension().width); @@ -194,7 +194,7 @@ struct DropdownWindow : Window { if (_current_text_dir == TD_RTL) { /* In case the list is wider than the parent button, the list should be right aligned to the button and overflow to the left. */ - this->position.x = button_rect.right + 1 - (int)(widget_dim.width + (list_dim.height > widget_dim.height ? NWidgetScrollbar::GetVerticalDimension().width : 0)); + this->position.x = button_rect.right + 1 - static_cast(widget_dim.width + (list_dim.height > widget_dim.height ? NWidgetScrollbar::GetVerticalDimension().width : 0)); } else { this->position.x = button_rect.left; } diff --git a/src/economy.cpp b/src/economy.cpp index 18af650990..c1c5ff5786 100644 --- a/src/economy.cpp +++ b/src/economy.cpp @@ -80,7 +80,7 @@ INSTANTIATE_POOL_METHODS(CargoPayment) */ static inline int32_t BigMulS(const int32_t a, const int32_t b, const uint8_t shift) { - return (int32_t)((int64_t)a * (int64_t)b >> shift); + return static_cast(static_cast(a) * static_cast(b) >> shift); } typedef std::vector SmallIndustryList; @@ -745,7 +745,7 @@ bool AddInflation(bool check_year) void RecomputePrices() { /* Setup maximum loan as a rounded down multiple of LOAN_INTERVAL. */ - _economy.max_loan = ((uint64_t)_settings_game.difficulty.max_loan * _economy.inflation_prices >> 16) / LOAN_INTERVAL * LOAN_INTERVAL; + _economy.max_loan = (static_cast(_settings_game.difficulty.max_loan) * _economy.inflation_prices >> 16) / LOAN_INTERVAL * LOAN_INTERVAL; /* Setup price bases */ for (Price i = PR_BEGIN; i < PR_END; i++) { @@ -798,7 +798,7 @@ void RecomputePrices() /* Setup cargo payment */ for (CargoSpec *cs : CargoSpec::Iterate()) { - cs->current_payment = (cs->initial_payment * (int64_t)_economy.inflation_payment) >> 16; + cs->current_payment = (cs->initial_payment * static_cast(_economy.inflation_payment)) >> 16; } SetWindowClassesDirty(WC_BUILD_VEHICLE); @@ -858,7 +858,7 @@ static void HandleEconomyFluctuations() } if (_economy.fluct == 0) { - _economy.fluct = -(int)GB(Random(), 0, 2); + _economy.fluct = -static_cast(GB(Random(), 0, 2)); AddNewsItem(GetEncodedString(STR_NEWS_BEGIN_OF_RECESSION), NewsType::Economy, NewsStyle::Normal, {}); } else if (_economy.fluct == -12) { _economy.fluct = GB(Random(), 0, 8) + 312; @@ -1898,7 +1898,7 @@ static void LoadUnloadVehicle(Vehicle *front) * if _settings_client.gui.loading_indicators == 1, _local_company must be the owner or must be a spectator to show ind., so 1 > 0 * if _settings_client.gui.loading_indicators == 0, do not display indicators ... 0 is never greater than anything */ - if (_game_mode != GM_MENU && (_settings_client.gui.loading_indicators > (uint)(front->owner != _local_company && _local_company != COMPANY_SPECTATOR))) { + if (_game_mode != GM_MENU && (_settings_client.gui.loading_indicators > static_cast(front->owner != _local_company && _local_company != COMPANY_SPECTATOR))) { StringID percent_up_down = STR_NULL; int percent = CalcPercentVehicleFilled(front, &percent_up_down); if (front->fill_percent_te_id == INVALID_TE_ID) { diff --git a/src/elrail.cpp b/src/elrail.cpp index a7912abb0f..c24bcc467d 100644 --- a/src/elrail.cpp +++ b/src/elrail.cpp @@ -74,7 +74,7 @@ */ static inline TLG GetTLG(TileIndex t) { - return (TLG)((HasBit(TileX(t), 0) << 1) + HasBit(TileY(t), 0)); + return static_cast((HasBit(TileX(t), 0) << 1) + HasBit(TileY(t), 0)); } /** @@ -151,7 +151,7 @@ static TrackBits MaskWireBits(TileIndex t, TrackBits tracks) if (tracks == TRACK_BIT_CROSS || !TracksOverlap(tracks)) { /* If the tracks form either a diagonal crossing or don't overlap, both * trackdirs have to be marked to mask the corresponding track bit. */ - mask = ~(TrackBits)((neighbour_tdb & (neighbour_tdb >> 8)) & TRACK_BIT_MASK); + mask = ~static_cast((neighbour_tdb & (neighbour_tdb >> 8)) & TRACK_BIT_MASK); /* If that results in no masked tracks and it is not a diagonal crossing, * require only one marked trackdir to mask. */ if (tracks != TRACK_BIT_CROSS && (mask & TRACK_BIT_MASK) == TRACK_BIT_MASK) mask = ~TrackdirBitsToTrackBits(neighbour_tdb); @@ -163,7 +163,7 @@ static TrackBits MaskWireBits(TileIndex t, TrackBits tracks) if ((neighbour_tdb & TRACKDIR_BIT_X_NE) == 0 || (neighbour_tdb & TRACKDIR_BIT_X_SW) == 0) mask |= TRACK_BIT_X; if ((neighbour_tdb & TRACKDIR_BIT_Y_NW) == 0 || (neighbour_tdb & TRACKDIR_BIT_Y_SE) == 0) mask |= TRACK_BIT_Y; /* If that still is not enough, require both trackdirs for any track. */ - if ((tracks & mask) == TRACK_BIT_NONE) mask = ~(TrackBits)((neighbour_tdb & (neighbour_tdb >> 8)) & TRACK_BIT_MASK); + if ((tracks & mask) == TRACK_BIT_NONE) mask = ~static_cast((neighbour_tdb & (neighbour_tdb >> 8)) & TRACK_BIT_MASK); } } @@ -516,7 +516,7 @@ void DrawRailCatenaryOnBridge(const TileInfo *ti) Axis axis = GetBridgeAxis(ti->tile); TLG tlg = GetTLG(ti->tile); - RailCatenarySprite offset = (RailCatenarySprite)(axis == AXIS_X ? 0 : WIRE_Y_FLAT_BOTH - WIRE_X_FLAT_BOTH); + RailCatenarySprite offset = static_cast(axis == AXIS_X ? 0 : WIRE_Y_FLAT_BOTH - WIRE_X_FLAT_BOTH); if ((length % 2) && num == length) { /* Draw the "short" wire on the southern end of the bridge diff --git a/src/engine.cpp b/src/engine.cpp index 650f491d79..d291071aba 100644 --- a/src/engine.cpp +++ b/src/engine.cpp @@ -676,7 +676,7 @@ void CalcEngineReliability(Engine *e, bool new_month) e->reliability = e->reliability_max; } else if ((age -= e->duration_phase_2) < e->duration_phase_3) { uint max = e->reliability_max; - e->reliability = (int)age * (int)(e->reliability_final - max) / e->duration_phase_3 + max; + e->reliability = static_cast(age) * static_cast(e->reliability_final - max) / e->duration_phase_3 + max; } else { /* time's up for this engine. * We will now completely retire this design */ @@ -737,7 +737,7 @@ void StartupOneEngine(Engine *e, const TimerGameCalendar::YearMonthDay &aging_ym /* Don't randomise the start-date in the first two years after gamestart to ensure availability * of engines in early starting games. * Note: TTDP uses fixed 1922 */ - e->intro_date = ei->base_intro <= TimerGameCalendar::ConvertYMDToDate(_settings_game.game_creation.starting_year + 2, 0, 1) ? ei->base_intro : (TimerGameCalendar::Date)GB(r, 0, 9) + ei->base_intro; + e->intro_date = ei->base_intro <= TimerGameCalendar::ConvertYMDToDate(_settings_game.game_creation.starting_year + 2, 0, 1) ? ei->base_intro : TimerGameCalendar::Date(GB(r, 0, 9)) + ei->base_intro; if (e->intro_date <= TimerGameCalendar::date) { TimerGameCalendar::YearMonthDay intro_ymd = TimerGameCalendar::ConvertDateToYMD(e->intro_date); int aging_months = aging_ymd.year.base() * 12 + aging_ymd.month; @@ -778,7 +778,7 @@ void StartupOneEngine(Engine *e, const TimerGameCalendar::YearMonthDay &aging_ym e->reliability_final = GB(r, 16, 14) + RELIABILITY_FINAL; e->duration_phase_1 = GB(r, 0, 5) + 7; - e->duration_phase_2 = std::max(0, int(GB(r, 5, 4)) + ei->base_life.base() * 12 - 96); + e->duration_phase_2 = std::max(0, static_cast(GB(r, 5, 4)) + ei->base_life.base() * 12 - 96); e->duration_phase_3 = GB(r, 9, 7) + 120; RestoreRandomSeeds(saved_seeds); diff --git a/src/fontcache/freetypefontcache.cpp b/src/fontcache/freetypefontcache.cpp index 04ddc3e21f..9dfca84eed 100644 --- a/src/fontcache/freetypefontcache.cpp +++ b/src/fontcache/freetypefontcache.cpp @@ -69,7 +69,7 @@ void FreeTypeFontCache::SetFontSize(int pixels) int scaled_height = ScaleGUITrad(FontCache::GetDefaultFontHeight(this->fs)); pixels = scaled_height; - TT_Header *head = (TT_Header *)FT_Get_Sfnt_Table(this->face, ft_sfnt_head); + TT_Header *head = static_cast(FT_Get_Sfnt_Table(this->face, ft_sfnt_head)); if (head != nullptr) { /* Font height is minimum height plus the difference between the default * height for this font size and the small size. */ @@ -235,8 +235,8 @@ const Sprite *FreeTypeFontCache::InternalGetGlyph(GlyphID key, bool aa) /* 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; - uint width = std::max(1U, (uint)slot->bitmap.width + shadow); - uint height = std::max(1U, (uint)slot->bitmap.rows + shadow); + uint width = std::max(1U, static_cast(slot->bitmap.width) + shadow); + uint height = std::max(1U, static_cast(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"); @@ -255,8 +255,8 @@ const Sprite *FreeTypeFontCache::InternalGetGlyph(GlyphID key, bool aa) /* Draw shadow for medium size */ if (this->fs == FS_NORMAL && !aa) { - for (uint y = 0; y < (uint)slot->bitmap.rows; y++) { - for (uint x = 0; x < (uint)slot->bitmap.width; x++) { + for (uint y = 0; y < static_cast(slot->bitmap.rows); y++) { + for (uint x = 0; x < static_cast(slot->bitmap.width); x++) { if (HasBit(slot->bitmap.buffer[(x / 8) + y * slot->bitmap.pitch], 7 - (x % 8))) { sprite.data[shadow + x + (shadow + y) * sprite.width].m = SHADOW_COLOUR; sprite.data[shadow + x + (shadow + y) * sprite.width].a = 0xFF; @@ -265,8 +265,8 @@ const Sprite *FreeTypeFontCache::InternalGetGlyph(GlyphID key, bool aa) } } - for (uint y = 0; y < (uint)slot->bitmap.rows; y++) { - for (uint x = 0; x < (uint)slot->bitmap.width; x++) { + for (uint y = 0; y < static_cast(slot->bitmap.rows); y++) { + for (uint x = 0; x < static_cast(slot->bitmap.width); x++) { if (aa ? (slot->bitmap.buffer[x + y * slot->bitmap.pitch] > 0) : HasBit(slot->bitmap.buffer[(x / 8) + y * slot->bitmap.pitch], 7 - (x % 8))) { sprite.data[x + y * sprite.width].m = FACE_COLOUR; sprite.data[x + y * sprite.width].a = aa ? slot->bitmap.buffer[x + y * slot->bitmap.pitch] : 0xFF; diff --git a/src/framerate_gui.cpp b/src/framerate_gui.cpp index 075af39c0a..0220437b8b 100644 --- a/src/framerate_gui.cpp +++ b/src/framerate_gui.cpp @@ -177,7 +177,7 @@ namespace { } if (total == 0 || count == 0) return 0; - return (double)count * TIMESTAMP_PRECISION / total; + return static_cast(count) * TIMESTAMP_PRECISION / total; } }; @@ -232,7 +232,7 @@ namespace { static TimingMeasurement GetPerformanceTimer() { using namespace std::chrono; - return (TimingMeasurement)time_point_cast(high_resolution_clock::now()).time_since_epoch().count(); + return static_cast(time_point_cast(high_resolution_clock::now()).time_since_epoch().count()); } @@ -418,7 +418,7 @@ struct FramerateWindow : Window { { const double threshold_good = target * 0.95; const double threshold_bad = target * 2 / 3; - this->value = (uint32_t)(value * 100); + this->value = static_cast(value * 100); this->strid = (value > threshold_good) ? STR_FRAMERATE_FPS_GOOD : (value < threshold_bad) ? STR_FRAMERATE_FPS_BAD : STR_FRAMERATE_FPS_WARN; } @@ -426,7 +426,7 @@ struct FramerateWindow : Window { { const double threshold_good = target / 3; const double threshold_bad = target; - this->value = (uint32_t)(value * 100); + this->value = static_cast(value * 100); this->strid = (value < threshold_good) ? STR_FRAMERATE_MS_GOOD : (value > threshold_bad) ? STR_FRAMERATE_MS_BAD : STR_FRAMERATE_MS_WARN; } @@ -786,7 +786,7 @@ struct FrametimeGraphWindow : Window { TIMESTAMP_PRECISION / 200, }; for (const auto &sc : vscales) { - if (range < sc) this->vertical_scale = (int)sc; + if (range < sc) this->vertical_scale = static_cast(sc); } } @@ -859,16 +859,16 @@ struct FrametimeGraphWindow : Window { const auto ×tamps = _pf_data[this->element].timestamps; int point = _pf_data[this->element].prev_index; - const int x_zero = r.right - (int)this->graph_size.width; + const int x_zero = r.right - static_cast(this->graph_size.width); const int x_max = r.right; - const int y_zero = r.top + (int)this->graph_size.height; + const int y_zero = r.top + static_cast(this->graph_size.height); const int y_max = r.top; const int c_grid = PC_DARK_GREY; const int c_lines = PC_BLACK; const int c_peak = PC_DARK_RED; - const TimingMeasurement draw_horz_scale = (TimingMeasurement)this->horizontal_scale * TIMESTAMP_PRECISION / 2; - const TimingMeasurement draw_vert_scale = (TimingMeasurement)this->vertical_scale; + const TimingMeasurement draw_horz_scale = static_cast(this->horizontal_scale) * TIMESTAMP_PRECISION / 2; + const TimingMeasurement draw_vert_scale = static_cast(this->vertical_scale); /* Number of \c horizontal_scale units in each horizontal division */ const uint horz_div_scl = (this->horizontal_scale <= 20) ? 1 : 10; @@ -879,10 +879,10 @@ struct FrametimeGraphWindow : Window { /* Draw division lines and labels for the vertical axis */ for (uint division = 0; division < vert_divisions; division++) { - int y = Scinterlate(y_zero, y_max, 0, (int)vert_divisions, (int)division); + int y = Scinterlate(y_zero, y_max, 0, static_cast(vert_divisions), static_cast(division)); GfxDrawLine(x_zero, y, x_max, y, c_grid); if (division % 2 == 0) { - if ((TimingMeasurement)this->vertical_scale > TIMESTAMP_PRECISION) { + if (static_cast(this->vertical_scale) > TIMESTAMP_PRECISION) { DrawString(r.left, x_zero - 2, y - GetCharacterHeight(FS_SMALL), GetString(STR_FRAMERATE_GRAPH_SECONDS, this->vertical_scale * division / 10 / TIMESTAMP_PRECISION), TC_GREY, SA_RIGHT | SA_FORCE, false, FS_SMALL); @@ -895,7 +895,7 @@ struct FrametimeGraphWindow : Window { } /* Draw division lines and labels for the horizontal axis */ for (uint division = horz_divisions; division > 0; division--) { - int x = Scinterlate(x_zero, x_max, 0, (int)horz_divisions, (int)horz_divisions - (int)division); + int x = Scinterlate(x_zero, x_max, 0, static_cast(horz_divisions), static_cast(horz_divisions) - static_cast(division)); GfxDrawLine(x, y_max, x, y_zero, c_grid); if (division % 2 == 0) { DrawString(x, x_max, y_zero + 2, @@ -907,7 +907,7 @@ struct FrametimeGraphWindow : Window { /* Position of last rendered data point */ Point lastpoint = { x_max, - (int)Scinterlate(y_zero, y_max, 0, this->vertical_scale, durations[point]) + static_cast(Scinterlate(y_zero, y_max, 0, this->vertical_scale, durations[point])) }; /* Timestamp of last rendered data point */ TimingMeasurement lastts = timestamps[point]; @@ -937,8 +937,8 @@ struct FrametimeGraphWindow : Window { /* Draw line from previous point to new point */ Point newpoint = { - (int)Scinterlate(x_zero, x_max, 0, (int64_t)draw_horz_scale, (int64_t)draw_horz_scale - (int64_t)time_sum), - (int)Scinterlate(y_zero, y_max, 0, (int64_t)draw_vert_scale, (int64_t)value) + static_cast(Scinterlate(x_zero, x_max, 0, static_cast(draw_horz_scale), static_cast(draw_horz_scale) - static_cast(time_sum))), + static_cast(Scinterlate(y_zero, y_max, 0, static_cast(draw_vert_scale), static_cast(value))) }; if (newpoint.x > lastpoint.x) continue; // don't draw backwards GfxDrawLine(lastpoint.x, lastpoint.y, newpoint.x, newpoint.y, c_lines); @@ -955,11 +955,11 @@ struct FrametimeGraphWindow : Window { /* If the peak value is significantly larger than the average, mark and label it */ if (points_drawn > 0 && peak_value > TIMESTAMP_PRECISION / 100 && 2 * peak_value > 3 * value_sum / points_drawn) { - TextColour tc_peak = (TextColour)(TC_IS_PALETTE_COLOUR | c_peak); + TextColour tc_peak = static_cast(TC_IS_PALETTE_COLOUR | c_peak); GfxFillRect(peak_point.x - 1, peak_point.y - 1, peak_point.x + 1, peak_point.y + 1, c_peak); uint64_t value = peak_value * 1000 / TIMESTAMP_PRECISION; int label_y = std::max(y_max, peak_point.y - GetCharacterHeight(FS_SMALL)); - if (peak_point.x - x_zero > (int)this->graph_size.width / 2) { + if (peak_point.x - x_zero > static_cast(this->graph_size.width) / 2) { DrawString(x_zero, peak_point.x - 2, label_y, GetString(STR_FRAMERATE_GRAPH_MILLISECONDS, value), tc_peak, SA_RIGHT | SA_FORCE, false, FS_SMALL); } else { DrawString(peak_point.x + 2, x_max, label_y, GetString(STR_FRAMERATE_GRAPH_MILLISECONDS, value), tc_peak, SA_LEFT | SA_FORCE, false, FS_SMALL); diff --git a/src/game/game_gui.cpp b/src/game/game_gui.cpp index 308d14fdc5..51f361ff95 100644 --- a/src/game/game_gui.cpp +++ b/src/game/game_gui.cpp @@ -226,19 +226,19 @@ struct GSConfigWindow : public Window { if (widget >= WID_GSC_TEXTFILE && widget < WID_GSC_TEXTFILE + TFT_CONTENT_END) { if (GameConfig::GetConfig() == nullptr) return; - ShowScriptTextfileWindow((TextfileType)(widget - WID_GSC_TEXTFILE), (CompanyID)OWNER_DEITY); + ShowScriptTextfileWindow(static_cast(widget - WID_GSC_TEXTFILE), CompanyID(OWNER_DEITY)); return; } switch (widget) { case WID_GSC_GSLIST: { this->InvalidateData(); - if (click_count > 1 && _game_mode != GM_NORMAL) ShowScriptListWindow((CompanyID)OWNER_DEITY, _ctrl_pressed); + if (click_count > 1 && _game_mode != GM_NORMAL) ShowScriptListWindow(CompanyID(OWNER_DEITY), _ctrl_pressed); break; } case WID_GSC_CHANGE: // choose other Game Script - ShowScriptListWindow((CompanyID)OWNER_DEITY, _ctrl_pressed); + ShowScriptListWindow(CompanyID(OWNER_DEITY), _ctrl_pressed); break; case WID_GSC_CONTENT_DOWNLOAD: @@ -394,7 +394,7 @@ struct GSConfigWindow : public Window { const GameConfig *config = GameConfig::GetConfig(); this->SetWidgetDisabledState(WID_GSC_OPEN_URL, config->GetInfo() == nullptr || config->GetInfo()->GetURL().empty()); for (TextfileType tft = TFT_CONTENT_BEGIN; tft < TFT_CONTENT_END; tft++) { - this->SetWidgetDisabledState(WID_GSC_TEXTFILE + tft, !config->GetTextfile(tft, (CompanyID)OWNER_DEITY).has_value()); + this->SetWidgetDisabledState(WID_GSC_TEXTFILE + tft, !config->GetTextfile(tft, CompanyID(OWNER_DEITY)).has_value()); } this->RebuildVisibleSettings(); this->CloseChildWindows(WC_DROPDOWN_MENU); diff --git a/src/game/game_info.cpp b/src/game/game_info.cpp index 1045f01d82..276859b402 100644 --- a/src/game/game_info.cpp +++ b/src/game/game_info.cpp @@ -50,7 +50,7 @@ template <> SQInteger PushClassName(HSQUIRRELVM vm) { /* Get the GameInfo */ SQUserPointer instance = nullptr; if (SQ_FAILED(sq_getinstanceup(vm, 2, &instance, nullptr)) || instance == nullptr) return sq_throwerror(vm, "Pass an instance of a child class of GameInfo to RegisterGame"); - GameInfo *info = (GameInfo *)instance; + GameInfo *info = static_cast(instance); SQInteger res = ScriptInfo::Constructor(vm, info); if (res != 0) return res; diff --git a/src/game/game_text.cpp b/src/game/game_text.cpp index bf8192ed97..92bac84e26 100644 --- a/src/game/game_text.cpp +++ b/src/game/game_text.cpp @@ -136,7 +136,7 @@ struct TranslationWriter : LanguageWriter { void Write(const uint8_t *buffer, size_t length) override { - this->strings.emplace_back((const char *)buffer, length); + this->strings.emplace_back(reinterpret_cast(buffer), length); } }; @@ -154,7 +154,7 @@ struct StringNameWriter : HeaderWriter { void WriteStringID(const std::string &name, int stringid) override { - if (stringid == (int)this->strings.size()) this->strings.emplace_back(name); + if (stringid == static_cast(this->strings.size())) this->strings.emplace_back(name); } void Finalise(const StringData &) override diff --git a/src/gamelog.cpp b/src/gamelog.cpp index c99854a4af..becccc3dc9 100644 --- a/src/gamelog.cpp +++ b/src/gamelog.cpp @@ -401,7 +401,7 @@ void Gamelog::Oldver() assert(this->action_type == GLAT_LOAD); this->Change(std::make_unique(_savegame_type, - (_savegame_type == SGT_OTTD ? ((uint32_t)_sl_version << 8 | _sl_minor_version) : _ttdp_version))); + (_savegame_type == SGT_OTTD ? (static_cast(_sl_version) << 8 | _sl_minor_version) : _ttdp_version))); } /** @@ -655,7 +655,7 @@ void Gamelog::GRFUpdate(const GRFConfigList &oldc, const GRFConfigList &newc) /* GRF was moved down */ this->GRFMove(ol[o++]->ident.grfid, ni); } else { - this->GRFMove(nl[n++]->ident.grfid, -(int)oi); + this->GRFMove(nl[n++]->ident.grfid, -static_cast(oi)); } } else { if (og.ident.md5sum != ng.ident.md5sum) { diff --git a/src/genworld_gui.cpp b/src/genworld_gui.cpp index 190119459f..dc017787ba 100644 --- a/src/genworld_gui.cpp +++ b/src/genworld_gui.cpp @@ -560,7 +560,7 @@ struct GenerateLandscapeWindow : public Window { void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override { - Dimension d{0, (uint)GetCharacterHeight(FS_NORMAL)}; + Dimension d{0, static_cast(GetCharacterHeight(FS_NORMAL))}; std::span strs; switch (widget) { case WID_GL_TEMPERATE: case WID_GL_ARCTIC: @@ -860,7 +860,7 @@ struct GenerateLandscapeWindow : public Window { case WID_GL_HEIGHTMAP_ROTATION_PULLDOWN: _settings_newgame.game_creation.heightmap_rotation = index; break; case WID_GL_TOWN_PULLDOWN: - if ((uint)index == CUSTOM_TOWN_NUMBER_DIFFICULTY) { + if (static_cast(index) == CUSTOM_TOWN_NUMBER_DIFFICULTY) { this->widget_id = widget; ShowQueryString(GetString(STR_JUST_INT, _settings_newgame.game_creation.custom_town_number), STR_MAPGEN_NUMBER_OF_TOWNS, 5, this, CS_NUMERAL, {}); } @@ -875,7 +875,7 @@ struct GenerateLandscapeWindow : public Window { break; case WID_GL_INDUSTRY_PULLDOWN: - if ((uint)index == ID_CUSTOM) { + if (static_cast(index) == ID_CUSTOM) { this->widget_id = widget; ShowQueryString(GetString(STR_JUST_INT, _settings_newgame.game_creation.custom_industry_number), STR_MAPGEN_NUMBER_OF_INDUSTRIES, 5, this, CS_NUMERAL, {}); } @@ -883,7 +883,7 @@ struct GenerateLandscapeWindow : public Window { break; case WID_GL_TERRAIN_PULLDOWN: { - if ((uint)index == CUSTOM_TERRAIN_TYPE_NUMBER_DIFFICULTY) { + if (static_cast(index) == CUSTOM_TERRAIN_TYPE_NUMBER_DIFFICULTY) { this->widget_id = widget; ShowQueryString(GetString(STR_JUST_INT, _settings_newgame.game_creation.custom_terrain_type), STR_MAPGEN_TERRAIN_TYPE_QUERY_CAPT, 4, this, CS_NUMERAL, {}); } @@ -892,7 +892,7 @@ struct GenerateLandscapeWindow : public Window { } case WID_GL_WATER_PULLDOWN: { - if ((uint)index == CUSTOM_SEA_LEVEL_NUMBER_DIFFICULTY) { + if (static_cast(index) == CUSTOM_SEA_LEVEL_NUMBER_DIFFICULTY) { this->widget_id = widget; ShowQueryString(GetString(STR_JUST_INT, _settings_newgame.game_creation.custom_sea_level), STR_MAPGEN_SEA_LEVEL, 3, this, CS_NUMERAL, {}); } diff --git a/src/gfx.cpp b/src/gfx.cpp index 21dfc75292..a2ced1aea6 100644 --- a/src/gfx.cpp +++ b/src/gfx.cpp @@ -141,7 +141,7 @@ void GfxFillRect(int left, int top, int right, int bottom, int colour, FillRectM switch (mode) { default: // FILLRECT_OPAQUE - blitter->DrawRect(dst, right, bottom, (uint8_t)colour); + blitter->DrawRect(dst, right, bottom, static_cast(colour)); break; case FILLRECT_RECOLOUR: @@ -151,7 +151,7 @@ void GfxFillRect(int left, int top, int right, int bottom, int colour, FillRectM case FILLRECT_CHECKER: { uint8_t bo = (oleft - left + dpi->left + otop - top + dpi->top) & 1; do { - for (int i = (bo ^= 1); i < right; i += 2) blitter->SetPixel(dst, i, 0, (uint8_t)colour); + for (int i = (bo ^= 1); i < right; i += 2) blitter->SetPixel(dst, i, 0, static_cast(colour)); dst = blitter->MoveTo(dst, 0, 1); } while (--bottom > 0); break; @@ -277,7 +277,7 @@ void GfxFillPolygon(const std::vector &shape, int colour, FillRectMode mo void *dst = blitter->MoveTo(dpi->dst_ptr, x1, y); switch (mode) { default: // FILLRECT_OPAQUE - blitter->DrawRect(dst, x2 - x1, 1, (uint8_t)colour); + blitter->DrawRect(dst, x2 - x1, 1, static_cast(colour)); break; case FILLRECT_RECOLOUR: blitter->DrawColourMappingRect(dst, x2 - x1, 1, GB(colour, 0, PALETTE_WIDTH)); @@ -286,7 +286,7 @@ void GfxFillPolygon(const std::vector &shape, int colour, FillRectMode mo /* Fill every other pixel, offset such that the sum of filled pixels' X and Y coordinates is odd. * This creates a checkerboard effect. */ for (int x = (x1 + y) & 1; x < x2 - x1; x += 2) { - blitter->SetPixel(dst, x, 0, (uint8_t)colour); + blitter->SetPixel(dst, x, 0, static_cast(colour)); } break; } @@ -327,7 +327,7 @@ static inline void GfxDoDrawLine(void *video, int x, int y, int x2, int y2, int int grade_x = x2 - x; /* Clipping rectangle. Slightly extended so we can ignore the width of the line. */ - int extra = (int)CeilDiv(3 * width, 4); // not less then "width * sqrt(2) / 2" + int extra = static_cast(CeilDiv(3 * width, 4)); // not less then "width * sqrt(2) / 2" Rect clip = { -extra, -extra, screen_width - 1 + extra, screen_height - 1 + extra }; /* prevent integer overflows. */ @@ -476,7 +476,7 @@ static void SetColourRemap(TextColour colour) bool raw_colour = (colour & TC_IS_PALETTE_COLOUR) != 0; colour &= ~(TC_NO_SHADE | TC_IS_PALETTE_COLOUR | TC_FORCED); - _string_colourremap[1] = raw_colour ? (uint8_t)colour : _string_colourmap[colour]; + _string_colourremap[1] = raw_colour ? static_cast(colour) : _string_colourmap[colour]; _string_colourremap[2] = no_shade ? 0 : 1; _colour_remap_ptr = _string_colourremap; } @@ -729,7 +729,7 @@ int GetStringHeight(StringID str, int maxw) int GetStringLineCount(std::string_view str, int maxw) { Layouter layout(str, maxw); - return (uint)layout.size(); + return static_cast(layout.size()); } /** @@ -740,7 +740,7 @@ int GetStringLineCount(std::string_view str, int maxw) */ Dimension GetStringMultiLineBoundingBox(StringID str, const Dimension &suggestion) { - Dimension box = {suggestion.width, (uint)GetStringHeight(str, suggestion.width)}; + Dimension box = {suggestion.width, static_cast(GetStringHeight(str, suggestion.width))}; return box; } @@ -752,7 +752,7 @@ Dimension GetStringMultiLineBoundingBox(StringID str, const Dimension &suggestio */ Dimension GetStringMultiLineBoundingBox(std::string_view str, const Dimension &suggestion, FontSize fontsize) { - Dimension box = {suggestion.width, (uint)GetStringHeight(str, suggestion.width, fontsize)}; + Dimension box = {suggestion.width, static_cast(GetStringHeight(str, suggestion.width, fontsize))}; return box; } @@ -967,7 +967,7 @@ void DrawSpriteViewport(SpriteID img, PaletteID pal, int x, int y, const SubSpri GfxMainBlitterViewport(GetSprite(real_sprite, SpriteType::Normal), x, y, pal == PALETTE_TO_TRANSPARENT ? BlitterMode::Transparent : BlitterMode::TransparentRemap, sub, real_sprite); } else if (pal != PAL_NONE) { if (HasBit(pal, PALETTE_TEXT_RECOLOUR)) { - SetColourRemap((TextColour)GB(pal, 0, PALETTE_WIDTH)); + SetColourRemap(static_cast(GB(pal, 0, PALETTE_WIDTH))); } else { _colour_remap_ptr = GetNonSprite(GB(pal, 0, PALETTE_WIDTH), SpriteType::Recolour) + 1; } @@ -995,7 +995,7 @@ void DrawSprite(SpriteID img, PaletteID pal, int x, int y, const SubSprite *sub, GfxMainBlitter(GetSprite(real_sprite, SpriteType::Normal), x, y, pal == PALETTE_TO_TRANSPARENT ? BlitterMode::Transparent : BlitterMode::TransparentRemap, sub, real_sprite, zoom); } else if (pal != PAL_NONE) { if (HasBit(pal, PALETTE_TEXT_RECOLOUR)) { - SetColourRemap((TextColour)GB(pal, 0, PALETTE_WIDTH)); + SetColourRemap(static_cast(GB(pal, 0, PALETTE_WIDTH))); } else { _colour_remap_ptr = GetNonSprite(GB(pal, 0, PALETTE_WIDTH), SpriteType::Recolour) + 1; } @@ -1126,7 +1126,7 @@ static void GfxBlitter(const Sprite * const sprite, int x, int y, BlitterMode mo if (topleft <= clicked && clicked <= bottomright) { uint offset = (((size_t)clicked - (size_t)topleft) / (blitter->GetScreenDepth() / 8)) % bp.pitch; - if (offset < (uint)bp.width) { + if (offset < static_cast(bp.width)) { include(_newgrf_debug_sprite_picker.sprites, sprite_id); } } diff --git a/src/gfx_layout.cpp b/src/gfx_layout.cpp index b3b5138f3e..2ae505c6fa 100644 --- a/src/gfx_layout.cpp +++ b/src/gfx_layout.cpp @@ -87,13 +87,13 @@ static inline void GetLayouter(Layouter::LineCacheItem &line, std::string_view s /* Caller should already have filtered out these characters. */ NOT_REACHED(); } else if (c >= SCC_BLUE && c <= SCC_BLACK) { - state.SetColour((TextColour)(c - SCC_BLUE)); + state.SetColour(static_cast(c - SCC_BLUE)); } else if (c == SCC_PUSH_COLOUR) { state.PushColour(); } else if (c == SCC_POP_COLOUR) { state.PopColour(); } else if (c >= SCC_FIRST_FONT && c <= SCC_LAST_FONT) { - state.SetFontSize((FontSize)(c - SCC_FIRST_FONT)); + state.SetFontSize(static_cast(c - SCC_FIRST_FONT)); } else { /* Filter out non printable characters */ if (!IsPrintable(c)) continue; diff --git a/src/gfx_layout_fallback.cpp b/src/gfx_layout_fallback.cpp index d2a43fb602..3669db6cc5 100644 --- a/src/gfx_layout_fallback.cpp +++ b/src/gfx_layout_fallback.cpp @@ -173,7 +173,7 @@ int FallbackParagraphLayout::FallbackLine::GetWidth() const */ int FallbackParagraphLayout::FallbackLine::CountRuns() const { - return (uint)this->size(); + return static_cast(this->size()); } /** diff --git a/src/gfx_layout_icu.cpp b/src/gfx_layout_icu.cpp index d7ee97e7ce..8a7b1eb916 100644 --- a/src/gfx_layout_icu.cpp +++ b/src/gfx_layout_icu.cpp @@ -86,7 +86,7 @@ public: public: int GetLeading() const override; int GetWidth() const override; - int CountRuns() const override { return (uint)this->size(); } + int CountRuns() const override { return static_cast(this->size()); } const VisualRun &GetVisualRun(int run) const override { return this->at(run); } int GetInternalCharLength(char32_t c) const override @@ -538,6 +538,6 @@ std::unique_ptr ICUParagraphLayout::NextLine(int /* Transform from UTF-32 to internal ICU format of UTF-16. */ int32_t length = 0; UErrorCode err = U_ZERO_ERROR; - u_strFromUTF32(buff, buffer_last - buff, &length, (UChar32*)&c, 1, &err); + u_strFromUTF32(buff, buffer_last - buff, &length, reinterpret_cast(&c), 1, &err); return length; } diff --git a/src/goal.cpp b/src/goal.cpp index 2b200683ef..751e076e9b 100644 --- a/src/goal.cpp +++ b/src/goal.cpp @@ -243,9 +243,9 @@ CommandCost CmdSetGoalCompleted(DoCommandFlags flags, GoalID goal, bool complete CommandCost CmdGoalQuestion(DoCommandFlags flags, uint16_t uniqueid, uint32_t target, bool is_client, uint32_t button_mask, GoalQuestionType type, const EncodedString &text) { static_assert(sizeof(uint32_t) >= sizeof(CompanyID)); - CompanyID company = (CompanyID)target; + CompanyID company = CompanyID(target); static_assert(sizeof(uint32_t) >= sizeof(ClientID)); - ClientID client = (ClientID)target; + ClientID client = static_cast(target); static_assert(GOAL_QUESTION_BUTTON_COUNT < 29); button_mask &= (1U << GOAL_QUESTION_BUTTON_COUNT) - 1; @@ -301,7 +301,7 @@ CommandCost CmdGoalQuestionAnswer(DoCommandFlags flags, uint16_t uniqueid, uint8 } if (flags.Test(DoCommandFlag::Execute)) { - Game::NewEvent(new ScriptEventGoalQuestionAnswer(uniqueid, _current_company, (ScriptGoal::QuestionButton)(1 << button))); + Game::NewEvent(new ScriptEventGoalQuestionAnswer(uniqueid, _current_company, static_cast(1 << button))); } return CommandCost(); diff --git a/src/goal_gui.cpp b/src/goal_gui.cpp index cccb600371..b05289f16b 100644 --- a/src/goal_gui.cpp +++ b/src/goal_gui.cpp @@ -105,7 +105,7 @@ struct GoalListWindow : public Window { case GT_COMPANY: /* s->dst here is not a tile, but a CompanyID. * Show the window with the overview of the company instead. */ - ShowCompany((CompanyID)s->dst); + ShowCompany(CompanyID(s->dst)); return; case GT_TILE: @@ -310,7 +310,7 @@ static WindowDesc _goals_list_desc( */ void ShowGoalsList(CompanyID company) { - if (!Company::IsValidID(company)) company = (CompanyID)CompanyID::Invalid(); + if (!Company::IsValidID(company)) company = static_cast(CompanyID::Invalid()); AllocateWindowDescFront(_goals_list_desc, company); } diff --git a/src/graph_gui.cpp b/src/graph_gui.cpp index a056186edb..2bdc6c96a2 100644 --- a/src/graph_gui.cpp +++ b/src/graph_gui.cpp @@ -65,7 +65,7 @@ struct GraphLegendWindow : Window { { if (!IsInsideMM(widget, WID_GL_FIRST_COMPANY, WID_GL_FIRST_COMPANY + MAX_COMPANIES)) return; - CompanyID cid = (CompanyID)(widget - WID_GL_FIRST_COMPANY); + CompanyID cid = CompanyID(widget - WID_GL_FIRST_COMPANY); if (!Company::IsValidID(cid)) return; @@ -261,7 +261,7 @@ protected: if (abs_lower != 0 || abs_higher != 0) { /* The number of grids to reserve for the positive part is: */ - num_pos_grids = (int)floor(0.5 + num_hori_lines * abs_higher / (abs_higher + abs_lower)); + num_pos_grids = static_cast(floor(0.5 + num_hori_lines * abs_higher / (abs_higher + abs_lower))); /* If there are any positive or negative values, force that they have at least one grid. */ if (num_pos_grids == 0 && abs_higher != 0) num_pos_grids++; @@ -328,7 +328,7 @@ protected: /* the colours and cost array of GraphDrawer must accommodate * both values for cargo and companies. So if any are higher, quit */ - static_assert(GRAPH_MAX_DATASETS >= (int)NUM_CARGO && GRAPH_MAX_DATASETS >= (int)MAX_COMPANIES); + static_assert(GRAPH_MAX_DATASETS >= static_cast(NUM_CARGO) && GRAPH_MAX_DATASETS >= static_cast(MAX_COMPANIES)); assert(this->num_vert_lines > 0); /* Rect r will be adjusted to contain just the graph, with labels being @@ -360,7 +360,7 @@ protected: OverflowSafeInt64 interval_size = interval.highest + abs(interval.lowest); /* Where to draw the X axis. Use floating point to avoid overflowing and results of zero. */ - x_axis_offset = (int)((r.bottom - r.top) * (double)interval.highest / (double)interval_size); + x_axis_offset = static_cast((r.bottom - r.top) * (double)interval.highest / (double)interval_size); /* Draw the background of the graph itself. */ GfxFillRect(r.left, r.top, r.right, r.bottom, GRAPH_BASE_COLOUR); @@ -1339,7 +1339,7 @@ struct PerformanceRatingDetailWindow : Window { if (IsInsideMM(widget, WID_PRD_COMPANY_FIRST, WID_PRD_COMPANY_LAST + 1)) { if (this->IsWidgetDisabled(widget)) return; - CompanyID cid = (CompanyID)(widget - WID_PRD_COMPANY_FIRST); + CompanyID cid = CompanyID(widget - WID_PRD_COMPANY_FIRST); Dimension sprite_size = GetSpriteSize(SPR_COMPANY_ICON); DrawCompanyIcon(cid, CenterBounds(r.left, r.right, sprite_size.width), CenterBounds(r.top, r.bottom, sprite_size.height)); return; @@ -1347,7 +1347,7 @@ struct PerformanceRatingDetailWindow : Window { if (!IsInsideMM(widget, WID_PRD_SCORE_FIRST, WID_PRD_SCORE_LAST + 1)) return; - ScoreID score_type = (ScoreID)(widget - WID_PRD_SCORE_FIRST); + ScoreID score_type = static_cast(widget - WID_PRD_SCORE_FIRST); /* The colours used to show how the progress is going */ int colour_done = GetColourGradient(COLOUR_GREEN, SHADE_NORMAL); @@ -1414,7 +1414,7 @@ struct PerformanceRatingDetailWindow : Window { /* Is it no on disable? */ if (!this->IsWidgetDisabled(widget)) { this->RaiseWidget(WID_PRD_COMPANY_FIRST + this->company); - this->company = (CompanyID)(widget - WID_PRD_COMPANY_FIRST); + this->company = CompanyID(widget - WID_PRD_COMPANY_FIRST); this->LowerWidget(WID_PRD_COMPANY_FIRST + this->company); this->SetDirty(); } diff --git a/src/ground_vehicle.cpp b/src/ground_vehicle.cpp index ca8fe65fcf..918a55d106 100644 --- a/src/ground_vehicle.cpp +++ b/src/ground_vehicle.cpp @@ -191,8 +191,8 @@ bool GroundVehicle::IsChainInDepot() const { const T *v = this->First(); /* Is the front engine stationary in the depot? */ - static_assert((int)TRANSPORT_RAIL == (int)VEH_TRAIN); - static_assert((int)TRANSPORT_ROAD == (int)VEH_ROAD); + static_assert(static_cast(TRANSPORT_RAIL) == static_cast(VEH_TRAIN)); + static_assert(static_cast(TRANSPORT_ROAD) == static_cast(VEH_ROAD)); if (!IsDepotTypeTile(v->tile, (TransportType)Type) || v->cur_speed != 0) return false; /* Check whether the rest is also already trying to enter the depot. */ diff --git a/src/group_cmd.cpp b/src/group_cmd.cpp index 2ccbfe2420..65520f609e 100644 --- a/src/group_cmd.cpp +++ b/src/group_cmd.cpp @@ -766,7 +766,7 @@ void UpdateTrainGroupID(Train *v) { assert(v->IsFrontEngine() || v->IsFreeWagon()); - GroupID new_g = v->IsFrontEngine() ? v->group_id : (GroupID)DEFAULT_GROUP; + GroupID new_g = v->IsFrontEngine() ? v->group_id : GroupID(DEFAULT_GROUP); for (Vehicle *u = v; u != nullptr; u = u->Next()) { if (u->IsEngineCountable()) UpdateNumEngineGroup(u, u->group_id, new_g); diff --git a/src/group_gui.cpp b/src/group_gui.cpp index f13061c405..a57e762d77 100644 --- a/src/group_gui.cpp +++ b/src/group_gui.cpp @@ -295,7 +295,7 @@ private: const GroupStatistics &stats = GroupStatistics::Get(this->vli.company, g_id, this->vli.vtype); bool rtl = _current_text_dir == TD_RTL; - const int offset = (rtl ? -(int)this->column_size[VGC_FOLD].width : (int)this->column_size[VGC_FOLD].width) / 2; + const int offset = (rtl ? -static_cast(this->column_size[VGC_FOLD].width) : static_cast(this->column_size[VGC_FOLD].width)) / 2; const int level_width = rtl ? -WidgetDimensions::scaled.hsep_indent : WidgetDimensions::scaled.hsep_indent; const int linecolour = GetColourGradient(COLOUR_ORANGE, SHADE_NORMAL); @@ -638,7 +638,7 @@ public: y1 += this->tiny_step_height; } - if ((uint)this->group_sb->GetPosition() + this->group_sb->GetCapacity() > this->groups.size()) { + if (static_cast(this->group_sb->GetPosition()) + this->group_sb->GetCapacity() > this->groups.size()) { DrawGroupInfo(y1, r.left, r.right, NEW_GROUP); } break; @@ -730,7 +730,7 @@ public: int x = _current_text_dir == TD_RTL ? group_display->pos_x + group_display->current_x - WidgetDimensions::scaled.framerect.right - it->indent * WidgetDimensions::scaled.hsep_indent - this->column_size[VGC_FOLD].width : group_display->pos_x + WidgetDimensions::scaled.framerect.left + it->indent * WidgetDimensions::scaled.hsep_indent; - if (click_count > 1 || (pt.x >= x && pt.x < (int)(x + this->column_size[VGC_FOLD].width))) { + if (click_count > 1 || (pt.x >= x && pt.x < static_cast(x + this->column_size[VGC_FOLD].width))) { GroupID g = this->vli.ToGroupID(); if (!IsAllGroupID(g) && !IsDefaultGroupID(g)) { diff --git a/src/heightmap.cpp b/src/heightmap.cpp index 7520745cc0..eb02b76c88 100644 --- a/src/heightmap.cpp +++ b/src/heightmap.cpp @@ -52,7 +52,7 @@ static_assert(MAX_HEIGHTMAP_SIZE_PIXELS < UINT32_MAX / 8); */ static inline bool IsValidHeightmapDimension(size_t width, size_t height) { - return (uint64_t)width * height <= MAX_HEIGHTMAP_SIZE_PIXELS && + return static_cast(width) * height <= MAX_HEIGHTMAP_SIZE_PIXELS && width > 0 && width <= MAX_HEIGHTMAP_SIDE_LENGTH_IN_PIXELS && height > 0 && height <= MAX_HEIGHTMAP_SIDE_LENGTH_IN_PIXELS; } @@ -409,8 +409,8 @@ void FixSlopes() height = Map::SizeY(); /* Top and left edge */ - for (row = 0; (uint)row < height; row++) { - for (col = 0; (uint)col < width; col++) { + for (row = 0; static_cast(row) < height; row++) { + for (col = 0; static_cast(col) < width; col++) { current_height = MAX_TILE_HEIGHT; if (col != 0) { /* Find lowest tile; either the top or left one */ @@ -424,7 +424,7 @@ void FixSlopes() /* Does the height differ more than one? */ TileIndex tile = TileXY(col, row); - if (TileHeight(tile) >= (uint)current_height + 2) { + if (TileHeight(tile) >= static_cast(current_height) + 2) { /* Then change the height to be no more than one */ SetTileHeight(tile, current_height + 1); /* Height was changed so now there's a chance, more likely at higher altitude, of the @@ -440,12 +440,12 @@ void FixSlopes() for (row = height - 1; row >= 0; row--) { for (col = width - 1; col >= 0; col--) { current_height = MAX_TILE_HEIGHT; - if ((uint)col != width - 1) { + if (static_cast(col) != width - 1) { /* Find lowest tile; either the bottom and right one */ current_height = TileHeight(TileXY(col + 1, row)); // bottom edge } - if ((uint)row != height - 1) { + if (static_cast(row) != height - 1) { if (TileHeight(TileXY(col, row + 1)) < current_height) { current_height = TileHeight(TileXY(col, row + 1)); // right edge } @@ -453,7 +453,7 @@ void FixSlopes() /* Does the height differ more than one? */ TileIndex tile = TileXY(col, row); - if (TileHeight(tile) >= (uint)current_height + 2) { + if (TileHeight(tile) >= static_cast(current_height) + 2) { /* Then change the height to be no more than one */ SetTileHeight(tile, current_height + 1); /* Height was changed so now there's a chance, more likely at higher altitude, of the diff --git a/src/hotkeys.cpp b/src/hotkeys.cpp index 476b92f8fe..0bc1956e01 100644 --- a/src/hotkeys.cpp +++ b/src/hotkeys.cpp @@ -108,7 +108,7 @@ static uint16_t ParseCode(const char *start, const char *end) if (end - start == 1) { if (*start >= 'a' && *start <= 'z') return *start - ('a'-'A'); /* Ignore invalid keycodes */ - if (*(const uint8_t *)start < 128) return *start; + if (*reinterpret_cast(start) < 128) return *start; } return 0; } diff --git a/src/industry_cmd.cpp b/src/industry_cmd.cpp index 76b6340ba0..e6c274c289 100644 --- a/src/industry_cmd.cpp +++ b/src/industry_cmd.cpp @@ -224,7 +224,7 @@ void Industry::PostDestructor(size_t) /* static */ Industry *Industry::GetRandom() { if (Industry::GetNumItems() == 0) return nullptr; - int num = RandomRange((uint16_t)Industry::GetNumItems()); + int num = RandomRange(static_cast(Industry::GetNumItems())); size_t index = std::numeric_limits::max(); while (num >= 0) { @@ -1815,7 +1815,7 @@ static void DoCreateNewIndustry(Industry *i, TileIndex tile, IndustryType type, /* Adding 1 here makes it conform to specs of var44 of varaction2 for industries * 0 = created prior of newindustries * else, chosen layout + 1 */ - i->selected_layout = (uint8_t)(layout_index + 1); + i->selected_layout = static_cast(layout_index + 1); i->exclusive_supplier = INVALID_OWNER; i->exclusive_consumer = INVALID_OWNER; @@ -2091,7 +2091,7 @@ CommandCost CmdBuildIndustry(DoCommandFlags flags, TileIndex tile, IndustryType */ tile = RandomTile(); /* Start with a random layout */ - size_t layout = RandomRange((uint32_t)num_layouts); + size_t layout = RandomRange(static_cast(num_layouts)); /* Check now each layout, starting with the random one */ for (size_t j = 0; j < num_layouts; j++) { layout = (layout + 1) % num_layouts; @@ -2275,7 +2275,7 @@ static Industry *CreateNewIndustry(TileIndex tile, IndustryType type, IndustryAv uint32_t seed = Random(); uint32_t seed2 = Random(); Industry *i = nullptr; - size_t layout_index = RandomRange((uint32_t)indspec->layouts.size()); + size_t layout_index = RandomRange(static_cast(indspec->layouts.size())); [[maybe_unused]] CommandCost ret = CreateNewIndustryHelper(tile, type, DoCommandFlag::Execute, indspec, layout_index, seed, GB(seed2, 0, 16), OWNER_NONE, creation_type, &i); assert(i != nullptr || ret.Failed()); return i; @@ -2351,7 +2351,7 @@ static uint GetNumberOfIndustries() }; assert(lengthof(numof_industry_table) == ID_END); - uint difficulty = (_game_mode != GM_EDITOR) ? _settings_game.difficulty.industry_density : (uint)ID_VERY_LOW; + uint difficulty = (_game_mode != GM_EDITOR) ? _settings_game.difficulty.industry_density : static_cast(ID_VERY_LOW); if (difficulty == ID_CUSTOM) return std::min(IndustryPool::MAX_SIZE, _settings_game.game_creation.custom_industry_number); @@ -2639,7 +2639,7 @@ void IndustryBuildData::TryBuildNewIndustry() int difference = this->builddata[it].target_count - Industry::GetIndustryTypeCount(it); if (difference <= 0) continue; // Too many of this kind. if (count == 1) break; - if (r < (uint)difference) break; + if (r < static_cast(difference)) break; r -= difference; } assert(it < NUM_INDUSTRYTYPES && this->builddata[it].target_count > Industry::GetIndustryTypeCount(it)); diff --git a/src/industry_gui.cpp b/src/industry_gui.cpp index 9c3b4ac7dc..e0418fe11d 100644 --- a/src/industry_gui.cpp +++ b/src/industry_gui.cpp @@ -712,7 +712,7 @@ public: /* We do not need to protect ourselves against "Random Many Industries" in this mode */ const IndustrySpec *indsp = GetIndustrySpec(this->selected_type); uint32_t seed = InteractiveRandom(); - uint32_t layout_index = InteractiveRandomRange((uint32_t)indsp->layouts.size()); + uint32_t layout_index = InteractiveRandomRange(static_cast(indsp->layouts.size())); if (_game_mode == GM_EDITOR) { /* Show error if no town exists at all */ @@ -1030,7 +1030,7 @@ public: if (!IsValidCargoType(itp->cargo)) continue; row--; if (row < 0) { - line = (InfoLine)(IL_RATE1 + (itp - std::begin(i->produced))); + line = static_cast(IL_RATE1 + (itp - std::begin(i->produced))); break; } } @@ -2312,7 +2312,7 @@ struct CargoesField { uint col; for (col = 0; col < this->u.cargo.num_cargoes; col++) { if (pt.x < cpos) break; - if (pt.x < cpos + (int)CargoesField::cargo_line.width) return this->u.cargo.vertical_cargoes[col]; + if (pt.x < cpos + static_cast(CargoesField::cargo_line.width)) return this->u.cargo.vertical_cargoes[col]; cpos += CargoesField::cargo_line.width + CargoesField::cargo_space.width; } /* col = 0 -> left of first col, 1 -> left of 2nd col, ... this->u.cargo.num_cargoes right of last-col. */ @@ -3033,7 +3033,7 @@ struct IndustryCargoesWindow : public Window { if (pt.y < vpos) return false; int row = (pt.y - vpos) / CargoesField::normal_height; // row is relative to row 1. - if (row + 1 >= (int)this->fields.size()) return false; + if (row + 1 >= static_cast(this->fields.size())) return false; vpos = pt.y - vpos - row * CargoesField::normal_height; // Position in the row + 1 field row++; // rebase row to match index of this->fields. @@ -3113,7 +3113,7 @@ struct IndustryCargoesWindow : public Window { lst.push_back(MakeDropDownListIconItem(d, cs->GetCargoIcon(), PAL_NONE, cs->name, cs->Index())); } if (!lst.empty()) { - int selected = (this->ind_cargo >= NUM_INDUSTRYTYPES) ? (int)(this->ind_cargo - NUM_INDUSTRYTYPES) : -1; + int selected = (this->ind_cargo >= NUM_INDUSTRYTYPES) ? static_cast(this->ind_cargo - NUM_INDUSTRYTYPES) : -1; ShowDropDownList(this, std::move(lst), selected, WID_IC_CARGO_DROPDOWN); } break; @@ -3127,7 +3127,7 @@ struct IndustryCargoesWindow : public Window { lst.push_back(MakeDropDownListStringItem(indsp->name, ind)); } if (!lst.empty()) { - int selected = (this->ind_cargo < NUM_INDUSTRYTYPES) ? (int)this->ind_cargo : -1; + int selected = (this->ind_cargo < NUM_INDUSTRYTYPES) ? static_cast(this->ind_cargo) : -1; ShowDropDownList(this, std::move(lst), selected, WID_IC_IND_DROPDOWN); } break; diff --git a/src/intro_gui.cpp b/src/intro_gui.cpp index eae9cb1c3e..ab681d0c67 100644 --- a/src/intro_gui.cpp +++ b/src/intro_gui.cpp @@ -239,9 +239,9 @@ struct SelectGameWindow : public Window { size_t next_command_index = (this->cur_viewport_command_index + 1) % intro_viewport_commands.size(); IntroGameViewportCommand &nvc = intro_viewport_commands[next_command_index]; Point pos2 = nvc.PositionForViewport(vp); - const double t = this->cur_viewport_command_time / (double)vc.delay; - pos.x = pos.x + (int)(t * (pos2.x - pos.x)); - pos.y = pos.y + (int)(t * (pos2.y - pos.y)); + const double t = this->cur_viewport_command_time / static_cast(vc.delay); + pos.x = pos.x + static_cast(t * (pos2.x - pos.x)); + pos.y = pos.y + static_cast(t * (pos2.y - pos.y)); } /* Update the viewport position. */ diff --git a/src/landscape.cpp b/src/landscape.cpp index fd499c97c6..af5561f482 100644 --- a/src/landscape.cpp +++ b/src/landscape.cpp @@ -236,7 +236,7 @@ uint GetPartialPixelZ(int x, int y, Slope corners) break; case CORNER_S: - if (x + y >= (int)TILE_SIZE) return GetSlopeMaxPixelZ(corners); + if (x + y >= static_cast(TILE_SIZE)) return GetSlopeMaxPixelZ(corners); break; case CORNER_E: @@ -244,7 +244,7 @@ uint GetPartialPixelZ(int x, int y, Slope corners) break; case CORNER_N: - if (x + y < (int)TILE_SIZE) return GetSlopeMaxPixelZ(corners); + if (x + y < static_cast(TILE_SIZE)) return GetSlopeMaxPixelZ(corners); break; default: NOT_REACHED(); @@ -255,9 +255,9 @@ uint GetPartialPixelZ(int x, int y, Slope corners) case SLOPE_FLAT: return 0; /* One corner is up.*/ - case SLOPE_N: return x + y <= (int)TILE_SIZE ? (TILE_SIZE - x - y) >> 1 : 0; + case SLOPE_N: return x + y <= static_cast(TILE_SIZE) ? (TILE_SIZE - x - y) >> 1 : 0; case SLOPE_E: return y >= x ? (1 + y - x) >> 1 : 0; - case SLOPE_S: return x + y >= (int)TILE_SIZE ? (1 + x + y - TILE_SIZE) >> 1 : 0; + case SLOPE_S: return x + y >= static_cast(TILE_SIZE) ? (1 + x + y - TILE_SIZE) >> 1 : 0; case SLOPE_W: return x >= y ? (x - y) >> 1 : 0; /* Two corners next to each other are up. */ @@ -267,13 +267,13 @@ uint GetPartialPixelZ(int x, int y, Slope corners) case SLOPE_NW: return (TILE_SIZE - y) >> 1; /* Three corners are up on the same level. */ - case SLOPE_ENW: return x + y >= (int)TILE_SIZE ? TILE_HEIGHT - ((1 + x + y - TILE_SIZE) >> 1) : TILE_HEIGHT; + case SLOPE_ENW: return x + y >= static_cast(TILE_SIZE) ? TILE_HEIGHT - ((1 + x + y - TILE_SIZE) >> 1) : TILE_HEIGHT; case SLOPE_SEN: return y < x ? TILE_HEIGHT - ((x - y) >> 1) : TILE_HEIGHT; - case SLOPE_WSE: return x + y <= (int)TILE_SIZE ? TILE_HEIGHT - ((TILE_SIZE - x - y) >> 1) : TILE_HEIGHT; + case SLOPE_WSE: return x + y <= static_cast(TILE_SIZE) ? TILE_HEIGHT - ((TILE_SIZE - x - y) >> 1) : TILE_HEIGHT; case SLOPE_NWS: return x < y ? TILE_HEIGHT - ((1 + y - x) >> 1) : TILE_HEIGHT; /* Two corners at opposite sides are up. */ - case SLOPE_NS: return x + y < (int)TILE_SIZE ? (TILE_SIZE - x - y) >> 1 : (1 + x + y - TILE_SIZE) >> 1; + case SLOPE_NS: return x + y < static_cast(TILE_SIZE) ? (TILE_SIZE - x - y) >> 1 : (1 + x + y - TILE_SIZE) >> 1; case SLOPE_EW: return x >= y ? (x - y) >> 1 : (1 + y - x) >> 1; /* Very special cases. */ @@ -442,7 +442,7 @@ void DrawFoundation(TileInfo *ti, Foundation f) if (!HasFoundationNE(ti->tile, slope, z)) sprite_block += 2; /* Use the original slope sprites if NW and NE borders should be visible */ - SpriteID leveled_base = (sprite_block == 0 ? (int)SPR_FOUNDATION_BASE : (SPR_SLOPES_VIRTUAL_BASE + sprite_block * TRKFOUND_BLOCK_SIZE)); + SpriteID leveled_base = (sprite_block == 0 ? static_cast(SPR_FOUNDATION_BASE) : (SPR_SLOPES_VIRTUAL_BASE + sprite_block * TRKFOUND_BLOCK_SIZE)); SpriteID inclined_base = SPR_SLOPES_VIRTUAL_BASE + SLOPES_INCLINED_OFFSET + sprite_block * TRKFOUND_BLOCK_SIZE; SpriteID halftile_base = SPR_HALFTILE_FOUNDATION_BASE + sprite_block * HALFTILE_BLOCK_SIZE; @@ -469,10 +469,10 @@ void DrawFoundation(TileInfo *ti, Foundation f) OffsetGroundSprite(0, 0); } else if (IsLeveledFoundation(f)) { AddSortableSpriteToDraw(leveled_base + SlopeWithOneCornerRaised(highest_corner), PAL_NONE, ti->x, ti->y, TILE_SIZE, TILE_SIZE, TILE_HEIGHT - 1, ti->z - TILE_HEIGHT); - OffsetGroundSprite(0, -(int)TILE_HEIGHT); + OffsetGroundSprite(0, -static_cast(TILE_HEIGHT)); } else if (f == FOUNDATION_STEEP_LOWER) { /* one corner raised */ - OffsetGroundSprite(0, -(int)TILE_HEIGHT); + OffsetGroundSprite(0, -static_cast(TILE_HEIGHT)); } else { /* halftile foundation */ int x_bb = (((highest_corner == CORNER_W) || (highest_corner == CORNER_S)) ? TILE_SIZE / 2 : 0); @@ -488,7 +488,7 @@ void DrawFoundation(TileInfo *ti, Foundation f) if (IsLeveledFoundation(f)) { /* leveled foundation */ AddSortableSpriteToDraw(leveled_base + ti->tileh, PAL_NONE, ti->x, ti->y, TILE_SIZE, TILE_SIZE, TILE_HEIGHT - 1, ti->z); - OffsetGroundSprite(0, -(int)TILE_HEIGHT); + OffsetGroundSprite(0, -static_cast(TILE_HEIGHT)); } else if (IsNonContinuousFoundation(f)) { /* halftile foundation */ Corner halftile_corner = GetHalftileFoundationCorner(f); @@ -652,7 +652,7 @@ CommandCost CmdLandscapeClear(DoCommandFlags flags, TileIndex tile) } Company *c = flags.Any({DoCommandFlag::Auto, DoCommandFlag::Bankrupt}) ? nullptr : Company::GetIfValid(_current_company); - if (c != nullptr && (int)GB(c->clear_limit, 16, 16) < 1) { + if (c != nullptr && static_cast(GB(c->clear_limit, 16, 16)) < 1) { return CommandCost(STR_ERROR_CLEARING_LIMIT_REACHED); } @@ -790,7 +790,7 @@ void RunTileLoop() _tile_type_procs[GetTileType(tile)]->tile_loop_proc(tile); /* Get the next tile in sequence using a Galois LFSR. */ - tile = TileIndex{(tile.base() >> 1) ^ (-(int32_t)(tile.base() & 1) & feedback)}; + tile = TileIndex{(tile.base() >> 1) ^ (-static_cast(tile.base() & 1) & feedback)}; } _cur_tileloop_tile = tile; @@ -830,7 +830,7 @@ static void GenerateTerrain(int type, uint flag) uint edge_distance = 1 + (_settings_game.construction.freeform_edges ? 1 : 0); if (x <= edge_distance || y <= edge_distance) return; - DiagDirection direction = (DiagDirection)GB(r, 22, 2); + DiagDirection direction = static_cast(GB(r, 22, 2)); uint w = templ->width; uint h = templ->height; diff --git a/src/league_gui.cpp b/src/league_gui.cpp index 898f873056..197a4e083e 100644 --- a/src/league_gui.cpp +++ b/src/league_gui.cpp @@ -226,7 +226,7 @@ static void HandleLinkClick(Link link) break; case LT_COMPANY: - ShowCompany((CompanyID)link.target); + ShowCompany(CompanyID(link.target)); return; case LT_STORY_PAGE: { diff --git a/src/linkgraph/linkgraph_gui.cpp b/src/linkgraph/linkgraph_gui.cpp index cf74a7d9fd..644635c3cc 100644 --- a/src/linkgraph/linkgraph_gui.cpp +++ b/src/linkgraph/linkgraph_gui.cpp @@ -186,16 +186,16 @@ inline bool LinkGraphOverlay::IsLinkVisible(Point pta, Point ptb, const DrawPixe if ((c0 & c1) != 0) return false; if (c0 & TOP) { // point 0 is above the clip window - x0 = x0 + (int)(((int64_t) (x1 - x0)) * ((int64_t) (top - y0)) / ((int64_t) (y1 - y0))); + x0 = x0 + static_cast((static_cast(x1 - x0)) * (static_cast(top - y0)) / (static_cast(y1 - y0))); y0 = top; } else if (c0 & BOTTOM) { // point 0 is below the clip window - x0 = x0 + (int)(((int64_t) (x1 - x0)) * ((int64_t) (bottom - y0)) / ((int64_t) (y1 - y0))); + x0 = x0 + static_cast((static_cast(x1 - x0)) * (static_cast(bottom - y0)) / (static_cast(y1 - y0))); y0 = bottom; } else if (c0 & RIGHT) { // point 0 is to the right of clip window - y0 = y0 + (int)(((int64_t) (y1 - y0)) * ((int64_t) (right - x0)) / ((int64_t) (x1 - x0))); + y0 = y0 + static_cast((static_cast(y1 - y0)) * (static_cast(right - x0)) / (static_cast(x1 - x0))); x0 = right; } else if (c0 & LEFT) { // point 0 is to the left of clip window - y0 = y0 + (int)(((int64_t) (y1 - y0)) * ((int64_t) (left - x0)) / ((int64_t) (x1 - x0))); + y0 = y0 + static_cast((static_cast(y1 - y0)) * (static_cast(left - x0)) / (static_cast(x1 - x0))); x0 = left; } @@ -367,8 +367,8 @@ bool LinkGraphOverlay::ShowTooltip(Point pt, TooltipCloseCondition close_cond) /* Check the distance from the cursor to the line defined by the two stations. */ Point ptb = this->GetStationMiddle(Station::Get(j->first)); - float dist = std::abs((int64_t)(ptb.x - pta.x) * (int64_t)(pta.y - pt.y) - (int64_t)(pta.x - pt.x) * (int64_t)(ptb.y - pta.y)) / - std::sqrt((int64_t)(ptb.x - pta.x) * (int64_t)(ptb.x - pta.x) + (int64_t)(ptb.y - pta.y) * (int64_t)(ptb.y - pta.y)); + float dist = std::abs(static_cast(ptb.x - pta.x) * static_cast(pta.y - pt.y) - static_cast(pta.x - pt.x) * static_cast(ptb.y - pta.y)) / + std::sqrt(static_cast(ptb.x - pta.x) * static_cast(ptb.x - pta.x) + static_cast(ptb.y - pta.y) * static_cast(ptb.y - pta.y)); const auto &link = j->second; if (dist <= 4 && link.Usage() > 0 && pt.x + 2 >= std::min(pta.x, ptb.x) && @@ -602,7 +602,7 @@ void LinkGraphLegendWindow::DrawWidget(const Rect &r, WidgetID widget) const Rect br = r.Shrink(WidgetDimensions::scaled.bevel); if (IsInsideMM(widget, WID_LGL_COMPANY_FIRST, WID_LGL_COMPANY_LAST + 1)) { if (this->IsWidgetDisabled(widget)) return; - CompanyID cid = (CompanyID)(widget - WID_LGL_COMPANY_FIRST); + CompanyID cid = CompanyID(widget - WID_LGL_COMPANY_FIRST); Dimension sprite_size = GetSpriteSize(SPR_COMPANY_ICON); DrawCompanyIcon(cid, CenterBounds(br.left, br.right, sprite_size.width), CenterBounds(br.top, br.bottom, sprite_size.height)); } diff --git a/src/linkgraph/refresh.cpp b/src/linkgraph/refresh.cpp index 1f3aa364f8..d79bebd705 100644 --- a/src/linkgraph/refresh.cpp +++ b/src/linkgraph/refresh.cpp @@ -233,7 +233,7 @@ void LinkRefresher::RefreshStats(const Order *cur, const Order *next) st->index == vehicle->last_station_visited && this->vehicle->orders->GetTotalDuration() > this->vehicle->current_order_time) { uint effective_capacity = cargo_quantity * this->vehicle->load_unload_ticks; - if (effective_capacity > (uint)this->vehicle->orders->GetTotalDuration()) { + if (effective_capacity > static_cast(this->vehicle->orders->GetTotalDuration())) { IncreaseStats(st, c, next_station, effective_capacity / this->vehicle->orders->GetTotalDuration(), 0, 0, {EdgeUpdateMode::Increase, restricted_mode}); diff --git a/src/main_gui.cpp b/src/main_gui.cpp index 931142b6f6..f3ef064681 100644 --- a/src/main_gui.cpp +++ b/src/main_gui.cpp @@ -104,7 +104,7 @@ bool DoZoomInOutWindow(ZoomStateChange how, Window *w) case ZOOM_IN: if (vp->zoom <= _settings_client.gui.zoom_min) return false; - vp->zoom = (ZoomLevel)((int)vp->zoom - 1); + vp->zoom = static_cast(static_cast(vp->zoom) - 1); vp->virtual_width >>= 1; vp->virtual_height >>= 1; @@ -115,7 +115,7 @@ bool DoZoomInOutWindow(ZoomStateChange how, Window *w) break; case ZOOM_OUT: if (vp->zoom >= _settings_client.gui.zoom_max) return false; - vp->zoom = (ZoomLevel)((int)vp->zoom + 1); + vp->zoom = static_cast(static_cast(vp->zoom) + 1); w->viewport->scrollpos_x -= vp->virtual_width >> 1; w->viewport->scrollpos_y -= vp->virtual_height >> 1; @@ -355,7 +355,7 @@ struct MainWindow : Window case GHK_TOGGLE_TRANSPARENCY + 7: case GHK_TOGGLE_TRANSPARENCY + 8: /* Transparency toggle hot keys */ - ToggleTransparency((TransparencyOption)(hotkey - GHK_TOGGLE_TRANSPARENCY)); + ToggleTransparency(static_cast(hotkey - GHK_TOGGLE_TRANSPARENCY)); MarkWholeScreenDirty(); break; @@ -368,7 +368,7 @@ struct MainWindow : Window case GHK_TOGGLE_INVISIBILITY + 6: case GHK_TOGGLE_INVISIBILITY + 7: /* Invisibility toggle hot keys */ - ToggleInvisibilityWithTransparency((TransparencyOption)(hotkey - GHK_TOGGLE_INVISIBILITY)); + ToggleInvisibilityWithTransparency(static_cast(hotkey - GHK_TOGGLE_INVISIBILITY)); MarkWholeScreenDirty(); break; diff --git a/src/map.cpp b/src/map.cpp index 315b89cba9..11d3ac13f9 100644 --- a/src/map.cpp +++ b/src/map.cpp @@ -63,8 +63,8 @@ TileIndex TileAdd(TileIndex tile, TileIndexDiff offset) { int dx = offset & Map::MaxX(); - if (dx >= (int)Map::SizeX() / 2) dx -= Map::SizeX(); - int dy = (offset - dx) / (int)Map::SizeX(); + if (dx >= static_cast(Map::SizeX()) / 2) dx -= Map::SizeX(); + int dy = (offset - dx) / static_cast(Map::SizeX()); uint32_t x = TileX(tile) + dx; uint32_t y = TileY(tile) + dy; diff --git a/src/misc_cmd.cpp b/src/misc_cmd.cpp index 9b25d741fa..28d0cb5bb0 100644 --- a/src/misc_cmd.cpp +++ b/src/misc_cmd.cpp @@ -92,10 +92,10 @@ CommandCost CmdDecreaseLoan(DoCommandFlags flags, LoanCommand cmd, Money amount) switch (cmd) { default: return CMD_ERROR; // Invalid method case LoanCommand::Interval: // Pay back one step - loan = std::min(c->current_loan, (Money)LOAN_INTERVAL); + loan = std::min(c->current_loan, Money(LOAN_INTERVAL)); break; case LoanCommand::Max: // Pay back as much as possible - loan = std::max(std::min(c->current_loan, GetAvailableMoneyForCommand()), (Money)LOAN_INTERVAL); + loan = std::max(std::min(c->current_loan, GetAvailableMoneyForCommand()), Money(LOAN_INTERVAL)); loan -= loan % LOAN_INTERVAL; break; case LoanCommand::Amount: // Repay the given amount of loan @@ -126,7 +126,7 @@ CommandCost CmdSetCompanyMaxLoan(DoCommandFlags flags, CompanyID company, Money { if (_current_company != OWNER_DEITY) return CMD_ERROR; if (amount != COMPANY_MAX_LOAN_DEFAULT) { - if (amount < 0 || amount > (Money)MAX_LOAN_LIMIT) return CMD_ERROR; + if (amount < 0 || amount > Money(MAX_LOAN_LIMIT)) return CMD_ERROR; } Company *c = Company::GetIfValid(company); @@ -249,6 +249,6 @@ CommandCost CmdChangeBankBalance(DoCommandFlags flags, TileIndex tile, Money del } /* This command doesn't cost anything for deity. */ - CommandCost zero_cost(expenses_type, (Money)0); + CommandCost zero_cost(expenses_type, Money(0)); return zero_cost; } diff --git a/src/misc_gui.cpp b/src/misc_gui.cpp index 3bfc1e1aec..47ceb2f352 100644 --- a/src/misc_gui.cpp +++ b/src/misc_gui.cpp @@ -470,7 +470,7 @@ struct AboutWindow : public Window { IntervalTimer scroll_interval = {std::chrono::milliseconds(2100) / GetCharacterHeight(FS_NORMAL), [this](uint count) { this->text_position -= count; /* If the last text has scrolled start a new from the start */ - if (this->text_position < (int)(this->GetWidget(WID_A_SCROLLING_TEXT)->pos_y - std::size(_credits) * this->line_height)) { + if (this->text_position < static_cast(this->GetWidget(WID_A_SCROLLING_TEXT)->pos_y - std::size(_credits) * this->line_height)) { this->text_position = this->GetWidget(WID_A_SCROLLING_TEXT)->pos_y + this->GetWidget(WID_A_SCROLLING_TEXT)->current_y; } this->SetWidgetDirty(WID_A_SCROLLING_TEXT); diff --git a/src/mixer.cpp b/src/mixer.cpp index 81205cf398..6169a013c3 100644 --- a/src/mixer.cpp +++ b/src/mixer.cpp @@ -126,7 +126,7 @@ void MxMixSamples(void *buffer, uint samples) PerformanceMeasurer framerate(PFE_SOUND); static uint last_samples = 0; if (samples != last_samples) { - framerate.SetExpectedRate((double)_play_rate / samples); + framerate.SetExpectedRate(static_cast(_play_rate) / samples); last_samples = samples; } @@ -136,7 +136,7 @@ void MxMixSamples(void *buffer, uint samples) { std::lock_guard lock{ _music_stream_mutex }; /* Fetch music if a sampled stream is available */ - if (_music_stream) _music_stream((int16_t*)buffer, samples); + if (_music_stream) _music_stream(static_cast(buffer), samples); } /* Check if any channels should be stopped. */ @@ -159,9 +159,9 @@ void MxMixSamples(void *buffer, uint samples) for (uint8_t idx : SetBitIterator(active)) { MixerChannel *mc = &_channels[idx]; if (mc->is16bit) { - mix_int16(mc, (int16_t*)buffer, samples, effect_vol); + mix_int16(mc, static_cast(buffer), samples, effect_vol); } else { - mix_int16(mc, (int16_t*)buffer, samples, effect_vol); + mix_int16(mc, static_cast(buffer), samples, effect_vol); } if (mc->samples_left == 0) MxCloseChannel(idx); } @@ -200,7 +200,7 @@ void MxSetChannelRawSrc(MixerChannel *mc, const std::shared_ptrsamples_left = (uint)size * _play_rate / rate; + mc->samples_left = static_cast(size) * _play_rate / rate; mc->is16bit = is16bit; } @@ -214,8 +214,8 @@ void MxSetChannelVolume(MixerChannel *mc, uint volume, float pan) { /* Use sinusoidal pan to maintain overall sound power level regardless * of position. */ - mc->volume_left = (uint)(sin((1.0 - pan) * M_PI / 2.0) * volume); - mc->volume_right = (uint)(sin(pan * M_PI / 2.0) * volume); + mc->volume_left = static_cast(sin((1.0 - pan) * M_PI / 2.0) * volume); + mc->volume_right = static_cast(sin(pan * M_PI / 2.0) * volume); } diff --git a/src/music/dmusic.cpp b/src/music/dmusic.cpp index 18ee2655a5..5f70fab799 100644 --- a/src/music/dmusic.cpp +++ b/src/music/dmusic.cpp @@ -717,7 +717,7 @@ static void MidiThreadProc() REFERENCE_TIME playback_time = current_time - playback_start_time; if (block.realtime * MIDITIME_TO_REFTIME > playback_time + 3 *_playback.preload_time * MS_TO_REFTIME) { /* Stop the thread loop until we are at the preload time of the next block. */ - next_timeout = Clamp(((int64_t)block.realtime * MIDITIME_TO_REFTIME - playback_time) / MS_TO_REFTIME - _playback.preload_time, 0, 1000); + next_timeout = Clamp((static_cast(block.realtime) * MIDITIME_TO_REFTIME - playback_time) / MS_TO_REFTIME - _playback.preload_time, 0, 1000); Debug(driver, 9, "DMusic thread: Next event in {} ms (music {}, ref {})", next_timeout, block.realtime * MIDITIME_TO_REFTIME, playback_time); break; } @@ -971,7 +971,7 @@ static const char *LoadDefaultDLSFile(const char *user_dls) download_port->Release(); return "Can't get instrument download buffer"; } - char *inst_base = (char *)instrument; + char *inst_base = static_cast(instrument); /* Fill download header. */ DMUS_DOWNLOADINFO *d_info = (DMUS_DOWNLOADINFO *)instrument; @@ -996,7 +996,7 @@ static const char *LoadDefaultDLSFile(const char *user_dls) /* Write global articulations. */ if (!dls_file.instruments[i].articulators.empty()) { inst_data->ulGlobalArtIdx = last_offset; - offset_table[last_offset++] = (char *)instrument - inst_base; + offset_table[last_offset++] = static_cast(instrument) - inst_base; offset_table[last_offset++] = (char *)instrument + sizeof(DMUS_ARTICULATION2) - inst_base; instrument = DownloadArticulationData(inst_data->ulGlobalArtIdx, instrument, dls_file.instruments[i].articulators); @@ -1036,7 +1036,7 @@ static const char *LoadDefaultDLSFile(const char *user_dls) /* Write local articulator data. */ if (!rgn.articulators.empty()) { inst_region->ulRegionArtIdx = last_offset; - offset_table[last_offset++] = (char *)instrument - inst_base; + offset_table[last_offset++] = static_cast(instrument) - inst_base; offset_table[last_offset++] = (char *)instrument + sizeof(DMUS_ARTICULATION2) - inst_base; instrument = DownloadArticulationData(inst_region->ulRegionArtIdx, instrument, rgn.articulators); diff --git a/src/music/midifile.cpp b/src/music/midifile.cpp index 7dc09b6e01..a6517f5a88 100644 --- a/src/music/midifile.cpp +++ b/src/music/midifile.cpp @@ -381,14 +381,14 @@ static bool FixupMidiData(MidiFile &target) /* block is within the current tempo */ int64_t tickdiff = block.ticktime - last_ticktime; last_ticktime = block.ticktime; - last_realtime += uint32_t(tickdiff * tempo.tempo / target.tickdiv); + last_realtime += static_cast(tickdiff * tempo.tempo / target.tickdiv); block.realtime = last_realtime; cur_block++; } else { /* tempo change occurs before this block */ int64_t tickdiff = next_tempo.ticktime - last_ticktime; last_ticktime = next_tempo.ticktime; - last_realtime += uint32_t(tickdiff * tempo.tempo / target.tickdiv); // current tempo until the tempo change + last_realtime += static_cast(tickdiff * tempo.tempo / target.tickdiv); // current tempo until the tempo change cur_tempo++; } } @@ -564,7 +564,7 @@ struct MpsMachine { * Two bytes between offset to next and start of data * are unaccounted for. */ this->segments.push_back(pos + 4); - pos += FROM_LE16(*(const int16_t *)(this->songdata + pos)); + pos += FROM_LE16(*reinterpret_cast(this->songdata + pos)); } /* After segments follows list of master tracks for each channel, @@ -576,7 +576,7 @@ struct MpsMachine { * to next track. */ uint8_t ch = this->songdata[pos++]; this->channels[ch].startpos = pos + 4; - pos += FROM_LE16(*(const int16_t *)(this->songdata + pos)); + pos += FROM_LE16(*reinterpret_cast(this->songdata + pos)); } } @@ -674,7 +674,7 @@ struct MpsMachine { int16_t velocity; if (channel == 9) { /* Percussion channel, fixed velocity scaling not in the table */ - velocity = (int16_t)b2 * 0x50; + velocity = static_cast(b2) * 0x50; } else { /* Regular channel, use scaling from table */ velocity = b2 * programvelocities[chandata.cur_program]; @@ -698,7 +698,7 @@ struct MpsMachine { /* Standard MIDI controller 0 is "bank select", override meaning to change tempo. * This is not actually used in any of the original songs. */ if (b2 != 0) { - this->current_tempo = ((int)b2) * 48 / 60; + this->current_tempo = (static_cast(b2)) * 48 / 60; } break; } else if (b1 == MIDICT_EFFECTS1) { @@ -781,7 +781,7 @@ struct MpsMachine { /* Initialize playback simulation */ this->RestartSong(); this->shouldplayflag = true; - this->current_tempo = (int32_t)this->initial_tempo * 24 / 60; + this->current_tempo = static_cast(this->initial_tempo) * 24 / 60; this->tempo_ticks = this->current_tempo; /* Always reset percussion channel to program 0 */ @@ -909,7 +909,7 @@ bool MidiFile::WriteSMF(const std::string &filename) 0x00, 0x00, 0x00, 0x06, // BE32 block length, always 6 bytes 0x00, 0x00, // writing format 0 (all in one track) 0x00, 0x01, // containing 1 track (BE16) - (uint8_t)(this->tickdiv >> 8), (uint8_t)this->tickdiv, // tickdiv in BE16 + static_cast(this->tickdiv >> 8), static_cast(this->tickdiv), // tickdiv in BE16 }; fwrite(fileheader, sizeof(fileheader), 1, f); @@ -1010,7 +1010,7 @@ bool MidiFile::WriteSMF(const std::string &filename) /* Fill out the RIFF block length */ size_t trackendpos = ftell(f); fseek(f, tracksizepos, SEEK_SET); - uint32_t tracksize = (uint32_t)(trackendpos - tracksizepos - 4); // blindly assume we never produce files larger than 2 GB + uint32_t tracksize = static_cast(trackendpos - tracksizepos - 4); // blindly assume we never produce files larger than 2 GB tracksize = TO_BE32(tracksize); fwrite(&tracksize, 4, 1, f); diff --git a/src/music/win32_m.cpp b/src/music/win32_m.cpp index 729af5d948..812b6fe0b9 100644 --- a/src/music/win32_m.cpp +++ b/src/music/win32_m.cpp @@ -370,7 +370,7 @@ std::optional MusicDriver_Win32::Start(const StringList &parm) Debug(driver, 2, "Win32-MIDI: Start: initializing"); int resolution = GetDriverParamInt(parm, "resolution", 5); - uint port = (uint)GetDriverParamInt(parm, "port", UINT_MAX); + uint port = static_cast(GetDriverParamInt(parm, "port", UINT_MAX)); const char *portname = GetDriverParam(parm, "portname"); /* Enumerate ports either for selecting port by name, or for debug output */ diff --git a/src/music_gui.cpp b/src/music_gui.cpp index 5a56fd8449..7ad9d5cb85 100644 --- a/src/music_gui.cpp +++ b/src/music_gui.cpp @@ -288,7 +288,7 @@ void MusicSystem::CheckStatus() { if ((_game_mode == GM_MENU) != (this->selected_playlist == PLCH_THEMEONLY)) { /* Make sure the theme-only playlist is active when on the title screen, and not during gameplay */ - this->ChangePlaylist((_game_mode == GM_MENU) ? PLCH_THEMEONLY : (PlaylistChoices)_settings_client.music.playlist); + this->ChangePlaylist((_game_mode == GM_MENU) ? PLCH_THEMEONLY : static_cast(_settings_client.music.playlist)); } if (this->active_playlist.empty()) return; /* If we were supposed to be playing, but music has stopped, move to next song */ @@ -350,7 +350,7 @@ void MusicSystem::PlaylistAdd(size_t song_index) size_t newpos = InteractiveRandom() % maxpos; this->active_playlist.insert(this->active_playlist.begin() + newpos, entry); /* Make sure to shift up the current playback position if the song was inserted before it */ - if ((int)newpos <= this->playlist_position) this->playlist_position++; + if (static_cast(newpos) <= this->playlist_position) this->playlist_position++; } else { this->active_playlist.push_back(std::move(entry)); } @@ -382,7 +382,7 @@ void MusicSystem::PlaylistRemove(size_t song_index) Playlist::iterator s2 = this->active_playlist.begin() + i; if (s2->filename == song.filename && s2->cat_index == song.cat_index) { this->active_playlist.erase(s2); - if ((int)i == this->playlist_position && this->IsPlaying()) this->Play(); + if (static_cast(i) == this->playlist_position && this->IsPlaying()) this->Play(); break; } } @@ -417,8 +417,8 @@ void MusicSystem::ChangePlaylistPosition(int ofs) this->playlist_position = 0; } else { this->playlist_position += ofs; - while (this->playlist_position >= (int)this->active_playlist.size()) this->playlist_position -= (int)this->active_playlist.size(); - while (this->playlist_position < 0) this->playlist_position += (int)this->active_playlist.size(); + while (this->playlist_position >= static_cast(this->active_playlist.size())) this->playlist_position -= static_cast(this->active_playlist.size()); + while (this->playlist_position < 0) this->playlist_position += static_cast(this->active_playlist.size()); } } @@ -442,7 +442,7 @@ void MusicSystem::SaveCustomPlaylist(PlaylistChoices pl) for (const auto &song : this->standard_playlists[pl]) { /* Music set indices in the settings playlist are 1-based, 0 means unused slot */ - settings_pl[num++] = (uint8_t)song.set_index + 1; + settings_pl[num++] = static_cast(song.set_index) + 1; } } @@ -605,7 +605,7 @@ struct MusicTrackSelectionWindow : public Window { case WID_MTS_ALL: case WID_MTS_OLD: case WID_MTS_NEW: case WID_MTS_EZY: case WID_MTS_CUSTOM1: case WID_MTS_CUSTOM2: // set playlist - _music.ChangePlaylist((MusicSystem::PlaylistChoices)(widget - WID_MTS_ALL)); + _music.ChangePlaylist(static_cast(widget - WID_MTS_ALL)); break; } } @@ -848,7 +848,7 @@ struct MusicWindow : public Window { case WID_M_ALL: case WID_M_OLD: case WID_M_NEW: case WID_M_EZY: case WID_M_CUSTOM1: case WID_M_CUSTOM2: // playlist - _music.ChangePlaylist((MusicSystem::PlaylistChoices)(widget - WID_M_ALL)); + _music.ChangePlaylist(static_cast(widget - WID_M_ALL)); break; } } diff --git a/src/network/core/address.cpp b/src/network/core/address.cpp index dee1bcc1d0..3d4b7afc5a 100644 --- a/src/network/core/address.cpp +++ b/src/network/core/address.cpp @@ -25,7 +25,7 @@ const std::string &NetworkAddress::GetHostname() if (this->hostname.empty() && this->address.ss_family != AF_UNSPEC) { assert(this->address_length != 0); char buffer[NETWORK_HOSTNAME_LENGTH]; - getnameinfo((struct sockaddr *)&this->address, this->address_length, buffer, sizeof(buffer), nullptr, 0, NI_NUMERICHOST); + getnameinfo(reinterpret_cast(&this->address), this->address_length, buffer, sizeof(buffer), nullptr, 0, NI_NUMERICHOST); this->hostname = buffer; } return this->hostname; @@ -40,10 +40,10 @@ uint16_t NetworkAddress::GetPort() const switch (this->address.ss_family) { case AF_UNSPEC: case AF_INET: - return ntohs(((const struct sockaddr_in *)&this->address)->sin_port); + return ntohs((reinterpret_cast(&this->address))->sin_port); case AF_INET6: - return ntohs(((const struct sockaddr_in6 *)&this->address)->sin6_port); + return ntohs((reinterpret_cast(&this->address))->sin6_port); default: NOT_REACHED(); @@ -59,11 +59,11 @@ void NetworkAddress::SetPort(uint16_t port) switch (this->address.ss_family) { case AF_UNSPEC: case AF_INET: - ((struct sockaddr_in*)&this->address)->sin_port = htons(port); + (reinterpret_cast(&this->address))->sin_port = htons(port); break; case AF_INET6: - ((struct sockaddr_in6*)&this->address)->sin6_port = htons(port); + (reinterpret_cast(&this->address))->sin6_port = htons(port); break; default: @@ -172,13 +172,13 @@ bool NetworkAddress::IsInNetmask(const std::string &netmask) uint32_t *mask; switch (this->address.ss_family) { case AF_INET: - ip = (uint32_t*)&((struct sockaddr_in*)&this->address)->sin_addr.s_addr; - mask = (uint32_t*)&((struct sockaddr_in*)&mask_address.address)->sin_addr.s_addr; + ip = static_cast(&(reinterpret_cast(&this->address))->sin_addr.s_addr); + mask = static_cast(&(reinterpret_cast(&mask_address.address))->sin_addr.s_addr); break; case AF_INET6: - ip = (uint32_t*)&((struct sockaddr_in6*)&this->address)->sin6_addr; - mask = (uint32_t*)&((struct sockaddr_in6*)&mask_address.address)->sin6_addr; + ip = reinterpret_cast(&(reinterpret_cast(&this->address))->sin6_addr); + mask = reinterpret_cast(&(reinterpret_cast(&mask_address.address))->sin6_addr); break; default: @@ -186,7 +186,7 @@ bool NetworkAddress::IsInNetmask(const std::string &netmask) } while (cidr > 0) { - uint32_t msk = cidr >= 32 ? (uint32_t)-1 : htonl(-(1 << (32 - cidr))); + uint32_t msk = cidr >= 32 ? static_cast(-1) : htonl(-(1 << (32 - cidr))); if ((*mask++ & msk) != (*ip++ & msk)) return false; cidr -= 32; @@ -256,14 +256,14 @@ SOCKET NetworkAddress::Resolve(int family, int socktype, int flags, SocketList * * connect to one with exactly the same address twice. That's * of course totally unneeded ;) */ if (sockets != nullptr) { - NetworkAddress address(runp->ai_addr, (int)runp->ai_addrlen); + NetworkAddress address(runp->ai_addr, static_cast(runp->ai_addrlen)); if (std::any_of(sockets->begin(), sockets->end(), [&address](const auto &p) { return p.second == address; })) continue; } sock = func(runp); if (sock == INVALID_SOCKET) continue; if (sockets == nullptr) { - this->address_length = (int)runp->ai_addrlen; + this->address_length = static_cast(runp->ai_addrlen); assert(sizeof(this->address) >= runp->ai_addrlen); memcpy(&this->address, runp->ai_addr, runp->ai_addrlen); #ifdef __EMSCRIPTEN__ @@ -281,7 +281,7 @@ SOCKET NetworkAddress::Resolve(int family, int socktype, int flags, SocketList * break; } - NetworkAddress addr(runp->ai_addr, (int)runp->ai_addrlen); + NetworkAddress addr(runp->ai_addr, static_cast(runp->ai_addrlen)); (*sockets)[sock] = std::move(addr); sock = INVALID_SOCKET; } @@ -297,7 +297,7 @@ SOCKET NetworkAddress::Resolve(int family, int socktype, int flags, SocketList * */ static SOCKET ListenLoopProc(addrinfo *runp) { - std::string address = NetworkAddress(runp->ai_addr, (int)runp->ai_addrlen).GetAddressAsString(); + std::string address = NetworkAddress(runp->ai_addr, static_cast(runp->ai_addrlen)).GetAddressAsString(); SOCKET sock = socket(runp->ai_family, runp->ai_socktype, runp->ai_protocol); if (sock == INVALID_SOCKET) { @@ -317,11 +317,11 @@ static SOCKET ListenLoopProc(addrinfo *runp) int on = 1; if (runp->ai_family == AF_INET6 && - setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&on, sizeof(on)) == -1) { + setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, reinterpret_cast(&on), sizeof(on)) == -1) { Debug(net, 3, "Could not disable IPv4 over IPv6: {}", NetworkError::GetLast().AsString()); } - if (bind(sock, runp->ai_addr, (int)runp->ai_addrlen) != 0) { + if (bind(sock, runp->ai_addr, static_cast(runp->ai_addrlen)) != 0) { Debug(net, 0, "Could not bind socket on {}: {}", address, NetworkError::GetLast().AsString()); closesocket(sock); return INVALID_SOCKET; @@ -404,7 +404,7 @@ void NetworkAddress::Listen(int socktype, SocketList *sockets) { sockaddr_storage addr = {}; socklen_t addr_len = sizeof(addr); - if (getpeername(sock, (sockaddr *)&addr, &addr_len) != 0) { + if (getpeername(sock, reinterpret_cast(&addr), &addr_len) != 0) { Debug(net, 0, "Failed to get address of the peer: {}", NetworkError::GetLast().AsString()); return NetworkAddress(); } @@ -420,7 +420,7 @@ void NetworkAddress::Listen(int socktype, SocketList *sockets) { sockaddr_storage addr = {}; socklen_t addr_len = sizeof(addr); - if (getsockname(sock, (sockaddr *)&addr, &addr_len) != 0) { + if (getsockname(sock, reinterpret_cast(&addr), &addr_len) != 0) { Debug(net, 0, "Failed to get address of the socket: {}", NetworkError::GetLast().AsString()); return NetworkAddress(); } diff --git a/src/network/core/network_game_info.cpp b/src/network/core/network_game_info.cpp index 8a48c8bb4a..7e1bc8e317 100644 --- a/src/network/core/network_game_info.cpp +++ b/src/network/core/network_game_info.cpp @@ -165,7 +165,7 @@ const NetworkServerGameInfo &GetCurrentNetworkServerGameInfo() * - invite_code * These don't need to be updated manually here. */ - _network_game_info.companies_on = (uint8_t)Company::GetNumItems(); + _network_game_info.companies_on = static_cast(Company::GetNumItems()); _network_game_info.spectators_on = NetworkSpectatorCount(); _network_game_info.calendar_date = TimerGameCalendar::date; _network_game_info.ticks_playing = TimerGameTick::counter; @@ -221,7 +221,7 @@ void SerializeNetworkGameInfo(Packet &p, const NetworkServerGameInfo &info, bool /* NETWORK_GAME_INFO_VERSION = 5 */ GameInfo *game_info = Game::GetInfo(); - p.Send_uint32(game_info == nullptr ? -1 : (uint32_t)game_info->GetVersion()); + p.Send_uint32(game_info == nullptr ? -1 : static_cast(game_info->GetVersion())); p.Send_string(game_info == nullptr ? "" : game_info->GetName()); /* NETWORK_GAME_INFO_VERSION = 4 */ @@ -288,12 +288,12 @@ void DeserializeNetworkGameInfo(Packet &p, NetworkGameInfo &info, const GameInfo [[fallthrough]]; case 6: - newgrf_serialisation = (NewGRFSerializationType)p.Recv_uint8(); + newgrf_serialisation = static_cast(p.Recv_uint8()); if (newgrf_serialisation >= NST_END) return; [[fallthrough]]; case 5: { - info.gamescript_version = (int)p.Recv_uint32(); + info.gamescript_version = static_cast(p.Recv_uint32()); info.gamescript_name = p.Recv_string(NETWORK_NAME_LENGTH); [[fallthrough]]; } diff --git a/src/network/core/os_abstraction.cpp b/src/network/core/os_abstraction.cpp index 238f368f6e..e41f8fb4bc 100644 --- a/src/network/core/os_abstraction.cpp +++ b/src/network/core/os_abstraction.cpp @@ -156,7 +156,7 @@ bool SetNoDelay([[maybe_unused]] SOCKET d) #else int flags = 1; /* The (const char*) cast is needed for windows */ - return setsockopt(d, IPPROTO_TCP, TCP_NODELAY, (const char *)&flags, sizeof(flags)) == 0; + return setsockopt(d, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast(&flags), sizeof(flags)) == 0; #endif } @@ -186,7 +186,7 @@ NetworkError GetSocketError(SOCKET d) { int err; socklen_t len = sizeof(err); - if (getsockopt(d, SOL_SOCKET, SO_ERROR, (char *)&err, &len) != 0) return NetworkError(-1, "Could not get error for socket"); + if (getsockopt(d, SOL_SOCKET, SO_ERROR, reinterpret_cast(&err), &len) != 0) return NetworkError(-1, "Could not get error for socket"); return NetworkError(err); } diff --git a/src/network/core/packet.cpp b/src/network/core/packet.cpp index ef43de7ed1..3e1ab2263c 100644 --- a/src/network/core/packet.cpp +++ b/src/network/core/packet.cpp @@ -183,7 +183,7 @@ void Packet::Send_string(const std::string_view data) void Packet::Send_buffer(const std::vector &data) { assert(this->CanWriteToPacket(sizeof(uint16_t) + data.size())); - this->Send_uint16((uint16_t)data.size()); + this->Send_uint16(static_cast(data.size())); this->buffer.insert(this->buffer.end(), data.begin(), data.end()); } @@ -335,8 +335,8 @@ uint16_t Packet::Recv_uint16() if (!this->CanReadFromPacket(sizeof(n), true)) return 0; - n = (uint16_t)this->buffer[this->pos++]; - n += (uint16_t)this->buffer[this->pos++] << 8; + n = static_cast(this->buffer[this->pos++]); + n += static_cast(this->buffer[this->pos++]) << 8; return n; } @@ -350,10 +350,10 @@ uint32_t Packet::Recv_uint32() if (!this->CanReadFromPacket(sizeof(n), true)) return 0; - n = (uint32_t)this->buffer[this->pos++]; - n += (uint32_t)this->buffer[this->pos++] << 8; - n += (uint32_t)this->buffer[this->pos++] << 16; - n += (uint32_t)this->buffer[this->pos++] << 24; + n = static_cast(this->buffer[this->pos++]); + n += static_cast(this->buffer[this->pos++]) << 8; + n += static_cast(this->buffer[this->pos++]) << 16; + n += static_cast(this->buffer[this->pos++]) << 24; return n; } @@ -367,14 +367,14 @@ uint64_t Packet::Recv_uint64() if (!this->CanReadFromPacket(sizeof(n), true)) return 0; - n = (uint64_t)this->buffer[this->pos++]; - n += (uint64_t)this->buffer[this->pos++] << 8; - n += (uint64_t)this->buffer[this->pos++] << 16; - n += (uint64_t)this->buffer[this->pos++] << 24; - n += (uint64_t)this->buffer[this->pos++] << 32; - n += (uint64_t)this->buffer[this->pos++] << 40; - n += (uint64_t)this->buffer[this->pos++] << 48; - n += (uint64_t)this->buffer[this->pos++] << 56; + n = static_cast(this->buffer[this->pos++]); + n += static_cast(this->buffer[this->pos++]) << 8; + n += static_cast(this->buffer[this->pos++]) << 16; + n += static_cast(this->buffer[this->pos++]) << 24; + n += static_cast(this->buffer[this->pos++]) << 32; + n += static_cast(this->buffer[this->pos++]) << 40; + n += static_cast(this->buffer[this->pos++]) << 48; + n += static_cast(this->buffer[this->pos++]) << 56; return n; } diff --git a/src/network/core/tcp_admin.cpp b/src/network/core/tcp_admin.cpp index 12d2d02e47..5bca85400c 100644 --- a/src/network/core/tcp_admin.cpp +++ b/src/network/core/tcp_admin.cpp @@ -18,10 +18,10 @@ #include "../../safeguards.h" /* Make sure that these enums match. */ -static_assert((int)CRR_MANUAL == (int)ADMIN_CRR_MANUAL); -static_assert((int)CRR_AUTOCLEAN == (int)ADMIN_CRR_AUTOCLEAN); -static_assert((int)CRR_BANKRUPT == (int)ADMIN_CRR_BANKRUPT); -static_assert((int)CRR_END == (int)ADMIN_CRR_END); +static_assert(static_cast(CRR_MANUAL) == static_cast(ADMIN_CRR_MANUAL)); +static_assert(static_cast(CRR_AUTOCLEAN) == static_cast(ADMIN_CRR_AUTOCLEAN)); +static_assert(static_cast(CRR_BANKRUPT) == static_cast(ADMIN_CRR_BANKRUPT)); +static_assert(static_cast(CRR_END) == static_cast(ADMIN_CRR_END)); NetworkRecvStatus NetworkAdminSocketHandler::CloseConnection(bool) { @@ -36,7 +36,7 @@ NetworkRecvStatus NetworkAdminSocketHandler::CloseConnection(bool) */ NetworkRecvStatus NetworkAdminSocketHandler::HandlePacket(Packet &p) { - PacketAdminType type = (PacketAdminType)p.Recv_uint8(); + PacketAdminType type = static_cast(p.Recv_uint8()); if (this->HasClientQuit()) { Debug(net, 0, "[tcp/admin] Received invalid packet from '{}' ({})", this->admin_name, this->admin_version); diff --git a/src/network/core/tcp_connect.cpp b/src/network/core/tcp_connect.cpp index 1559f95172..ab500023e2 100644 --- a/src/network/core/tcp_connect.cpp +++ b/src/network/core/tcp_connect.cpp @@ -98,7 +98,7 @@ void TCPConnecter::Connect(addrinfo *address) } if (this->bind_address.GetPort() > 0) { - if (bind(sock, (const sockaddr *)this->bind_address.GetAddress(), this->bind_address.GetAddressLength()) != 0) { + if (bind(sock, reinterpret_cast(this->bind_address.GetAddress()), this->bind_address.GetAddressLength()) != 0) { Debug(net, 1, "Could not bind socket on {}: {}", this->bind_address.GetAddressAsString(), NetworkError::GetLast().AsString()); closesocket(sock); return; @@ -112,10 +112,10 @@ void TCPConnecter::Connect(addrinfo *address) Debug(net, 0, "Setting non-blocking mode failed: {}", NetworkError::GetLast().AsString()); } - NetworkAddress network_address = NetworkAddress(address->ai_addr, (int)address->ai_addrlen); + NetworkAddress network_address = NetworkAddress(address->ai_addr, static_cast(address->ai_addrlen)); Debug(net, 5, "Attempting to connect to {}", network_address.GetAddressAsString()); - int err = connect(sock, address->ai_addr, (int)address->ai_addrlen); + int err = connect(sock, address->ai_addr, static_cast(address->ai_addrlen)); if (err != 0 && !NetworkError::GetLast().IsConnectInProgress()) { closesocket(sock); diff --git a/src/network/core/tcp_content.cpp b/src/network/core/tcp_content.cpp index 766a4894c3..489155fbcb 100644 --- a/src/network/core/tcp_content.cpp +++ b/src/network/core/tcp_content.cpp @@ -100,7 +100,7 @@ std::optional ContentInfo::GetTextfile(TextfileType type) const */ bool NetworkContentSocketHandler::HandlePacket(Packet &p) { - PacketContentType type = (PacketContentType)p.Recv_uint8(); + PacketContentType type = static_cast(p.Recv_uint8()); switch (this->HasClientQuit() ? PACKET_CONTENT_END : type) { case PACKET_CONTENT_CLIENT_INFO_LIST: return this->Receive_CLIENT_INFO_LIST(p); diff --git a/src/network/core/tcp_coordinator.cpp b/src/network/core/tcp_coordinator.cpp index da030dd680..38322041cc 100644 --- a/src/network/core/tcp_coordinator.cpp +++ b/src/network/core/tcp_coordinator.cpp @@ -24,7 +24,7 @@ */ bool NetworkCoordinatorSocketHandler::HandlePacket(Packet &p) { - PacketCoordinatorType type = (PacketCoordinatorType)p.Recv_uint8(); + PacketCoordinatorType type = static_cast(p.Recv_uint8()); switch (type) { case PACKET_COORDINATOR_GC_ERROR: return this->Receive_GC_ERROR(p); diff --git a/src/network/core/tcp_game.cpp b/src/network/core/tcp_game.cpp index 5d072dbb92..30dbea9b24 100644 --- a/src/network/core/tcp_game.cpp +++ b/src/network/core/tcp_game.cpp @@ -60,7 +60,7 @@ NetworkRecvStatus NetworkGameSocketHandler::CloseConnection(bool) */ NetworkRecvStatus NetworkGameSocketHandler::HandlePacket(Packet &p) { - PacketGameType type = (PacketGameType)p.Recv_uint8(); + PacketGameType type = static_cast(p.Recv_uint8()); if (this->HasClientQuit()) { Debug(net, 0, "[tcp/game] Received invalid packet from client {}", this->client_id); diff --git a/src/network/core/tcp_turn.cpp b/src/network/core/tcp_turn.cpp index ae600e7bfb..a45614cebf 100644 --- a/src/network/core/tcp_turn.cpp +++ b/src/network/core/tcp_turn.cpp @@ -24,7 +24,7 @@ */ bool NetworkTurnSocketHandler::HandlePacket(Packet &p) { - PacketTurnType type = (PacketTurnType)p.Recv_uint8(); + PacketTurnType type = static_cast(p.Recv_uint8()); switch (type) { case PACKET_TURN_TURN_ERROR: return this->Receive_TURN_ERROR(p); diff --git a/src/network/core/udp.cpp b/src/network/core/udp.cpp index d3e69fce85..33640396ae 100644 --- a/src/network/core/udp.cpp +++ b/src/network/core/udp.cpp @@ -88,13 +88,13 @@ void NetworkUDPSocketHandler::SendPacket(Packet &p, NetworkAddress &recv, bool a if (broadcast) { /* Enable broadcast */ unsigned long val = 1; - if (setsockopt(s.first, SOL_SOCKET, SO_BROADCAST, (char *) &val, sizeof(val)) < 0) { + if (setsockopt(s.first, SOL_SOCKET, SO_BROADCAST, reinterpret_cast(&val), sizeof(val)) < 0) { Debug(net, 1, "Setting broadcast mode failed: {}", NetworkError::GetLast().AsString()); } } /* Send the buffer */ - ssize_t res = p.TransferOut(sendto, s.first, 0, (const struct sockaddr *)send.GetAddress(), send.GetAddressLength()); + ssize_t res = p.TransferOut(sendto, s.first, 0, reinterpret_cast(send.GetAddress()), send.GetAddressLength()); Debug(net, 7, "sendto({})", send.GetAddressAsString()); /* Check for any errors, but ignore it otherwise */ @@ -120,7 +120,7 @@ void NetworkUDPSocketHandler::ReceivePackets() /* Try to receive anything */ SetNonBlocking(s.first); // Some OSes seem to lose the non-blocking status of the socket - ssize_t nbytes = p.TransferIn(recvfrom, s.first, 0, (struct sockaddr *)&client_addr, &client_len); + ssize_t nbytes = p.TransferIn(recvfrom, s.first, 0, reinterpret_cast(&client_addr), &client_len); /* Did we get the bytes for the base header of the packet? */ if (nbytes <= 0) break; // No data, i.e. no packet @@ -160,7 +160,7 @@ void NetworkUDPSocketHandler::HandleUDPPacket(Packet &p, NetworkAddress &client_ /* New packet == new client, which has not quit yet */ this->Reopen(); - type = (PacketUDPType)p.Recv_uint8(); + type = static_cast(p.Recv_uint8()); switch (this->HasClientQuit() ? PACKET_UDP_END : type) { case PACKET_UDP_CLIENT_FIND_SERVER: this->Receive_CLIENT_FIND_SERVER(p, client_addr); break; diff --git a/src/network/network.cpp b/src/network/network.cpp index 79b7667351..5efc574cdf 100644 --- a/src/network/network.cpp +++ b/src/network/network.cpp @@ -338,7 +338,7 @@ StringID GetNetworkErrorMsg(NetworkErrorCode err) }; static_assert(lengthof(network_error_strings) == NETWORK_ERROR_END); - if (err >= (ptrdiff_t)lengthof(network_error_strings)) err = NETWORK_ERROR_GENERAL; + if (err >= static_castlengthof(network_error_strings)) err = NETWORK_ERROR_GENERAL; return network_error_strings[err]; } @@ -490,10 +490,10 @@ std::string_view ParseCompanyFromConnectionString(const std::string &connection_ *company_id = COMPANY_SPECTATOR; } else { /* "#1" means the first company, which has index 0. */ - *company_id = (CompanyID)(company_value - 1); + *company_id = CompanyID(company_value - 1); } } else { - *company_id = (CompanyID)company_value; + *company_id = CompanyID(company_value); } } } diff --git a/src/network/network_admin.cpp b/src/network/network_admin.cpp index c8a2295b94..9c02283384 100644 --- a/src/network/network_admin.cpp +++ b/src/network/network_admin.cpp @@ -660,7 +660,7 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::Receive_ADMIN_UPDATE_FREQUENC { if (this->status <= ADMIN_STATUS_AUTHENTICATE) return this->SendError(NETWORK_ERROR_NOT_EXPECTED); - AdminUpdateType type = (AdminUpdateType)p.Recv_uint16(); + AdminUpdateType type = static_cast(p.Recv_uint16()); AdminUpdateFrequencies freq = static_cast(p.Recv_uint16()); if (type >= ADMIN_UPDATE_END || !_admin_update_type_frequencies[type].All(freq)) { @@ -680,7 +680,7 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::Receive_ADMIN_POLL(Packet &p) { if (this->status <= ADMIN_STATUS_AUTHENTICATE) return this->SendError(NETWORK_ERROR_NOT_EXPECTED); - AdminUpdateType type = (AdminUpdateType)p.Recv_uint8(); + AdminUpdateType type = static_cast(p.Recv_uint8()); uint32_t d1 = p.Recv_uint32(); switch (type) { @@ -700,7 +700,7 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::Receive_ADMIN_POLL(Packet &p) if (d1 == CLIENT_ID_SERVER) { this->SendClientInfo(nullptr, NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER)); } else { - const NetworkClientSocket *cs = NetworkClientSocket::GetByClientID((ClientID)d1); + const NetworkClientSocket *cs = NetworkClientSocket::GetByClientID(static_cast(d1)); if (cs != nullptr) this->SendClientInfo(cs, cs->GetInfo()); } } @@ -746,8 +746,8 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::Receive_ADMIN_CHAT(Packet &p) { if (this->status <= ADMIN_STATUS_AUTHENTICATE) return this->SendError(NETWORK_ERROR_NOT_EXPECTED); - NetworkAction action = (NetworkAction)p.Recv_uint8(); - DestType desttype = (DestType)p.Recv_uint8(); + NetworkAction action = static_cast(p.Recv_uint8()); + DestType desttype = static_cast(p.Recv_uint8()); int dest = p.Recv_uint32(); std::string msg = p.Recv_string(NETWORK_CHAT_LENGTH); @@ -773,7 +773,7 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::Receive_ADMIN_EXTERNAL_CHAT(P if (this->status <= ADMIN_STATUS_AUTHENTICATE) return this->SendError(NETWORK_ERROR_NOT_EXPECTED); std::string source = p.Recv_string(NETWORK_CHAT_LENGTH); - TextColour colour = (TextColour)p.Recv_uint16(); + TextColour colour = static_cast(p.Recv_uint16()); std::string user = p.Recv_string(NETWORK_CHAT_LENGTH); std::string msg = p.Recv_string(NETWORK_CHAT_LENGTH); diff --git a/src/network/network_chat_gui.cpp b/src/network/network_chat_gui.cpp index cef0062ae5..fe8aca028e 100644 --- a/src/network/network_chat_gui.cpp +++ b/src/network/network_chat_gui.cpp @@ -255,9 +255,9 @@ static void SendChat(const std::string &buf, DestType type, int dest) { if (buf.empty()) return; if (!_network_server) { - MyClient::SendChat((NetworkAction)(NETWORK_ACTION_CHAT + type), type, dest, buf, 0); + MyClient::SendChat(static_cast(NETWORK_ACTION_CHAT + type), type, dest, buf, 0); } else { - NetworkServerSendChat((NetworkAction)(NETWORK_ACTION_CHAT + type), type, dest, buf, CLIENT_ID_SERVER); + NetworkServerSendChat(static_cast(NETWORK_ACTION_CHAT + type), type, dest, buf, CLIENT_ID_SERVER); } } @@ -363,7 +363,7 @@ struct NetworkChatWindow : public Window { assert((uint)this->dtype < lengthof(chat_captions)); if (this->dtype == DESTTYPE_CLIENT) { - return GetString(STR_NETWORK_CHAT_CLIENT_CAPTION, NetworkClientInfo::GetByClientID((ClientID)this->dest)->client_name); + return GetString(STR_NETWORK_CHAT_CLIENT_CAPTION, NetworkClientInfo::GetByClientID(static_cast(this->dest))->client_name); } return GetString(chat_captions[this->dtype]); diff --git a/src/network/network_client.cpp b/src/network/network_client.cpp index 928b01f828..fd5cf14e92 100644 --- a/src/network/network_client.cpp +++ b/src/network/network_client.cpp @@ -529,8 +529,8 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_BANNED(Packet & NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_CLIENT_INFO(Packet &p) { NetworkClientInfo *ci; - ClientID client_id = (ClientID)p.Recv_uint32(); - CompanyID playas = (CompanyID)p.Recv_uint8(); + ClientID client_id = static_cast(p.Recv_uint32()); + CompanyID playas = CompanyID(p.Recv_uint8()); Debug(net, 9, "Client::Receive_SERVER_CLIENT_INFO(): client_id={}, playas={}", client_id, playas); @@ -616,12 +616,12 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_ERROR(Packet &p }; static_assert(lengthof(network_error_strings) == NETWORK_ERROR_END); - NetworkErrorCode error = (NetworkErrorCode)p.Recv_uint8(); + NetworkErrorCode error = static_cast(p.Recv_uint8()); Debug(net, 9, "Client::Receive_SERVER_ERROR(): error={}", error); StringID err = STR_NETWORK_ERROR_LOSTCONNECTION; - if (error < (ptrdiff_t)lengthof(network_error_strings)) err = network_error_strings[error]; + if (error < static_castlengthof(network_error_strings)) err = network_error_strings[error]; /* In case of kicking a client, we assume there is a kick message in the packet if we can read one byte */ if (error == NETWORK_ERROR_KICKED && p.CanReadFromPacket(1)) { ShowErrorMessage(GetEncodedString(err), @@ -731,7 +731,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_WELCOME(Packet Debug(net, 9, "Client::status = AUTHORIZED"); this->status = STATUS_AUTHORIZED; - _network_own_client_id = (ClientID)p.Recv_uint32(); + _network_own_client_id = static_cast(p.Recv_uint32()); Debug(net, 9, "Client::Receive_SERVER_WELCOME(): client_id={}", _network_own_client_id); @@ -948,8 +948,8 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_CHAT(Packet &p) std::string name; const NetworkClientInfo *ci = nullptr, *ci_to; - NetworkAction action = (NetworkAction)p.Recv_uint8(); - ClientID client_id = (ClientID)p.Recv_uint32(); + NetworkAction action = static_cast(p.Recv_uint8()); + ClientID client_id = static_cast(p.Recv_uint32()); bool self_send = p.Recv_bool(); std::string msg = p.Recv_string(NETWORK_CHAT_LENGTH); int64_t data = p.Recv_uint64(); @@ -996,7 +996,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_EXTERNAL_CHAT(P if (this->status != STATUS_ACTIVE) return NETWORK_RECV_STATUS_MALFORMED_PACKET; std::string source = p.Recv_string(NETWORK_CHAT_LENGTH); - TextColour colour = (TextColour)p.Recv_uint16(); + TextColour colour = static_cast(p.Recv_uint16()); std::string user = p.Recv_string(NETWORK_CHAT_LENGTH); std::string msg = p.Recv_string(NETWORK_CHAT_LENGTH); @@ -1013,13 +1013,13 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_ERROR_QUIT(Pack { if (this->status < STATUS_AUTHORIZED) return NETWORK_RECV_STATUS_MALFORMED_PACKET; - ClientID client_id = (ClientID)p.Recv_uint32(); + ClientID client_id = static_cast(p.Recv_uint32()); Debug(net, 9, "Client::Receive_SERVER_ERROR_QUIT(): client_id={}", client_id); NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id); if (ci != nullptr) { - NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, ci->client_name, "", GetNetworkErrorMsg((NetworkErrorCode)p.Recv_uint8())); + NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, ci->client_name, "", GetNetworkErrorMsg(static_cast(p.Recv_uint8()))); delete ci; } @@ -1032,7 +1032,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_QUIT(Packet &p) { if (this->status < STATUS_AUTHORIZED) return NETWORK_RECV_STATUS_MALFORMED_PACKET; - ClientID client_id = (ClientID)p.Recv_uint32(); + ClientID client_id = static_cast(p.Recv_uint32()); Debug(net, 9, "Client::Receive_SERVER_QUIT(): client_id={}", client_id); @@ -1054,7 +1054,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_JOIN(Packet &p) { if (this->status < STATUS_AUTHORIZED) return NETWORK_RECV_STATUS_MALFORMED_PACKET; - ClientID client_id = (ClientID)p.Recv_uint32(); + ClientID client_id = static_cast(p.Recv_uint32()); Debug(net, 9, "Client::Receive_SERVER_JOIN(): client_id={}", client_id); @@ -1108,7 +1108,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_RCON(Packet &p) Debug(net, 9, "Client::Receive_SERVER_RCON()"); - TextColour colour_code = (TextColour)p.Recv_uint16(); + TextColour colour_code = static_cast(p.Recv_uint16()); if (!IsValidConsoleColour(colour_code)) return NETWORK_RECV_STATUS_MALFORMED_PACKET; std::string rcon_out = p.Recv_string(NETWORK_RCONCOMMAND_LENGTH); @@ -1123,8 +1123,8 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MOVE(Packet &p) if (this->status < STATUS_AUTHORIZED) return NETWORK_RECV_STATUS_MALFORMED_PACKET; /* Nothing more in this packet... */ - ClientID client_id = (ClientID)p.Recv_uint32(); - CompanyID company_id = (CompanyID)p.Recv_uint8(); + ClientID client_id = static_cast(p.Recv_uint32()); + CompanyID company_id = CompanyID(p.Recv_uint8()); Debug(net, 9, "Client::Receive_SERVER_MOVE(): client_id={}, comapny_id={}", client_id, company_id); diff --git a/src/network/network_command.cpp b/src/network/network_command.cpp index b1662534ff..f0d5ab901a 100644 --- a/src/network/network_command.cpp +++ b/src/network/network_command.cpp @@ -139,8 +139,8 @@ constexpr UnpackNetworkCommandProc MakeUnpackNetworkCommandCallback() noexcept using Tcallback = std::tuple_element_t; if constexpr (std::is_same_v || // Callback type is CommandCallback. std::is_same_v || // Callback type is CommandCallbackData. - std::is_same_v::CbArgs, typename CallbackArgsHelper::Args> || // Callback proc takes all command return values and parameters. - (!std::is_void_v::RetTypes> && std::is_same_v::RetCallbackProc const>::Args, typename CallbackArgsHelper::Args>)) { // Callback return is more than CommandCost and the proc takes all return values. + std::is_same_v(Tcmd)>::CbArgs, typename CallbackArgsHelper::Args> || // Callback proc takes all command return values and parameters. + (!std::is_void_v(Tcmd)>::RetTypes> && std::is_same_v(Tcmd)>::RetCallbackProc const>::Args, typename CallbackArgsHelper::Args>)) { // Callback return is more than CommandCost and the proc takes all return values. return &UnpackNetworkCommand; } else { return nullptr; @@ -362,7 +362,7 @@ void NetworkDistributeCommands() */ const char *NetworkGameSocketHandler::ReceiveCommand(Packet &p, CommandPacket &cp) { - cp.company = (CompanyID)p.Recv_uint8(); + cp.company = CompanyID(p.Recv_uint8()); cp.cmd = static_cast(p.Recv_uint16()); if (!IsValidCommand(cp.cmd)) return "invalid command"; if (GetCommandFlags(cp.cmd).Test(CommandFlag::Offline)) return "single-player only command"; @@ -393,7 +393,7 @@ void NetworkGameSocketHandler::SendCommand(Packet &p, const CommandPacket &cp) Debug(net, 0, "Unknown callback for command; no callback sent (command: {})", cp.cmd); callback = 0; // _callback_table[0] == nullptr } - p.Send_uint8 ((uint8_t)callback); + p.Send_uint8 (static_cast(callback)); } /** Helper to process a single ClientID argument. */ @@ -462,7 +462,7 @@ template CommandDataBuffer SanitizeCmdStrings(const CommandDataBuffer &data) { auto args = EndianBufferReader::ToValue::Args>(data); - SanitizeStringsHelper(CommandTraits::flags, args, std::make_index_sequence::Args>>{}); + SanitizeStringsHelper(CommandTraits::flags, args, std::make_index_sequence(Tcmd)>::Args>>{}); return EndianBufferWriter::FromValue(args); } diff --git a/src/network/network_content.cpp b/src/network/network_content.cpp index dafae1cd06..39c61a111d 100644 --- a/src/network/network_content.cpp +++ b/src/network/network_content.cpp @@ -58,8 +58,8 @@ typedef bool (*HasProc)(const ContentInfo *ci, bool md5sum); bool ClientNetworkContentSocketHandler::Receive_SERVER_INFO(Packet &p) { ContentInfo *ci = new ContentInfo(); - ci->type = (ContentType)p.Recv_uint8(); - ci->id = (ContentID)p.Recv_uint32(); + ci->type = static_cast(p.Recv_uint8()); + ci->id = static_cast(p.Recv_uint32()); ci->filesize = p.Recv_uint32(); ci->name = p.Recv_string(NETWORK_CONTENT_NAME_LENGTH); @@ -73,7 +73,7 @@ bool ClientNetworkContentSocketHandler::Receive_SERVER_INFO(Packet &p) uint dependency_count = p.Recv_uint8(); ci->dependencies.reserve(dependency_count); for (uint i = 0; i < dependency_count; i++) { - ContentID dependency_cid = (ContentID)p.Recv_uint32(); + ContentID dependency_cid = static_cast(p.Recv_uint32()); ci->dependencies.push_back(dependency_cid); this->reverse_dependency_map.emplace(dependency_cid, ci->id); } @@ -209,7 +209,7 @@ void ClientNetworkContentSocketHandler::RequestContentList(ContentType type) this->Connect(); auto p = std::make_unique(this, PACKET_CONTENT_CLIENT_INFO_LIST); - p->Send_uint8 ((uint8_t)type); + p->Send_uint8 (static_cast(type)); p->Send_uint32(0xffffffff); p->Send_uint8 (1); p->Send_string("vanilla"); @@ -273,10 +273,10 @@ void ClientNetworkContentSocketHandler::RequestContentList(ContentVector *cv, bo (sizeof(uint8_t) + sizeof(uint32_t) + (send_md5sum ? MD5_HASH_BYTES : 0))); auto p = std::make_unique(this, send_md5sum ? PACKET_CONTENT_CLIENT_INFO_EXTID_MD5 : PACKET_CONTENT_CLIENT_INFO_EXTID, TCP_MTU); - p->Send_uint8((uint8_t)cv->size()); + p->Send_uint8(static_cast(cv->size())); for (const ContentInfo *ci : *cv) { - p->Send_uint8((uint8_t)ci->type); + p->Send_uint8(static_cast(ci->type)); p->Send_uint32(ci->unique_id); if (!send_md5sum) continue; p->Send_bytes(ci->md5sum); @@ -319,7 +319,7 @@ void ClientNetworkContentSocketHandler::DownloadSelectedContent(uint &files, uin bytes += ci->filesize; } - files = (uint)content.size(); + files = static_cast(content.size()); /* If there's nothing to download, do nothing. */ if (files == 0) return; @@ -355,7 +355,7 @@ void ClientNetworkContentSocketHandler::DownloadSelectedContentHTTP(const Conten */ void ClientNetworkContentSocketHandler::DownloadSelectedContentFallback(const ContentIDList &content) { - uint count = (uint)content.size(); + uint count = static_cast(content.size()); const ContentID *content_ids = content.data(); this->Connect(); @@ -483,8 +483,8 @@ bool ClientNetworkContentSocketHandler::Receive_SERVER_CONTENT(Packet &p) delete this->curInfo; /* When we haven't opened a file this must be our first packet with metadata. */ this->curInfo = new ContentInfo; - this->curInfo->type = (ContentType)p.Recv_uint8(); - this->curInfo->id = (ContentID)p.Recv_uint32(); + this->curInfo->type = static_cast(p.Recv_uint8()); + this->curInfo->id = static_cast(p.Recv_uint32()); this->curInfo->filesize = p.Recv_uint32(); this->curInfo->filename = p.Recv_string(NETWORK_CONTENT_FILENAME_LENGTH); @@ -507,7 +507,7 @@ bool ClientNetworkContentSocketHandler::Receive_SERVER_CONTENT(Packet &p) return false; } - this->OnDownloadProgress(this->curInfo, (int)toRead); + this->OnDownloadProgress(this->curInfo, static_cast(toRead)); if (toRead == 0) this->AfterDownload(); } @@ -635,7 +635,7 @@ void ClientNetworkContentSocketHandler::OnReceiveData(std::unique_ptr da this->OnFailure(); } else { /* Just received the data. */ - this->OnDownloadProgress(this->curInfo, (int)length); + this->OnDownloadProgress(this->curInfo, static_cast(length)); } /* Nothing more to do now. */ @@ -647,7 +647,7 @@ void ClientNetworkContentSocketHandler::OnReceiveData(std::unique_ptr da this->AfterDownload(); } - if ((uint)this->http_response_index >= this->http_response.size()) { + if (static_cast(this->http_response_index) >= this->http_response.size()) { /* It's not a real failure, but if there's * nothing more to download it helps with * cleaning up the stuff we allocated. */ @@ -670,18 +670,18 @@ void ClientNetworkContentSocketHandler::OnReceiveData(std::unique_ptr da check_and_terminate(p); /* Update the index for the next one */ - this->http_response_index += (int)strlen(str) + 1; + this->http_response_index += static_cast(strlen(str)) + 1; /* Read the ID */ p = strchr(str, ','); check_and_terminate(p); - this->curInfo->id = (ContentID)atoi(str); + this->curInfo->id = static_cast(atoi(str)); /* Read the type */ str = p + 1; p = strchr(str, ','); check_and_terminate(p); - this->curInfo->type = (ContentType)atoi(str); + this->curInfo->type = static_cast(atoi(str)); /* Read the file size */ str = p + 1; @@ -693,7 +693,7 @@ void ClientNetworkContentSocketHandler::OnReceiveData(std::unique_ptr da str = p + 1; /* Is it a fallback URL? If so, just continue with the next one. */ if (strncmp(str, "ottd", 4) == 0) { - if ((uint)this->http_response_index >= this->http_response.size()) { + if (static_cast(this->http_response_index) >= this->http_response.size()) { /* Have we gone through all lines? */ this->OnFailure(); return; diff --git a/src/network/network_content_gui.cpp b/src/network/network_content_gui.cpp index 0d556f4e39..96841b7880 100644 --- a/src/network/network_content_gui.cpp +++ b/src/network/network_content_gui.cpp @@ -141,7 +141,7 @@ void BaseNetworkContentDownloadStatusWindow::DrawWidget(const Rect &r, WidgetID /* Draw the % complete with a bar and a text */ DrawFrameRect(r, COLOUR_GREY, {FrameFlag::BorderOnly, FrameFlag::Lowered}); Rect ir = r.Shrink(WidgetDimensions::scaled.bevel); - DrawFrameRect(ir.WithWidth((uint64_t)ir.Width() * this->downloaded_bytes / this->total_bytes, _current_text_dir == TD_RTL), COLOUR_MAUVE, {}); + DrawFrameRect(ir.WithWidth(static_cast(ir.Width()) * this->downloaded_bytes / this->total_bytes, _current_text_dir == TD_RTL), COLOUR_MAUVE, {}); DrawString(ir.left, ir.right, CenterBounds(ir.top, ir.bottom, GetCharacterHeight(FS_NORMAL)), GetString(STR_CONTENT_DOWNLOAD_PROGRESS_SIZE, this->downloaded_bytes, this->total_bytes, this->downloaded_bytes * 100LL / this->total_bytes), TC_FROMSTRING, SA_HOR_CENTER); @@ -593,7 +593,7 @@ public: } case WID_NCL_MATRIX: - resize.height = std::max(this->checkbox_size.height, (uint)GetCharacterHeight(FS_NORMAL)) + padding.height; + resize.height = std::max(this->checkbox_size.height, static_cast(GetCharacterHeight(FS_NORMAL))) + padding.height; size.height = 10 * resize.height; break; } @@ -775,7 +775,7 @@ public: if (widget >= WID_NCL_TEXTFILE && widget < WID_NCL_TEXTFILE + TFT_CONTENT_END) { if (this->selected == nullptr || this->selected->state != ContentInfo::ALREADY_HERE) return; - ShowContentTextfileWindow((TextfileType)(widget - WID_NCL_TEXTFILE), this->selected); + ShowContentTextfileWindow(static_cast(widget - WID_NCL_TEXTFILE), this->selected); return; } @@ -807,7 +807,7 @@ public: case WID_NCL_NAME: if (this->content.SortType() == widget - WID_NCL_CHECKBOX) { this->content.ToggleSortOrder(); - if (!this->content.empty()) this->list_pos = (int)this->content.size() - this->list_pos - 1; + if (!this->content.empty()) this->list_pos = static_cast(this->content.size()) - this->list_pos - 1; } else { this->content.SetSortType(widget - WID_NCL_CHECKBOX); this->content.ForceResort(); diff --git a/src/network/network_coordinator.cpp b/src/network/network_coordinator.cpp index 064461f52b..c84ec691e9 100644 --- a/src/network/network_coordinator.cpp +++ b/src/network/network_coordinator.cpp @@ -126,7 +126,7 @@ public: bool ClientNetworkCoordinatorSocketHandler::Receive_GC_ERROR(Packet &p) { - NetworkCoordinatorErrorType error = (NetworkCoordinatorErrorType)p.Recv_uint8(); + NetworkCoordinatorErrorType error = static_cast(p.Recv_uint8()); std::string detail = p.Recv_string(NETWORK_ERROR_DETAIL_LENGTH); switch (error) { @@ -181,7 +181,7 @@ bool ClientNetworkCoordinatorSocketHandler::Receive_GC_REGISTER_ACK(Packet &p) _settings_client.network.server_invite_code = p.Recv_string(NETWORK_INVITE_CODE_LENGTH); _settings_client.network.server_invite_code_secret = p.Recv_string(NETWORK_INVITE_CODE_SECRET_LENGTH); - _network_server_connection_type = (ConnectionType)p.Recv_uint8(); + _network_server_connection_type = static_cast(p.Recv_uint8()); if (_network_server_connection_type == CONNECTION_TYPE_ISOLATED) { ShowErrorMessage( diff --git a/src/network/network_gui.cpp b/src/network/network_gui.cpp index 82e511613e..7086f53f74 100644 --- a/src/network/network_gui.cpp +++ b/src/network/network_gui.cpp @@ -356,7 +356,7 @@ protected: /* show highlighted item with a different colour */ if (highlight) { - Rect r = {std::min(name.left, info.left), y, std::max(name.right, info.right), y + (int)this->resize.step_height - 1}; + Rect r = {std::min(name.left, info.left), y, std::max(name.right, info.right), y + static_cast(this->resize.step_height) - 1}; GfxFillRect(r.Shrink(WidgetDimensions::scaled.bevel), PC_GREY); } @@ -476,13 +476,13 @@ public: { switch (widget) { case WID_NG_MATRIX: - resize.height = std::max(GetSpriteSize(SPR_BLOT).height, (uint)GetCharacterHeight(FS_NORMAL)) + padding.height; + resize.height = std::max(GetSpriteSize(SPR_BLOT).height, static_cast(GetCharacterHeight(FS_NORMAL))) + padding.height; fill.height = resize.height; size.height = 12 * resize.height; break; case WID_NG_LASTJOINED: - size.height = std::max(GetSpriteSize(SPR_BLOT).height, (uint)GetCharacterHeight(FS_NORMAL)) + WidgetDimensions::scaled.matrix.Vertical(); + size.height = std::max(GetSpriteSize(SPR_BLOT).height, static_cast(GetCharacterHeight(FS_NORMAL))) + WidgetDimensions::scaled.matrix.Vertical(); break; case WID_NG_LASTJOINED_SPACER: @@ -683,7 +683,7 @@ public: case WID_NG_INFO: // Connectivity (green dot) if (this->servers.SortType() == widget - WID_NG_NAME) { this->servers.ToggleSortOrder(); - if (this->list_pos != SLP_INVALID) this->list_pos = (ServerListPosition)this->servers.size() - this->list_pos - 1; + if (this->list_pos != SLP_INVALID) this->list_pos = static_cast(this->servers.size()) - this->list_pos - 1; } else { this->servers.SetSortType(widget - WID_NG_NAME); this->servers.ForceResort(); @@ -1091,7 +1091,7 @@ struct NetworkStartServerWindow : public Window { { switch (widget) { case WID_NSS_CONNTYPE_BTN: - _settings_client.network.server_game_type = (ServerGameType)index; + _settings_client.network.server_game_type = static_cast(index); break; default: NOT_REACHED(); @@ -1657,7 +1657,7 @@ public: case WID_CL_MATRIX: { uint height = std::max({GetSpriteSize(SPR_COMPANY_ICON).height, GetSpriteSize(SPR_JOIN).height, GetSpriteSize(SPR_ADMIN).height, GetSpriteSize(SPR_CHAT).height}); height += WidgetDimensions::scaled.framerect.Vertical(); - this->line_height = std::max(height, (uint)GetCharacterHeight(FS_NORMAL)) + padding.height; + this->line_height = std::max(height, static_cast(GetCharacterHeight(FS_NORMAL))) + padding.height; resize.width = 1; resize.height = this->line_height; @@ -1786,7 +1786,7 @@ public: case WID_CL_SERVER_VISIBILITY: if (!_network_server) break; - _settings_client.network.server_game_type = (ServerGameType)index; + _settings_client.network.server_game_type = static_cast(index); NetworkUpdateServerGameType(); break; diff --git a/src/network/network_query.cpp b/src/network/network_query.cpp index a648ebde30..34d73c25cb 100644 --- a/src/network/network_query.cpp +++ b/src/network/network_query.cpp @@ -136,7 +136,7 @@ NetworkRecvStatus QueryNetworkGameSocketHandler::Receive_SERVER_GAME_INFO(Packet NetworkRecvStatus QueryNetworkGameSocketHandler::Receive_SERVER_ERROR(Packet &p) { - NetworkErrorCode error = (NetworkErrorCode)p.Recv_uint8(); + NetworkErrorCode error = static_cast(p.Recv_uint8()); Debug(net, 9, "Query::Receive_SERVER_ERROR(): error={}", error); diff --git a/src/network/network_server.cpp b/src/network/network_server.cpp index eaa5e93ace..93fd610b39 100644 --- a/src/network/network_server.cpp +++ b/src/network/network_server.cpp @@ -176,7 +176,7 @@ struct PacketWriter : SaveFilter { /* Fast-track the size to the client. */ auto p = std::make_unique(this->cs, PACKET_SERVER_MAP_SIZE); - p->Send_uint32((uint32_t)this->total_size); + p->Send_uint32(static_cast(this->total_size)); this->packets.push_front(std::move(p)); } }; @@ -874,7 +874,7 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_IDENTIFY(Packet Debug(net, 9, "client[{}] Receive_CLIENT_IDENTIFY()", this->client_id); std::string client_name = p.Recv_string(NETWORK_CLIENT_NAME_LENGTH); - CompanyID playas = (Owner)p.Recv_uint8(); + CompanyID playas = Owner(p.Recv_uint8()); if (this->HasClientQuit()) return NETWORK_RECV_STATUS_CLIENT_QUIT; @@ -1138,7 +1138,7 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_ERROR(Packet &p { /* This packets means a client noticed an error and is reporting this * to us. Display the error and report it to the other clients */ - NetworkErrorCode errorno = (NetworkErrorCode)p.Recv_uint8(); + NetworkErrorCode errorno = static_cast(p.Recv_uint8()); Debug(net, 9, "client[{}] Receive_CLIENT_ERROR(): errorno={}", this->client_id, errorno); @@ -1255,7 +1255,7 @@ void NetworkServerSendChat(NetworkAction action, DestType desttype, int dest, co switch (desttype) { case DESTTYPE_CLIENT: /* Are we sending to the server? */ - if ((ClientID)dest == CLIENT_ID_SERVER) { + if (static_cast(dest) == CLIENT_ID_SERVER) { ci = NetworkClientInfo::GetByClientID(from_id); /* Display the text locally, and that is it */ if (ci != nullptr) { @@ -1268,7 +1268,7 @@ void NetworkServerSendChat(NetworkAction action, DestType desttype, int dest, co } else { /* Else find the client to send the message to */ for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) { - if (cs->client_id == (ClientID)dest && cs->status >= ServerNetworkGameSocketHandler::STATUS_AUTHORIZED) { + if (cs->client_id == static_cast(dest) && cs->status >= ServerNetworkGameSocketHandler::STATUS_AUTHORIZED) { cs->SendChat(action, from_id, false, msg, data); break; } @@ -1276,17 +1276,17 @@ void NetworkServerSendChat(NetworkAction action, DestType desttype, int dest, co } /* Display the message locally (so you know you have sent it) */ - if (from_id != (ClientID)dest) { + if (from_id != static_cast(dest)) { if (from_id == CLIENT_ID_SERVER) { ci = NetworkClientInfo::GetByClientID(from_id); - ci_to = NetworkClientInfo::GetByClientID((ClientID)dest); + ci_to = NetworkClientInfo::GetByClientID(static_cast(dest)); if (ci != nullptr && ci_to != nullptr) { NetworkTextMessage(action, GetDrawStringCompanyColour(ci->client_playas), true, ci_to->client_name, msg, data); } } else { for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) { if (cs->client_id == from_id && cs->status >= ServerNetworkGameSocketHandler::STATUS_AUTHORIZED) { - cs->SendChat(action, (ClientID)dest, true, msg, data); + cs->SendChat(action, static_cast(dest), true, msg, data); break; } } @@ -1300,7 +1300,7 @@ void NetworkServerSendChat(NetworkAction action, DestType desttype, int dest, co ci_to = nullptr; for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) { ci = cs->GetInfo(); - if (ci != nullptr && ci->client_playas == (CompanyID)dest && cs->status >= ServerNetworkGameSocketHandler::STATUS_AUTHORIZED) { + if (ci != nullptr && ci->client_playas == CompanyID(dest) && cs->status >= ServerNetworkGameSocketHandler::STATUS_AUTHORIZED) { cs->SendChat(action, from_id, false, msg, data); if (cs->client_id == from_id) show_local = false; ci_to = ci; // Remember a client that is in the company for company-name @@ -1308,7 +1308,7 @@ void NetworkServerSendChat(NetworkAction action, DestType desttype, int dest, co } /* if the server can read it, let the admin network read it, too. */ - if (_local_company == (CompanyID)dest && _settings_client.network.server_admin_chat) { + if (_local_company == CompanyID(dest) && _settings_client.network.server_admin_chat) { NetworkAdminChat(action, desttype, from_id, msg, data, from_admin); } @@ -1380,8 +1380,8 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_CHAT(Packet &p) return this->SendError(NETWORK_ERROR_NOT_AUTHORIZED); } - NetworkAction action = (NetworkAction)p.Recv_uint8(); - DestType desttype = (DestType)p.Recv_uint8(); + NetworkAction action = static_cast(p.Recv_uint8()); + DestType desttype = static_cast(p.Recv_uint8()); int dest = p.Recv_uint32(); Debug(net, 9, "client[{}] Receive_CLIENT_CHAT(): action={}, desttype={}, dest={}", this->client_id, action, desttype, dest); @@ -1467,7 +1467,7 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_MOVE(Packet &p) { if (this->status != STATUS_ACTIVE) return this->SendError(NETWORK_ERROR_NOT_EXPECTED); - CompanyID company_id = (Owner)p.Recv_uint8(); + CompanyID company_id = Owner(p.Recv_uint8()); Debug(net, 9, "client[{}] Receive_CLIENT_MOVE(): company_id={}", this->client_id, company_id); @@ -1719,7 +1719,7 @@ void NetworkServer_Tick(bool send_frame) * did not receive a packet, then the client is not just * slow, but the connection is likely severed. Mentioning * frame_freq is not useful in this case. */ - if (lag > (uint)Ticks::DAY_TICKS && cs->lag_test == 0 && cs->last_packet + std::chrono::seconds(2) > std::chrono::steady_clock::now()) { + if (lag > static_cast(Ticks::DAY_TICKS) && cs->lag_test == 0 && cs->last_packet + std::chrono::seconds(2) > std::chrono::steady_clock::now()) { IConsolePrint(CC_WARNING, "[{}] Client #{} is slow, try increasing [network.]frame_freq to a higher value!", _frame_counter, cs->client_id); cs->lag_test = 1; } @@ -1943,7 +1943,7 @@ void NetworkServerShowStatusToConsole() uint lag = NetworkCalculateLag(cs); const char *status; - status = (cs->status < (ptrdiff_t)lengthof(stat_str) ? stat_str[cs->status] : "unknown"); + status = (cs->status < static_castlengthof(stat_str) ? stat_str[cs->status] : "unknown"); IConsolePrint(CC_INFO, "Client #{} name: '{}' status: '{}' frame-lag: {} company: {} IP: {}", cs->client_id, ci->client_name, status, lag, ci->client_playas + (Company::IsValidID(ci->client_playas) ? 1 : 0), diff --git a/src/newgrf.cpp b/src/newgrf.cpp index 0e2a85d0c3..934f211260 100644 --- a/src/newgrf.cpp +++ b/src/newgrf.cpp @@ -760,7 +760,7 @@ static TileLayoutFlags ReadSpriteLayoutSprite(ByteReader &buf, bool read_flags, { grf_sprite->sprite = buf.ReadWord(); grf_sprite->pal = buf.ReadWord(); - TileLayoutFlags flags = read_flags ? (TileLayoutFlags)buf.ReadWord() : TLF_NOTHING; + TileLayoutFlags flags = read_flags ? static_cast(buf.ReadWord()) : TLF_NOTHING; MapSpriteMappingRecolour(grf_sprite); @@ -993,7 +993,7 @@ static void ConvertTTDBasePrice(uint32_t base_pointer, const char *error_locatio return; } - *index = (Price)((base_pointer - start) / size); + *index = static_cast((base_pointer - start) / size); } /** Possible return values for the FeatureChangeInfo functions */ @@ -2186,7 +2186,7 @@ static ChangeInfoResult StationChangeInfo(uint first, uint last, int prop, ByteR if (_cur.grffile->grf_version >= 7) { statspec->cargo_triggers = TranslateRefitMask(buf.ReadDWord()); } else { - statspec->cargo_triggers = (CargoTypes)buf.ReadDWord(); + statspec->cargo_triggers = static_cast(buf.ReadDWord()); } break; @@ -2582,7 +2582,7 @@ static ChangeInfoResult TownHouseChangeInfo(uint first, uint last, int prop, Byt } case 0x09: // Building flags - housespec->building_flags = (BuildingFlags)buf.ReadByte(); + housespec->building_flags = BuildingFlags(buf.ReadByte()); break; case 0x0A: { // Availability years @@ -2635,7 +2635,7 @@ static ChangeInfoResult TownHouseChangeInfo(uint first, uint last, int prop, Byt break; case 0x13: // Building availability mask - housespec->building_availability = (HouseZones)buf.ReadWord(); + housespec->building_availability = static_cast(buf.ReadWord()); break; case 0x14: { // House callback mask @@ -3500,7 +3500,7 @@ static ChangeInfoResult IndustrytilesChangeInfo(uint first, uint last, int prop, } case 0x0D: // Land shape flags - tsp->slopes_refused = (Slope)buf.ReadByte(); + tsp->slopes_refused = static_cast(buf.ReadByte()); break; case 0x0E: // Callback mask @@ -3535,7 +3535,7 @@ static ChangeInfoResult IndustrytilesChangeInfo(uint first, uint last, int prop, if (i < num_cargoes) { tsp->accepts_cargo[i] = GetCargoTranslation(buf.ReadByte(), _cur.grffile); /* Tile acceptance can be negative to counteract the IndustryTileSpecialFlag::AcceptsAllCargo flag */ - tsp->acceptance[i] = (int8_t)buf.ReadByte(); + tsp->acceptance[i] = static_cast(buf.ReadByte()); } else { tsp->accepts_cargo[i] = INVALID_CARGO; tsp->acceptance[i] = 0; @@ -3825,8 +3825,8 @@ static ChangeInfoResult IndustriesChangeInfo(uint first, uint last, int prop, By it.gfx = tempid; } } else if (it.gfx == GFX_WATERTILE_SPECIALCHECK) { - it.ti.x = (int8_t)GB(it.ti.x, 0, 8); - it.ti.y = (int8_t)GB(it.ti.y, 0, 8); + it.ti.x = static_cast(GB(it.ti.x, 0, 8)); + it.ti.y = static_cast(GB(it.ti.y, 0, 8)); /* When there were only 256x256 maps, TileIndex was a uint16_t and * it.ti was just a TileIndexDiff that was added to it. @@ -4184,7 +4184,7 @@ static ChangeInfoResult AirportChangeInfo(uint first, uint last, int prop, ByteR break; case 0x0D: - as->ttd_airport_type = (TTDPAirportType)buf.ReadByte(); + as->ttd_airport_type = static_cast(buf.ReadByte()); break; case 0x0E: @@ -4345,7 +4345,7 @@ static ChangeInfoResult ObjectChangeInfo(uint first, uint last, int prop, ByteRe break; case 0x10: // Flags - spec->flags = (ObjectFlags)buf.ReadWord(); + spec->flags = ObjectFlags(buf.ReadWord()); _loaded_newgrf_features.has_2CC |= spec->flags.Test(ObjectFlag::Uses2CC); break; @@ -5062,7 +5062,7 @@ static ChangeInfoResult RoadStopChangeInfo(uint first, uint last, int prop, Byte } case 0x09: // Road stop type - rs->stop_type = (RoadStopAvailabilityType)buf.ReadByte(); + rs->stop_type = static_cast(buf.ReadByte()); break; case 0x0A: // Road Stop Name @@ -5487,7 +5487,7 @@ static void NewSpriteGroup(ByteReader &buf) DeterministicSpriteGroupAdjust &adjust = group->adjusts.emplace_back(); /* The first var adjust doesn't have an operation specified, so we set it to add. */ - adjust.operation = group->adjusts.size() == 1 ? DSGA_OP_ADD : (DeterministicSpriteGroupAdjustOperation)buf.ReadByte(); + adjust.operation = group->adjusts.size() == 1 ? DSGA_OP_ADD : static_cast(buf.ReadByte()); adjust.variable = buf.ReadByte(); if (adjust.variable == 0x7E) { /* Link subroutine group */ @@ -5498,7 +5498,7 @@ static void NewSpriteGroup(ByteReader &buf) varadjust = buf.ReadByte(); adjust.shift_num = GB(varadjust, 0, 5); - adjust.type = (DeterministicSpriteGroupAdjustType)GB(varadjust, 6, 2); + adjust.type = static_cast(GB(varadjust, 6, 2)); adjust.and_mask = buf.ReadVarSize(varsize); if (adjust.type != DSGA_TYPE_NONE) { @@ -5693,7 +5693,7 @@ static void NewSpriteGroup(ByteReader &buf) case GSF_OBJECTS: case GSF_INDUSTRYTILES: case GSF_ROADSTOPS: { - uint8_t num_building_sprites = std::max((uint8_t)1, type); + uint8_t num_building_sprites = std::max(static_cast(1), type); assert(TileLayoutSpriteGroup::CanAllocateItem()); TileLayoutSpriteGroup *group = new TileLayoutSpriteGroup(); @@ -5719,7 +5719,7 @@ static void NewSpriteGroup(ByteReader &buf) if (type == 0) { group->num_input = INDUSTRY_ORIGINAL_NUM_INPUTS; for (uint i = 0; i < INDUSTRY_ORIGINAL_NUM_INPUTS; i++) { - group->subtract_input[i] = (int16_t)buf.ReadWord(); // signed + group->subtract_input[i] = static_cast(buf.ReadWord()); // signed } group->num_output = INDUSTRY_ORIGINAL_NUM_OUTPUTS; for (uint i = 0; i < INDUSTRY_ORIGINAL_NUM_OUTPUTS; i++) { @@ -5878,7 +5878,7 @@ static void VehicleMapSpriteGroup(ByteReader &buf, uint8_t feature, uint8_t idco std::vector engines; engines.reserve(idcount); for (uint i = 0; i < idcount; i++) { - Engine *e = GetNewEngine(_cur.grffile, (VehicleType)feature, buf.ReadExtendedByte()); + Engine *e = GetNewEngine(_cur.grffile, static_cast(feature), buf.ReadExtendedByte()); if (e == nullptr) { /* No engine could be allocated?!? Deal with it. Okay, * this might look bad. Also make sure this NewGRF @@ -6608,7 +6608,7 @@ static void FeatureNewName(ByteReader &buf) case GSF_SHIPS: case GSF_AIRCRAFT: if (!generic) { - Engine *e = GetNewEngine(_cur.grffile, (VehicleType)feature, id, _cur.grfconfig->flags.Test(GRFConfigFlag::Static)); + Engine *e = GetNewEngine(_cur.grffile, static_cast(feature), id, _cur.grfconfig->flags.Test(GRFConfigFlag::Static)); if (e == nullptr) break; StringID string = AddGRFString(_cur.grffile->grfid, GRFStringID{feature_overlay | e->index.base()}, lang, new_scheme, false, name, e->info.string_id); e->info.string_id = string; @@ -7909,22 +7909,22 @@ static void ParamSet(ByteReader &buf) break; case 0x04: - res = (int32_t)src1 * (int32_t)src2; + res = static_cast(src1) * static_cast(src2); break; case 0x05: - if ((int32_t)src2 < 0) { - res = src1 >> -(int32_t)src2; + if (static_cast(src2) < 0) { + res = src1 >> -static_cast(src2); } else { res = src1 << (src2 & 0x1F); // Same behaviour as in EvalAdjustT, mask 'value' to 5 bits, which should behave the same on all architectures. } break; case 0x06: - if ((int32_t)src2 < 0) { - res = (int32_t)src1 >> -(int32_t)src2; + if (static_cast(src2) < 0) { + res = static_cast(src1) >> -static_cast(src2); } else { - res = (int32_t)src1 << (src2 & 0x1F); // Same behaviour as in EvalAdjustT, mask 'value' to 5 bits, which should behave the same on all architectures. + res = static_cast(src1) << (src2 & 0x1F); // Same behaviour as in EvalAdjustT, mask 'value' to 5 bits, which should behave the same on all architectures. } break; @@ -7948,7 +7948,7 @@ static void ParamSet(ByteReader &buf) if (src2 == 0) { res = src1; } else { - res = (int32_t)src1 / (int32_t)src2; + res = static_cast(src1) / static_cast(src2); } break; @@ -7964,7 +7964,7 @@ static void ParamSet(ByteReader &buf) if (src2 == 0) { res = src1; } else { - res = (int32_t)src1 % (int32_t)src2; + res = static_cast(src1) % static_cast(src2); } break; @@ -8342,7 +8342,7 @@ static void LoadFontGlyph(ByteReader &buf) uint8_t num_def = buf.ReadByte(); for (uint i = 0; i < num_def; i++) { - FontSize size = (FontSize)buf.ReadByte(); + FontSize size = static_cast(buf.ReadByte()); uint8_t num_char = buf.ReadByte(); uint16_t base_char = buf.ReadWord(); @@ -8576,7 +8576,7 @@ static bool ChangeGRFParamType(size_t len, ByteReader &buf) GrfMsg(2, "StaticGRFInfo: expected 1 byte for 'INFO'->'PARA'->'TYPE' but got {}, ignoring this field", len); buf.Skip(len); } else { - GRFParameterType type = (GRFParameterType)buf.ReadByte(); + GRFParameterType type = static_cast(buf.ReadByte()); if (type < PTYPE_END) { _cur_parameter->type = type; } else { @@ -9449,7 +9449,7 @@ static void CalculateRefitMasks() if (!IsValidCargoType(ei->cargo_type)) { /* Use first refittable cargo slot */ - ei->cargo_type = (CargoType)FindFirstBit(ei->refit_mask); + ei->cargo_type = static_cast(FindFirstBit(ei->refit_mask)); } } if (!IsValidCargoType(ei->cargo_type) && e->type == VEH_TRAIN && e->u.rail.railveh_type != RAILVEH_WAGON && e->u.rail.capacity == 0) { @@ -9712,7 +9712,7 @@ static void FinaliseHouseArray() } } - HouseZones climate_mask = (HouseZones)(1 << (to_underlying(_settings_game.game_creation.landscape) + 12)); + HouseZones climate_mask = static_cast(1 << (to_underlying(_settings_game.game_creation.landscape) + 12)); EnsureEarlyHouse(HZ_ZON1 | climate_mask); EnsureEarlyHouse(HZ_ZON2 | climate_mask); EnsureEarlyHouse(HZ_ZON3 | climate_mask); @@ -10096,7 +10096,7 @@ static void FinalisePriceBaseMultipliers() static const uint32_t override_features = (1 << GSF_TRAINS) | (1 << GSF_ROADVEHICLES) | (1 << GSF_SHIPS) | (1 << GSF_AIRCRAFT); /* Evaluate grf overrides */ - int num_grfs = (uint)_grf_files.size(); + int num_grfs = static_cast(_grf_files.size()); std::vector grf_overrides(num_grfs, -1); for (int i = 0; i < num_grfs; i++) { GRFFile *source = _grf_files[i]; diff --git a/src/newgrf_airport.cpp b/src/newgrf_airport.cpp index 7d5ad89f1c..a2ef1b8739 100644 --- a/src/newgrf_airport.cpp +++ b/src/newgrf_airport.cpp @@ -276,7 +276,7 @@ uint16_t GetAirportCallback(CallbackID callback, uint32_t param1, uint32_t param */ StringID GetAirportTextCallback(const AirportSpec *as, uint8_t layout, uint16_t callback) { - AirportResolverObject object(INVALID_TILE, nullptr, as, layout, (CallbackID)callback); + AirportResolverObject object(INVALID_TILE, nullptr, as, layout, static_cast(callback)); uint16_t cb_res = object.ResolveCallback(); if (cb_res == CALLBACK_FAILED || cb_res == 0x400) return STR_UNDEFINED; if (cb_res > 0x400) { diff --git a/src/newgrf_airporttiles.cpp b/src/newgrf_airporttiles.cpp index 8f5650d69e..04c1808b75 100644 --- a/src/newgrf_airporttiles.cpp +++ b/src/newgrf_airporttiles.cpp @@ -304,7 +304,7 @@ void AirportTileAnimationTrigger(Station *st, TileIndex tile, AirpAnimationTrigg const AirportTileSpec *ats = AirportTileSpec::GetByTile(tile); if (!HasBit(ats->animation.triggers, trigger)) return; - AirportTileAnimationBase::ChangeAnimationFrame(CBID_AIRPTILE_ANIM_START_STOP, ats, st, tile, Random(), (uint8_t)trigger | (cargo_type << 8)); + AirportTileAnimationBase::ChangeAnimationFrame(CBID_AIRPTILE_ANIM_START_STOP, ats, st, tile, Random(), static_cast(trigger) | (cargo_type << 8)); } void AirportAnimationTrigger(Station *st, AirpAnimationTrigger trigger, CargoType cargo_type) diff --git a/src/newgrf_commons.cpp b/src/newgrf_commons.cpp index 4c8dcf8f57..a5167ef468 100644 --- a/src/newgrf_commons.cpp +++ b/src/newgrf_commons.cpp @@ -685,7 +685,7 @@ void NewGRFSpriteLayout::ProcessRegisters(uint8_t resolved_var10, uint32_t resol } else { if (HasBit(result.image.sprite, SPRITE_MODIFIER_CUSTOM_SPRITE)) result.image.sprite += resolved_sprite; if (flags & TLF_SPRITE) { - int16_t offset = (int16_t)GetRegister(regs->sprite); // mask to 16 bits to avoid trouble + int16_t offset = static_cast(GetRegister(regs->sprite)); // mask to 16 bits to avoid trouble if (!HasBit(result.image.sprite, SPRITE_MODIFIER_CUSTOM_SPRITE) || (offset >= 0 && offset < regs->max_sprite_offset)) { result.image.sprite += offset; } else { @@ -715,7 +715,7 @@ void NewGRFSpriteLayout::ProcessRegisters(uint8_t resolved_var10, uint32_t resol /* Apply registers */ if (HasBit(result.image.pal, SPRITE_MODIFIER_CUSTOM_SPRITE)) result.image.pal += resolved_sprite; if (flags & TLF_PALETTE) { - int16_t offset = (int16_t)GetRegister(regs->palette); // mask to 16 bits to avoid trouble + int16_t offset = static_cast(GetRegister(regs->palette)); // mask to 16 bits to avoid trouble if (!HasBit(result.image.pal, SPRITE_MODIFIER_CUSTOM_SPRITE) || (offset >= 0 && offset < regs->max_palette_offset)) { result.image.pal += offset; } else { diff --git a/src/newgrf_debug_gui.cpp b/src/newgrf_debug_gui.cpp index 40fabd2e0c..8984052d84 100644 --- a/src/newgrf_debug_gui.cpp +++ b/src/newgrf_debug_gui.cpp @@ -230,7 +230,7 @@ struct NIFeature { */ static inline GrfSpecFeature GetFeatureNum(uint window_number) { - return (GrfSpecFeature)GB(window_number, 24, 8); + return static_cast(GB(window_number, 24, 8)); } /** @@ -355,7 +355,7 @@ struct NewGRFInspectWindow : Window { case WID_NGRFI_VEH_CHAIN: { assert(this->HasChainIndex()); GrfSpecFeature f = GetFeatureNum(this->window_number); - size.height = std::max(size.height, GetVehicleImageCellSize((VehicleType)(VEH_TRAIN + (f - GSF_TRAINS)), EIT_IN_DEPOT).height + 2 + WidgetDimensions::scaled.bevel.Vertical()); + size.height = std::max(size.height, GetVehicleImageCellSize(static_cast(VEH_TRAIN + (f - GSF_TRAINS)), EIT_IN_DEPOT).height + 2 + WidgetDimensions::scaled.bevel.Vertical()); break; } @@ -411,7 +411,7 @@ struct NewGRFInspectWindow : Window { } GrfSpecFeature f = GetFeatureNum(this->window_number); - int h = GetVehicleImageCellSize((VehicleType)(VEH_TRAIN + (f - GSF_TRAINS)), EIT_IN_DEPOT).height; + int h = GetVehicleImageCellSize(static_cast(VEH_TRAIN + (f - GSF_TRAINS)), EIT_IN_DEPOT).height; int y = CenterBounds(br.top, br.bottom, h); DrawVehicleImage(v->First(), br, VehicleID::Invalid(), EIT_IN_DETAILS, skip); @@ -490,9 +490,9 @@ struct NewGRFInspectWindow : Window { const void *ptr = nip.offset_proc(base); uint value; switch (nip.read_size) { - case 1: value = *(const uint8_t *)ptr; break; - case 2: value = *(const uint16_t *)ptr; break; - case 4: value = *(const uint32_t *)ptr; break; + case 1: value = *static_cast(ptr); break; + case 2: value = *static_cast(ptr); break; + case 4: value = *static_cast(ptr); break; default: NOT_REACHED(); } @@ -507,9 +507,9 @@ struct NewGRFInspectWindow : Window { const void *ptr = nic.offset_proc(base_spec); uint value; switch (nic.read_size) { - case 1: value = *(const uint8_t *)ptr; break; - case 2: value = *(const uint16_t *)ptr; break; - case 4: value = *(const uint32_t *)ptr; break; + case 1: value = *static_cast(ptr); break; + case 2: value = *static_cast(ptr); break; + case 4: value = *static_cast(ptr); break; default: NOT_REACHED(); } diff --git a/src/newgrf_engine.cpp b/src/newgrf_engine.cpp index a6f7cb34e8..55883508e1 100644 --- a/src/newgrf_engine.cpp +++ b/src/newgrf_engine.cpp @@ -621,7 +621,7 @@ static uint32_t VehicleGetVariable(Vehicle *v, const VehicleScopeResolver *objec if (object->ro.callback == CBID_NO_CALLBACK || object->ro.callback == CBID_RANDOM_TRIGGER || object->ro.callback == CBID_TRAIN_ALLOW_WAGON_ATTACH || object->ro.callback == CBID_VEHICLE_START_STOP_CHECK || object->ro.callback == CBID_VEHICLE_32DAY_CALLBACK || object->ro.callback == CBID_VEHICLE_COLOUR_MAPPING || object->ro.callback == CBID_VEHICLE_SPAWN_VISUAL_EFFECT) { - Vehicle *u = v->Move((int32_t)GetRegister(0x10F)); + Vehicle *u = v->Move(static_cast(GetRegister(0x10F))); if (u == nullptr) return 0; // available, but zero if (parameter == 0x5F) { @@ -644,11 +644,11 @@ static uint32_t VehicleGetVariable(Vehicle *v, const VehicleScopeResolver *objec */ if (!v->IsGroundVehicle()) return 0; - const Vehicle *u = v->Move((int8_t)parameter); + const Vehicle *u = v->Move(static_cast(parameter)); if (u == nullptr) return 0; /* Get direction difference. */ - bool prev = (int8_t)parameter < 0; + bool prev = static_cast(parameter) < 0; uint32_t ret = prev ? DirDifference(u->direction, v->direction) : DirDifference(v->direction, u->direction); if (ret > DIRDIFF_REVERSE) ret |= 0x08; @@ -1012,7 +1012,7 @@ static uint32_t VehicleGetVariable(Vehicle *v, const VehicleScopeResolver *objec bool not_loading = (order.GetUnloadType() & OUFB_NO_UNLOAD) && (order.GetLoadType() & OLFB_NO_LOAD); bool in_motion = !order.IsType(OT_LOADING) || not_loading; - uint totalsets = in_motion ? (uint)group->loaded.size() : (uint)group->loading.size(); + uint totalsets = in_motion ? static_cast(group->loaded.size()) : static_cast(group->loading.size()); if (totalsets == 0) return nullptr; diff --git a/src/newgrf_generic.cpp b/src/newgrf_generic.cpp index fb5f7d80c0..a8bb78af7c 100644 --- a/src/newgrf_generic.cpp +++ b/src/newgrf_generic.cpp @@ -64,7 +64,7 @@ struct GenericResolverObject : public ResolverObject { GrfSpecFeature GetFeature() const override { - return (GrfSpecFeature)this->generic_scope.feature; + return static_cast(this->generic_scope.feature); } uint32_t GetDebugID() const override diff --git a/src/newgrf_gui.cpp b/src/newgrf_gui.cpp index 45e496a940..9860be5183 100644 --- a/src/newgrf_gui.cpp +++ b/src/newgrf_gui.cpp @@ -228,7 +228,7 @@ struct NewGRFParametersWindow : public Window { case WID_NP_DESCRIPTION: /* Minimum size of 4 lines. The 500 is the default size of the window. */ - Dimension suggestion = {500U - WidgetDimensions::scaled.frametext.Horizontal(), (uint)GetCharacterHeight(FS_NORMAL) * 4 + WidgetDimensions::scaled.frametext.Vertical()}; + Dimension suggestion = {500U - WidgetDimensions::scaled.frametext.Horizontal(), static_cast(GetCharacterHeight(FS_NORMAL)) * 4 + WidgetDimensions::scaled.frametext.Vertical()}; for (const auto &par_info : this->grf_config.param_info) { if (!par_info.has_value()) continue; const char *desc = GetGRFStringFromGRFText(par_info->desc); @@ -925,7 +925,7 @@ struct NewGRFWindow : public Window, NewGRFScanCallback { if (widget >= WID_NS_NEWGRF_TEXTFILE && widget < WID_NS_NEWGRF_TEXTFILE + TFT_CONTENT_END) { if (this->active_sel == nullptr && this->avail_sel == nullptr) return; - ShowNewGRFTextfileWindow((TextfileType)(widget - WID_NS_NEWGRF_TEXTFILE), this->active_sel != nullptr ? this->active_sel : this->avail_sel); + ShowNewGRFTextfileWindow(static_cast(widget - WID_NS_NEWGRF_TEXTFILE), this->active_sel != nullptr ? this->active_sel : this->avail_sel); return; } @@ -1493,7 +1493,7 @@ private: /* Select next (or previous, if last one) item in the list. */ int new_pos = this->avail_pos + 1; - if (new_pos >= (int)this->avails.size()) new_pos = this->avail_pos - 1; + if (new_pos >= static_cast(this->avails.size())) new_pos = this->avail_pos - 1; this->avail_pos = new_pos; if (new_pos >= 0) this->avail_sel = this->avails[new_pos]; @@ -2057,7 +2057,7 @@ struct SavePresetWindow : public Window { size.width = std::max(size.width, d.width + padding.width); resize.height = std::max(resize.height, d.height); } - size.height = ClampU((uint)this->presets.size(), 5, 20) * resize.height + padding.height; + size.height = ClampU(static_cast(this->presets.size()), 5, 20) * resize.height + padding.height; break; } } diff --git a/src/newgrf_house.cpp b/src/newgrf_house.cpp index 4d99affbbc..e08b61650a 100644 --- a/src/newgrf_house.cpp +++ b/src/newgrf_house.cpp @@ -275,7 +275,7 @@ static bool SearchNearbyHouseID(TileIndex tile, void *user_data) HouseID house = GetHouseType(tile); // tile been examined const HouseSpec *hs = HouseSpec::Get(house); if (hs->grf_prop.HasGrfFile()) { // must be one from a grf file - SearchNearbyHouseData *nbhd = (SearchNearbyHouseData *)user_data; + SearchNearbyHouseData *nbhd = static_cast(user_data); TileIndex north_tile = tile + GetHouseNorthPart(house); // modifies 'house'! if (north_tile == nbhd->north_tile) return false; // Always ignore origin house @@ -299,7 +299,7 @@ static bool SearchNearbyHouseClass(TileIndex tile, void *user_data) HouseID house = GetHouseType(tile); // tile been examined const HouseSpec *hs = HouseSpec::Get(house); if (hs->grf_prop.HasGrfFile()) { // must be one from a grf file - SearchNearbyHouseData *nbhd = (SearchNearbyHouseData *)user_data; + SearchNearbyHouseData *nbhd = static_cast(user_data); TileIndex north_tile = tile + GetHouseNorthPart(house); // modifies 'house'! if (north_tile == nbhd->north_tile) return false; // Always ignore origin house @@ -323,7 +323,7 @@ static bool SearchNearbyHouseGRFID(TileIndex tile, void *user_data) HouseID house = GetHouseType(tile); // tile been examined const HouseSpec *hs = HouseSpec::Get(house); if (hs->grf_prop.HasGrfFile()) { // must be one from a grf file - SearchNearbyHouseData *nbhd = (SearchNearbyHouseData *)user_data; + SearchNearbyHouseData *nbhd = static_cast(user_data); TileIndex north_tile = tile + GetHouseNorthPart(house); // modifies 'house'! if (north_tile == nbhd->north_tile) return false; // Always ignore origin house @@ -746,7 +746,7 @@ void TriggerHouse(TileIndex t, HouseTrigger trigger) void DoWatchedCargoCallback(TileIndex tile, TileIndex origin, CargoTypes trigger_cargoes, uint16_t random) { TileIndexDiffC diff = TileIndexToTileIndexDiffC(origin, tile); - uint32_t cb_info = random << 16 | (uint8_t)diff.y << 8 | (uint8_t)diff.x; + uint32_t cb_info = random << 16 | static_cast(diff.y) << 8 | static_cast(diff.x); HouseAnimationBase::ChangeAnimationFrame(CBID_HOUSE_WATCHED_CARGO_ACCEPTED, HouseSpec::Get(GetHouseType(tile)), Town::GetByTile(tile), tile, 0, cb_info, trigger_cargoes); } diff --git a/src/newgrf_industries.cpp b/src/newgrf_industries.cpp index fa19d8f1f7..d7e73daa2d 100644 --- a/src/newgrf_industries.cpp +++ b/src/newgrf_industries.cpp @@ -551,7 +551,7 @@ CommandCost CheckIfCallBackAllowsCreation(TileIndex tile, IndustryType type, siz ind.location.tile = tile; ind.location.w = 0; // important to mark the industry invalid ind.type = type; - ind.selected_layout = (uint8_t)layout; + ind.selected_layout = static_cast(layout); ind.town = ClosestTownFromTile(tile, UINT_MAX); ind.random = initial_random_bits; ind.founder = founder; @@ -598,7 +598,7 @@ uint32_t GetIndustryProbabilityCallback(IndustryType type, IndustryAvailabilityC static int32_t DerefIndProd(int field, bool use_register) { - return use_register ? (int32_t)GetRegister(field) : field; + return use_register ? static_cast(GetRegister(field)) : field; } /** diff --git a/src/newgrf_industrytiles.cpp b/src/newgrf_industrytiles.cpp index 60988f6e1d..54215870fe 100644 --- a/src/newgrf_industrytiles.cpp +++ b/src/newgrf_industrytiles.cpp @@ -79,7 +79,7 @@ uint32_t GetRelativePosition(TileIndex tile, TileIndex ind_tile) /* Land info of nearby tiles */ case 0x60: return GetNearbyIndustryTileInformation(parameter, this->tile, - this->industry == nullptr ? (IndustryID)IndustryID::Invalid() : this->industry->index, true, this->ro.grffile->grf_version >= 8); + this->industry == nullptr ? static_cast(IndustryID::Invalid()) : this->industry->index, true, this->ro.grffile->grf_version >= 8); /* Animation stage of nearby tiles */ case 0x61: { @@ -240,7 +240,7 @@ CommandCost PerformIndustryTileSlopeCheck(TileIndex ind_base_tile, TileIndex ind ind.random = initial_random_bits; ind.founder = founder; - uint16_t callback_res = GetIndustryTileCallback(CBID_INDTILE_SHAPE_CHECK, 0, creation_type << 8 | (uint32_t)layout_index, gfx, &ind, ind_tile); + uint16_t callback_res = GetIndustryTileCallback(CBID_INDTILE_SHAPE_CHECK, 0, creation_type << 8 | static_cast(layout_index), gfx, &ind, ind_tile); if (callback_res == CALLBACK_FAILED) { if (!IsSlopeRefused(GetTileSlope(ind_tile), its->slopes_refused)) return CommandCost(); return CommandCost(STR_ERROR_SITE_UNSUITABLE); diff --git a/src/newgrf_profiling.cpp b/src/newgrf_profiling.cpp index b2d9a0cf5e..e0bf61e9a6 100644 --- a/src/newgrf_profiling.cpp +++ b/src/newgrf_profiling.cpp @@ -47,7 +47,7 @@ void NewGRFProfiler::BeginResolve(const ResolverObject &resolver) using namespace std::chrono; this->cur_call.root_sprite = resolver.root_spritegroup->nfo_line; this->cur_call.subs = 0; - this->cur_call.time = (uint32_t)time_point_cast(high_resolution_clock::now()).time_since_epoch().count(); + this->cur_call.time = static_cast(time_point_cast(high_resolution_clock::now()).time_since_epoch().count()); this->cur_call.tick = TimerGameTick::counter; this->cur_call.cb = resolver.callback; this->cur_call.feat = resolver.GetFeature(); @@ -60,7 +60,7 @@ void NewGRFProfiler::BeginResolve(const ResolverObject &resolver) void NewGRFProfiler::EndResolve(const SpriteGroup *result) { using namespace std::chrono; - this->cur_call.time = (uint32_t)time_point_cast(high_resolution_clock::now()).time_since_epoch().count() - this->cur_call.time; + this->cur_call.time = static_cast(time_point_cast(high_resolution_clock::now()).time_since_epoch().count()) - this->cur_call.time; if (result == nullptr) { this->cur_call.result = 0; @@ -113,7 +113,7 @@ uint32_t NewGRFProfiler::Finish() } else { fmt::print(*f, "Tick,Sprite,Feature,Item,CallbackID,Microseconds,Depth,Result\n"); for (const Call &c : this->calls) { - fmt::print(*f, "{},{},{:#X},{},{:#X},{},{},{}\n", c.tick, c.root_sprite, c.feat, c.item, (uint)c.cb, c.time, c.subs, c.result); + fmt::print(*f, "{},{},{:#X},{},{:#X},{},{},{}\n", c.tick, c.root_sprite, c.feat, c.item, static_cast(c.cb), c.time, c.subs, c.result); total_microseconds += c.time; } } diff --git a/src/newgrf_roadstop.cpp b/src/newgrf_roadstop.cpp index 7ebec4340d..0c64a8f8f8 100644 --- a/src/newgrf_roadstop.cpp +++ b/src/newgrf_roadstop.cpp @@ -393,7 +393,7 @@ void TriggerRoadStopAnimation(BaseStation *st, TileIndex trigger_tile, StationAn } else { cargo = ss->grf_prop.grffile->cargo_map[cargo_type]; } - RoadStopAnimationBase::ChangeAnimationFrame(CBID_STATION_ANIM_START_STOP, ss, st, cur_tile, (random_bits << 16) | Random(), (uint8_t)trigger | (cargo << 8)); + RoadStopAnimationBase::ChangeAnimationFrame(CBID_STATION_ANIM_START_STOP, ss, st, cur_tile, (random_bits << 16) | Random(), static_cast(trigger) | (cargo << 8)); } }; diff --git a/src/newgrf_sound.cpp b/src/newgrf_sound.cpp index 48958dcf68..f0f91e194b 100644 --- a/src/newgrf_sound.cpp +++ b/src/newgrf_sound.cpp @@ -56,7 +56,7 @@ SoundEntry *GetSound(SoundID index) uint GetNumSounds() { - return (uint)_sounds.size(); + return static_cast(_sounds.size()); } /** diff --git a/src/newgrf_spritegroup.cpp b/src/newgrf_spritegroup.cpp index a8a081c0c2..0a60e232b8 100644 --- a/src/newgrf_spritegroup.cpp +++ b/src/newgrf_spritegroup.cpp @@ -267,7 +267,7 @@ const SpriteGroup *RandomizedSpriteGroup::Resolve(ResolverObject &object) const } } - uint32_t mask = ((uint)this->groups.size() - 1) << this->lowest_randbit; + uint32_t mask = (static_cast(this->groups.size()) - 1) << this->lowest_randbit; uint8_t index = (scope->GetRandomBits() & mask) >> this->lowest_randbit; return SpriteGroup::Resolve(this->groups[index], object, false); diff --git a/src/newgrf_station.cpp b/src/newgrf_station.cpp index 0b56a0ddc6..201dec0e9a 100644 --- a/src/newgrf_station.cpp +++ b/src/newgrf_station.cpp @@ -446,9 +446,9 @@ uint32_t Station::GetNewGRFVariable(const ResolverObject &object, uint8_t variab case 0x64: return ge->HasVehicleEverTriedLoading() ? ge->last_speed | (ge->last_age << 8) : 0xFF00; case 0x65: return GB(ge->status, GoodsEntry::GES_ACCEPTANCE, 1) << 3; case 0x69: { - static_assert((int)GoodsEntry::GES_EVER_ACCEPTED + 1 == (int)GoodsEntry::GES_LAST_MONTH); - static_assert((int)GoodsEntry::GES_EVER_ACCEPTED + 2 == (int)GoodsEntry::GES_CURRENT_MONTH); - static_assert((int)GoodsEntry::GES_EVER_ACCEPTED + 3 == (int)GoodsEntry::GES_ACCEPTED_BIGTICK); + static_assert(static_cast(GoodsEntry::GES_EVER_ACCEPTED) + 1 == static_cast(GoodsEntry::GES_LAST_MONTH)); + static_assert(static_cast(GoodsEntry::GES_EVER_ACCEPTED) + 2 == static_cast(GoodsEntry::GES_CURRENT_MONTH)); + static_assert(static_cast(GoodsEntry::GES_EVER_ACCEPTED) + 3 == static_cast(GoodsEntry::GES_ACCEPTED_BIGTICK)); return GB(ge->status, GoodsEntry::GES_EVER_ACCEPTED, 4); } } @@ -542,12 +542,12 @@ uint32_t Waypoint::GetNewGRFVariable(const ResolverObject &, uint8_t variable, [ if (cargo > this->station_scope.statspec->cargo_threshold) { if (!group->loading.empty()) { - uint set = ((cargo - this->station_scope.statspec->cargo_threshold) * (uint)group->loading.size()) / (4096 - this->station_scope.statspec->cargo_threshold); + uint set = ((cargo - this->station_scope.statspec->cargo_threshold) * static_cast(group->loading.size())) / (4096 - this->station_scope.statspec->cargo_threshold); return group->loading[set]; } } else { if (!group->loaded.empty()) { - uint set = (cargo * (uint)group->loaded.size()) / (this->station_scope.statspec->cargo_threshold + 1); + uint set = (cargo * static_cast(group->loaded.size())) / (this->station_scope.statspec->cargo_threshold + 1); return group->loaded[set]; } } @@ -811,7 +811,7 @@ bool DrawStationTile(int x, int y, RailType railtype, Axis axis, StationClassID if (statspec->renderdata.empty()) { sprites = GetStationTileLayout(StationType::Rail, tile + axis); } else { - layout = &statspec->renderdata[(tile < statspec->renderdata.size()) ? tile + axis : (uint)axis]; + layout = &statspec->renderdata[(tile < statspec->renderdata.size()) ? tile + axis : static_cast(axis)]; if (!layout->NeedsPreprocessing()) { sprites = layout; layout = nullptr; @@ -918,7 +918,7 @@ void TriggerStationAnimation(BaseStation *st, TileIndex trigger_tile, StationAni } else { cargo = ss->grf_prop.grffile->cargo_map[cargo_type]; } - StationAnimationBase::ChangeAnimationFrame(CBID_STATION_ANIM_START_STOP, ss, st, tile, (random_bits << 16) | GB(Random(), 0, 16), (uint8_t)trigger | (cargo << 8)); + StationAnimationBase::ChangeAnimationFrame(CBID_STATION_ANIM_START_STOP, ss, st, tile, (random_bits << 16) | GB(Random(), 0, 16), static_cast(trigger) | (cargo << 8)); } } } diff --git a/src/newgrf_text.cpp b/src/newgrf_text.cpp index 77fcff45f4..1f1c78bef4 100644 --- a/src/newgrf_text.cpp +++ b/src/newgrf_text.cpp @@ -704,28 +704,28 @@ struct TextRefStack { } uint8_t PopUnsignedByte() { assert(this->position < this->stack.size()); return this->stack[this->position++]; } - int8_t PopSignedByte() { return (int8_t)this->PopUnsignedByte(); } + int8_t PopSignedByte() { return static_cast(this->PopUnsignedByte()); } uint16_t PopUnsignedWord() { uint16_t val = this->PopUnsignedByte(); return val | (this->PopUnsignedByte() << 8); } - int16_t PopSignedWord() { return (int32_t)this->PopUnsignedWord(); } + int16_t PopSignedWord() { return static_cast(this->PopUnsignedWord()); } uint32_t PopUnsignedDWord() { uint32_t val = this->PopUnsignedWord(); return val | (this->PopUnsignedWord() << 16); } - int32_t PopSignedDWord() { return (int32_t)this->PopUnsignedDWord(); } + int32_t PopSignedDWord() { return static_cast(this->PopUnsignedDWord()); } uint64_t PopUnsignedQWord() { uint64_t val = this->PopUnsignedDWord(); - return val | (((uint64_t)this->PopUnsignedDWord()) << 32); + return val | ((static_cast(this->PopUnsignedDWord())) << 32); } - int64_t PopSignedQWord() { return (int64_t)this->PopUnsignedQWord(); } + int64_t PopSignedQWord() { return static_cast(this->PopUnsignedQWord()); } /** Rotate the top four words down: W1, W2, W3, W4 -> W4, W1, W2, W3 */ void RotateTop4Words() diff --git a/src/object_cmd.cpp b/src/object_cmd.cpp index 3cdaa07b72..91119e72d6 100644 --- a/src/object_cmd.cpp +++ b/src/object_cmd.cpp @@ -810,7 +810,7 @@ static bool TryBuildTransmitter() void GenerateObjects() { /* Set a guestimate on how much we progress */ - SetGeneratingWorldProgress(GWP_OBJECT, (uint)ObjectSpec::Count()); + SetGeneratingWorldProgress(GWP_OBJECT, static_cast(ObjectSpec::Count())); /* Determine number of water tiles at map border needed for freeform_edges */ uint num_water_tiles = 0; diff --git a/src/order_cmd.cpp b/src/order_cmd.cpp index f3d0f9a527..4f4179149e 100644 --- a/src/order_cmd.cpp +++ b/src/order_cmd.cpp @@ -1347,7 +1347,7 @@ CommandCost CmdModifyOrder(DoCommandFlags flags, VehicleID veh, VehicleOrderID s if (flags.Test(DoCommandFlag::Execute)) { switch (mof) { case MOF_NON_STOP: - order->SetNonStopType((OrderNonStopFlags)data); + order->SetNonStopType(static_cast(data)); if (data & ONSF_NO_STOP_AT_DESTINATION_STATION) { order->SetRefit(CARGO_NO_REFIT); order->SetLoadType(OLF_LOAD_IF_POSSIBLE); @@ -1356,44 +1356,44 @@ CommandCost CmdModifyOrder(DoCommandFlags flags, VehicleID veh, VehicleOrderID s break; case MOF_STOP_LOCATION: - order->SetStopLocation((OrderStopLocation)data); + order->SetStopLocation(static_cast(data)); break; case MOF_UNLOAD: - order->SetUnloadType((OrderUnloadFlags)data); + order->SetUnloadType(static_cast(data)); break; case MOF_LOAD: - order->SetLoadType((OrderLoadFlags)data); + order->SetLoadType(static_cast(data)); if (data & OLFB_NO_LOAD) order->SetRefit(CARGO_NO_REFIT); break; case MOF_DEPOT_ACTION: { switch (data) { case DA_ALWAYS_GO: - order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() & ~ODTFB_SERVICE)); - order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_HALT)); - order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_UNBUNCH)); + order->SetDepotOrderType(static_cast(order->GetDepotOrderType() & ~ODTFB_SERVICE)); + order->SetDepotActionType((order->GetDepotActionType() & ~ODATFB_HALT)); + order->SetDepotActionType((order->GetDepotActionType() & ~ODATFB_UNBUNCH)); break; case DA_SERVICE: - order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() | ODTFB_SERVICE)); - order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_HALT)); - order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_UNBUNCH)); + order->SetDepotOrderType(static_cast(order->GetDepotOrderType() | ODTFB_SERVICE)); + order->SetDepotActionType((order->GetDepotActionType() & ~ODATFB_HALT)); + order->SetDepotActionType((order->GetDepotActionType() & ~ODATFB_UNBUNCH)); order->SetRefit(CARGO_NO_REFIT); break; case DA_STOP: - order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() & ~ODTFB_SERVICE)); - order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() | ODATFB_HALT)); - order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_UNBUNCH)); + order->SetDepotOrderType(static_cast(order->GetDepotOrderType() & ~ODTFB_SERVICE)); + order->SetDepotActionType((order->GetDepotActionType() | ODATFB_HALT)); + order->SetDepotActionType((order->GetDepotActionType() & ~ODATFB_UNBUNCH)); order->SetRefit(CARGO_NO_REFIT); break; case DA_UNBUNCH: - order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() & ~ODTFB_SERVICE)); - order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_HALT)); - order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() | ODATFB_UNBUNCH)); + order->SetDepotOrderType(static_cast(order->GetDepotOrderType() & ~ODTFB_SERVICE)); + order->SetDepotActionType((order->GetDepotActionType() & ~ODATFB_HALT)); + order->SetDepotActionType((order->GetDepotActionType() | ODATFB_UNBUNCH)); break; default: @@ -1403,7 +1403,7 @@ CommandCost CmdModifyOrder(DoCommandFlags flags, VehicleID veh, VehicleOrderID s } case MOF_COND_VARIABLE: { - order->SetConditionVariable((OrderConditionVariable)data); + order->SetConditionVariable(static_cast(data)); OrderConditionComparator occ = order->GetConditionComparator(); switch (order->GetConditionVariable()) { @@ -1430,7 +1430,7 @@ CommandCost CmdModifyOrder(DoCommandFlags flags, VehicleID veh, VehicleOrderID s } case MOF_COND_COMPARATOR: - order->SetConditionComparator((OrderConditionComparator)data); + order->SetConditionComparator(static_cast(data)); break; case MOF_COND_VALUE: @@ -1675,8 +1675,8 @@ CommandCost CmdOrderRefit(DoCommandFlags flags, VehicleID veh, VehicleOrderID or /* Make the depot order an 'always go' order. */ if (cargo != CARGO_NO_REFIT && order->IsType(OT_GOTO_DEPOT)) { - order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() & ~ODTFB_SERVICE)); - order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_HALT)); + order->SetDepotOrderType(static_cast(order->GetDepotOrderType() & ~ODTFB_SERVICE)); + order->SetDepotActionType((order->GetDepotActionType() & ~ODATFB_HALT)); } for (Vehicle *u = v->FirstShared(); u != nullptr; u = u->NextShared()) { @@ -1974,7 +1974,7 @@ VehicleOrderID ProcessConditionalOrder(const Order *order, const Vehicle *v) default: NOT_REACHED(); } - return skip_order ? order->GetConditionSkipToOrder() : (VehicleOrderID)INVALID_VEH_ORDER_ID; + return skip_order ? order->GetConditionSkipToOrder() : INVALID_VEH_ORDER_ID; } /** diff --git a/src/order_gui.cpp b/src/order_gui.cpp index 1e68a0d948..7590c4e441 100644 --- a/src/order_gui.cpp +++ b/src/order_gui.cpp @@ -230,11 +230,11 @@ void DrawOrderString(const Vehicle *v, const Order *order, int order_index, int Dimension sprite_size = GetSpriteSize(sprite); if (v->cur_real_order_index == order_index) { /* Draw two arrows before the next real order. */ - DrawSprite(sprite, PAL_NONE, rtl ? right - sprite_size.width : left, y + ((int)GetCharacterHeight(FS_NORMAL) - (int)sprite_size.height) / 2); - DrawSprite(sprite, PAL_NONE, rtl ? right - 2 * sprite_size.width : left + sprite_size.width, y + ((int)GetCharacterHeight(FS_NORMAL) - (int)sprite_size.height) / 2); + DrawSprite(sprite, PAL_NONE, rtl ? right - sprite_size.width : left, y + (GetCharacterHeight(FS_NORMAL) - static_cast(sprite_size.height)) / 2); + DrawSprite(sprite, PAL_NONE, rtl ? right - 2 * sprite_size.width : left + sprite_size.width, y + (GetCharacterHeight(FS_NORMAL) - static_cast(sprite_size.height)) / 2); } else if (v->cur_implicit_order_index == order_index) { /* Draw one arrow before the next implicit order; the next real order will still get two arrows. */ - DrawSprite(sprite, PAL_NONE, rtl ? right - sprite_size.width : left, y + ((int)GetCharacterHeight(FS_NORMAL) - (int)sprite_size.height) / 2); + DrawSprite(sprite, PAL_NONE, rtl ? right - sprite_size.width : left, y + (GetCharacterHeight(FS_NORMAL) - static_cast(sprite_size.height)) / 2); } TextColour colour = TC_BLACK; @@ -285,7 +285,7 @@ void DrawOrderString(const Vehicle *v, const Order *order, int order_index, int if (v->type == VEH_TRAIN && (order->GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION) == 0) { /* Only show the stopping location if other than the default chosen by the player. */ - if (order->GetStopLocation() != (OrderStopLocation)(_settings_client.gui.stop_location)) { + if (order->GetStopLocation() != static_cast(_settings_client.gui.stop_location)) { line += GetString(STR_ORDER_STOP_LOCATION_NEAR_END + order->GetStopLocation()); } } @@ -374,7 +374,7 @@ static Order GetOrderCmdFromTile(const Vehicle *v, TileIndex tile) order.index = OrderID::Begin(); /* check depot first */ - if (IsDepotTypeTile(tile, (TransportType)(uint)v->type) && IsTileOwner(tile, _local_company)) { + if (IsDepotTypeTile(tile, static_cast(static_cast(v->type))) && IsTileOwner(tile, _local_company)) { order.MakeGoToDepot(GetDepotDestinationIndex(tile), ODTFB_PART_OF_ORDERS, (_settings_client.gui.new_nonstop && v->IsGroundVehicle()) ? ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS : ONSF_STOP_EVERYWHERE); @@ -456,7 +456,7 @@ static Order GetOrderCmdFromTile(const Vehicle *v, TileIndex tile) order.MakeGoToStation(st->index); if (_ctrl_pressed) order.SetLoadType(OLF_FULL_LOAD_ANY); if (_settings_client.gui.new_nonstop && v->IsGroundVehicle()) order.SetNonStopType(ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS); - order.SetStopLocation(v->type == VEH_TRAIN ? (OrderStopLocation)(_settings_client.gui.stop_location) : OSL_PLATFORM_FAR_END); + order.SetStopLocation(v->type == VEH_TRAIN ? static_cast(_settings_client.gui.stop_location) : OSL_PLATFORM_FAR_END); return order; } } @@ -732,7 +732,7 @@ private: void OrderClick_Delete() { /* When networking, move one order lower */ - int selected = this->selected_order + (int)_networking; + int selected = this->selected_order + static_cast(_networking); if (Command::Post(STR_ERROR_CAN_T_DELETE_THIS_ORDER, this->vehicle->tile, this->vehicle->index, this->OrderGetSel())) { this->selected_order = selected >= this->vehicle->GetNumOrders() ? -1 : selected; @@ -899,9 +899,9 @@ public: if (from != this->selected_order) { /* Moving from preceding order? */ - this->selected_order -= (int)(from <= this->selected_order); + this->selected_order -= static_cast(from <= this->selected_order); /* Moving to preceding order? */ - this->selected_order += (int)(to <= this->selected_order); + this->selected_order += static_cast(to <= this->selected_order); break; } @@ -948,7 +948,7 @@ public: /* The 'End of Shared Orders' order isn't selected, show the 'delete' button. */ delete_sel->SetDisplayedPlane(DP_BOTTOM_MIDDLE_DELETE); this->SetWidgetDisabledState(WID_O_DELETE, - (uint)this->vehicle->GetNumOrders() + ((shared_orders || this->vehicle->GetNumOrders() != 0) ? 1 : 0) <= (uint)this->selected_order); + static_cast(this->vehicle->GetNumOrders()) + ((shared_orders || this->vehicle->GetNumOrders() != 0) ? 1 : 0) <= static_cast(this->selected_order)); /* Set the tooltip of the 'delete' button depending on whether the * 'End of Orders' order or a regular order is selected. */ @@ -1386,11 +1386,11 @@ public: break; case WID_O_FULL_LOAD: - this->OrderClick_FullLoad((OrderLoadFlags)index); + this->OrderClick_FullLoad(static_cast(index)); break; case WID_O_UNLOAD: - this->OrderClick_Unload((OrderUnloadFlags)index); + this->OrderClick_Unload(static_cast(index)); break; case WID_O_GOTO: diff --git a/src/os/macosx/string_osx.cpp b/src/os/macosx/string_osx.cpp index 2153635d1e..ccd9afb402 100644 --- a/src/os/macosx/string_osx.cpp +++ b/src/os/macosx/string_osx.cpp @@ -137,8 +137,8 @@ public: /** Get the width of an encoded sprite font character. */ static CGFloat SpriteFontGetWidth(void *ref_con) { - FontSize fs = (FontSize)((size_t)ref_con >> 24); - char32_t c = (char32_t)((size_t)ref_con & 0xFFFFFF); + FontSize fs = static_cast((size_t)ref_con >> 24); + char32_t c = static_cast((size_t)ref_con & 0xFFFFFF); return GetGlyphWidth(fs, c); } diff --git a/src/os/unix/font_unix.cpp b/src/os/unix/font_unix.cpp index efaaa3e056..413a5a6955 100644 --- a/src/os/unix/font_unix.cpp +++ b/src/os/unix/font_unix.cpp @@ -79,13 +79,13 @@ FT_Error GetFontByFaceName(const char *font_name, FT_Face *face) FcPatternGetInteger(fs->fonts[i], FC_INDEX, 0, &index) == FcResultMatch) { /* The correct style? */ - if (!font_style.empty() && !StrEqualsIgnoreCase(font_style, (char *)style)) continue; + if (!font_style.empty() && !StrEqualsIgnoreCase(font_style, reinterpret_cast(style))) continue; /* Font config takes the best shot, which, if the family name is spelled * wrongly a 'random' font, so check whether the family name is the * same as the supplied name */ - if (StrEqualsIgnoreCase(font_family, (char *)family)) { - err = FT_New_Face(_library, (char *)file, index, face); + if (StrEqualsIgnoreCase(font_family, reinterpret_cast(family))) { + err = FT_New_Face(_library, reinterpret_cast(file), index, face); } } } @@ -113,7 +113,7 @@ bool SetFallbackFont(FontCacheSettings *settings, const std::string &language_is std::string lang = fmt::format(":lang={}", language_isocode.substr(0, language_isocode.find('_'))); /* First create a pattern to match the wanted language. */ - FcPattern *pat = FcNameParse((const FcChar8 *)lang.c_str()); + FcPattern *pat = FcNameParse(reinterpret_cast(lang.c_str())); /* We only want to know these attributes. */ FcObjectSet *os = FcObjectSetBuild(FC_FILE, FC_INDEX, FC_SPACING, FC_SLANT, FC_WEIGHT, nullptr); /* Get the list of filenames matching the wanted language. */ @@ -155,14 +155,14 @@ bool SetFallbackFont(FontCacheSettings *settings, const std::string &language_is res = FcPatternGetInteger(font, FC_INDEX, 0, &index); if (res != FcResultMatch) continue; - callback->SetFontNames(settings, (const char *)file, &index); + callback->SetFontNames(settings, reinterpret_cast(file), &index); bool missing = callback->FindMissingGlyphs(); Debug(fontcache, 1, "Font \"{}\" misses{} glyphs", (char *)file, missing ? "" : " no"); if (!missing) { best_weight = value; - best_font = (const char *)file; + best_font = reinterpret_cast(file); best_index = index; } } diff --git a/src/os/windows/font_win32.cpp b/src/os/windows/font_win32.cpp index db1573d20a..7362d96583 100644 --- a/src/os/windows/font_win32.cpp +++ b/src/os/windows/font_win32.cpp @@ -282,10 +282,10 @@ void Win32FontCache::ClearFontCache() /* Convert characters outside of the BMP into surrogate pairs. */ WCHAR chars[2]; if (key >= 0x010000U) { - chars[0] = (wchar_t)(((key - 0x010000U) >> 10) + 0xD800); - chars[1] = (wchar_t)(((key - 0x010000U) & 0x3FF) + 0xDC00); + chars[0] = static_cast(((key - 0x010000U) >> 10) + 0xD800); + chars[1] = static_cast(((key - 0x010000U) & 0x3FF) + 0xDC00); } else { - chars[0] = (wchar_t)(key & 0xFFFF); + chars[0] = static_cast(key & 0xFFFF); } WORD glyphs[2] = { 0, 0 }; diff --git a/src/os/windows/string_uniscribe.cpp b/src/os/windows/string_uniscribe.cpp index f062187d39..880bc08bf7 100644 --- a/src/os/windows/string_uniscribe.cpp +++ b/src/os/windows/string_uniscribe.cpp @@ -532,11 +532,11 @@ std::span UniscribeParagraphLayout::UniscribeVisualRun::GetGlyphToCha char32_t c = Utf8Consume(&s); if (c < 0x10000) { - utf16_str.push_back((wchar_t)c); + utf16_str.push_back(static_cast(c)); } else { /* Make a surrogate pair. */ - utf16_str.push_back((wchar_t)(0xD800 + ((c - 0x10000) >> 10))); - utf16_str.push_back((wchar_t)(0xDC00 + ((c - 0x10000) & 0x3FF))); + utf16_str.push_back(static_cast(0xD800 + ((c - 0x10000) >> 10))); + utf16_str.push_back(static_cast(0xDC00 + ((c - 0x10000) & 0x3FF))); this->utf16_to_utf8.push_back(idx); } this->utf16_to_utf8.push_back(idx); diff --git a/src/os/windows/win32.cpp b/src/os/windows/win32.cpp index 8ac0a5ccc9..914d40ec69 100644 --- a/src/os/windows/win32.cpp +++ b/src/os/windows/win32.cpp @@ -73,7 +73,7 @@ void FiosGetDrives(FileList &file_list) FiosItem *fios = &file_list.emplace_back(); fios->type = FIOS_TYPE_DRIVE; fios->mtime = 0; - fios->name += (char)(s[0] & 0xFF); + fios->name += static_cast(s[0] & 0xFF); fios->name += ':'; fios->title = fios->name; while (*s++ != '\0') { /* Nothing */ } @@ -336,7 +336,7 @@ std::optional GetClipboardContents() */ std::string FS2OTTD(const std::wstring &name) { - int name_len = (name.length() >= INT_MAX) ? INT_MAX : (int)name.length(); + int name_len = (name.length() >= INT_MAX) ? INT_MAX : static_cast(name.length()); int len = WideCharToMultiByte(CP_UTF8, 0, name.c_str(), name_len, nullptr, 0, nullptr, nullptr); if (len <= 0) return std::string(); std::string utf8_buf(len, '\0'); // len includes terminating null @@ -353,7 +353,7 @@ std::string FS2OTTD(const std::wstring &name) */ std::wstring OTTD2FS(const std::string &name) { - int name_len = (name.length() >= INT_MAX) ? INT_MAX : (int)name.length(); + int name_len = (name.length() >= INT_MAX) ? INT_MAX : static_cast(name.length()); int len = MultiByteToWideChar(CP_UTF8, 0, name.c_str(), name_len, nullptr, 0); if (len <= 0) return std::wstring(); std::wstring system_buf(len, L'\0'); // len includes terminating null diff --git a/src/palette.cpp b/src/palette.cpp index 96ab905d83..ab696a0e7b 100644 --- a/src/palette.cpp +++ b/src/palette.cpp @@ -73,9 +73,9 @@ inline uint CrunchColour(uint c) static uint CalculateColourDistance(const Colour &col1, int r2, int g2, int b2) { /* Euclidean colour distance for sRGB based on https://en.wikipedia.org/wiki/Color_difference#sRGB */ - int r = (int)col1.r - (int)r2; - int g = (int)col1.g - (int)g2; - int b = (int)col1.b - (int)b2; + int r = static_cast(col1.r) - r2; + int g = static_cast(col1.g) - g2; + int b = static_cast(col1.b) - b2; int avgr = (col1.r + r2) / 2; return ((2 + (avgr / 256.0)) * r * r) + (4 * g * g) + ((2 + ((255 - avgr) / 256.0)) * b * b); @@ -364,7 +364,7 @@ TextColour GetContrastColour(uint8_t background, uint8_t threshold) * The following formula computes 1000 * brightness^2, with brightness being in range 0 to 255. */ uint sq1000_brightness = c.r * c.r * 299 + c.g * c.g * 587 + c.b * c.b * 114; /* Compare with threshold brightness which defaults to 128 (50%) */ - return sq1000_brightness < ((uint) threshold) * ((uint) threshold) * 1000 ? TC_WHITE : TC_BLACK; + return sq1000_brightness < (static_cast(threshold)) * (static_cast(threshold)) * 1000 ? TC_WHITE : TC_BLACK; } /** diff --git a/src/pathfinder/yapf/yapf_road.cpp b/src/pathfinder/yapf/yapf_road.cpp index b065274858..7e5ba98ba8 100644 --- a/src/pathfinder/yapf/yapf_road.cpp +++ b/src/pathfinder/yapf/yapf_road.cpp @@ -305,8 +305,8 @@ public: TileIndex tile = n.segment_last_tile; DiagDirection exitdir = TrackdirToExitdir(n.segment_last_td); - int x1 = 2 * TileX(tile) + dg_dir_to_x_offs[(int)exitdir]; - int y1 = 2 * TileY(tile) + dg_dir_to_y_offs[(int)exitdir]; + int x1 = 2 * TileX(tile) + dg_dir_to_x_offs[static_cast(exitdir)]; + int y1 = 2 * TileY(tile) + dg_dir_to_y_offs[static_cast(exitdir)]; int x2 = 2 * TileX(this->dest_tile); int y2 = 2 * TileY(this->dest_tile); int dx = abs(x1 - x2); @@ -532,7 +532,7 @@ Trackdir YapfRoadVehicleChooseTrack(const RoadVehicle *v, TileIndex tile, DiagDi ? CYapfRoad1::stChooseRoadTrack(v, tile, enterdir, path_found, path_cache) // Trackdir : CYapfRoad2::stChooseRoadTrack(v, tile, enterdir, path_found, path_cache); // ExitDir, allow 90-deg - return (td_ret != INVALID_TRACKDIR) ? td_ret : (Trackdir)FindFirstBit(trackdirs); + return (td_ret != INVALID_TRACKDIR) ? td_ret : static_cast(FindFirstBit(trackdirs)); } FindDepotData YapfRoadVehicleFindNearestDepot(const RoadVehicle *v, int max_distance) diff --git a/src/pathfinder/yapf/yapf_ship.cpp b/src/pathfinder/yapf/yapf_ship.cpp index 6a34d5dc89..43834cd5a4 100644 --- a/src/pathfinder/yapf/yapf_ship.cpp +++ b/src/pathfinder/yapf/yapf_ship.cpp @@ -106,8 +106,8 @@ public: TileIndex tile = n.segment_last_tile; DiagDirection exitdir = TrackdirToExitdir(n.segment_last_td); - int x1 = 2 * TileX(tile) + dg_dir_to_x_offs[(int)exitdir]; - int y1 = 2 * TileY(tile) + dg_dir_to_y_offs[(int)exitdir]; + int x1 = 2 * TileX(tile) + dg_dir_to_x_offs[static_cast(exitdir)]; + int y1 = 2 * TileY(tile) + dg_dir_to_y_offs[static_cast(exitdir)]; int x2 = 2 * TileX(destination_tile); int y2 = 2 * TileY(destination_tile); int dx = abs(x1 - x2); @@ -357,7 +357,7 @@ public: static Vehicle *CountShipProc(Vehicle *v, void *data) { - uint *count = (uint*)data; + uint *count = static_cast(data); /* Ignore other vehicles (aircraft) and ships inside depot. */ if (v->type == VEH_SHIP && !v->vehstatus.Test(VehState::Hidden)) (*count)++; diff --git a/src/pbs.cpp b/src/pbs.cpp index 9e37633a04..bf2a6cfd93 100644 --- a/src/pbs.cpp +++ b/src/pbs.cpp @@ -262,12 +262,12 @@ struct FindTrainOnTrackInfo { /** Callback for Has/FindVehicleOnPos to find a train on a specific track. */ static Vehicle *FindTrainOnTrackEnum(Vehicle *v, void *data) { - FindTrainOnTrackInfo *info = (FindTrainOnTrackInfo *)data; + FindTrainOnTrackInfo *info = static_cast(data); if (v->type != VEH_TRAIN || v->vehstatus.Test(VehState::Crashed)) return nullptr; Train *t = Train::From(v); - if (t->track == TRACK_BIT_WORMHOLE || HasBit((TrackBits)t->track, TrackdirToTrack(info->res.trackdir))) { + if (t->track == TRACK_BIT_WORMHOLE || HasBit(t->track, TrackdirToTrack(info->res.trackdir))) { t = t->First(); /* ALWAYS return the lowest ID (anti-desync!) */ diff --git a/src/rail_cmd.cpp b/src/rail_cmd.cpp index 621aa6bd1c..3e37ec0ecc 100644 --- a/src/rail_cmd.cpp +++ b/src/rail_cmd.cpp @@ -103,8 +103,8 @@ void ResolveRailTypeGUISprites(RailTypeInfo *rti) SPR_IMG_SIGNAL_SEMAPHORE_COMBO, SPR_IMG_SIGNAL_SEMAPHORE_PBS, SPR_IMG_SIGNAL_SEMAPHORE_PBS_OWAY}, }; - for (SignalType type = SIGTYPE_BLOCK; type < SIGTYPE_END; type = (SignalType)(type + 1)) { - for (SignalVariant var = SIG_ELECTRIC; var <= SIG_SEMAPHORE; var = (SignalVariant)(var + 1)) { + for (SignalType type = SIGTYPE_BLOCK; type < SIGTYPE_END; type = static_cast(type + 1)) { + for (SignalVariant var = SIG_ELECTRIC; var <= SIG_SEMAPHORE; var = static_cast(var + 1)) { SpriteID red = GetCustomSignalSprite(rti, INVALID_TILE, type, var, SIGNAL_STATE_RED, true); SpriteID green = GetCustomSignalSprite(rti, INVALID_TILE, type, var, SIGNAL_STATE_GREEN, true); rti->gui_sprites.signals[type][var][0] = (red != 0) ? red + SIGNAL_TO_SOUTH : _signal_lookup[var][type]; @@ -159,11 +159,11 @@ RailType AllocateRailType(RailTypeLabel label) rti->alternate_labels.clear(); /* Make us compatible with ourself. */ - rti->powered_railtypes = (RailTypes)(1LL << rt); - rti->compatible_railtypes = (RailTypes)(1LL << rt); + rti->powered_railtypes = static_cast(1LL << rt); + rti->compatible_railtypes = static_cast(1LL << rt); /* We also introduce ourself. */ - rti->introduces_railtypes = (RailTypes)(1LL << rt); + rti->introduces_railtypes = static_cast(1LL << rt); /* Default sort order; order of allocation, but with some * offsets so it's easier for NewGRF to pick a spot without @@ -405,7 +405,7 @@ static CommandCost CheckRailSlope(Slope tileh, TrackBits rail_bits, TrackBits ex } Foundation f_old = GetRailFoundation(tileh, existing); - return CommandCost(EXPENSES_CONSTRUCTION, f_new != f_old ? _price[PR_BUILD_FOUNDATION] : (Money)0); + return CommandCost(EXPENSES_CONSTRUCTION, f_new != f_old ? _price[PR_BUILD_FOUNDATION] : Money(0)); } /* Validate functions for rail building */ @@ -1053,7 +1053,7 @@ CommandCost CmdBuildSingleSignal(DoCommandFlags flags, TileIndex tile, Track tra if (sigtype > SIGTYPE_LAST || sigvar > SIG_SEMAPHORE) return CMD_ERROR; if (cycle_start > cycle_stop || cycle_stop > SIGTYPE_LAST) return CMD_ERROR; - if (ctrl_pressed) sigvar = (SignalVariant)(sigvar ^ SIG_SEMAPHORE); + if (ctrl_pressed) sigvar = static_cast(sigvar ^ SIG_SEMAPHORE); /* You can only build signals on plain rail tiles, and the selected track must exist */ if (!ValParamTrackOrientation(track) || !IsPlainRailTile(tile) || @@ -1148,7 +1148,7 @@ CommandCost CmdBuildSingleSignal(DoCommandFlags flags, TileIndex tile, Track tra } else if (ctrl_pressed) { /* cycle between cycle_start and cycle_end */ - sigtype = (SignalType)(GetSignalType(tile, track) + 1); + sigtype = static_cast(GetSignalType(tile, track) + 1); if (sigtype < cycle_start || sigtype > cycle_stop) sigtype = cycle_start; @@ -2356,10 +2356,10 @@ static void DrawTrackBits(TileInfo *ti, TrackBits track) DrawGroundSprite(_track_sloped_sprites[ti->tileh - 1] + rti->base_sprites.single_sloped - 20, PALETTE_CRASH); } } - if (pbs & TRACK_BIT_UPPER) DrawGroundSprite(rti->base_sprites.single_n, PALETTE_CRASH, nullptr, 0, ti->tileh & SLOPE_N ? -(int)TILE_HEIGHT : 0); - if (pbs & TRACK_BIT_LOWER) DrawGroundSprite(rti->base_sprites.single_s, PALETTE_CRASH, nullptr, 0, ti->tileh & SLOPE_S ? -(int)TILE_HEIGHT : 0); - if (pbs & TRACK_BIT_LEFT) DrawGroundSprite(rti->base_sprites.single_w, PALETTE_CRASH, nullptr, 0, ti->tileh & SLOPE_W ? -(int)TILE_HEIGHT : 0); - if (pbs & TRACK_BIT_RIGHT) DrawGroundSprite(rti->base_sprites.single_e, PALETTE_CRASH, nullptr, 0, ti->tileh & SLOPE_E ? -(int)TILE_HEIGHT : 0); + if (pbs & TRACK_BIT_UPPER) DrawGroundSprite(rti->base_sprites.single_n, PALETTE_CRASH, nullptr, 0, ti->tileh & SLOPE_N ? -static_cast(TILE_HEIGHT) : 0); + if (pbs & TRACK_BIT_LOWER) DrawGroundSprite(rti->base_sprites.single_s, PALETTE_CRASH, nullptr, 0, ti->tileh & SLOPE_S ? -static_cast(TILE_HEIGHT) : 0); + if (pbs & TRACK_BIT_LEFT) DrawGroundSprite(rti->base_sprites.single_w, PALETTE_CRASH, nullptr, 0, ti->tileh & SLOPE_W ? -static_cast(TILE_HEIGHT) : 0); + if (pbs & TRACK_BIT_RIGHT) DrawGroundSprite(rti->base_sprites.single_e, PALETTE_CRASH, nullptr, 0, ti->tileh & SLOPE_E ? -static_cast(TILE_HEIGHT) : 0); } if (IsValidCorner(halftile_corner)) { @@ -2379,7 +2379,7 @@ static void DrawTrackBits(TileInfo *ti, TrackBits track) if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasReservedTracks(ti->tile, CornerToTrackBits(halftile_corner))) { static const uint8_t _corner_to_track_sprite[] = {3, 1, 2, 0}; - DrawGroundSprite(_corner_to_track_sprite[halftile_corner] + rti->base_sprites.single_n, PALETTE_CRASH, nullptr, 0, -(int)TILE_HEIGHT); + DrawGroundSprite(_corner_to_track_sprite[halftile_corner] + rti->base_sprites.single_n, PALETTE_CRASH, nullptr, 0, -static_cast(TILE_HEIGHT)); } } } @@ -2921,10 +2921,10 @@ int TicksToLeaveDepot(const Train *v) int length = v->CalcNextVehicleOffset(); switch (dir) { - case DIAGDIR_NE: return ((int)(v->x_pos & 0x0F) - ((_fractcoords_enter[dir] & 0x0F) - (length + 1))); - case DIAGDIR_SE: return -((int)(v->y_pos & 0x0F) - ((_fractcoords_enter[dir] >> 4) + (length + 1))); - case DIAGDIR_SW: return -((int)(v->x_pos & 0x0F) - ((_fractcoords_enter[dir] & 0x0F) + (length + 1))); - case DIAGDIR_NW: return ((int)(v->y_pos & 0x0F) - ((_fractcoords_enter[dir] >> 4) - (length + 1))); + case DIAGDIR_NE: return ((v->x_pos & 0x0F) - ((_fractcoords_enter[dir] & 0x0F) - (length + 1))); + case DIAGDIR_SE: return -((v->y_pos & 0x0F) - ((_fractcoords_enter[dir] >> 4) + (length + 1))); + case DIAGDIR_SW: return -((v->x_pos & 0x0F) - ((_fractcoords_enter[dir] & 0x0F) + (length + 1))); + case DIAGDIR_NW: return ((v->y_pos & 0x0F) - ((_fractcoords_enter[dir] >> 4) - (length + 1))); default: NOT_REACHED(); } } @@ -3070,7 +3070,7 @@ static CommandCost TerraformTile_Track(TileIndex tile, DoCommandFlags flags, int if (tileh_old != SLOPE_NS && tileh_old != SLOPE_EW && IsSpecialRailFoundation(f_old)) return autoslope_result; /* Everything is valid, which only changes allowed_corner */ - for (Corner corner = (Corner)0; corner < CORNER_END; corner = (Corner)(corner + 1)) { + for (Corner corner = static_cast(0); corner < CORNER_END; corner = static_cast(corner + 1)) { if (allowed_corner == corner) continue; if (z_old + GetSlopeZInCorner(tileh_old, corner) != z_new + GetSlopeZInCorner(tileh_new, corner)) return autoslope_result; } @@ -3079,7 +3079,7 @@ static CommandCost TerraformTile_Track(TileIndex tile, DoCommandFlags flags, int if (flags.Test(DoCommandFlag::Execute)) SetRailGroundType(tile, RAIL_GROUND_BARREN); /* allow terraforming */ - return CommandCost(EXPENSES_CONSTRUCTION, was_water ? _price[PR_CLEAR_WATER] : (Money)0); + return CommandCost(EXPENSES_CONSTRUCTION, was_water ? _price[PR_CLEAR_WATER] : Money(0)); } else if (_settings_game.construction.build_on_slopes && AutoslopeEnabled() && AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, GetRailDepotDirection(tile))) { return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]); diff --git a/src/rail_gui.cpp b/src/rail_gui.cpp index 90718b064c..0dc8d18c59 100644 --- a/src/rail_gui.cpp +++ b/src/rail_gui.cpp @@ -410,7 +410,7 @@ static void HandleAutodirPlacement() */ static void HandleAutoSignalPlacement() { - Track track = (Track)GB(_thd.drawstyle, 0, 3); // 0..5 + Track track = static_cast(GB(_thd.drawstyle, 0, 3)); // 0..5 if ((_thd.drawstyle & HT_DRAG_MASK) == HT_RECT) { // one tile case GenericPlaceSignals(TileVirtXY(_thd.selend.x, _thd.selend.y)); @@ -1234,7 +1234,7 @@ public: case WID_BRAS_PLATFORM_DIR_X: case WID_BRAS_PLATFORM_DIR_Y: this->RaiseWidget(WID_BRAS_PLATFORM_DIR_X + _station_gui.axis); - _station_gui.axis = (Axis)(widget - WID_BRAS_PLATFORM_DIR_X); + _station_gui.axis = static_cast(widget - WID_BRAS_PLATFORM_DIR_X); this->LowerWidget(WID_BRAS_PLATFORM_DIR_X + _station_gui.axis); if (_settings_client.sound.click_beep) SndPlayFx(SND_15_BEEP); this->SetDirty(); @@ -1565,7 +1565,7 @@ public: case WID_BS_ELECTRIC_PBS_OWAY: this->RaiseWidget((_cur_signal_variant == SIG_ELECTRIC ? WID_BS_ELECTRIC_NORM : WID_BS_SEMAPHORE_NORM) + _cur_signal_type); - _cur_signal_type = (SignalType)((uint)((widget - WID_BS_SEMAPHORE_NORM) % (SIGTYPE_LAST + 1))); + _cur_signal_type = static_cast(static_cast((widget - WID_BS_SEMAPHORE_NORM) % (SIGTYPE_LAST + 1))); _cur_signal_variant = widget >= WID_BS_ELECTRIC_NORM ? SIG_ELECTRIC : SIG_SEMAPHORE; /* Update default (last-used) signal type in config file. */ @@ -1745,7 +1745,7 @@ struct BuildRailDepotWindow : public PickerWindowBase { case WID_BRAD_DEPOT_SW: case WID_BRAD_DEPOT_NW: this->RaiseWidget(WID_BRAD_DEPOT_NE + _build_depot_direction); - _build_depot_direction = (DiagDirection)(widget - WID_BRAD_DEPOT_NE); + _build_depot_direction = static_cast(widget - WID_BRAD_DEPOT_NE); this->LowerWidget(WID_BRAD_DEPOT_NE + _build_depot_direction); if (_settings_client.sound.click_beep) SndPlayFx(SND_15_BEEP); this->SetDirty(); diff --git a/src/road_cmd.cpp b/src/road_cmd.cpp index a804e84570..87de298c26 100644 --- a/src/road_cmd.cpp +++ b/src/road_cmd.cpp @@ -145,10 +145,10 @@ RoadType AllocateRoadType(RoadTypeLabel label, RoadTramType rtt) rti->introduction_date = CalendarTime::INVALID_DATE; /* Make us compatible with ourself. */ - rti->powered_roadtypes = (RoadTypes)(1ULL << rt); + rti->powered_roadtypes = static_cast(1ULL << rt); /* We also introduce ourself. */ - rti->introduces_roadtypes = (RoadTypes)(1ULL << rt); + rti->introduces_roadtypes = static_cast(1ULL << rt); /* Default sort order; order of allocation, but with some * offsets so it's easier for NewGRF to pick a spot without @@ -373,7 +373,7 @@ static CommandCost RemoveRoad(TileIndex tile, DoCommandFlags flags, RoadBits pie cost.AddCost(len * 2 * RoadClearCost(existing_rt)); if (flags.Test(DoCommandFlag::Execute)) { /* A full diagonal road tile has two road bits. */ - UpdateCompanyRoadInfrastructure(existing_rt, GetRoadOwner(tile, rtt), -(int)(len * 2 * TUNNELBRIDGE_TRACKBIT_FACTOR)); + UpdateCompanyRoadInfrastructure(existing_rt, GetRoadOwner(tile, rtt), -static_cast(len * 2 * TUNNELBRIDGE_TRACKBIT_FACTOR)); SetRoadType(other_end, rtt, INVALID_ROADTYPE); SetRoadType(tile, rtt, INVALID_ROADTYPE); @@ -454,7 +454,7 @@ static CommandCost RemoveRoad(TileIndex tile, DoCommandFlags flags, RoadBits pie } } - UpdateCompanyRoadInfrastructure(existing_rt, GetRoadOwner(tile, rtt), -(int)CountBits(pieces)); + UpdateCompanyRoadInfrastructure(existing_rt, GetRoadOwner(tile, rtt), -static_cast(CountBits(pieces))); if (present == ROAD_NONE) { /* No other road type, just clear tile. */ @@ -2125,7 +2125,7 @@ static TrackStatus GetTileTrackStatus_Road(TileIndex tile, TransportType mode, u if (side != INVALID_DIAGDIR && (DiagDirToRoadBits(side) & bits) == 0) break; uint multiplier = drd_to_multiplier[(rtt == RTT_TRAM) ? DRD_NONE : GetDisallowedRoadDirections(tile)]; - if (!HasRoadWorks(tile)) trackdirbits = (TrackdirBits)(_road_trackbits[bits] * multiplier); + if (!HasRoadWorks(tile)) trackdirbits = static_cast(_road_trackbits[bits] * multiplier); break; } @@ -2415,7 +2415,7 @@ static void ConvertRoadTypeOwner(TileIndex tile, uint num_pieces, Owner owner, R switch (owner.base()) { case OWNER_NONE.base(): - SetRoadOwner(tile, GetRoadTramType(to_type), (Owner)_current_company); + SetRoadOwner(tile, GetRoadTramType(to_type), Owner(_current_company)); UpdateCompanyRoadInfrastructure(to_type, _current_company, num_pieces); break; diff --git a/src/road_gui.cpp b/src/road_gui.cpp index 54c63bdbde..7f67096cc5 100644 --- a/src/road_gui.cpp +++ b/src/road_gui.cpp @@ -201,7 +201,7 @@ void CcRoadStop(Commands, const CommandCost &result, TileIndex tile, uint8_t wid if (!_settings_client.gui.persistent_buildingtools) ResetObjectToPlace(); bool connect_to_road = true; - if ((uint)spec_class < RoadStopClass::GetClassCount() && spec_index < RoadStopClass::Get(spec_class)->GetSpecCount()) { + if (static_cast(spec_class) < RoadStopClass::GetClassCount() && spec_index < RoadStopClass::Get(spec_class)->GetSpecCount()) { const RoadStopSpec *roadstopspec = RoadStopClass::Get(spec_class)->GetSpec(spec_index); if (roadstopspec != nullptr && roadstopspec->flags.Test(RoadStopSpecFlag::NoAutoRoadConnection)) connect_to_road = false; } @@ -592,7 +592,7 @@ struct BuildRoadToolbarWindow : Window { default: NOT_REACHED(); } - this->UpdateOptionWidgetStatus((RoadToolbarWidgets)widget); + this->UpdateOptionWidgetStatus(static_cast(widget)); if (_ctrl_pressed) RoadToolbar_CtrlChanged(this); } @@ -1123,7 +1123,7 @@ struct BuildRoadDepotWindow : public PickerWindowBase { AutoRestoreBackup dpi_backup(_cur_dpi, &tmp_dpi); int x = (ir.Width() - ScaleSpriteTrad(64)) / 2 + ScaleSpriteTrad(31); int y = (ir.Height() + ScaleSpriteTrad(48)) / 2 - ScaleSpriteTrad(31); - DrawRoadDepotSprite(x, y, (DiagDirection)(widget - WID_BROD_DEPOT_NE + DIAGDIR_NE), _cur_roadtype); + DrawRoadDepotSprite(x, y, static_cast(widget - WID_BROD_DEPOT_NE + DIAGDIR_NE), _cur_roadtype); } } @@ -1135,7 +1135,7 @@ struct BuildRoadDepotWindow : public PickerWindowBase { case WID_BROD_DEPOT_SW: case WID_BROD_DEPOT_SE: this->RaiseWidget(WID_BROD_DEPOT_NE + _road_depot_orientation); - _road_depot_orientation = (DiagDirection)(widget - WID_BROD_DEPOT_NE); + _road_depot_orientation = static_cast(widget - WID_BROD_DEPOT_NE); this->LowerWidget(WID_BROD_DEPOT_NE + _road_depot_orientation); if (_settings_client.sound.click_beep) SndPlayFx(SND_15_BEEP); this->SetDirty(); @@ -1254,7 +1254,7 @@ public: } else { DiagDirection orientation = _roadstop_gui.orientation; if (orientation < DIAGDIR_END && spec->flags.Test(RoadStopSpecFlag::DriveThroughOnly)) orientation = DIAGDIR_END; - DrawRoadStopTile(x, y, _cur_roadtype, spec, roadstoptype == RoadStopType::Bus ? StationType::Bus : StationType::Truck, (uint8_t)orientation); + DrawRoadStopTile(x, y, _cur_roadtype, spec, roadstoptype == RoadStopType::Bus ? StationType::Bus : StationType::Truck, static_cast(orientation)); } } @@ -1467,7 +1467,7 @@ public: if (spec != nullptr && spec->flags.Test(RoadStopSpecFlag::DriveThroughOnly)) return; } this->RaiseWidget(WID_BROS_STATION_NE + _roadstop_gui.orientation); - _roadstop_gui.orientation = (DiagDirection)(widget - WID_BROS_STATION_NE); + _roadstop_gui.orientation = static_cast(widget - WID_BROS_STATION_NE); this->LowerWidget(WID_BROS_STATION_NE + _roadstop_gui.orientation); if (_settings_client.sound.click_beep) SndPlayFx(SND_15_BEEP); this->SetDirty(); diff --git a/src/roadstop.cpp b/src/roadstop.cpp index 4c68e2688f..ebd19068ea 100644 --- a/src/roadstop.cpp +++ b/src/roadstop.cpp @@ -325,7 +325,7 @@ struct RoadStopEntryRebuilderHelper { */ Vehicle *FindVehiclesInRoadStop(Vehicle *v, void *data) { - RoadStopEntryRebuilderHelper *rserh = (RoadStopEntryRebuilderHelper*)data; + RoadStopEntryRebuilderHelper *rserh = static_cast(data); /* Not a RV or not in the right direction or crashed :( */ if (v->type != VEH_ROAD || DirToDiagDir(v->direction) != rserh->dir || !v->IsPrimaryVehicle() || v->vehstatus.Test(VehState::Crashed)) return nullptr; diff --git a/src/roadveh_cmd.cpp b/src/roadveh_cmd.cpp index ebe41585a8..1b3aa401bb 100644 --- a/src/roadveh_cmd.cpp +++ b/src/roadveh_cmd.cpp @@ -439,7 +439,7 @@ inline int RoadVehicle::GetCurrentMaxSpeed() const /* Limit speed to 50% while reversing, 75% in curves. */ for (const RoadVehicle *u = this; u != nullptr; u = u->Next()) { if (_settings_game.vehicle.roadveh_acceleration_model == AM_REALISTIC) { - if (this->state <= RVSB_TRACKDIR_MASK && IsReversingRoadTrackdir((Trackdir)this->state)) { + if (this->state <= RVSB_TRACKDIR_MASK && IsReversingRoadTrackdir(static_cast(this->state))) { max_speed = this->gcache.cached_max_track_speed / 2; break; } else if ((u->direction & 1) == 0) { @@ -517,7 +517,7 @@ static bool RoadVehIsCrashed(RoadVehicle *v) */ static Vehicle *EnumCheckRoadVehCrashTrain(Vehicle *v, void *data) { - const Vehicle *u = (Vehicle*)data; + const Vehicle *u = static_cast(data); return (v->type == VEH_TRAIN && abs(v->z_pos - u->z_pos) <= 6 && @@ -615,7 +615,7 @@ static Vehicle *EnumCheckRoadVehClose(Vehicle *v, void *data) static const int8_t dist_x[] = { -4, -8, -4, -1, 4, 8, 4, 1 }; static const int8_t dist_y[] = { -4, -1, 4, 8, 4, 1, -4, -8 }; - RoadVehFindData *rvf = (RoadVehFindData*)data; + RoadVehFindData *rvf = static_cast(data); short x_diff = v->x_pos - rvf->x; short y_diff = v->y_pos - rvf->y; @@ -740,7 +740,7 @@ static Direction RoadVehGetNewDirection(const RoadVehicle *v, int x, int y) x = x - v->x_pos + 1; y = y - v->y_pos + 1; - if ((uint)x > 2 || (uint)y > 2) return v->direction; + if (static_cast(x) > 2 || static_cast(y) > 2) return v->direction; return _roadveh_new_dir[y * 4 + x]; } @@ -764,7 +764,7 @@ struct OvertakeData { static Vehicle *EnumFindVehBlockingOvertake(Vehicle *v, void *data) { - const OvertakeData *od = (OvertakeData*)data; + const OvertakeData *od = static_cast(data); return (v->type == VEH_ROAD && v->First() == v && v != od->u && v != od->v) ? v : nullptr; } @@ -810,7 +810,7 @@ static void RoadVehCheckOvertake(RoadVehicle *v, RoadVehicle *u) if (v->direction != u->direction || !(v->direction & 1)) return; /* Check if vehicle is in a road stop, depot, tunnel or bridge or not on a straight road */ - if (v->state >= RVSB_IN_ROAD_STOP || !IsStraightRoadTrackdir((Trackdir)(v->state & RVSB_TRACKDIR_MASK))) return; + if (v->state >= RVSB_IN_ROAD_STOP || !IsStraightRoadTrackdir(static_cast(v->state & RVSB_TRACKDIR_MASK))) return; /* Can't overtake a vehicle that is moving faster than us. If the vehicle in front is * accelerating, take the maximum speed for the comparison, else the current speed. @@ -859,7 +859,7 @@ static int PickRandomBit(uint bits) uint i; uint num = RandomRange(CountBits(bits)); - for (i = 0; !(bits & 1) || (int)--num >= 0; bits >>= 1, i++) {} + for (i = 0; !(bits & 1) || static_cast(--num) >= 0; bits >>= 1, i++) {} return i; } @@ -1085,9 +1085,9 @@ static Trackdir FollowPreviousRoadVehicle(const RoadVehicle *v, const RoadVehicl { TRACKDIR_RIGHT_S, TRACKDIR_LOWER_W, TRACKDIR_LOWER_E, TRACKDIR_LEFT_S }}; dir = reversed_turn_lookup[prev->tile < tile ? 0 : 1][ReverseDiagDir(entry_dir)]; } else if (HasBit(prev_state, RVS_IN_DT_ROAD_STOP)) { - dir = (Trackdir)(prev_state & RVSB_ROAD_STOP_TRACKDIR_MASK); + dir = static_cast(prev_state & RVSB_ROAD_STOP_TRACKDIR_MASK); } else if (prev_state < TRACKDIR_END) { - dir = (Trackdir)prev_state; + dir = static_cast(prev_state); } else { return INVALID_TRACKDIR; } @@ -1136,7 +1136,7 @@ bool IndividualRoadVehicleController(RoadVehicle *v, const RoadVehicle *prev) /* If overtaking just aborts at a random moment, we can have a out-of-bound problem, * if the vehicle started a corner. To protect that, only allow an abort of * overtake if we are on straight roads */ - if (v->state < RVSB_IN_ROAD_STOP && IsStraightRoadTrackdir((Trackdir)v->state)) { + if (v->state < RVSB_IN_ROAD_STOP && IsStraightRoadTrackdir(static_cast(v->state))) { v->overtaking = 0; } } @@ -1183,18 +1183,18 @@ bool IndividualRoadVehicleController(RoadVehicle *v, const RoadVehicle *prev) (_settings_game.vehicle.road_side << RVS_DRIVE_SIDE)) ^ v->overtaking][v->frame + 1]; if (rd.x & RDE_NEXT_TILE) { - TileIndex tile = v->tile + TileOffsByDiagDir((DiagDirection)(rd.x & 3)); + TileIndex tile = v->tile + TileOffsByDiagDir(static_cast(rd.x & 3)); Trackdir dir; if (v->IsFrontEngine()) { /* If this is the front engine, look for the right path. */ if (HasTileAnyRoadType(tile, v->compatible_roadtypes)) { - dir = RoadFindPathToDest(v, tile, (DiagDirection)(rd.x & 3)); + dir = RoadFindPathToDest(v, tile, static_cast(rd.x & 3)); } else { - dir = _road_reverse_table[(DiagDirection)(rd.x & 3)]; + dir = _road_reverse_table[static_cast(rd.x & 3)]; } } else { - dir = FollowPreviousRoadVehicle(v, prev, tile, (DiagDirection)(rd.x & 3), false); + dir = FollowPreviousRoadVehicle(v, prev, tile, static_cast(rd.x & 3), false); } if (dir == INVALID_TRACKDIR) { @@ -1309,7 +1309,7 @@ again: RoadStop::IsDriveThroughRoadStopContinuation(v->tile, tile) && v->tile != tile) { /* So, keep 'our' state */ - dir = (Trackdir)v->state; + dir = static_cast(v->state); } else if (IsStationRoadStop(v->tile)) { /* We're not continuing our drive through road stop, so leave. */ RoadStop::GetByTile(v->tile, GetRoadStopType(v->tile))->Leave(v); @@ -1320,7 +1320,7 @@ again: TileIndex old_tile = v->tile; v->tile = tile; - v->state = (uint8_t)dir; + v->state = static_cast(dir); v->frame = start_frame; RoadTramType rtt = GetRoadTramType(v->roadtype); if (GetRoadType(old_tile, rtt) != GetRoadType(tile, rtt)) { @@ -1367,9 +1367,9 @@ again: } else { if (v->IsFrontEngine()) { /* If this is the front engine, look for the right path. */ - dir = RoadFindPathToDest(v, v->tile, (DiagDirection)(rd.x & 3)); + dir = RoadFindPathToDest(v, v->tile, static_cast(rd.x & 3)); } else { - dir = FollowPreviousRoadVehicle(v, prev, v->tile, (DiagDirection)(rd.x & 3), true); + dir = FollowPreviousRoadVehicle(v, prev, v->tile, static_cast(rd.x & 3), true); } } @@ -1745,7 +1745,7 @@ Trackdir RoadVehicle::GetVehicleTrackdir() const /* If vehicle's state is a valid track direction (vehicle is not turning around) return it, * otherwise transform it into a valid track direction */ - return (Trackdir)((IsReversingRoadTrackdir((Trackdir)this->state)) ? (this->state - 6) : this->state); + return static_cast((IsReversingRoadTrackdir(static_cast(this->state))) ? (this->state - 6) : this->state); } uint16_t RoadVehicle::GetMaxWeight() const diff --git a/src/saveload/afterload.cpp b/src/saveload/afterload.cpp index 1d5b970be7..ea9e5a0161 100644 --- a/src/saveload/afterload.cpp +++ b/src/saveload/afterload.cpp @@ -208,7 +208,7 @@ static void UpdateVoidTiles() static inline RailType UpdateRailType(RailType rt, RailType min) { - return rt >= min ? (RailType)(rt + 1): rt; + return rt >= min ? static_cast(rt + 1): rt; } /** @@ -998,7 +998,7 @@ bool AfterLoadGame() case MP_ROAD: t.m4() |= (t.m2() << 4); - if ((GB(t.m5(), 4, 2) == ROAD_TILE_CROSSING ? (Owner)t.m3() : GetTileOwner(t)) == OWNER_TOWN) { + if ((GB(t.m5(), 4, 2) == ROAD_TILE_CROSSING ? Owner(t.m3()) : GetTileOwner(t)) == OWNER_TOWN) { SetTownIndex(t, CalcClosestTownFromTile(t)->index); } else { SetTownIndex(t, TownID::Begin()); @@ -1100,7 +1100,7 @@ bool AfterLoadGame() case MP_TUNNELBRIDGE: /* Middle part of "old" bridges */ if (old_bridge && IsBridge(t) && HasBit(t.m5(), 6)) break; - if (((old_bridge && IsBridge(t)) ? (TransportType)GB(t.m5(), 1, 2) : GetTunnelBridgeTransportType(t)) == TRANSPORT_ROAD) { + if (((old_bridge && IsBridge(t)) ? static_cast(GB(t.m5(), 1, 2)) : GetTunnelBridgeTransportType(t)) == TRANSPORT_ROAD) { SB(t.m7(), 6, 2, 1); // Set pre-NRT road type bits for conversion later. } break; @@ -1117,7 +1117,7 @@ bool AfterLoadGame() for (auto t : Map::Iterate()) { switch (GetTileType(t)) { case MP_ROAD: - if (fix_roadtypes) SB(t.m7(), 6, 2, (RoadTypes)GB(t.m7(), 5, 3)); + if (fix_roadtypes) SB(t.m7(), 6, 2, static_cast(GB(t.m7(), 5, 3))); SB(t.m7(), 5, 1, GB(t.m3(), 7, 1)); // snow/desert switch (GetRoadTileType(t)) { default: SlErrorCorrupt("Invalid road tile type"); @@ -1150,7 +1150,7 @@ bool AfterLoadGame() case MP_STATION: if (!IsStationRoadStop(t)) break; - if (fix_roadtypes) SB(t.m7(), 6, 2, (RoadTypes)GB(t.m3(), 0, 3)); + if (fix_roadtypes) SB(t.m7(), 6, 2, static_cast(GB(t.m3(), 0, 3))); SB(t.m7(), 0, 5, (HasBit(t.m6(), 2) ? OWNER_TOWN : GetTileOwner(t)).base()); SB(t.m3(), 4, 4, t.m1()); t.m4() = 0; @@ -1158,8 +1158,8 @@ bool AfterLoadGame() case MP_TUNNELBRIDGE: if (old_bridge && IsBridge(t) && HasBit(t.m5(), 6)) break; - if (((old_bridge && IsBridge(t)) ? (TransportType)GB(t.m5(), 1, 2) : GetTunnelBridgeTransportType(t)) == TRANSPORT_ROAD) { - if (fix_roadtypes) SB(t.m7(), 6, 2, (RoadTypes)GB(t.m3(), 0, 3)); + if (((old_bridge && IsBridge(t)) ? static_cast(GB(t.m5(), 1, 2)) : GetTunnelBridgeTransportType(t)) == TRANSPORT_ROAD) { + if (fix_roadtypes) SB(t.m7(), 6, 2, static_cast(GB(t.m3(), 0, 3))); Owner o = GetTileOwner(t); SB(t.m7(), 0, 5, o.base()); // road owner @@ -1182,24 +1182,24 @@ bool AfterLoadGame() for (auto t : Map::Iterate()) { switch (GetTileType(t)) { case MP_RAILWAY: - SetRailType(t, (RailType)GB(t.m3(), 0, 4)); + SetRailType(t, static_cast(GB(t.m3(), 0, 4))); break; case MP_ROAD: if (IsLevelCrossing(t)) { - SetRailType(t, (RailType)GB(t.m3(), 0, 4)); + SetRailType(t, static_cast(GB(t.m3(), 0, 4))); } break; case MP_STATION: if (HasStationRail(t)) { - SetRailType(t, (RailType)GB(t.m3(), 0, 4)); + SetRailType(t, static_cast(GB(t.m3(), 0, 4))); } break; case MP_TUNNELBRIDGE: if (GetTunnelBridgeTransportType(t) == TRANSPORT_RAIL) { - SetRailType(t, (RailType)GB(t.m3(), 0, 4)); + SetRailType(t, static_cast(GB(t.m3(), 0, 4))); } break; @@ -1214,7 +1214,7 @@ bool AfterLoadGame() if (MayHaveBridgeAbove(t)) ClearBridgeMiddle(t); if (IsBridgeTile(t)) { if (HasBit(t.m5(), 6)) { // middle part - Axis axis = (Axis)GB(t.m5(), 0, 1); + Axis axis = static_cast(GB(t.m5(), 0, 1)); if (HasBit(t.m5(), 5)) { // transport route under bridge? if (GB(t.m5(), 3, 2) == TRANSPORT_RAIL) { @@ -1253,10 +1253,10 @@ bool AfterLoadGame() } SetBridgeMiddle(t, axis); } else { // ramp - Axis axis = (Axis)GB(t.m5(), 0, 1); + Axis axis = static_cast(GB(t.m5(), 0, 1)); uint north_south = GB(t.m5(), 5, 1); DiagDirection dir = ReverseDiagDir(XYNSToDiagDir(axis, north_south)); - TransportType type = (TransportType)GB(t.m5(), 1, 2); + TransportType type = static_cast(GB(t.m5(), 1, 2)); t.m5() = 1 << 7 | type << 2 | dir; } @@ -1767,7 +1767,7 @@ bool AfterLoadGame() if (IsSavegameVersionBefore(SLV_81)) { for (auto t : Map::Iterate()) { if (GetTileType(t) == MP_TREES) { - TreeGround groundType = (TreeGround)GB(t.m2(), 4, 2); + TreeGround groundType = static_cast(GB(t.m2(), 4, 2)); if (groundType != TREE_GROUND_SNOW_DESERT) SB(t.m2(), 6, 2, 3); } } @@ -1808,12 +1808,12 @@ bool AfterLoadGame() /* OrderDepotActionFlags were moved, instead of starting at bit 4 they now start at bit 3. */ for (Order *order : Order::Iterate()) { if (!order->IsType(OT_GOTO_DEPOT)) continue; - order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() >> 1)); + order->SetDepotActionType(static_cast(order->GetDepotActionType() >> 1)); } for (Vehicle *v : Vehicle::Iterate()) { if (!v->current_order.IsType(OT_GOTO_DEPOT)) continue; - v->current_order.SetDepotActionType((OrderDepotActionFlags)(v->current_order.GetDepotActionType() >> 1)); + v->current_order.SetDepotActionType(static_cast(v->current_order.GetDepotActionType() >> 1)); } } @@ -1826,7 +1826,7 @@ bool AfterLoadGame() case StationType::Oilrig: case StationType::Dock: case StationType::Buoy: - SetWaterClass(t, (WaterClass)GB(t.m3(), 0, 2)); + SetWaterClass(t, static_cast(GB(t.m3(), 0, 2))); SB(t.m3(), 0, 2, 0); break; @@ -1837,7 +1837,7 @@ bool AfterLoadGame() break; case MP_WATER: - SetWaterClass(t, (WaterClass)GB(t.m3(), 0, 2)); + SetWaterClass(t, static_cast(GB(t.m3(), 0, 2))); SB(t.m3(), 0, 2, 0); break; @@ -1865,7 +1865,7 @@ bool AfterLoadGame() MakeCanal(t, o, Random()); } } else if (IsShipDepot(t)) { - Owner o = (Owner)t.m4(); // Original water owner + Owner o = Owner(t.m4()); // Original water owner SetWaterClass(t, o == OWNER_WATER ? WATER_CLASS_SEA : WATER_CLASS_CANAL); } } @@ -2113,7 +2113,7 @@ bool AfterLoadGame() } Object *o = new Object(); - o->location.tile = (TileIndex)t; + o->location.tile = TileIndex(t); o->location.w = size; o->location.h = size; o->build_date = TimerGameCalendar::date; @@ -3129,10 +3129,10 @@ bool AfterLoadGame() /* Heading up slope == passed half way */ if ((shipdiagdir == slopediagdir) == second_half) { /* On top half of lock */ - s->z_pos = GetTileMaxZ(s->tile) * (int)TILE_HEIGHT; + s->z_pos = GetTileMaxZ(s->tile) * static_cast(TILE_HEIGHT); } else { /* On lower half of lock */ - s->z_pos = GetTileZ(s->tile) * (int)TILE_HEIGHT; + s->z_pos = GetTileZ(s->tile) * static_cast(TILE_HEIGHT); } } } diff --git a/src/saveload/ai_sl.cpp b/src/saveload/ai_sl.cpp index 29f759361c..6424196ddc 100644 --- a/src/saveload/ai_sl.cpp +++ b/src/saveload/ai_sl.cpp @@ -85,7 +85,7 @@ struct AIPLChunkHandler : ChunkHandler { } CompanyID index; - while ((index = (CompanyID)SlIterateArray()) != (CompanyID)-1) { + while ((index = CompanyID(SlIterateArray())) != CompanyID(-1)) { if (index >= MAX_COMPANIES) SlErrorCorrupt("Too many AI configs"); _ai_saveload_is_random = false; diff --git a/src/saveload/company_sl.cpp b/src/saveload/company_sl.cpp index 2b80659d47..9ee27a8937 100644 --- a/src/saveload/company_sl.cpp +++ b/src/saveload/company_sl.cpp @@ -365,7 +365,7 @@ public: void Load(CompanyProperties *c) const override { if (!IsSavegameVersionBefore(SLV_SAVELOAD_LIST_LENGTH)) { - c->num_valid_stat_ent = (uint8_t)SlGetStructListLength(UINT8_MAX); + c->num_valid_stat_ent = static_cast(SlGetStructListLength(UINT8_MAX)); } if (c->num_valid_stat_ent > std::size(c->old_economy)) SlErrorCorrupt("Too many old economy entries"); diff --git a/src/saveload/game_sl.cpp b/src/saveload/game_sl.cpp index fdfce16c68..7dddace925 100644 --- a/src/saveload/game_sl.cpp +++ b/src/saveload/game_sl.cpp @@ -137,7 +137,7 @@ public: void Load(LanguageStrings *ls) const override { - uint32_t length = IsSavegameVersionBefore(SLV_SAVELOAD_LIST_LENGTH) ? _game_saveload_strings : (uint32_t)SlGetStructListLength(UINT32_MAX); + uint32_t length = IsSavegameVersionBefore(SLV_SAVELOAD_LIST_LENGTH) ? _game_saveload_strings : static_cast(SlGetStructListLength(UINT32_MAX)); for (uint32_t i = 0; i < length; i++) { SlObject(nullptr, this->GetLoadDescription()); diff --git a/src/saveload/gamelog_sl.cpp b/src/saveload/gamelog_sl.cpp index fe85af5727..b773129cb4 100644 --- a/src/saveload/gamelog_sl.cpp +++ b/src/saveload/gamelog_sl.cpp @@ -351,7 +351,7 @@ public: uint8_t type; while ((type = SlReadByte()) != GLCT_NONE) { if (type >= GLCT_END) SlErrorCorrupt("Invalid gamelog change type"); - LoadChange(la, (GamelogChangeType)type); + LoadChange(la, static_cast(type)); } return; } @@ -360,7 +360,7 @@ public: la->change.reserve(length); for (size_t i = 0; i < length; i++) { - LoadChange(la, (GamelogChangeType)SlReadByte()); + LoadChange(la, static_cast(SlReadByte())); } } @@ -389,7 +389,7 @@ struct GLOGChunkHandler : ChunkHandler { if (type >= GLAT_END) SlErrorCorrupt("Invalid gamelog action type"); LoggedAction &la = gamelog.data->action.emplace_back(); - la.at = (GamelogActionType)type; + la.at = static_cast(type); SlObject(&la, slt); } return; diff --git a/src/saveload/industry_sl.cpp b/src/saveload/industry_sl.cpp index 17b61c5b8b..bfaa33cc4d 100644 --- a/src/saveload/industry_sl.cpp +++ b/src/saveload/industry_sl.cpp @@ -307,7 +307,7 @@ struct ITBLChunkHandler : ChunkHandler { } int index; while ((index = SlIterateArray()) != -1) { - if ((uint)index >= NUM_INDUSTRYTYPES) SlErrorCorrupt("Too many industry builder datas"); + if (static_cast(index) >= NUM_INDUSTRYTYPES) SlErrorCorrupt("Too many industry builder datas"); SlObject(_industry_builder.builddata + index, slt); } } diff --git a/src/saveload/linkgraph_sl.cpp b/src/saveload/linkgraph_sl.cpp index 9dfebbf899..3948f2e839 100644 --- a/src/saveload/linkgraph_sl.cpp +++ b/src/saveload/linkgraph_sl.cpp @@ -120,7 +120,7 @@ public: { _linkgraph = lg; - uint16_t length = IsSavegameVersionBefore(SLV_SAVELOAD_LIST_LENGTH) ? _num_nodes : (uint16_t)SlGetStructListLength(UINT16_MAX); + uint16_t length = IsSavegameVersionBefore(SLV_SAVELOAD_LIST_LENGTH) ? _num_nodes : static_cast(SlGetStructListLength(UINT16_MAX)); lg->Init(length); for (NodeID from = 0; from < length; ++from) { _linkgraph_from = from; diff --git a/src/saveload/newgrf_sl.cpp b/src/saveload/newgrf_sl.cpp index 41501260fa..b427f617d2 100644 --- a/src/saveload/newgrf_sl.cpp +++ b/src/saveload/newgrf_sl.cpp @@ -56,7 +56,7 @@ void NewGRFMappingChunkHandler::Load() const int index; while ((index = SlIterateArray()) != -1) { - if ((uint)index >= max_id) SlErrorCorrupt("Too many NewGRF entity mappings"); + if (static_cast(index) >= max_id) SlErrorCorrupt("Too many NewGRF entity mappings"); SlObject(&this->mapping.mappings[index], slt); } } diff --git a/src/saveload/oldloader.cpp b/src/saveload/oldloader.cpp index 7f2fd62929..661002209c 100644 --- a/src/saveload/oldloader.cpp +++ b/src/saveload/oldloader.cpp @@ -29,9 +29,9 @@ static const int HEADER_CHECKSUM_SIZE = 2; uint32_t _bump_assert_value; -static inline OldChunkType GetOldChunkType(OldChunkType type) {return (OldChunkType)GB(type, 0, 4);} -static inline OldChunkType GetOldChunkVarType(OldChunkType type) {return (OldChunkType)(GB(type, 8, 8) << 8);} -static inline OldChunkType GetOldChunkFileType(OldChunkType type) {return (OldChunkType)(GB(type, 16, 8) << 16);} +static inline OldChunkType GetOldChunkType(OldChunkType type) {return static_cast(GB(type, 0, 4));} +static inline OldChunkType GetOldChunkVarType(OldChunkType type) {return static_cast(GB(type, 8, 8) << 8);} +static inline OldChunkType GetOldChunkFileType(OldChunkType type) {return static_cast(GB(type, 16, 8) << 16);} /** * Return expected size in bytes of a OldChunkType @@ -128,7 +128,7 @@ bool LoadChunk(LoadgameState &ls, void *base, const OldChunks *chunks) continue; } - uint8_t *ptr = (uint8_t*)chunk->ptr; + uint8_t *ptr = static_cast(chunk->ptr); for (uint i = 0; i < chunk->amount; i++) { /* Handle simple types */ @@ -153,11 +153,11 @@ bool LoadChunk(LoadgameState &ls, void *base, const OldChunks *chunks) /* Reading from the file: bits 16 to 23 have the FILE type */ switch (GetOldChunkFileType(chunk->type)) { - case OC_FILE_I8: res = (int8_t)ReadByte(ls); break; + case OC_FILE_I8: res = static_cast(ReadByte(ls)); break; case OC_FILE_U8: res = ReadByte(ls); break; - case OC_FILE_I16: res = (int16_t)ReadUint16(ls); break; + case OC_FILE_I16: res = static_cast(ReadUint16(ls)); break; case OC_FILE_U16: res = ReadUint16(ls); break; - case OC_FILE_I32: res = (int32_t)ReadUint32(ls); break; + case OC_FILE_I32: res = static_cast(ReadUint32(ls)); break; case OC_FILE_U32: res = ReadUint32(ls); break; default: NOT_REACHED(); } @@ -166,18 +166,18 @@ bool LoadChunk(LoadgameState &ls, void *base, const OldChunks *chunks) if (base == nullptr && chunk->ptr == nullptr) continue; /* Chunk refers to a struct member, get address in base. */ - if (chunk->ptr == nullptr) ptr = (uint8_t *)chunk->offset(base); + if (chunk->ptr == nullptr) ptr = static_cast(chunk->offset(base)); /* Write the data */ switch (GetOldChunkVarType(chunk->type)) { - case OC_VAR_I8: *(int8_t *)ptr = GB(res, 0, 8); break; - case OC_VAR_U8: *(uint8_t *)ptr = GB(res, 0, 8); break; - case OC_VAR_I16:*(int16_t *)ptr = GB(res, 0, 16); break; - case OC_VAR_U16:*(uint16_t*)ptr = GB(res, 0, 16); break; - case OC_VAR_I32:*(int32_t *)ptr = res; break; - case OC_VAR_U32:*(uint32_t*)ptr = res; break; - case OC_VAR_I64:*(int64_t *)ptr = res; break; - case OC_VAR_U64:*(uint64_t*)ptr = res; break; + case OC_VAR_I8: *reinterpret_cast(ptr) = GB(res, 0, 8); break; + case OC_VAR_U8: *ptr = GB(res, 0, 8); break; + case OC_VAR_I16:*reinterpret_cast(ptr) = GB(res, 0, 16); break; + case OC_VAR_U16:*reinterpret_cast(ptr) = GB(res, 0, 16); break; + case OC_VAR_I32:*reinterpret_cast(ptr) = res; break; + case OC_VAR_U32:*reinterpret_cast(ptr) = res; break; + case OC_VAR_I64:*reinterpret_cast(ptr) = res; break; + case OC_VAR_U64:*reinterpret_cast(ptr) = res; break; default: NOT_REACHED(); } diff --git a/src/saveload/oldloader_sl.cpp b/src/saveload/oldloader_sl.cpp index 86069c870f..7a6c29b8bc 100644 --- a/src/saveload/oldloader_sl.cpp +++ b/src/saveload/oldloader_sl.cpp @@ -983,7 +983,7 @@ static bool LoadOldCompany(LoadgameState &ls, int num) { Company *c = new (CompanyID(num)) Company(); - _current_company_id = (CompanyID)num; + _current_company_id = CompanyID(num); if (!LoadChunk(ls, c, _company_chunk)) return false; @@ -1372,11 +1372,11 @@ bool LoadOldVehicle(LoadgameState &ls, int num) DisasterVehicle::From(v)->state = UnpackOldOrder(_old_order).GetDestination().value; } - v->next = (Vehicle *)(size_t)_old_next_ptr; + v->next = (Vehicle *)static_cast(_old_next_ptr); if (_cargo_count != 0 && CargoPacket::CanAllocateItem()) { StationID source = (_cargo_source == 0xFF) ? StationID::Invalid() : StationID{_cargo_source}; - TileIndex source_xy = (source != StationID::Invalid()) ? Station::Get(source)->xy : (TileIndex)0; + TileIndex source_xy = (source != StationID::Invalid()) ? Station::Get(source)->xy : TileIndex(0); v->cargo.Append(new CargoPacket(_cargo_count, _cargo_periods, source, source_xy, 0)); } } @@ -1828,7 +1828,7 @@ bool LoadTTOMain(LoadgameState &ls) _read_ttdpatch_flags = false; std::array engines; // we don't want to call Engine constructor here - _old_engines = (Engine *)engines.data(); + _old_engines = reinterpret_cast(engines.data()); /* Load the biggest chunk */ if (!LoadChunk(ls, nullptr, main_chunk)) { diff --git a/src/saveload/order_sl.cpp b/src/saveload/order_sl.cpp index 4d84ba9c7a..f2caeb2aa8 100644 --- a/src/saveload/order_sl.cpp +++ b/src/saveload/order_sl.cpp @@ -70,7 +70,7 @@ void Order::ConvertFromOldSavegame() /* Finally fix the depot type flags */ uint t = ((old_flags & 6) == 6) ? ODTFB_SERVICE : ODTF_MANUAL; if ((old_flags & 2) != 0) t |= ODTFB_PART_OF_ORDERS; - this->SetDepotOrderType((OrderDepotTypeFlags)t); + this->SetDepotOrderType(static_cast(t)); } } diff --git a/src/saveload/randomizer_sl.cpp b/src/saveload/randomizer_sl.cpp index b5da1428a4..f005a15b07 100644 --- a/src/saveload/randomizer_sl.cpp +++ b/src/saveload/randomizer_sl.cpp @@ -37,7 +37,7 @@ struct SRNDChunkHandler : ChunkHandler { SlTableHeader(_randomizer_desc); Owner index; - while ((index = (Owner)SlIterateArray()) != (Owner)-1) { + while ((index = Owner(SlIterateArray())) != Owner(-1)) { SlObject(&ScriptObject::GetRandomizer(index), _randomizer_desc); } } diff --git a/src/saveload/saveload.cpp b/src/saveload/saveload.cpp index 6b786f8d38..360da8b631 100644 --- a/src/saveload/saveload.cpp +++ b/src/saveload/saveload.cpp @@ -58,7 +58,7 @@ #include "../safeguards.h" -extern const SaveLoadVersion SAVEGAME_VERSION = (SaveLoadVersion)(SL_MAX_VERSION - 1); ///< Current savegame version of OpenTTD. +extern const SaveLoadVersion SAVEGAME_VERSION = static_cast(SL_MAX_VERSION - 1); ///< Current savegame version of OpenTTD. SavegameType _savegame_type; ///< type of savegame we are loading FileToSaveLoad _file_to_saveload; ///< File to save or load in the openttd loop. @@ -423,7 +423,7 @@ static inline uint64_t SlReadUint64() { uint32_t x = SlReadUint32(); uint32_t y = SlReadUint32(); - return (uint64_t)x << 32 | y; + return static_cast(x) << 32 | y; } static inline void SlWriteUint16(uint16_t v) @@ -440,8 +440,8 @@ static inline void SlWriteUint32(uint32_t v) static inline void SlWriteUint64(uint64_t x) { - SlWriteUint32((uint32_t)(x >> 32)); - SlWriteUint32((uint32_t)x); + SlWriteUint32(static_cast(x >> 32)); + SlWriteUint32(static_cast(x)); } /** @@ -502,21 +502,21 @@ static void SlWriteSimpleGamma(size_t i) if (i >= (1 << 21)) { if (i >= (1 << 28)) { assert(i <= UINT32_MAX); // We can only support 32 bits for now. - SlWriteByte((uint8_t)(0xF0)); - SlWriteByte((uint8_t)(i >> 24)); + SlWriteByte(static_cast(0xF0)); + SlWriteByte(static_cast(i >> 24)); } else { - SlWriteByte((uint8_t)(0xE0 | (i >> 24))); + SlWriteByte(static_cast(0xE0 | (i >> 24))); } - SlWriteByte((uint8_t)(i >> 16)); + SlWriteByte(static_cast(i >> 16)); } else { - SlWriteByte((uint8_t)(0xC0 | (i >> 16))); + SlWriteByte(static_cast(0xC0 | (i >> 16))); } - SlWriteByte((uint8_t)(i >> 8)); + SlWriteByte(static_cast(i >> 8)); } else { - SlWriteByte((uint8_t)(0x80 | (i >> 8))); + SlWriteByte(static_cast(0x80 | (i >> 8))); } } - SlWriteByte((uint8_t)i); + SlWriteByte(static_cast(i)); } /** Return how many bytes used to encode a gamma value */ @@ -687,7 +687,7 @@ int SlIterateArray() int index; switch (_sl.block_mode) { case CH_SPARSE_TABLE: - case CH_SPARSE_ARRAY: index = (int)SlReadSparseIndex(); break; + case CH_SPARSE_ARRAY: index = static_cast(SlReadSparseIndex()); break; case CH_TABLE: case CH_ARRAY: index = _sl.array_index++; break; default: @@ -733,7 +733,7 @@ void SlSetLength(size_t length) * The lower 24 bits are normal * The uppermost 4 bits are bits 24:27 */ assert(length < (1 << 28)); - SlWriteUint32((uint32_t)((length & 0xFFFFFF) | ((length >> 24) << 28))); + SlWriteUint32(static_cast((length & 0xFFFFFF) | ((length >> 24) << 28))); break; case CH_TABLE: case CH_ARRAY: @@ -753,7 +753,7 @@ void SlSetLength(size_t length) break; case NL_CALCLENGTH: - _sl.obj_len += (int)length; + _sl.obj_len += static_cast(length); break; default: NOT_REACHED(); @@ -768,7 +768,7 @@ void SlSetLength(size_t length) */ static void SlCopyBytes(void *ptr, size_t length) { - uint8_t *p = (uint8_t *)ptr; + uint8_t *p = static_cast(ptr); switch (_sl.action) { case SLA_LOAD_CHECK: @@ -798,15 +798,15 @@ size_t SlGetFieldLength() int64_t ReadValue(const void *ptr, VarType conv) { switch (GetVarMemType(conv)) { - case SLE_VAR_BL: return (*(const bool *)ptr != 0); - case SLE_VAR_I8: return *(const int8_t *)ptr; - case SLE_VAR_U8: return *(const uint8_t *)ptr; - case SLE_VAR_I16: return *(const int16_t *)ptr; - case SLE_VAR_U16: return *(const uint16_t*)ptr; - case SLE_VAR_I32: return *(const int32_t *)ptr; - case SLE_VAR_U32: return *(const uint32_t*)ptr; - case SLE_VAR_I64: return *(const int64_t *)ptr; - case SLE_VAR_U64: return *(const uint64_t*)ptr; + case SLE_VAR_BL: return (*static_cast(ptr) != 0); + case SLE_VAR_I8: return *static_cast(ptr); + case SLE_VAR_U8: return *static_cast(ptr); + case SLE_VAR_I16: return *static_cast(ptr); + case SLE_VAR_U16: return *static_cast(ptr); + case SLE_VAR_I32: return *static_cast(ptr); + case SLE_VAR_U32: return *static_cast(ptr); + case SLE_VAR_I64: return *static_cast(ptr); + case SLE_VAR_U64: return *static_cast(ptr); case SLE_VAR_NULL:return 0; default: NOT_REACHED(); } @@ -822,15 +822,15 @@ int64_t ReadValue(const void *ptr, VarType conv) void WriteValue(void *ptr, VarType conv, int64_t val) { switch (GetVarMemType(conv)) { - case SLE_VAR_BL: *(bool *)ptr = (val != 0); break; - case SLE_VAR_I8: *(int8_t *)ptr = val; break; - case SLE_VAR_U8: *(uint8_t *)ptr = val; break; - case SLE_VAR_I16: *(int16_t *)ptr = val; break; - case SLE_VAR_U16: *(uint16_t*)ptr = val; break; - case SLE_VAR_I32: *(int32_t *)ptr = val; break; - case SLE_VAR_U32: *(uint32_t*)ptr = val; break; - case SLE_VAR_I64: *(int64_t *)ptr = val; break; - case SLE_VAR_U64: *(uint64_t*)ptr = val; break; + case SLE_VAR_BL: *static_cast(ptr) = (val != 0); break; + case SLE_VAR_I8: *static_cast(ptr) = val; break; + case SLE_VAR_U8: *static_cast(ptr) = val; break; + case SLE_VAR_I16: *static_cast(ptr) = val; break; + case SLE_VAR_U16: *static_cast(ptr) = val; break; + case SLE_VAR_I32: *static_cast(ptr) = val; break; + case SLE_VAR_U32: *static_cast(ptr) = val; break; + case SLE_VAR_I64: *static_cast(ptr) = val; break; + case SLE_VAR_U64: *static_cast(ptr) = val; break; case SLE_VAR_NAME: *reinterpret_cast(ptr) = CopyFromOldName(val); break; case SLE_VAR_NULL: break; default: NOT_REACHED(); @@ -859,7 +859,7 @@ static void SlSaveLoadConv(void *ptr, VarType conv) case SLE_FILE_STRINGID: case SLE_FILE_U16:assert(x >= 0 && x <= 65535); SlWriteUint16(x);break; case SLE_FILE_I32: - case SLE_FILE_U32: SlWriteUint32((uint32_t)x);break; + case SLE_FILE_U32: SlWriteUint32(static_cast(x));break; case SLE_FILE_I64: case SLE_FILE_U64: SlWriteUint64(x);break; default: NOT_REACHED(); @@ -871,15 +871,15 @@ static void SlSaveLoadConv(void *ptr, VarType conv) int64_t x; /* Read a value from the file */ switch (GetVarFileType(conv)) { - case SLE_FILE_I8: x = (int8_t )SlReadByte(); break; - case SLE_FILE_U8: x = (uint8_t )SlReadByte(); break; - case SLE_FILE_I16: x = (int16_t )SlReadUint16(); break; - case SLE_FILE_U16: x = (uint16_t)SlReadUint16(); break; - case SLE_FILE_I32: x = (int32_t )SlReadUint32(); break; - case SLE_FILE_U32: x = (uint32_t)SlReadUint32(); break; - case SLE_FILE_I64: x = (int64_t )SlReadUint64(); break; - case SLE_FILE_U64: x = (uint64_t)SlReadUint64(); break; - case SLE_FILE_STRINGID: x = RemapOldStringID((uint16_t)SlReadUint16()); break; + case SLE_FILE_I8: x = static_cast(SlReadByte()); break; + case SLE_FILE_U8: x = SlReadByte(); break; + case SLE_FILE_I16: x = static_cast(SlReadUint16()); break; + case SLE_FILE_U16: x = static_cast(SlReadUint16()); break; + case SLE_FILE_I32: x = static_cast(SlReadUint32()); break; + case SLE_FILE_U32: x = SlReadUint32(); break; + case SLE_FILE_I64: x = static_cast(SlReadUint64()); break; + case SLE_FILE_U64: x = SlReadUint64(); break; + case SLE_FILE_STRINGID: x = RemapOldStringID(static_cast(SlReadUint16())); break; default: NOT_REACHED(); } @@ -1065,7 +1065,7 @@ static void SlCopyInternal(void *object, size_t length, VarType conv) /* used for conversion of Money 32bit->64bit */ if (conv == (SLE_FILE_I32 | SLE_VAR_I64)) { for (uint i = 0; i < length; i++) { - ((int64_t*)object)[i] = (int32_t)std::byteswap(SlReadUint32()); + (static_cast(object))[i] = static_cast(std::byteswap(SlReadUint32())); } return; } @@ -1076,7 +1076,7 @@ static void SlCopyInternal(void *object, size_t length, VarType conv) if (conv == SLE_INT8 || conv == SLE_UINT8) { SlCopyBytes(object, length); } else { - uint8_t *a = (uint8_t*)object; + uint8_t *a = static_cast(object); uint8_t mem_size = SlCalcConvMemLen(conv); for (; length != 0; length --) { @@ -1178,17 +1178,17 @@ static size_t ReferenceToInt(const void *obj, SLRefType rt) switch (rt) { case REF_VEHICLE_OLD: // Old vehicles we save as new ones - case REF_VEHICLE: return ((const Vehicle*)obj)->index + 1; - case REF_STATION: return ((const Station*)obj)->index + 1; - case REF_TOWN: return ((const Town*)obj)->index + 1; - case REF_ORDER: return ((const Order*)obj)->index + 1; - case REF_ROADSTOPS: return ((const RoadStop*)obj)->index + 1; - case REF_ENGINE_RENEWS: return ((const EngineRenew*)obj)->index + 1; - case REF_CARGO_PACKET: return ((const CargoPacket*)obj)->index + 1; - case REF_ORDERLIST: return ((const OrderList*)obj)->index + 1; - case REF_STORAGE: return ((const PersistentStorage*)obj)->index + 1; - case REF_LINK_GRAPH: return ((const LinkGraph*)obj)->index + 1; - case REF_LINK_GRAPH_JOB: return ((const LinkGraphJob*)obj)->index + 1; + case REF_VEHICLE: return (static_cast(obj))->index + 1; + case REF_STATION: return (static_cast(obj))->index + 1; + case REF_TOWN: return (static_cast(obj))->index + 1; + case REF_ORDER: return (static_cast(obj))->index + 1; + case REF_ROADSTOPS: return (static_cast(obj))->index + 1; + case REF_ENGINE_RENEWS: return (static_cast(obj))->index + 1; + case REF_CARGO_PACKET: return (static_cast(obj))->index + 1; + case REF_ORDERLIST: return (static_cast(obj))->index + 1; + case REF_STORAGE: return (static_cast(obj))->index + 1; + case REF_LINK_GRAPH: return (static_cast(obj))->index + 1; + case REF_LINK_GRAPH_JOB: return (static_cast(obj))->index + 1; default: NOT_REACHED(); } } @@ -1283,17 +1283,17 @@ void SlSaveLoadRef(void *ptr, VarType conv) { switch (_sl.action) { case SLA_SAVE: - SlWriteUint32((uint32_t)ReferenceToInt(*(void **)ptr, (SLRefType)conv)); + SlWriteUint32(static_cast(ReferenceToInt(*static_cast(ptr), static_cast(conv)))); break; case SLA_LOAD_CHECK: case SLA_LOAD: - *(size_t *)ptr = IsSavegameVersionBefore(SLV_69) ? SlReadUint16() : SlReadUint32(); + *static_cast(ptr) = IsSavegameVersionBefore(SLV_69) ? SlReadUint16() : SlReadUint32(); break; case SLA_PTRS: - *(void **)ptr = IntToReference(*(size_t *)ptr, (SLRefType)conv); + *static_cast(ptr) = IntToReference(*static_cast(ptr), static_cast(conv)); break; case SLA_NULL: - *(void **)ptr = nullptr; + *static_cast(ptr) = nullptr; break; default: NOT_REACHED(); } @@ -1319,7 +1319,7 @@ public: const SlStorageT *list = static_cast(storage); int type_size = SlGetArrayLength(list->size()); - int item_size = SlCalcConvFileLen(cmd == SL_VAR ? conv : (VarType)SLE_FILE_U32); + int item_size = SlCalcConvFileLen(cmd == SL_VAR ? conv : static_cast(SLE_FILE_U32)); return list->size() * item_size + type_size; } @@ -1698,7 +1698,7 @@ static bool SlObjectMember(void *object, const SaveLoad &sld) void *ptr = GetVariableAddress(object, sld); switch (_sl.action) { - case SLA_SAVE: SlWriteByte(*(uint8_t *)ptr); break; + case SLA_SAVE: SlWriteByte(*static_cast(ptr)); break; case SLA_LOAD_CHECK: case SLA_LOAD: case SLA_PTRS: @@ -1903,7 +1903,7 @@ std::vector SlTableHeader(const SaveLoadTable &slt) } /* We don't know this field, so read to nothing. */ - saveloads.push_back({std::move(key), saveload_type, ((VarType)type & SLE_FILE_TYPE_MASK) | SLE_VAR_NULL, 1, SL_MIN_VERSION, SL_MAX_VERSION, nullptr, 0, std::move(handler)}); + saveloads.push_back({std::move(key), saveload_type, (static_cast(type) & SLE_FILE_TYPE_MASK) | SLE_VAR_NULL, 1, SL_MIN_VERSION, SL_MAX_VERSION, nullptr, 0, std::move(handler)}); continue; } @@ -2410,10 +2410,10 @@ struct LZOLoadFilter : LoadFilter { lzo_uint len = ssize; /* Read header*/ - if (this->chain->Read((uint8_t*)tmp, sizeof(tmp)) != sizeof(tmp)) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_READABLE, "File read failed"); + if (this->chain->Read(reinterpret_cast(tmp), sizeof(tmp)) != sizeof(tmp)) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_READABLE, "File read failed"); /* Check if size is bad */ - ((uint32_t*)out)[0] = size = tmp[1]; + (reinterpret_cast(out))[0] = size = tmp[1]; if (_sl_version != SL_MIN_VERSION) { tmp[0] = TO_BE32(tmp[0]); @@ -2456,10 +2456,10 @@ struct LZOSaveFilter : SaveFilter { do { /* Compress up to LZO_BUFFER_SIZE bytes at once. */ - lzo_uint len = size > LZO_BUFFER_SIZE ? LZO_BUFFER_SIZE : (lzo_uint)size; + lzo_uint len = size > LZO_BUFFER_SIZE ? LZO_BUFFER_SIZE : static_cast(size); lzo1x_1_compress(in, len, out + sizeof(uint32_t) * 2, &outlen, wrkmem); - ((uint32_t*)out)[1] = TO_BE32((uint32_t)outlen); - ((uint32_t*)out)[0] = TO_BE32(lzo_adler32(0, out + sizeof(uint32_t), outlen + sizeof(uint32_t))); + (reinterpret_cast(out))[1] = TO_BE32(static_cast(outlen)); + (reinterpret_cast(out))[0] = TO_BE32(lzo_adler32(0, out + sizeof(uint32_t), outlen + sizeof(uint32_t))); this->chain->Write(out, outlen + sizeof(uint32_t) * 2); /* Move to next data chunk. */ @@ -2538,13 +2538,13 @@ struct ZlibLoadFilter : LoadFilter { size_t Read(uint8_t *buf, size_t size) override { this->z.next_out = buf; - this->z.avail_out = (uint)size; + this->z.avail_out = static_cast(size); do { /* read more bytes from the file? */ if (this->z.avail_in == 0) { this->z.next_in = this->fread_buf; - this->z.avail_in = (uint)this->chain->Read(this->fread_buf, sizeof(this->fread_buf)); + this->z.avail_in = static_cast(this->chain->Read(this->fread_buf, sizeof(this->fread_buf))); } /* inflate the data */ @@ -2590,7 +2590,7 @@ struct ZlibSaveFilter : SaveFilter { { uint n; this->z.next_in = p; - this->z.avail_in = (uInt)len; + this->z.avail_in = static_cast(len); do { this->z.next_out = this->fwrite_buf; this->z.avail_out = sizeof(this->fwrite_buf); @@ -2933,7 +2933,7 @@ static SaveOrLoadResult SaveFileToDisk(bool threaded) /* We have written our stuff to memory, now write it to file! */ uint32_t hdr[2] = { fmt.tag, TO_BE32(SAVEGAME_VERSION << 16) }; - _sl.sf->Write((uint8_t*)hdr, sizeof(hdr)); + _sl.sf->Write(reinterpret_cast(hdr), sizeof(hdr)); _sl.sf = fmt.init_write(_sl.sf, compression); _sl.dumper->Flush(_sl.sf); @@ -3039,7 +3039,7 @@ static const SaveLoadFormat *DetermineSaveLoadFormat(uint32_t tag, uint32_t raw_ auto fmt = std::ranges::find(_saveload_formats, tag, &SaveLoadFormat::tag); if (fmt != std::end(_saveload_formats)) { /* Check version number */ - _sl_version = (SaveLoadVersion)(TO_BE32(raw_version) >> 16); + _sl_version = static_cast(TO_BE32(raw_version) >> 16); /* Minor is not used anymore from version 18.0, but it is still needed * in versions before that (4 cases) which can't be removed easy. * Therefore it is loaded, but never saved (or, it saves a 0 in any scenario). */ @@ -3087,7 +3087,7 @@ static SaveOrLoadResult DoLoad(std::shared_ptr reader, bool load_che } uint32_t hdr[2]; - if (_sl.lf->Read((uint8_t*)hdr, sizeof(hdr)) != sizeof(hdr)) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_READABLE); + if (_sl.lf->Read(reinterpret_cast(hdr), sizeof(hdr)) != sizeof(hdr)) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_READABLE); /* see if we have any loader for this type. */ const SaveLoadFormat *fmt = DetermineSaveLoadFormat(hdr[0], hdr[1]); diff --git a/src/saveload/settings_sl.cpp b/src/saveload/settings_sl.cpp index c36b0dd4c0..a2bed19273 100644 --- a/src/saveload/settings_sl.cpp +++ b/src/saveload/settings_sl.cpp @@ -63,7 +63,7 @@ void HandleOldDiffCustom(bool savegame) continue; } - int32_t value = (int32_t)((name == "max_loan" ? 1000 : 1) * _old_diff_custom[i++]); + int32_t value = static_cast((name == "max_loan" ? 1000 : 1) * _old_diff_custom[i++]); sd->AsIntSetting()->MakeValueValidAndWrite(savegame ? &_settings_game : &_settings_newgame, value); } } diff --git a/src/saveload/vehicle_sl.cpp b/src/saveload/vehicle_sl.cpp index c98f8df68a..71d5983eb9 100644 --- a/src/saveload/vehicle_sl.cpp +++ b/src/saveload/vehicle_sl.cpp @@ -1121,7 +1121,7 @@ struct VEHSChunkHandler : ChunkHandler { while ((index = SlIterateArray()) != -1) { Vehicle *v; - VehicleType vtype = (VehicleType)SlReadByte(); + VehicleType vtype = static_cast(SlReadByte()); switch (vtype) { case VEH_TRAIN: v = new (VehicleID(index)) Train(); break; diff --git a/src/saveload/waypoint_sl.cpp b/src/saveload/waypoint_sl.cpp index 676d162195..c25882998b 100644 --- a/src/saveload/waypoint_sl.cpp +++ b/src/saveload/waypoint_sl.cpp @@ -130,7 +130,7 @@ void MoveWaypointsToBaseStations() bool reserved = !IsSavegameVersionBefore(SLV_100) && HasBit(tile.m5(), 4); /* The tile really has our waypoint, so reassign the map array */ - MakeRailWaypoint(tile, GetTileOwner(tile), new_wp->index, (Axis)GB(tile.m5(), 0, 1), 0, GetRailType(tile)); + MakeRailWaypoint(tile, GetTileOwner(tile), new_wp->index, static_cast(GB(tile.m5(), 0, 1)), 0, GetRailType(tile)); new_wp->facilities.Set(StationFacility::Train); new_wp->owner = GetTileOwner(tile); diff --git a/src/screenshot.cpp b/src/screenshot.cpp index 1d7898b7b9..0cbf538010 100644 --- a/src/screenshot.cpp +++ b/src/screenshot.cpp @@ -87,7 +87,7 @@ static void CurrentScreenCallback(void *, void *buf, uint y, uint pitch, uint n) */ static void LargeWorldCallback(void *userdata, void *buf, uint y, uint pitch, uint n) { - Viewport *vp = (Viewport *)userdata; + Viewport *vp = static_cast(userdata); DrawPixelInfo dpi; int wx, left; @@ -293,7 +293,7 @@ static bool MakeLargeWorldScreenshot(ScreenshotType t, uint32_t width = 0, uint3 */ static void HeightmapCallback(void *, void *buffer, uint y, uint, uint n) { - uint8_t *buf = (uint8_t *)buffer; + uint8_t *buf = static_cast(buffer); while (n > 0) { TileIndex ti = TileXY(Map::MaxX(), y); for (uint x = Map::MaxX(); true; x--) { @@ -473,10 +473,10 @@ bool MakeScreenshot(ScreenshotType t, const std::string &name, uint32_t width, u static void MinimapScreenCallback(void *, void *buf, uint y, uint pitch, uint n) { - uint32_t *ubuf = (uint32_t *)buf; + uint32_t *ubuf = static_cast(buf); uint num = (pitch * n); for (uint i = 0; i < num; i++) { - uint row = y + (int)(i / pitch); + uint row = y + static_cast(i / pitch); uint col = (Map::SizeX() - 1) - (i % pitch); TileIndex tile = TileXY(col, row); diff --git a/src/screenshot_bmp.cpp b/src/screenshot_bmp.cpp index f86f2d7e4a..d655b9562c 100644 --- a/src/screenshot_bmp.cpp +++ b/src/screenshot_bmp.cpp @@ -127,7 +127,7 @@ public: } else { /* Convert from 'native' 32bpp to BMP-like 24bpp. * Works for both big and little endian machines */ - Colour *src = ((Colour *)buff.data()) + n * w; + Colour *src = (reinterpret_cast(buff.data())) + n * w; uint8_t *dst = line.data(); for (uint i = 0; i < w; i++) { dst[i * 3 ] = src[i].b; diff --git a/src/screenshot_png.cpp b/src/screenshot_png.cpp index 1abc0fb198..449c7dbd61 100644 --- a/src/screenshot_png.cpp +++ b/src/screenshot_png.cpp @@ -155,7 +155,7 @@ public: /* write them to png */ for (i = 0; i != n; i++) { - png_write_row(png_ptr, (png_bytep)buff.data() + i * w * bpp); + png_write_row(png_ptr, static_cast(buff.data()) + i * w * bpp); } } while (y != h); diff --git a/src/script/api/script_airport.cpp b/src/script/api/script_airport.cpp index 054c3f4add..cf80fe7cd4 100644 --- a/src/script/api/script_airport.cpp +++ b/src/script/api/script_airport.cpp @@ -24,7 +24,7 @@ /* static */ bool ScriptAirport::IsAirportInformationAvailable(AirportType type) { - return type >= 0 && type < (AirportType)NUM_AIRPORTS && AirportSpec::Get(type)->enabled; + return type >= 0 && type < static_cast(NUM_AIRPORTS) && AirportSpec::Get(type)->enabled; } /* static */ Money ScriptAirport::GetPrice(AirportType type) @@ -67,7 +67,7 @@ { if (!IsAirportInformationAvailable(type)) return -1; - return _settings_game.station.modified_catchment ? ::AirportSpec::Get(type)->catchment : (uint)CA_UNMODIFIED; + return _settings_game.station.modified_catchment ? ::AirportSpec::Get(type)->catchment : CA_UNMODIFIED; } /* static */ bool ScriptAirport::BuildAirport(TileIndex tile, AirportType type, StationID station_id) @@ -124,7 +124,7 @@ if (!ScriptStation::HasStationType(station_id, ScriptStation::STATION_AIRPORT)) return AT_INVALID; - return (AirportType)::Station::Get(station_id)->airport.type; + return static_cast(::Station::Get(station_id)->airport.type); } @@ -170,7 +170,7 @@ { if (!IsAirportInformationAvailable(type)) return -1; - return (int64_t)GetMaintenanceCostFactor(type) * _price[PR_INFRASTRUCTURE_AIRPORT] >> 3; + return static_cast(GetMaintenanceCostFactor(type)) * _price[PR_INFRASTRUCTURE_AIRPORT] >> 3; } /* static */ SQInteger ScriptAirport::GetAirportNumHelipads(AirportType type) diff --git a/src/script/api/script_basestation.cpp b/src/script/api/script_basestation.cpp index f8a0d34c90..af5fbf76c7 100644 --- a/src/script/api/script_basestation.cpp +++ b/src/script/api/script_basestation.cpp @@ -63,5 +63,5 @@ { if (!IsValidBaseStation(station_id)) return ScriptDate::DATE_INVALID; - return (ScriptDate::Date)::BaseStation::Get(station_id)->build_date.base(); + return static_cast(::BaseStation::Get(station_id)->build_date.base()); } diff --git a/src/script/api/script_bridge.cpp b/src/script/api/script_bridge.cpp index 3236c863e8..f202ecf512 100644 --- a/src/script/api/script_bridge.cpp +++ b/src/script/api/script_bridge.cpp @@ -34,8 +34,8 @@ /* static */ BridgeType ScriptBridge::GetBridgeType(TileIndex tile) { - if (!IsBridgeTile(tile)) return (BridgeType)-1; - return (BridgeType)::GetBridgeType(tile); + if (!IsBridgeTile(tile)) return static_cast(-1); + return ::GetBridgeType(tile); } /** @@ -105,7 +105,7 @@ static void _DoCommandReturnBuildBridge1(class ScriptInstance *instance) DiagDirection dir_1 = ::DiagdirBetweenTiles(end, start); DiagDirection dir_2 = ::ReverseDiagDir(dir_1); - return ScriptObject::Command::Do(&::_DoCommandReturnBuildBridge2, start + ::TileOffsByDiagDir(dir_1), ::DiagDirToRoadBits(dir_2), (::RoadType)ScriptRoad::GetCurrentRoadType(), DRD_NONE, TownID::Invalid()); + return ScriptObject::Command::Do(&::_DoCommandReturnBuildBridge2, start + ::TileOffsByDiagDir(dir_1), ::DiagDirToRoadBits(dir_2), static_cast<::RoadType>(ScriptRoad::GetCurrentRoadType()), DRD_NONE, TownID::Invalid()); } /* static */ bool ScriptBridge::_BuildBridgeRoad2() @@ -119,7 +119,7 @@ static void _DoCommandReturnBuildBridge1(class ScriptInstance *instance) DiagDirection dir_1 = ::DiagdirBetweenTiles(end, start); DiagDirection dir_2 = ::ReverseDiagDir(dir_1); - return ScriptObject::Command::Do(end + ::TileOffsByDiagDir(dir_2), ::DiagDirToRoadBits(dir_1), (::RoadType)ScriptRoad::GetCurrentRoadType(), DRD_NONE, TownID::Invalid()); + return ScriptObject::Command::Do(end + ::TileOffsByDiagDir(dir_2), ::DiagDirToRoadBits(dir_1), static_cast<::RoadType>(ScriptRoad::GetCurrentRoadType()), DRD_NONE, TownID::Invalid()); } /* static */ bool ScriptBridge::RemoveBridge(TileIndex tile) diff --git a/src/script/api/script_cargo.cpp b/src/script/api/script_cargo.cpp index 712daa6ed3..4ddd0a582d 100644 --- a/src/script/api/script_cargo.cpp +++ b/src/script/api/script_cargo.cpp @@ -24,7 +24,7 @@ /* static */ bool ScriptCargo::IsValidTownEffect(TownEffect towneffect_type) { - return (towneffect_type >= (TownEffect)TAE_BEGIN && towneffect_type < (TownEffect)TAE_END); + return (towneffect_type >= static_cast(TAE_BEGIN) && towneffect_type < static_cast(TAE_END)); } /* static */ std::optional ScriptCargo::GetName(CargoType cargo_type) @@ -43,7 +43,7 @@ * like "PASS", "COAL", "OIL_". New ones can be defined by NewGRFs */ std::string cargo_label; for (uint i = 0; i < sizeof(cargo->label); i++) { - cargo_label.push_back(GB(cargo->label.base(), (uint8_t)(sizeof(cargo->label) - i - 1) * 8, 8)); + cargo_label.push_back(GB(cargo->label.base(), static_cast(sizeof(cargo->label) - i - 1) * 8, 8)); } return cargo_label; } @@ -65,7 +65,7 @@ { if (!IsValidCargo(cargo_type)) return TE_NONE; - return (ScriptCargo::TownEffect)::CargoSpec::Get(cargo_type)->town_acceptance_effect; + return static_cast(::CargoSpec::Get(cargo_type)->town_acceptance_effect); } /* static */ Money ScriptCargo::GetCargoIncome(CargoType cargo_type, SQInteger distance, SQInteger days_in_transit) @@ -80,7 +80,7 @@ /* static */ ScriptCargo::DistributionType ScriptCargo::GetDistributionType(CargoType cargo_type) { if (!ScriptCargo::IsValidCargo(cargo_type)) return INVALID_DISTRIBUTION_TYPE; - return (ScriptCargo::DistributionType)_settings_game.linkgraph.GetDistributionType(cargo_type); + return static_cast(_settings_game.linkgraph.GetDistributionType(cargo_type)); } /* static */ SQInteger ScriptCargo::GetWeight(CargoType cargo_type, SQInteger amount) diff --git a/src/script/api/script_client.cpp b/src/script/api/script_client.cpp index 10e3c73f2a..d184215aae 100644 --- a/src/script/api/script_client.cpp +++ b/src/script/api/script_client.cpp @@ -24,7 +24,7 @@ static NetworkClientInfo *FindClientInfo(ScriptClient::ClientID client) { if (client == ScriptClient::CLIENT_INVALID) return nullptr; if (!_networking) return nullptr; - return NetworkClientInfo::GetByClientID((::ClientID)client); + return NetworkClientInfo::GetByClientID(static_cast<::ClientID>(client)); } /* static */ ScriptClient::ClientID ScriptClient::ResolveClientID(ScriptClient::ClientID client) @@ -50,5 +50,5 @@ static NetworkClientInfo *FindClientInfo(ScriptClient::ClientID client) { NetworkClientInfo *ci = FindClientInfo(client); if (ci == nullptr) return ScriptDate::DATE_INVALID; - return (ScriptDate::Date)ci->join_date.base(); + return static_cast(ci->join_date.base()); } diff --git a/src/script/api/script_company.cpp b/src/script/api/script_company.cpp index 9404b05b5a..53bf17f8dc 100644 --- a/src/script/api/script_company.cpp +++ b/src/script/api/script_company.cpp @@ -109,7 +109,7 @@ Randomizer &randomizer = ScriptObject::GetRandomizer(); CompanyManagerFace cmf; - GenderEthnicity ge = (GenderEthnicity)((gender == GENDER_FEMALE ? (1 << ::GENDER_FEMALE) : 0) | (randomizer.Next() & (1 << ETHNICITY_BLACK))); + GenderEthnicity ge = static_cast((gender == GENDER_FEMALE ? (1 << ::GENDER_FEMALE) : 0) | (randomizer.Next() & (1 << ETHNICITY_BLACK))); RandomCompanyManagerFaceBits(cmf, ge, false, randomizer); return ScriptObject::Command::Do(cmf); @@ -120,7 +120,7 @@ company = ResolveCompanyID(company); if (company == ScriptCompany::COMPANY_INVALID) return GENDER_INVALID; - GenderEthnicity ge = (GenderEthnicity)GetCompanyManagerFaceBits(Company::Get(ScriptCompany::FromScriptCompanyID(company))->face, CMFV_GEN_ETHN, GE_WM); + GenderEthnicity ge = static_cast(GetCompanyManagerFaceBits(Company::Get(ScriptCompany::FromScriptCompanyID(company))->face, CMFV_GEN_ETHN, GE_WM)); return HasBit(ge, ::GENDER_FEMALE) ? GENDER_FEMALE : GENDER_MALE; } @@ -284,7 +284,7 @@ EnforcePrecondition(false, company != ScriptCompany::COMPANY_INVALID); /* Network commands only allow 0 to indicate invalid tiles, not INVALID_TILE */ - return ScriptObject::Command::Do(tile == INVALID_TILE ? (TileIndex)0U : tile, delta, ScriptCompany::FromScriptCompanyID(company), (::ExpensesType)expenses_type); + return ScriptObject::Command::Do(tile == INVALID_TILE ? TileIndex(0U) : tile, delta, ScriptCompany::FromScriptCompanyID(company), static_cast<::ExpensesType>(expenses_type)); } /* static */ bool ScriptCompany::BuildCompanyHQ(TileIndex tile) @@ -353,31 +353,31 @@ /* static */ bool ScriptCompany::SetPrimaryLiveryColour(LiveryScheme scheme, Colours colour) { EnforceCompanyModeValid(false); - return ScriptObject::Command::Do((::LiveryScheme)scheme, true, (::Colours)colour); + return ScriptObject::Command::Do(static_cast<::LiveryScheme>(scheme), true, static_cast<::Colours>(colour)); } /* static */ bool ScriptCompany::SetSecondaryLiveryColour(LiveryScheme scheme, Colours colour) { EnforceCompanyModeValid(false); - return ScriptObject::Command::Do((::LiveryScheme)scheme, false, (::Colours)colour); + return ScriptObject::Command::Do(static_cast<::LiveryScheme>(scheme), false, static_cast<::Colours>(colour)); } /* static */ ScriptCompany::Colours ScriptCompany::GetPrimaryLiveryColour(ScriptCompany::LiveryScheme scheme) { - if ((::LiveryScheme)scheme < LS_BEGIN || (::LiveryScheme)scheme >= LS_END) return COLOUR_INVALID; + if (static_cast<::LiveryScheme>(scheme) < LS_BEGIN || static_cast<::LiveryScheme>(scheme) >= LS_END) return COLOUR_INVALID; const Company *c = ::Company::GetIfValid(_current_company); if (c == nullptr) return COLOUR_INVALID; - return (ScriptCompany::Colours)c->livery[scheme].colour1; + return static_cast(c->livery[scheme].colour1); } /* static */ ScriptCompany::Colours ScriptCompany::GetSecondaryLiveryColour(ScriptCompany::LiveryScheme scheme) { - if ((::LiveryScheme)scheme < LS_BEGIN || (::LiveryScheme)scheme >= LS_END) return COLOUR_INVALID; + if (static_cast<::LiveryScheme>(scheme) < LS_BEGIN || static_cast<::LiveryScheme>(scheme) >= LS_END) return COLOUR_INVALID; const Company *c = ::Company::GetIfValid(_current_company); if (c == nullptr) return COLOUR_INVALID; - return (ScriptCompany::Colours)c->livery[scheme].colour2; + return static_cast(c->livery[scheme].colour2); } diff --git a/src/script/api/script_date.cpp b/src/script/api/script_date.cpp index 3ff39b6232..6867aedc98 100644 --- a/src/script/api/script_date.cpp +++ b/src/script/api/script_date.cpp @@ -22,7 +22,7 @@ /* static */ ScriptDate::Date ScriptDate::GetCurrentDate() { - return (ScriptDate::Date)TimerGameEconomy::date.base(); + return static_cast(TimerGameEconomy::date.base()); } /* static */ SQInteger ScriptDate::GetYear(ScriptDate::Date date) diff --git a/src/script/api/script_engine.cpp b/src/script/api/script_engine.cpp index 305d55cf09..1054b47448 100644 --- a/src/script/api/script_engine.cpp +++ b/src/script/api/script_engine.cpp @@ -58,7 +58,7 @@ auto it = std::max_element(std::cbegin(cap), std::cend(cap)); if (*it == 0) return INVALID_CARGO; - return CargoType(std::distance(std::cbegin(cap), it)); + return static_cast(std::distance(std::cbegin(cap), it)); } /* static */ bool ScriptEngine::CanRefitCargo(EngineID engine_id, CargoType cargo_type) @@ -172,7 +172,7 @@ { if (!IsValidEngine(engine_id)) return ScriptDate::DATE_INVALID; - return (ScriptDate::Date)::Engine::Get(engine_id)->intro_date.base(); + return static_cast(::Engine::Get(engine_id)->intro_date.base()); } /* static */ ScriptVehicle::VehicleType ScriptEngine::GetVehicleType(EngineID engine_id) @@ -202,7 +202,7 @@ if (GetVehicleType(engine_id) != ScriptVehicle::VT_RAIL) return false; if (!ScriptRail::IsRailTypeAvailable(track_rail_type)) return false; - return ::IsCompatibleRail((::RailType)::RailVehInfo(engine_id)->railtype, (::RailType)track_rail_type); + return ::IsCompatibleRail(::RailVehInfo(engine_id)->railtype, static_cast<::RailType>(track_rail_type)); } /* static */ bool ScriptEngine::HasPowerOnRail(EngineID engine_id, ScriptRail::RailType track_rail_type) @@ -211,7 +211,7 @@ if (GetVehicleType(engine_id) != ScriptVehicle::VT_RAIL) return false; if (!ScriptRail::IsRailTypeAvailable(track_rail_type)) return false; - return ::HasPowerOnRail((::RailType)::RailVehInfo(engine_id)->railtype, (::RailType)track_rail_type); + return ::HasPowerOnRail(::RailVehInfo(engine_id)->railtype, static_cast<::RailType>(track_rail_type)); } /* static */ bool ScriptEngine::CanRunOnRoad(EngineID engine_id, ScriptRoad::RoadType road_type) @@ -225,7 +225,7 @@ if (GetVehicleType(engine_id) != ScriptVehicle::VT_ROAD) return false; if (!ScriptRoad::IsRoadTypeAvailable(road_type)) return false; - return ::HasPowerOnRoad((::RoadType)::RoadVehInfo(engine_id)->roadtype, (::RoadType)road_type); + return ::HasPowerOnRoad(::RoadVehInfo(engine_id)->roadtype, static_cast<::RoadType>(road_type)); } /* static */ ScriptRoad::RoadType ScriptEngine::GetRoadType(EngineID engine_id) @@ -233,7 +233,7 @@ if (!IsValidEngine(engine_id)) return ScriptRoad::ROADTYPE_INVALID; if (GetVehicleType(engine_id) != ScriptVehicle::VT_ROAD) return ScriptRoad::ROADTYPE_INVALID; - return (ScriptRoad::RoadType)(uint)::RoadVehInfo(engine_id)->roadtype; + return static_cast(static_cast(::RoadVehInfo(engine_id)->roadtype)); } /* static */ ScriptRail::RailType ScriptEngine::GetRailType(EngineID engine_id) @@ -241,7 +241,7 @@ if (!IsValidEngine(engine_id)) return ScriptRail::RAILTYPE_INVALID; if (GetVehicleType(engine_id) != ScriptVehicle::VT_RAIL) return ScriptRail::RAILTYPE_INVALID; - return (ScriptRail::RailType)(uint)::RailVehInfo(engine_id)->railtype; + return static_cast(static_cast(::RailVehInfo(engine_id)->railtype)); } /* static */ bool ScriptEngine::IsArticulated(EngineID engine_id) @@ -257,7 +257,7 @@ if (!IsValidEngine(engine_id)) return ScriptAirport::PT_INVALID; if (GetVehicleType(engine_id) != ScriptVehicle::VT_AIR) return ScriptAirport::PT_INVALID; - return (ScriptAirport::PlaneType)::AircraftVehInfo(engine_id)->subtype; + return static_cast(::AircraftVehInfo(engine_id)->subtype); } /* static */ SQInteger ScriptEngine::GetMaximumOrderDistance(EngineID engine_id) @@ -265,7 +265,7 @@ if (!IsValidEngine(engine_id)) return 0; if (GetVehicleType(engine_id) != ScriptVehicle::VT_AIR) return 0; - return (SQInteger)::Engine::Get(engine_id)->GetRange() * ::Engine::Get(engine_id)->GetRange(); + return static_cast(::Engine::Get(engine_id)->GetRange()) * ::Engine::Get(engine_id)->GetRange(); } /* static */ bool ScriptEngine::EnableForCompany(EngineID engine_id, ScriptCompany::CompanyID company) diff --git a/src/script/api/script_enginelist.cpp b/src/script/api/script_enginelist.cpp index 3b86bd5ebc..59385b6f61 100644 --- a/src/script/api/script_enginelist.cpp +++ b/src/script/api/script_enginelist.cpp @@ -18,7 +18,7 @@ ScriptEngineList::ScriptEngineList(ScriptVehicle::VehicleType vehicle_type) EnforceDeityOrCompanyModeValid_Void(); bool is_deity = ScriptCompanyMode::IsDeity(); ::CompanyID owner = ScriptObject::GetCompany(); - for (const Engine *e : Engine::IterateType((::VehicleType)vehicle_type)) { + for (const Engine *e : Engine::IterateType(static_cast<::VehicleType>(vehicle_type))) { if (is_deity || e->company_avail.Test(owner)) this->AddItem(e->index.base()); } } diff --git a/src/script/api/script_error.cpp b/src/script/api/script_error.cpp index 4c82dfd8bd..cbd401f280 100644 --- a/src/script/api/script_error.cpp +++ b/src/script/api/script_error.cpp @@ -69,5 +69,5 @@ ScriptError::ScriptErrorMapString ScriptError::error_map_string = ScriptError::S /* static */ ScriptError::ErrorCategories ScriptError::GetErrorCategory() { - return (ScriptError::ErrorCategories)(GetLastError() >> (uint)ERR_CAT_BIT_SIZE); + return static_cast(GetLastError() >> static_cast(ERR_CAT_BIT_SIZE)); } diff --git a/src/script/api/script_event.cpp b/src/script/api/script_event.cpp index efdc720cf3..fa73c51093 100644 --- a/src/script/api/script_event.cpp +++ b/src/script/api/script_event.cpp @@ -28,7 +28,7 @@ struct ScriptEventData { /* static */ void ScriptEventController::FreeEventPointer() { - ScriptEventData *data = (ScriptEventData *)ScriptObject::GetEventPointer(); + ScriptEventData *data = static_cast(ScriptObject::GetEventPointer()); /* Free all waiting events (if any) */ while (!data->stack.empty()) { @@ -44,7 +44,7 @@ struct ScriptEventData { /* static */ bool ScriptEventController::IsEventWaiting() { if (ScriptObject::GetEventPointer() == nullptr) ScriptEventController::CreateEventPointer(); - ScriptEventData *data = (ScriptEventData *)ScriptObject::GetEventPointer(); + ScriptEventData *data = static_cast(ScriptObject::GetEventPointer()); return !data->stack.empty(); } @@ -52,7 +52,7 @@ struct ScriptEventData { /* static */ ScriptEvent *ScriptEventController::GetNextEvent() { if (ScriptObject::GetEventPointer() == nullptr) ScriptEventController::CreateEventPointer(); - ScriptEventData *data = (ScriptEventData *)ScriptObject::GetEventPointer(); + ScriptEventData *data = static_cast(ScriptObject::GetEventPointer()); if (data->stack.empty()) return nullptr; @@ -64,7 +64,7 @@ struct ScriptEventData { /* static */ void ScriptEventController::InsertEvent(ScriptEvent *event) { if (ScriptObject::GetEventPointer() == nullptr) ScriptEventController::CreateEventPointer(); - ScriptEventData *data = (ScriptEventData *)ScriptObject::GetEventPointer(); + ScriptEventData *data = static_cast(ScriptObject::GetEventPointer()); event->AddRef(); data->stack.push(event); diff --git a/src/script/api/script_event_types.cpp b/src/script/api/script_event_types.cpp index bcb36871a1..e57171899a 100644 --- a/src/script/api/script_event_types.cpp +++ b/src/script/api/script_event_types.cpp @@ -44,7 +44,7 @@ CargoType ScriptEventEnginePreview::GetCargoType() auto it = std::max_element(std::cbegin(cap), std::cend(cap)); if (*it == 0) return INVALID_CARGO; - return CargoType(std::distance(std::cbegin(cap), it)); + return static_cast(std::distance(std::cbegin(cap), it)); } int32_t ScriptEventEnginePreview::GetCapacity() diff --git a/src/script/api/script_game.cpp b/src/script/api/script_game.cpp index 2b9fb4381b..b0f2bdab04 100644 --- a/src/script/api/script_game.cpp +++ b/src/script/api/script_game.cpp @@ -34,7 +34,7 @@ /* static */ ScriptGame::LandscapeType ScriptGame::GetLandscape() { - return (ScriptGame::LandscapeType)_settings_game.game_creation.landscape; + return static_cast(_settings_game.game_creation.landscape); } /* static */ bool ScriptGame::IsMultiplayer() diff --git a/src/script/api/script_goal.cpp b/src/script/api/script_goal.cpp index 1f4e7cf1e8..64bc69eef1 100644 --- a/src/script/api/script_goal.cpp +++ b/src/script/api/script_goal.cpp @@ -52,7 +52,7 @@ EnforcePrecondition(GOAL_INVALID, company == ScriptCompany::COMPANY_INVALID || ScriptCompany::ResolveCompanyID(company) != ScriptCompany::COMPANY_INVALID); EnforcePrecondition(GOAL_INVALID, IsValidGoalDestination(company, type, destination)); - if (!ScriptObject::Command::Do(&ScriptInstance::DoCommandReturnGoalID, ScriptCompany::FromScriptCompanyID(company), (::GoalType)type, destination, text)) return GOAL_INVALID; + if (!ScriptObject::Command::Do(&ScriptInstance::DoCommandReturnGoalID, ScriptCompany::FromScriptCompanyID(company), static_cast<::GoalType>(type), destination, text)) return GOAL_INVALID; /* In case of test-mode, we return GoalID 0 */ return GoalID::Begin(); @@ -73,7 +73,7 @@ const Goal *g = Goal::Get(goal_id); EnforcePrecondition(false, IsValidGoalDestination(ScriptCompany::ToScriptCompanyID(g->company), type, destination)); - return ScriptObject::Command::Do(goal_id, (::GoalType)type, destination); + return ScriptObject::Command::Do(goal_id, static_cast<::GoalType>(type), destination); } /* static */ bool ScriptGoal::SetText(GoalID goal_id, Text *goal) @@ -130,7 +130,7 @@ EnforcePrecondition(false, (int)type < ::GQT_END); EnforcePrecondition(false, uniqueid >= 0 && uniqueid <= UINT16_MAX); - return ScriptObject::Command::Do(uniqueid, target, is_client, buttons, (::GoalQuestionType)type, text); + return ScriptObject::Command::Do(uniqueid, target, is_client, buttons, static_cast<::GoalQuestionType>(type), text); } /* static */ bool ScriptGoal::Question(SQInteger uniqueid, ScriptCompany::CompanyID company, Text *question, QuestionType type, SQInteger buttons) diff --git a/src/script/api/script_group.cpp b/src/script/api/script_group.cpp index a636316e30..a1b440e05a 100644 --- a/src/script/api/script_group.cpp +++ b/src/script/api/script_group.cpp @@ -33,7 +33,7 @@ /* static */ GroupID ScriptGroup::CreateGroup(ScriptVehicle::VehicleType vehicle_type, GroupID parent_group_id) { EnforceCompanyModeValid(GROUP_INVALID); - if (!ScriptObject::Command::Do(&ScriptInstance::DoCommandReturnGroupID, (::VehicleType)vehicle_type, parent_group_id)) return GROUP_INVALID; + if (!ScriptObject::Command::Do(&ScriptInstance::DoCommandReturnGroupID, static_cast<::VehicleType>(vehicle_type), parent_group_id)) return GROUP_INVALID; /* In case of test-mode, we return GroupID 0 */ return GroupID::Begin(); @@ -51,7 +51,7 @@ { if (!IsValidGroup(group_id)) return ScriptVehicle::VT_INVALID; - return (ScriptVehicle::VehicleType)((::VehicleType)::Group::Get(group_id)->vehicle_type); + return static_cast(::Group::Get(group_id)->vehicle_type); } /* static */ bool ScriptGroup::SetName(GroupID group_id, Text *name) @@ -125,7 +125,7 @@ if (!valid_group && group_id != GROUP_DEFAULT && group_id != GROUP_ALL) return -1; if (!valid_group && (vehicle_type < ScriptVehicle::VT_RAIL || vehicle_type > ScriptVehicle::VT_AIR)) return -1; - return GetGroupNumVehicle(ScriptObject::GetCompany(), group_id, valid_group ? ::Group::Get(group_id)->vehicle_type : (::VehicleType)vehicle_type); + return GetGroupNumVehicle(ScriptObject::GetCompany(), group_id, valid_group ? ::Group::Get(group_id)->vehicle_type : static_cast<::VehicleType>(vehicle_type)); } /* static */ bool ScriptGroup::MoveVehicle(GroupID group_id, VehicleID vehicle_id) @@ -224,7 +224,7 @@ EnforceCompanyModeValid(false); EnforcePrecondition(false, IsValidGroup(group_id)); - return ScriptObject::Command::Do(group_id, true, (::Colours)colour); + return ScriptObject::Command::Do(group_id, true, static_cast<::Colours>(colour)); } /* static */ bool ScriptGroup::SetSecondaryColour(GroupID group_id, ScriptCompany::Colours colour) @@ -232,7 +232,7 @@ EnforceCompanyModeValid(false); EnforcePrecondition(false, IsValidGroup(group_id)); - return ScriptObject::Command::Do(group_id, false, (::Colours)colour); + return ScriptObject::Command::Do(group_id, false, static_cast<::Colours>(colour)); } /* static */ ScriptCompany::Colours ScriptGroup::GetPrimaryColour(GroupID group_id) @@ -241,7 +241,7 @@ const Group *g = ::Group::Get(group_id); if (!HasBit(g->livery.in_use, 0)) return ScriptCompany::Colours::COLOUR_INVALID; - return (ScriptCompany::Colours)g->livery.colour1; + return static_cast(g->livery.colour1); } /* static */ ScriptCompany::Colours ScriptGroup::GetSecondaryColour(GroupID group_id) @@ -250,5 +250,5 @@ const Group *g = ::Group::Get(group_id); if (!HasBit(g->livery.in_use, 1)) return ScriptCompany::Colours::COLOUR_INVALID; - return (ScriptCompany::Colours)g->livery.colour2; + return static_cast(g->livery.colour2); } diff --git a/src/script/api/script_industry.cpp b/src/script/api/script_industry.cpp index 74945bceba..593897b901 100644 --- a/src/script/api/script_industry.cpp +++ b/src/script/api/script_industry.cpp @@ -52,7 +52,7 @@ { const Industry *i = Industry::GetIfValid(industry_id); if (i == nullptr) return ScriptDate::DATE_INVALID; - return (ScriptDate::Date)i->construction_date.base(); + return static_cast(i->construction_date.base()); } /* static */ bool ScriptIndustry::SetText(IndustryID industry_id, Text *text) @@ -232,11 +232,11 @@ if (!::IsValidCargoType(cargo_type)) { auto it = std::max_element(std::begin(i->accepted), std::end(i->accepted), [](const auto &a, const auto &b) { return a.last_accepted < b.last_accepted; }); - return (ScriptDate::Date)it->last_accepted.base(); + return static_cast(it->last_accepted.base()); } else { auto it = i->GetCargoAccepted(cargo_type); if (it == std::end(i->accepted)) return ScriptDate::DATE_INVALID; - return (ScriptDate::Date)it->last_accepted.base(); + return static_cast(it->last_accepted.base()); } } @@ -271,7 +271,7 @@ EnforcePrecondition(false, IsValidIndustry(industry_id)); auto company = ScriptCompany::ResolveCompanyID(company_id); - ::Owner owner = (company == ScriptCompany::COMPANY_INVALID ? ::INVALID_OWNER : (::Owner)company); + ::Owner owner = (company == ScriptCompany::COMPANY_INVALID ? ::INVALID_OWNER : ::Owner(company)); return ScriptObject::Command::Do(industry_id, owner, false); } @@ -291,7 +291,7 @@ EnforcePrecondition(false, IsValidIndustry(industry_id)); auto company = ScriptCompany::ResolveCompanyID(company_id); - ::Owner owner = (company == ScriptCompany::COMPANY_INVALID ? ::INVALID_OWNER : (::Owner)company); + ::Owner owner = (company == ScriptCompany::COMPANY_INVALID ? ::INVALID_OWNER : ::Owner(company)); return ScriptObject::Command::Do(industry_id, owner, true); } diff --git a/src/script/api/script_industrytype.cpp b/src/script/api/script_industrytype.cpp index 5806a9f522..69f27e43a3 100644 --- a/src/script/api/script_industrytype.cpp +++ b/src/script/api/script_industrytype.cpp @@ -124,7 +124,7 @@ EnforcePrecondition(false, ScriptMap::IsValidTile(tile)); uint32_t seed = ScriptBase::Rand(); - uint32_t layout_index = ScriptBase::RandRange((uint32_t)::GetIndustrySpec(industry_type)->layouts.size()); + uint32_t layout_index = ScriptBase::RandRange(static_cast(::GetIndustrySpec(industry_type)->layouts.size())); return ScriptObject::Command::Do(tile, industry_type, layout_index, true, seed); } diff --git a/src/script/api/script_infrastructure.cpp b/src/script/api/script_infrastructure.cpp index 523caebe21..84177ef9a1 100644 --- a/src/script/api/script_infrastructure.cpp +++ b/src/script/api/script_infrastructure.cpp @@ -21,7 +21,7 @@ /* static */ SQInteger ScriptInfrastructure::GetRailPieceCount(ScriptCompany::CompanyID company, ScriptRail::RailType railtype) { company = ScriptCompany::ResolveCompanyID(company); - if (company == ScriptCompany::COMPANY_INVALID || (::RailType)railtype >= RAILTYPE_END) return 0; + if (company == ScriptCompany::COMPANY_INVALID || static_cast<::RailType>(railtype) >= RAILTYPE_END) return 0; return ::Company::Get(ScriptCompany::FromScriptCompanyID(company))->infrastructure.rail[railtype]; } @@ -29,7 +29,7 @@ /* static */ SQInteger ScriptInfrastructure::GetRoadPieceCount(ScriptCompany::CompanyID company, ScriptRoad::RoadType roadtype) { company = ScriptCompany::ResolveCompanyID(company); - if (company == ScriptCompany::COMPANY_INVALID || (::RoadType)roadtype >= ROADTYPE_END) return 0; + if (company == ScriptCompany::COMPANY_INVALID || static_cast<::RoadType>(roadtype) >= ROADTYPE_END) return 0; return ::Company::Get(ScriptCompany::FromScriptCompanyID(company))->infrastructure.road[roadtype]; } @@ -67,19 +67,19 @@ /* static */ Money ScriptInfrastructure::GetMonthlyRailCosts(ScriptCompany::CompanyID company, ScriptRail::RailType railtype) { company = ScriptCompany::ResolveCompanyID(company); - if (company == ScriptCompany::COMPANY_INVALID || (::RailType)railtype >= RAILTYPE_END || !_settings_game.economy.infrastructure_maintenance) return 0; + if (company == ScriptCompany::COMPANY_INVALID || static_cast<::RailType>(railtype) >= RAILTYPE_END || !_settings_game.economy.infrastructure_maintenance) return 0; const ::Company *c = ::Company::Get(ScriptCompany::FromScriptCompanyID(company)); - return ::RailMaintenanceCost((::RailType)railtype, c->infrastructure.rail[railtype], c->infrastructure.GetRailTotal()); + return ::RailMaintenanceCost(static_cast<::RailType>(railtype), c->infrastructure.rail[railtype], c->infrastructure.GetRailTotal()); } /* static */ Money ScriptInfrastructure::GetMonthlyRoadCosts(ScriptCompany::CompanyID company, ScriptRoad::RoadType roadtype) { company = ScriptCompany::ResolveCompanyID(company); - if (company == ScriptCompany::COMPANY_INVALID || (::RoadType)roadtype >= ROADTYPE_END || !_settings_game.economy.infrastructure_maintenance) return 0; + if (company == ScriptCompany::COMPANY_INVALID || static_cast<::RoadType>(roadtype) >= ROADTYPE_END || !_settings_game.economy.infrastructure_maintenance) return 0; const ::Company *c = ::Company::Get(ScriptCompany::FromScriptCompanyID(company)); - return ::RoadMaintenanceCost((::RoadType)roadtype, c->infrastructure.road[roadtype], RoadTypeIsRoad((::RoadType)roadtype) ? c->infrastructure.GetRoadTotal() : c->infrastructure.GetTramTotal()); + return ::RoadMaintenanceCost(static_cast<::RoadType>(roadtype), c->infrastructure.road[roadtype], RoadTypeIsRoad(static_cast<::RoadType>(roadtype)) ? c->infrastructure.GetRoadTotal() : c->infrastructure.GetTramTotal()); } /* static */ Money ScriptInfrastructure::GetMonthlyInfrastructureCosts(ScriptCompany::CompanyID company, Infrastructure infra_type) diff --git a/src/script/api/script_league.cpp b/src/script/api/script_league.cpp index 33d74e45e8..cf4ca58a53 100644 --- a/src/script/api/script_league.cpp +++ b/src/script/api/script_league.cpp @@ -71,7 +71,7 @@ EnforcePrecondition(LEAGUE_TABLE_ELEMENT_INVALID, IsValidLink(Link((::LinkType)link_type, link_target))); - if (!ScriptObject::Command::Do(&ScriptInstance::DoCommandReturnLeagueTableElementID, table, rating, c, encoded_text, encoded_score, (::LinkType)link_type, (::LinkTargetID)link_target)) return LEAGUE_TABLE_ELEMENT_INVALID; + if (!ScriptObject::Command::Do(&ScriptInstance::DoCommandReturnLeagueTableElementID, table, rating, c, encoded_text, encoded_score, static_cast<::LinkType>(link_type), static_cast<::LinkTargetID>(link_target))) return LEAGUE_TABLE_ELEMENT_INVALID; /* In case of test-mode, we return LeagueTableElementID 0 */ return LeagueTableElementID::Begin(); @@ -93,7 +93,7 @@ EnforcePrecondition(false, IsValidLink(Link((::LinkType)link_type, link_target))); - return ScriptObject::Command::Do(element, c, encoded_text, (::LinkType)link_type, (::LinkTargetID)link_target); + return ScriptObject::Command::Do(element, c, encoded_text, static_cast<::LinkType>(link_type), static_cast<::LinkTargetID>(link_target)); } /* static */ bool ScriptLeagueTable::UpdateElementScore(LeagueTableElementID element, SQInteger rating, Text *score) diff --git a/src/script/api/script_news.cpp b/src/script/api/script_news.cpp index ae4daa9f01..e52c008f9e 100644 --- a/src/script/api/script_news.cpp +++ b/src/script/api/script_news.cpp @@ -50,5 +50,5 @@ static NewsReference CreateReference(ScriptNews::NewsReferenceType ref_type, SQI ::CompanyID c = ScriptCompany::FromScriptCompanyID(company); - return ScriptObject::Command::Do((::NewsType)type, c, CreateReference(ref_type, reference), encoded); + return ScriptObject::Command::Do(static_cast<::NewsType>(type), c, CreateReference(ref_type, reference), encoded); } diff --git a/src/script/api/script_object.cpp b/src/script/api/script_object.cpp index a7caf017b9..9bf12fe2fc 100644 --- a/src/script/api/script_object.cpp +++ b/src/script/api/script_object.cpp @@ -322,12 +322,12 @@ bool ScriptObject::DoCommandProcessResult(const CommandCost &res, Script_Suspend /* Insert return value into to stack and throw a control code that * the return value in the stack should be used. */ callback(GetActiveInstance()); - throw SQInteger(1); + throw static_cast(1); } return true; } else if (_networking) { /* Suspend the script till the command is really executed. */ - throw Script_Suspend(-(int)GetDoCommandDelay(), callback); + throw Script_Suspend(-static_cast(GetDoCommandDelay()), callback); } else { IncreaseDoCommandCosts(res.GetCost()); diff --git a/src/script/api/script_order.cpp b/src/script/api/script_order.cpp index e37ed9d1b3..b64eab2753 100644 --- a/src/script/api/script_order.cpp +++ b/src/script/api/script_order.cpp @@ -71,7 +71,7 @@ static const Order *ResolveOrder(VehicleID vehicle_id, ScriptOrder::OrderPositio assert(order != nullptr); while (order->GetType() == OT_IMPLICIT) order = order->next; while (order_position > 0) { - order_position = (ScriptOrder::OrderPosition)(order_position - 1); + order_position = static_cast(order_position - 1); order = order->next; while (order->GetType() == OT_IMPLICIT) order = order->next; } @@ -91,12 +91,12 @@ static int ScriptOrderPositionToRealOrderPosition(VehicleID vehicle_id, ScriptOr assert(ScriptOrder::IsValidVehicleOrder(vehicle_id, order_position)); - int res = (int)order_position; + int res = static_cast(order_position); const Order *order = v->orders->GetFirstOrder(); assert(order != nullptr); for (; order->GetType() == OT_IMPLICIT; order = order->next) res++; while (order_position > 0) { - order_position = (ScriptOrder::OrderPosition)(order_position - 1); + order_position = static_cast(order_position - 1); order = order->next; for (; order->GetType() == OT_IMPLICIT; order = order->next) res++; } @@ -313,7 +313,7 @@ static ScriptOrder::OrderPosition RealOrderPositionToScriptOrderPosition(Vehicle if (order == nullptr || order->GetType() == OT_CONDITIONAL || order->GetType() == OT_DUMMY) return OF_INVALID; ScriptOrderFlags order_flags = OF_NONE; - order_flags |= (ScriptOrderFlags)order->GetNonStopType(); + order_flags |= static_cast(order->GetNonStopType()); switch (order->GetType()) { case OT_GOTO_DEPOT: if (order->GetDepotOrderType() & ODTFB_SERVICE) order_flags |= OF_SERVICE_IF_NEEDED; @@ -322,8 +322,8 @@ static ScriptOrder::OrderPosition RealOrderPositionToScriptOrderPosition(Vehicle break; case OT_GOTO_STATION: - order_flags |= (ScriptOrderFlags)(order->GetLoadType() << 5); - order_flags |= (ScriptOrderFlags)(order->GetUnloadType() << 2); + order_flags |= static_cast(order->GetLoadType() << 5); + order_flags |= static_cast(order->GetUnloadType() << 2); break; default: break; @@ -347,7 +347,7 @@ static ScriptOrder::OrderPosition RealOrderPositionToScriptOrderPosition(Vehicle if (order_position == ORDER_CURRENT || !IsConditionalOrder(vehicle_id, order_position)) return OC_INVALID; const Order *order = ::ResolveOrder(vehicle_id, order_position); - return (OrderCondition)order->GetConditionVariable(); + return static_cast(order->GetConditionVariable()); } /* static */ ScriptOrder::CompareFunction ScriptOrder::GetOrderCompareFunction(VehicleID vehicle_id, OrderPosition order_position) @@ -356,7 +356,7 @@ static ScriptOrder::OrderPosition RealOrderPositionToScriptOrderPosition(Vehicle if (order_position == ORDER_CURRENT || !IsConditionalOrder(vehicle_id, order_position)) return CF_INVALID; const Order *order = ::ResolveOrder(vehicle_id, order_position); - return (CompareFunction)order->GetConditionComparator(); + return static_cast(order->GetConditionComparator()); } /* static */ SQInteger ScriptOrder::GetOrderCompareValue(VehicleID vehicle_id, OrderPosition order_position) @@ -377,7 +377,7 @@ static ScriptOrder::OrderPosition RealOrderPositionToScriptOrderPosition(Vehicle if (!IsGotoStationOrder(vehicle_id, order_position)) return STOPLOCATION_INVALID; const Order *order = ::ResolveOrder(vehicle_id, order_position); - return (ScriptOrder::StopLocation)order->GetStopLocation(); + return static_cast(order->GetStopLocation()); } /* static */ CargoType ScriptOrder::GetOrderRefit(VehicleID vehicle_id, OrderPosition order_position) @@ -465,7 +465,7 @@ static ScriptOrder::OrderPosition RealOrderPositionToScriptOrderPosition(Vehicle EnforcePrecondition(false, ScriptVehicle::IsPrimaryVehicle(vehicle_id)); EnforcePrecondition(false, AreOrderFlagsValid(destination, order_flags)); - return InsertOrder(vehicle_id, (ScriptOrder::OrderPosition)::Vehicle::Get(vehicle_id)->GetNumManualOrders(), destination, order_flags); + return InsertOrder(vehicle_id, static_cast(::Vehicle::Get(vehicle_id)->GetNumManualOrders()), destination, order_flags); } /* static */ bool ScriptOrder::AppendConditionalOrder(VehicleID vehicle_id, OrderPosition jump_to) @@ -474,7 +474,7 @@ static ScriptOrder::OrderPosition RealOrderPositionToScriptOrderPosition(Vehicle EnforcePrecondition(false, ScriptVehicle::IsPrimaryVehicle(vehicle_id)); EnforcePrecondition(false, IsValidVehicleOrder(vehicle_id, jump_to)); - return InsertConditionalOrder(vehicle_id, (ScriptOrder::OrderPosition)::Vehicle::Get(vehicle_id)->GetNumManualOrders(), jump_to); + return InsertConditionalOrder(vehicle_id, static_cast(::Vehicle::Get(vehicle_id)->GetNumManualOrders()), jump_to); } /* static */ bool ScriptOrder::InsertOrder(VehicleID vehicle_id, OrderPosition order_position, TileIndex destination, ScriptOrder::ScriptOrderFlags order_flags) @@ -491,10 +491,10 @@ static ScriptOrder::OrderPosition RealOrderPositionToScriptOrderPosition(Vehicle OrderType ot = (order_flags & OF_GOTO_NEAREST_DEPOT) ? OT_GOTO_DEPOT : ::GetOrderTypeByTile(destination); switch (ot) { case OT_GOTO_DEPOT: { - OrderDepotTypeFlags odtf = (OrderDepotTypeFlags)(ODTFB_PART_OF_ORDERS | ((order_flags & OF_SERVICE_IF_NEEDED) ? ODTFB_SERVICE : 0)); - OrderDepotActionFlags odaf = (OrderDepotActionFlags)(ODATF_SERVICE_ONLY | ((order_flags & OF_STOP_IN_DEPOT) ? ODATFB_HALT : 0)); + OrderDepotTypeFlags odtf = static_cast(ODTFB_PART_OF_ORDERS | ((order_flags & OF_SERVICE_IF_NEEDED) ? ODTFB_SERVICE : 0)); + OrderDepotActionFlags odaf = static_cast(ODATF_SERVICE_ONLY | ((order_flags & OF_STOP_IN_DEPOT) ? ODATFB_HALT : 0)); if (order_flags & OF_GOTO_NEAREST_DEPOT) odaf |= ODATFB_NEAREST_DEPOT; - OrderNonStopFlags onsf = (OrderNonStopFlags)((order_flags & OF_NON_STOP_INTERMEDIATE) ? ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS : ONSF_STOP_EVERYWHERE); + OrderNonStopFlags onsf = ((order_flags & OF_NON_STOP_INTERMEDIATE) ? ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS : ONSF_STOP_EVERYWHERE); if (order_flags & OF_GOTO_NEAREST_DEPOT) { order.MakeGoToDepot(DepotID::Invalid(), odtf, onsf, odaf); } else { @@ -513,8 +513,8 @@ static ScriptOrder::OrderPosition RealOrderPositionToScriptOrderPosition(Vehicle case OT_GOTO_STATION: order.MakeGoToStation(::GetStationIndex(destination)); - order.SetLoadType((OrderLoadFlags)GB(order_flags, 5, 3)); - order.SetUnloadType((OrderUnloadFlags)GB(order_flags, 2, 3)); + order.SetLoadType(static_cast(GB(order_flags, 5, 3))); + order.SetUnloadType(static_cast(GB(order_flags, 2, 3))); order.SetStopLocation(OSL_PLATFORM_FAR_END); break; @@ -526,7 +526,7 @@ static ScriptOrder::OrderPosition RealOrderPositionToScriptOrderPosition(Vehicle return false; } - order.SetNonStopType((OrderNonStopFlags)GB(order_flags, 0, 2)); + order.SetNonStopType(static_cast(GB(order_flags, 0, 2))); int order_pos = ScriptOrderPositionToRealOrderPosition(vehicle_id, order_position); return ScriptObject::Command::Do(0, vehicle_id, order_pos, order); @@ -596,9 +596,9 @@ static void _DoCommandReturnSetOrderFlags(class ScriptInstance *instance) } ScriptObject::SetCallbackVariable(3, retry); - VehicleID vehicle_id = (VehicleID)ScriptObject::GetCallbackVariable(0); - OrderPosition order_position = (OrderPosition)ScriptObject::GetCallbackVariable(1); - ScriptOrderFlags order_flags = (ScriptOrderFlags)ScriptObject::GetCallbackVariable(2); + VehicleID vehicle_id = VehicleID(ScriptObject::GetCallbackVariable(0)); + OrderPosition order_position = static_cast(ScriptObject::GetCallbackVariable(1)); + ScriptOrderFlags order_flags = static_cast(ScriptObject::GetCallbackVariable(2)); order_position = ScriptOrder::ResolveOrderPosition(vehicle_id, order_position); diff --git a/src/script/api/script_priorityqueue.cpp b/src/script/api/script_priorityqueue.cpp index c9cdc82862..cf977d6a9a 100644 --- a/src/script/api/script_priorityqueue.cpp +++ b/src/script/api/script_priorityqueue.cpp @@ -102,5 +102,5 @@ bool ScriptPriorityQueue::IsEmpty() SQInteger ScriptPriorityQueue::Count() { - return (SQInteger)this->queue.size(); + return static_cast(this->queue.size()); } diff --git a/src/script/api/script_rail.cpp b/src/script/api/script_rail.cpp index bfab381d05..ef9c7fc005 100644 --- a/src/script/api/script_rail.cpp +++ b/src/script/api/script_rail.cpp @@ -28,7 +28,7 @@ { if (!IsRailTypeAvailable(rail_type)) return std::nullopt; - return ::StrMakeValid(::GetString(GetRailTypeInfo((::RailType)rail_type)->strings.menu_text)); + return ::StrMakeValid(::GetString(GetRailTypeInfo(static_cast<::RailType>(rail_type))->strings.menu_text)); } /* static */ bool ScriptRail::IsRailTile(TileIndex tile) @@ -70,21 +70,21 @@ /* static */ bool ScriptRail::IsRailTypeAvailable(RailType rail_type) { EnforceDeityOrCompanyModeValid(false); - if ((::RailType)rail_type >= RAILTYPE_END) return false; + if (static_cast<::RailType>(rail_type) >= RAILTYPE_END) return false; - return ScriptCompanyMode::IsDeity() || ::HasRailTypeAvail(ScriptObject::GetCompany(), (::RailType)rail_type); + return ScriptCompanyMode::IsDeity() || ::HasRailTypeAvail(ScriptObject::GetCompany(), static_cast<::RailType>(rail_type)); } /* static */ ScriptRail::RailType ScriptRail::GetCurrentRailType() { - return (RailType)ScriptObject::GetRailType(); + return static_cast(ScriptObject::GetRailType()); } /* static */ void ScriptRail::SetCurrentRailType(RailType rail_type) { if (!IsRailTypeAvailable(rail_type)) return; - ScriptObject::SetRailType((::RailType)rail_type); + ScriptObject::SetRailType(static_cast<::RailType>(rail_type)); } /* static */ bool ScriptRail::TrainCanRunOnRail(ScriptRail::RailType engine_rail_type, ScriptRail::RailType track_rail_type) @@ -92,7 +92,7 @@ if (!ScriptRail::IsRailTypeAvailable(engine_rail_type)) return false; if (!ScriptRail::IsRailTypeAvailable(track_rail_type)) return false; - return ::IsCompatibleRail((::RailType)engine_rail_type, (::RailType)track_rail_type); + return ::IsCompatibleRail(static_cast<::RailType>(engine_rail_type), static_cast<::RailType>(track_rail_type)); } /* static */ bool ScriptRail::TrainHasPowerOnRail(ScriptRail::RailType engine_rail_type, ScriptRail::RailType track_rail_type) @@ -100,14 +100,14 @@ if (!ScriptRail::IsRailTypeAvailable(engine_rail_type)) return false; if (!ScriptRail::IsRailTypeAvailable(track_rail_type)) return false; - return ::HasPowerOnRail((::RailType)engine_rail_type, (::RailType)track_rail_type); + return ::HasPowerOnRail(static_cast<::RailType>(engine_rail_type), static_cast<::RailType>(track_rail_type)); } /* static */ ScriptRail::RailType ScriptRail::GetRailType(TileIndex tile) { if (!ScriptTile::HasTransportType(tile, ScriptTile::TRANSPORT_RAIL)) return RAILTYPE_INVALID; - return (RailType)::GetRailType(tile); + return static_cast(::GetRailType(tile)); } /* static */ bool ScriptRail::ConvertRailType(TileIndex start_tile, TileIndex end_tile, ScriptRail::RailType convert_to) @@ -117,7 +117,7 @@ EnforcePrecondition(false, ::IsValidTile(end_tile)); EnforcePrecondition(false, IsRailTypeAvailable(convert_to)); - return ScriptObject::Command::Do(start_tile, end_tile, (::RailType)convert_to, false); + return ScriptObject::Command::Do(start_tile, end_tile, static_cast<::RailType>(convert_to), false); } /* static */ TileIndex ScriptRail::GetRailDepotFrontTile(TileIndex depot) @@ -131,7 +131,7 @@ { if (!IsRailStationTile(tile)) return RAILTRACK_INVALID; - return (RailTrack)::GetRailStationTrackBits(tile); + return static_cast(::GetRailStationTrackBits(tile)); } /* static */ bool ScriptRail::BuildRailDepot(TileIndex tile, TileIndex front) @@ -145,7 +145,7 @@ DiagDirection entrance_dir = (::TileX(tile) == ::TileX(front)) ? (::TileY(tile) < ::TileY(front) ? DIAGDIR_SE : DIAGDIR_NW) : (::TileX(tile) < ::TileX(front) ? DIAGDIR_SW : DIAGDIR_NE); - return ScriptObject::Command::Do(tile, (::RailType)ScriptObject::GetRailType(), entrance_dir); + return ScriptObject::Command::Do(tile, ScriptObject::GetRailType(), entrance_dir); } /* static */ bool ScriptRail::BuildRailStation(TileIndex tile, RailTrack direction, SQInteger num_platforms, SQInteger platform_length, StationID station_id) @@ -159,7 +159,7 @@ EnforcePrecondition(false, station_id == ScriptStation::STATION_NEW || station_id == ScriptStation::STATION_JOIN_ADJACENT || ScriptStation::IsValidStation(station_id)); bool adjacent = station_id != ScriptStation::STATION_JOIN_ADJACENT; - return ScriptObject::Command::Do(tile, (::RailType)GetCurrentRailType(), direction == RAILTRACK_NW_SE ? AXIS_Y : AXIS_X, num_platforms, platform_length, STAT_CLASS_DFLT, 0, ScriptStation::IsValidStation(station_id) ? station_id : StationID::Invalid(), adjacent); + return ScriptObject::Command::Do(tile, static_cast<::RailType>(GetCurrentRailType()), direction == RAILTRACK_NW_SE ? AXIS_Y : AXIS_X, num_platforms, platform_length, STAT_CLASS_DFLT, 0, ScriptStation::IsValidStation(station_id) ? station_id : StationID::Invalid(), adjacent); } /* static */ bool ScriptRail::BuildNewGRFRailStation(TileIndex tile, RailTrack direction, SQInteger num_platforms, SQInteger platform_length, StationID station_id, CargoType cargo_type, IndustryType source_industry, IndustryType goal_industry, SQInteger distance, bool source_station) @@ -198,11 +198,11 @@ Debug(grf, 1, "{} returned an invalid station ID for 'AI construction/purchase selection (18)' callback", file->filename); } else { /* We might have gotten an usable station spec. Try to build it, but if it fails we'll fall back to the original station. */ - if (ScriptObject::Command::Do(tile, (::RailType)GetCurrentRailType(), axis, num_platforms, platform_length, spec->class_index, spec->index, to_join, adjacent)) return true; + if (ScriptObject::Command::Do(tile, static_cast<::RailType>(GetCurrentRailType()), axis, num_platforms, platform_length, spec->class_index, spec->index, to_join, adjacent)) return true; } } - return ScriptObject::Command::Do(tile, (::RailType)GetCurrentRailType(), axis, num_platforms, platform_length, STAT_CLASS_DFLT, 0, to_join, adjacent); + return ScriptObject::Command::Do(tile, static_cast<::RailType>(GetCurrentRailType()), axis, num_platforms, platform_length, STAT_CLASS_DFLT, 0, to_join, adjacent); } /* static */ bool ScriptRail::BuildRailWaypoint(TileIndex tile) @@ -253,7 +253,7 @@ EnforcePrecondition(false, KillFirstBit((uint)rail_track) == 0); EnforcePrecondition(false, IsRailTypeAvailable(GetCurrentRailType())); - return ScriptObject::Command::Do(tile, tile, (::RailType)GetCurrentRailType(), FindFirstTrack((::TrackBits)rail_track), false, false); + return ScriptObject::Command::Do(tile, tile, static_cast<::RailType>(GetCurrentRailType()), FindFirstTrack(static_cast<::TrackBits>(rail_track)), false, false); } /* static */ bool ScriptRail::RemoveRailTrack(TileIndex tile, RailTrack rail_track) @@ -264,7 +264,7 @@ EnforcePrecondition(false, GetRailTracks(tile) & rail_track); EnforcePrecondition(false, KillFirstBit((uint)rail_track) == 0); - return ScriptObject::Command::Do(tile, tile, FindFirstTrack((::TrackBits)rail_track)); + return ScriptObject::Command::Do(tile, tile, FindFirstTrack(static_cast<::TrackBits>(rail_track))); } /* static */ bool ScriptRail::AreTilesConnected(TileIndex from, TileIndex tile, TileIndex to) @@ -276,11 +276,11 @@ if (tile - from == 1) { if (to - tile == 1) return (GetRailTracks(tile) & RAILTRACK_NE_SW) != 0; - if (to - tile == (int)ScriptMap::GetMapSizeX()) return (GetRailTracks(tile) & RAILTRACK_NE_SE) != 0; - } else if (tile - from == (int)ScriptMap::GetMapSizeX()) { + if (to - tile == static_cast(ScriptMap::GetMapSizeX())) return (GetRailTracks(tile) & RAILTRACK_NE_SE) != 0; + } else if (tile - from == static_cast(ScriptMap::GetMapSizeX())) { if (tile - to == 1) return (GetRailTracks(tile) & RAILTRACK_NW_NE) != 0; if (to - tile == 1) return (GetRailTracks(tile) & RAILTRACK_NW_SW) != 0; - if (to - tile == (int)ScriptMap::GetMapSizeX()) return (GetRailTracks(tile) & RAILTRACK_NW_SE) != 0; + if (to - tile == static_cast(ScriptMap::GetMapSizeX())) return (GetRailTracks(tile) & RAILTRACK_NW_SE) != 0; } else { return (GetRailTracks(tile) & RAILTRACK_SW_SE) != 0; } @@ -294,14 +294,14 @@ */ static Track SimulateDrag(TileIndex from, TileIndex tile, TileIndex *to) { - int diag_offset = abs(abs((int)::TileX(*to) - (int)::TileX(tile)) - abs((int)::TileY(*to) - (int)::TileY(tile))); + int diag_offset = abs(abs(static_cast(::TileX(*to)) - static_cast(::TileX(tile))) - abs(static_cast(::TileY(*to)) - static_cast(::TileY(tile)))); Track track = TRACK_BEGIN; if (::TileY(from) == ::TileY(*to)) { track = TRACK_X; - *to -= Clamp((int)::TileX(*to) - (int)::TileX(tile), -1, 1); + *to -= Clamp(static_cast(::TileX(*to)) - static_cast(::TileX(tile)), -1, 1); } else if (::TileX(from) == ::TileX(*to)) { track = TRACK_Y; - *to -= ScriptMap::GetMapSizeX() * Clamp((int)::TileY(*to) - (int)::TileY(tile), -1, 1); + *to -= ScriptMap::GetMapSizeX() * Clamp(static_cast(::TileY(*to)) - static_cast(::TileY(tile)), -1, 1); } else if (::TileY(from) < ::TileY(tile)) { if (::TileX(*to) < ::TileX(tile)) { track = TRACK_UPPER; @@ -309,9 +309,9 @@ static Track SimulateDrag(TileIndex from, TileIndex tile, TileIndex *to) track = TRACK_LEFT; } if (diag_offset != 0) { - *to -= Clamp((int)::TileX(*to) - (int)::TileX(tile), -1, 1); + *to -= Clamp(static_cast(::TileX(*to)) - static_cast(::TileX(tile)), -1, 1); } else { - *to -= ScriptMap::GetMapSizeX() * Clamp((int)::TileY(*to) - (int)::TileY(tile), -1, 1); + *to -= ScriptMap::GetMapSizeX() * Clamp(static_cast(::TileY(*to)) - static_cast(::TileY(tile)), -1, 1); } } else if (::TileY(from) > ::TileY(tile)) { if (::TileX(*to) < ::TileX(tile)) { @@ -320,9 +320,9 @@ static Track SimulateDrag(TileIndex from, TileIndex tile, TileIndex *to) track = TRACK_LOWER; } if (diag_offset != 0) { - *to -= Clamp((int)::TileX(*to) - (int)::TileX(tile), -1, 1); + *to -= Clamp(static_cast(::TileX(*to)) - static_cast(::TileX(tile)), -1, 1); } else { - *to -= ScriptMap::GetMapSizeX() * Clamp((int)::TileY(*to) - (int)::TileY(tile), -1, 1); + *to -= ScriptMap::GetMapSizeX() * Clamp(static_cast(::TileY(*to)) - static_cast(::TileY(tile)), -1, 1); } } else if (::TileX(from) < ::TileX(tile)) { if (::TileY(*to) < ::TileY(tile)) { @@ -331,9 +331,9 @@ static Track SimulateDrag(TileIndex from, TileIndex tile, TileIndex *to) track = TRACK_RIGHT; } if (diag_offset == 0) { - *to -= Clamp((int)::TileX(*to) - (int)::TileX(tile), -1, 1); + *to -= Clamp(static_cast(::TileX(*to)) - static_cast(::TileX(tile)), -1, 1); } else { - *to -= ScriptMap::GetMapSizeX() * Clamp((int)::TileY(*to) - (int)::TileY(tile), -1, 1); + *to -= ScriptMap::GetMapSizeX() * Clamp(static_cast(::TileY(*to)) - static_cast(::TileY(tile)), -1, 1); } } else if (::TileX(from) > ::TileX(tile)) { if (::TileY(*to) < ::TileY(tile)) { @@ -342,9 +342,9 @@ static Track SimulateDrag(TileIndex from, TileIndex tile, TileIndex *to) track = TRACK_LOWER; } if (diag_offset == 0) { - *to -= Clamp((int)::TileX(*to) - (int)::TileX(tile), -1, 1); + *to -= Clamp(static_cast(::TileX(*to)) - static_cast(::TileX(tile)), -1, 1); } else { - *to -= ScriptMap::GetMapSizeX() * Clamp((int)::TileY(*to) - (int)::TileY(tile), -1, 1); + *to -= ScriptMap::GetMapSizeX() * Clamp(static_cast(::TileY(*to)) - static_cast(::TileY(tile)), -1, 1); } } return track; @@ -359,13 +359,13 @@ static Track SimulateDrag(TileIndex from, TileIndex tile, TileIndex *to) EnforcePrecondition(false, ::DistanceManhattan(from, tile) == 1); EnforcePrecondition(false, ::DistanceManhattan(tile, to) >= 1); EnforcePrecondition(false, IsRailTypeAvailable(GetCurrentRailType())); - int diag_offset = abs(abs((int)::TileX(to) - (int)::TileX(tile)) - abs((int)::TileY(to) - (int)::TileY(tile))); + int diag_offset = abs(abs(static_cast(::TileX(to)) - static_cast(::TileX(tile))) - abs(static_cast(::TileY(to)) - static_cast(::TileY(tile)))); EnforcePrecondition(false, diag_offset <= 1 || (::TileX(from) == ::TileX(tile) && ::TileX(tile) == ::TileX(to)) || (::TileY(from) == ::TileY(tile) && ::TileY(tile) == ::TileY(to))); Track track = SimulateDrag(from, tile, &to); - return ScriptObject::Command::Do(to, tile, (::RailType)ScriptRail::GetCurrentRailType(), track, false, true); + return ScriptObject::Command::Do(to, tile, static_cast<::RailType>(ScriptRail::GetCurrentRailType()), track, false, true); } /* static */ bool ScriptRail::RemoveRail(TileIndex from, TileIndex tile, TileIndex to) @@ -376,7 +376,7 @@ static Track SimulateDrag(TileIndex from, TileIndex tile, TileIndex *to) EnforcePrecondition(false, ::IsValidTile(to)); EnforcePrecondition(false, ::DistanceManhattan(from, tile) == 1); EnforcePrecondition(false, ::DistanceManhattan(tile, to) >= 1); - int diag_offset = abs(abs((int)::TileX(to) - (int)::TileX(tile)) - abs((int)::TileY(to) - (int)::TileY(tile))); + int diag_offset = abs(abs(static_cast(::TileX(to)) - static_cast(::TileX(tile))) - abs(static_cast(::TileY(to)) - static_cast(::TileY(tile)))); EnforcePrecondition(false, diag_offset <= 1 || (::TileX(from) == ::TileX(tile) && ::TileX(tile) == ::TileX(to)) || (::TileY(from) == ::TileY(tile) && ::TileY(tile) == ::TileY(to))); @@ -423,8 +423,8 @@ static const ScriptRailSignalData _possible_trackdirs[5][NUM_TRACK_DIRECTIONS] = if (!(::TrackToTrackBits(track) & GetRailTracks(tile))) continue; if (!HasSignalOnTrack(tile, track)) continue; if (!HasSignalOnTrackdir(tile, _possible_trackdirs[data_index][i].trackdir)) continue; - SignalType st = (SignalType)::GetSignalType(tile, track); - if (HasSignalOnTrackdir(tile, ::ReverseTrackdir(_possible_trackdirs[data_index][i].trackdir))) st = (SignalType)(st | SIGNALTYPE_TWOWAY); + SignalType st = static_cast(::GetSignalType(tile, track)); + if (HasSignalOnTrackdir(tile, ::ReverseTrackdir(_possible_trackdirs[data_index][i].trackdir))) st = static_cast(st | SIGNALTYPE_TWOWAY); return st; } @@ -466,7 +466,7 @@ static bool IsValidSignalType(int signal_type) } else { signal_cycles = 0; } - ::SignalType sig_type = (::SignalType)(signal >= SIGNALTYPE_TWOWAY ? signal ^ SIGNALTYPE_TWOWAY : signal); + ::SignalType sig_type = static_cast<::SignalType>(signal >= SIGNALTYPE_TWOWAY ? signal ^ SIGNALTYPE_TWOWAY : signal); return ScriptObject::Command::Do(tile, track, sig_type, ::SIG_ELECTRIC, false, false, false, ::SIGTYPE_BLOCK, ::SIGTYPE_BLOCK, signal_cycles, 0); } @@ -495,7 +495,7 @@ static bool IsValidSignalType(int signal_type) if (!ScriptRail::IsRailTypeAvailable(railtype)) return -1; switch (build_type) { - case BT_TRACK: return ::RailBuildCost((::RailType)railtype); + case BT_TRACK: return ::RailBuildCost(static_cast<::RailType>(railtype)); case BT_SIGNAL: return ::GetPrice(PR_BUILD_SIGNALS, 1, nullptr); case BT_DEPOT: return ::GetPrice(PR_BUILD_DEPOT_TRAIN, 1, nullptr); case BT_STATION: return ::GetPrice(PR_BUILD_STATION_RAIL, 1, nullptr) + ::GetPrice(PR_BUILD_STATION_RAIL_LENGTH, 1, nullptr); @@ -508,12 +508,12 @@ static bool IsValidSignalType(int signal_type) { if (!ScriptRail::IsRailTypeAvailable(railtype)) return -1; - return ::GetRailTypeInfo((::RailType)railtype)->max_speed; + return ::GetRailTypeInfo(static_cast<::RailType>(railtype))->max_speed; } /* static */ SQInteger ScriptRail::GetMaintenanceCostFactor(RailType railtype) { if (!ScriptRail::IsRailTypeAvailable(railtype)) return 0; - return ::GetRailTypeInfo((::RailType)railtype)->maintenance_multiplier; + return ::GetRailTypeInfo(static_cast<::RailType>(railtype))->maintenance_multiplier; } diff --git a/src/script/api/script_road.cpp b/src/script/api/script_road.cpp index c3bbef224c..12f58e552b 100644 --- a/src/script/api/script_road.cpp +++ b/src/script/api/script_road.cpp @@ -30,7 +30,7 @@ { if (!IsRoadTypeAvailable(road_type)) return std::nullopt; - return ::StrMakeValid(::GetString(GetRoadTypeInfo((::RoadType)road_type)->strings.name)); + return ::StrMakeValid(::GetString(GetRoadTypeInfo(static_cast<::RoadType>(road_type))->strings.name)); } /* static */ bool ScriptRoad::IsRoadTile(TileIndex tile) @@ -47,7 +47,7 @@ if (!IsRoadTypeAvailable(GetCurrentRoadType())) return false; return ::IsTileType(tile, MP_ROAD) && ::GetRoadTileType(tile) == ROAD_TILE_DEPOT && - HasBit(::GetPresentRoadTypes(tile), (::RoadType)GetCurrentRoadType()); + HasBit(::GetPresentRoadTypes(tile), static_cast<::RoadType>(GetCurrentRoadType())); } /* static */ bool ScriptRoad::IsRoadStationTile(TileIndex tile) @@ -55,7 +55,7 @@ if (!::IsValidTile(tile)) return false; if (!IsRoadTypeAvailable(GetCurrentRoadType())) return false; - return ::IsStationRoadStopTile(tile) && HasBit(::GetPresentRoadTypes(tile), (::RoadType)GetCurrentRoadType()); + return ::IsStationRoadStopTile(tile) && HasBit(::GetPresentRoadTypes(tile), static_cast<::RoadType>(GetCurrentRoadType())); } /* static */ bool ScriptRoad::IsDriveThroughRoadStationTile(TileIndex tile) @@ -63,25 +63,25 @@ if (!::IsValidTile(tile)) return false; if (!IsRoadTypeAvailable(GetCurrentRoadType())) return false; - return ::IsDriveThroughStopTile(tile) && HasBit(::GetPresentRoadTypes(tile), (::RoadType)GetCurrentRoadType()); + return ::IsDriveThroughStopTile(tile) && HasBit(::GetPresentRoadTypes(tile), static_cast<::RoadType>(GetCurrentRoadType())); } /* static */ bool ScriptRoad::IsRoadTypeAvailable(RoadType road_type) { EnforceDeityOrCompanyModeValid(false); - return (::RoadType)road_type < ROADTYPE_END && ::HasRoadTypeAvail(ScriptObject::GetCompany(), (::RoadType)road_type); + return static_cast<::RoadType>(road_type) < ROADTYPE_END && ::HasRoadTypeAvail(ScriptObject::GetCompany(), static_cast<::RoadType>(road_type)); } /* static */ ScriptRoad::RoadType ScriptRoad::GetCurrentRoadType() { - return (RoadType)ScriptObject::GetRoadType(); + return static_cast(ScriptObject::GetRoadType()); } /* static */ void ScriptRoad::SetCurrentRoadType(RoadType road_type) { if (!IsRoadTypeAvailable(road_type)) return; - ScriptObject::SetRoadType((::RoadType)road_type); + ScriptObject::SetRoadType(static_cast<::RoadType>(road_type)); } /* static */ bool ScriptRoad::RoadVehCanRunOnRoad(RoadType engine_road_type, RoadType road_road_type) @@ -94,14 +94,14 @@ if (!IsRoadTypeAvailable(engine_road_type)) return false; if (!IsRoadTypeAvailable(road_road_type)) return false; - return ::HasPowerOnRoad((::RoadType)engine_road_type, (::RoadType)road_road_type); + return ::HasPowerOnRoad(static_cast<::RoadType>(engine_road_type), static_cast<::RoadType>(road_road_type)); } /* static */ bool ScriptRoad::HasRoadType(TileIndex tile, RoadType road_type) { if (!ScriptMap::IsValidTile(tile)) return false; if (!IsRoadTypeAvailable(road_type)) return false; - return ::MayHaveRoad(tile) && HasBit(::GetPresentRoadTypes(tile), (::RoadType)road_type); + return ::MayHaveRoad(tile) && HasBit(::GetPresentRoadTypes(tile), static_cast<::RoadType>(road_type)); } /* static */ bool ScriptRoad::AreRoadTilesConnected(TileIndex t1, TileIndex t2) @@ -111,7 +111,7 @@ if (!IsRoadTypeAvailable(GetCurrentRoadType())) return false; /* Tiles not neighbouring */ - if ((abs((int)::TileX(t1) - (int)::TileX(t2)) + abs((int)::TileY(t1) - (int)::TileY(t2))) != 1) return false; + if ((abs(static_cast(::TileX(t1)) - static_cast(::TileX(t2))) + abs(static_cast(::TileY(t1)) - static_cast(::TileY(t2)))) != 1) return false; RoadTramType rtt = ::GetRoadTramType(ScriptObject::GetRoadType()); RoadBits r1 = ::GetAnyRoadBits(t1, rtt); // TODO @@ -132,7 +132,7 @@ EnforcePrecondition(false, ::IsValidTile(end_tile)); EnforcePrecondition(false, IsRoadTypeAvailable(road_type)); - return ScriptObject::Command::Do(start_tile, end_tile, (::RoadType)road_type); + return ScriptObject::Command::Do(start_tile, end_tile, static_cast<::RoadType>(road_type)); } /* Helper functions for ScriptRoad::CanBuildConnectedRoadParts(). */ @@ -274,7 +274,7 @@ static int32_t LookupWithBuildOnSlopes(::Slope slope, const Array= (::Slope)lengthof(base_slopes)) { + if (slope >= static_cast<::Slope>lengthof(base_slopes)) { /* This slope is an invalid slope, so ignore it. */ return -1; } @@ -399,7 +399,7 @@ static std::optional ToRoadPartOrientation(const TileIndex /* static */ SQInteger ScriptRoad::CanBuildConnectedRoadParts(ScriptTile::Slope slope_, Array &&existing, TileIndex start, TileIndex end) { - ::Slope slope = (::Slope)slope_; + ::Slope slope = static_cast<::Slope>(slope_); /* The start tile and end tile cannot be the same tile either. */ if (start == end) return -1; @@ -483,7 +483,7 @@ static bool NeighbourHasReachableRoad(::RoadType rt, TileIndex start_tile, DiagD if (!::IsValidTile(tile)) return -1; if (!IsRoadTypeAvailable(GetCurrentRoadType())) return -1; - ::RoadType rt = (::RoadType)GetCurrentRoadType(); + ::RoadType rt = static_cast<::RoadType>(GetCurrentRoadType()); int32_t neighbour = 0; if (TileX(tile) > 0 && NeighbourHasReachableRoad(rt, tile, DIAGDIR_NE)) neighbour++; @@ -643,7 +643,7 @@ static bool NeighbourHasReachableRoad(::RoadType rt, TileIndex start_tile, DiagD if (!ScriptRoad::IsRoadTypeAvailable(roadtype)) return -1; switch (build_type) { - case BT_ROAD: return ::RoadBuildCost((::RoadType)roadtype); + case BT_ROAD: return ::RoadBuildCost(static_cast<::RoadType>(roadtype)); case BT_DEPOT: return ::GetPrice(PR_BUILD_DEPOT_ROAD, 1, nullptr); case BT_BUS_STOP: return ::GetPrice(PR_BUILD_STATION_BUS, 1, nullptr); case BT_TRUCK_STOP: return ::GetPrice(PR_BUILD_STATION_TRUCK, 1, nullptr); @@ -653,19 +653,19 @@ static bool NeighbourHasReachableRoad(::RoadType rt, TileIndex start_tile, DiagD /* static */ ScriptRoad::RoadTramTypes ScriptRoad::GetRoadTramType(RoadType roadtype) { - return (RoadTramTypes)(1 << ::GetRoadTramType((::RoadType)roadtype)); + return static_cast(1 << ::GetRoadTramType(static_cast<::RoadType>(roadtype))); } /* static */ SQInteger ScriptRoad::GetMaxSpeed(RoadType road_type) { if (!ScriptRoad::IsRoadTypeAvailable(road_type)) return -1; - return GetRoadTypeInfo((::RoadType)road_type)->max_speed; + return GetRoadTypeInfo(static_cast<::RoadType>(road_type))->max_speed; } /* static */ SQInteger ScriptRoad::GetMaintenanceCostFactor(RoadType roadtype) { if (!ScriptRoad::IsRoadTypeAvailable(roadtype)) return 0; - return GetRoadTypeInfo((::RoadType)roadtype)->maintenance_multiplier; + return GetRoadTypeInfo(static_cast<::RoadType>(roadtype))->maintenance_multiplier; } diff --git a/src/script/api/script_station.cpp b/src/script/api/script_station.cpp index fb54eeacbe..a35352b8de 100644 --- a/src/script/api/script_station.cpp +++ b/src/script/api/script_station.cpp @@ -218,10 +218,10 @@ template if (!ScriptRoad::IsRoadTypeAvailable(road_type)) return false; for (const RoadStop *rs = ::Station::Get(station_id)->GetPrimaryRoadStop(RoadStopType::Bus); rs != nullptr; rs = rs->next) { - if (HasBit(::GetPresentRoadTypes(rs->xy), (::RoadType)road_type)) return true; + if (HasBit(::GetPresentRoadTypes(rs->xy), static_cast<::RoadType>(road_type))) return true; } for (const RoadStop *rs = ::Station::Get(station_id)->GetPrimaryRoadStop(RoadStopType::Truck); rs != nullptr; rs = rs->next) { - if (HasBit(::GetPresentRoadTypes(rs->xy), (::RoadType)road_type)) return true; + if (HasBit(::GetPresentRoadTypes(rs->xy), static_cast<::RoadType>(road_type))) return true; } return false; diff --git a/src/script/api/script_story_page.cpp b/src/script/api/script_story_page.cpp index 3a5fb911a5..fa5d7677f0 100644 --- a/src/script/api/script_story_page.cpp +++ b/src/script/api/script_story_page.cpp @@ -98,7 +98,7 @@ static inline bool StoryPageElementTypeRequiresText(StoryPageElementType type) if (!ScriptObject::Command::Do(&ScriptInstance::DoCommandReturnStoryPageElementID, reftile, - (::StoryPageID)story_page_id, (::StoryPageElementType)type, + ::StoryPageID(story_page_id), static_cast<::StoryPageElementType>(type), refid, encoded_text)) return STORY_PAGE_ELEMENT_INVALID; @@ -184,7 +184,7 @@ static inline bool StoryPageElementTypeRequiresText(StoryPageElementType type) EnforcePrecondition(ScriptDate::DATE_INVALID, IsValidStoryPage(story_page_id)); EnforceDeityMode(ScriptDate::DATE_INVALID); - return (ScriptDate::Date)StoryPage::Get(story_page_id)->date.base(); + return static_cast(StoryPage::Get(story_page_id)->date.base()); } /* static */ bool ScriptStoryPage::SetDate(StoryPageID story_page_id, ScriptDate::Date date) @@ -222,7 +222,7 @@ static inline bool StoryPageElementTypeRequiresText(StoryPageElementType type) /* static */ bool ScriptStoryPage::IsValidStoryPageButtonColour(StoryPageButtonColour colour) { - return ::IsValidColours((::Colours)colour); + return ::IsValidColours(static_cast<::Colours>(colour)); } /* static */ bool ScriptStoryPage::IsValidStoryPageButtonFlags(StoryPageButtonFlags flags) @@ -236,7 +236,7 @@ static inline bool StoryPageElementTypeRequiresText(StoryPageElementType type) /* static */ bool ScriptStoryPage::IsValidStoryPageButtonCursor(StoryPageButtonCursor cursor) { - return ::IsValidStoryPageButtonCursor((::StoryPageButtonCursor)cursor); + return ::IsValidStoryPageButtonCursor(static_cast<::StoryPageButtonCursor>(cursor)); } /* static */ ScriptStoryPage::StoryPageButtonFormatting ScriptStoryPage::MakePushButtonReference(StoryPageButtonColour colour, StoryPageButtonFlags flags) @@ -245,8 +245,8 @@ static inline bool StoryPageElementTypeRequiresText(StoryPageElementType type) EnforcePrecondition(UINT32_MAX, IsValidStoryPageButtonFlags(flags)); StoryPageButtonData data; - data.SetColour((::Colours)colour); - data.SetFlags((::StoryPageButtonFlags)flags); + data.SetColour(static_cast<::Colours>(colour)); + data.SetFlags(static_cast<::StoryPageButtonFlags>(flags)); if (!data.ValidateColour()) return UINT32_MAX; if (!data.ValidateFlags()) return UINT32_MAX; return data.referenced_id; @@ -259,9 +259,9 @@ static inline bool StoryPageElementTypeRequiresText(StoryPageElementType type) EnforcePrecondition(UINT32_MAX, IsValidStoryPageButtonCursor(cursor)); StoryPageButtonData data; - data.SetColour((::Colours)colour); - data.SetFlags((::StoryPageButtonFlags)flags); - data.SetCursor((::StoryPageButtonCursor)cursor); + data.SetColour(static_cast<::Colours>(colour)); + data.SetFlags(static_cast<::StoryPageButtonFlags>(flags)); + data.SetCursor(static_cast<::StoryPageButtonCursor>(cursor)); if (!data.ValidateColour()) return UINT32_MAX; if (!data.ValidateFlags()) return UINT32_MAX; if (!data.ValidateCursor()) return UINT32_MAX; @@ -276,10 +276,10 @@ static inline bool StoryPageElementTypeRequiresText(StoryPageElementType type) EnforcePrecondition(UINT32_MAX, vehtype == ScriptVehicle::VT_INVALID || vehtype == ScriptVehicle::VT_RAIL || vehtype == ScriptVehicle::VT_ROAD || vehtype == ScriptVehicle::VT_WATER || vehtype == ScriptVehicle::VT_AIR); StoryPageButtonData data; - data.SetColour((::Colours)colour); - data.SetFlags((::StoryPageButtonFlags)flags); - data.SetCursor((::StoryPageButtonCursor)cursor); - data.SetVehicleType((::VehicleType)vehtype); + data.SetColour(static_cast<::Colours>(colour)); + data.SetFlags(static_cast<::StoryPageButtonFlags>(flags)); + data.SetCursor(static_cast<::StoryPageButtonCursor>(cursor)); + data.SetVehicleType(static_cast<::VehicleType>(vehtype)); if (!data.ValidateColour()) return UINT32_MAX; if (!data.ValidateFlags()) return UINT32_MAX; if (!data.ValidateCursor()) return UINT32_MAX; diff --git a/src/script/api/script_subsidy.cpp b/src/script/api/script_subsidy.cpp index 586c436655..defd6b6535 100644 --- a/src/script/api/script_subsidy.cpp +++ b/src/script/api/script_subsidy.cpp @@ -63,7 +63,7 @@ ymd.month = m % 12; ymd.year += TimerGameEconomy::Year{m / 12}; - return (ScriptDate::Date)TimerGameEconomy::ConvertYMDToDate(ymd.year, ymd.month, ymd.day).base(); + return static_cast(TimerGameEconomy::ConvertYMDToDate(ymd.year, ymd.month, ymd.day).base()); } /* static */ CargoType ScriptSubsidy::GetCargoType(SubsidyID subsidy_id) diff --git a/src/script/api/script_text.cpp b/src/script/api/script_text.cpp index 9fea597317..aa02065bbe 100644 --- a/src/script/api/script_text.cpp +++ b/src/script/api/script_text.cpp @@ -141,7 +141,7 @@ SQInteger ScriptText::_set(HSQUIRRELVM vm) } else if (sq_gettype(vm, 2) == OT_INTEGER) { SQInteger key; sq_getinteger(vm, 2, &key); - k = (int32_t)key; + k = static_cast(key); } else { return SQ_ERROR; } @@ -183,7 +183,7 @@ void ScriptText::_FillParamList(ParamList ¶ms, ScriptTextList &seen_texts) /* Fill with dummy parameters to match FormatString() behaviour. */ if (seen_texts.empty()) { static Param dummy = 0; - int nb_extra = SCRIPT_TEXT_MAX_PARAMETERS - (int)params.size(); + int nb_extra = SCRIPT_TEXT_MAX_PARAMETERS - static_cast(params.size()); for (int i = 0; i < nb_extra; i++) params.emplace_back(StringIndexInTab(-1), i, &dummy); } diff --git a/src/script/api/script_tile.cpp b/src/script/api/script_tile.cpp index 57ba12ca78..23b8c3eb9f 100644 --- a/src/script/api/script_tile.cpp +++ b/src/script/api/script_tile.cpp @@ -102,14 +102,14 @@ { if ((slope & ~(SLOPE_ELEVATED | SLOPE_STEEP | SLOPE_HALFTILE_MASK)) != 0) return false; - return ::IsSteepSlope((::Slope)slope); + return ::IsSteepSlope(static_cast<::Slope>(slope)); } /* static */ bool ScriptTile::IsHalftileSlope(Slope slope) { if ((slope & ~(SLOPE_ELEVATED | SLOPE_STEEP | SLOPE_HALFTILE_MASK)) != 0) return false; - return ::IsHalftileSlope((::Slope)slope); + return ::IsHalftileSlope(static_cast<::Slope>(slope)); } /* static */ bool ScriptTile::HasTreeOnTile(TileIndex tile) @@ -171,14 +171,14 @@ { if (!::IsValidTile(tile)) return SLOPE_INVALID; - return (Slope)::GetTileSlope(tile); + return static_cast(::GetTileSlope(tile)); } /* static */ ScriptTile::Slope ScriptTile::GetComplementSlope(Slope slope) { if ((slope & ~SLOPE_ELEVATED) != 0) return SLOPE_INVALID; - return (Slope)::ComplementSlope((::Slope)slope); + return static_cast(::ComplementSlope(static_cast<::Slope>(slope))); } /* static */ SQInteger ScriptTile::GetMinHeight(TileIndex tile) @@ -197,10 +197,10 @@ /* static */ SQInteger ScriptTile::GetCornerHeight(TileIndex tile, Corner corner) { - if (!::IsValidTile(tile) || !::IsValidCorner((::Corner)corner)) return -1; + if (!::IsValidTile(tile) || !::IsValidCorner(static_cast<::Corner>(corner))) return -1; auto [slope, z] = ::GetTileSlopeZ(tile); - return (z + ::GetSlopeZInCorner(slope, (::Corner)corner)); + return (z + ::GetSlopeZInCorner(slope, static_cast<::Corner>(corner))); } /* static */ ScriptCompany::CompanyID ScriptTile::GetOwner(TileIndex tile) @@ -217,10 +217,10 @@ if (!::IsValidTile(tile)) return false; if (transport_type == TRANSPORT_ROAD) { - return ::TrackStatusToTrackdirBits(::GetTileTrackStatus(tile, (::TransportType)transport_type, 0)) != TRACKDIR_BIT_NONE || - ::TrackStatusToTrackdirBits(::GetTileTrackStatus(tile, (::TransportType)transport_type, 1)) != TRACKDIR_BIT_NONE; + return ::TrackStatusToTrackdirBits(::GetTileTrackStatus(tile, static_cast<::TransportType>(transport_type), 0)) != TRACKDIR_BIT_NONE || + ::TrackStatusToTrackdirBits(::GetTileTrackStatus(tile, static_cast<::TransportType>(transport_type), 1)) != TRACKDIR_BIT_NONE; } else { - return ::TrackStatusToTrackdirBits(::GetTileTrackStatus(tile, (::TransportType)transport_type, 0)) != TRACKDIR_BIT_NONE; + return ::TrackStatusToTrackdirBits(::GetTileTrackStatus(tile, static_cast<::TransportType>(transport_type), 0)) != TRACKDIR_BIT_NONE; } } @@ -228,7 +228,7 @@ { if (!::IsValidTile(tile) || width <= 0 || height <= 0 || radius < 0 || !ScriptCargo::IsValidCargo(cargo_type)) return -1; - CargoArray acceptance = ::GetAcceptanceAroundTiles(tile, width, height, _settings_game.station.modified_catchment ? radius : (int)CA_UNMODIFIED); + CargoArray acceptance = ::GetAcceptanceAroundTiles(tile, width, height, _settings_game.station.modified_catchment ? radius : static_cast(CA_UNMODIFIED)); return acceptance[cargo_type]; } @@ -236,7 +236,7 @@ { if (!::IsValidTile(tile) || width <= 0 || height <= 0 || radius < 0 || !ScriptCargo::IsValidCargo(cargo_type)) return -1; - CargoArray produced = ::GetProductionAroundTiles(tile, width, height, _settings_game.station.modified_catchment ? radius : (int)CA_UNMODIFIED); + CargoArray produced = ::GetProductionAroundTiles(tile, width, height, _settings_game.station.modified_catchment ? radius : static_cast(CA_UNMODIFIED)); return produced[cargo_type]; } @@ -255,7 +255,7 @@ EnforceCompanyModeValid(false); EnforcePrecondition(false, tile < ScriptMap::GetMapSize()); - return ScriptObject::Command::Do(tile, (::Slope)slope, true); + return ScriptObject::Command::Do(tile, static_cast<::Slope>(slope), true); } /* static */ bool ScriptTile::LowerTile(TileIndex tile, Slope slope) @@ -263,7 +263,7 @@ EnforceCompanyModeValid(false); EnforcePrecondition(false, tile < ScriptMap::GetMapSize()); - return ScriptObject::Command::Do(tile, (::Slope)slope, false); + return ScriptObject::Command::Do(tile, static_cast<::Slope>(slope), false); } /* static */ bool ScriptTile::LevelTiles(TileIndex start_tile, TileIndex end_tile) diff --git a/src/script/api/script_tilelist.cpp b/src/script/api/script_tilelist.cpp index 83596d22bc..79c95277d6 100644 --- a/src/script/api/script_tilelist.cpp +++ b/src/script/api/script_tilelist.cpp @@ -69,9 +69,9 @@ static void FillIndustryCatchment(const Industry *i, SQInteger radius, BitmapTil int tx = TileX(cur_tile); int ty = TileY(cur_tile); for (int y = -radius; y <= radius; y++) { - if (ty + y < 0 || ty + y > (int)Map::MaxY()) continue; + if (ty + y < 0 || ty + y > static_cast(Map::MaxY())) continue; for (int x = -radius; x <= radius; x++) { - if (tx + x < 0 || tx + x > (int)Map::MaxX()) continue; + if (tx + x < 0 || tx + x > static_cast(Map::MaxX())) continue; TileIndex tile = TileXY(tx + x, ty + y); if (!IsValidTile(tile)) continue; if (::IsTileType(tile, MP_INDUSTRY) && ::GetIndustryIndex(tile) == i->index) continue; diff --git a/src/script/api/script_town.cpp b/src/script/api/script_town.cpp index bf456dddb2..6c3a32a931 100644 --- a/src/script/api/script_town.cpp +++ b/src/script/api/script_town.cpp @@ -132,7 +132,7 @@ goal = Clamp(goal, 0, UINT32_MAX); - return ScriptObject::Command::Do(town_id, (::TownAcceptanceEffect)towneffect_id, goal); + return ScriptObject::Command::Do(town_id, static_cast<::TownAcceptanceEffect>(towneffect_id), goal); } /* static */ SQInteger ScriptTown::GetCargoGoal(TownID town_id, ScriptCargo::TownEffect towneffect_id) @@ -205,7 +205,7 @@ if (!IsValidTown(town_id)) return false; const Town *t = ::Town::Get(town_id); - return ((uint32_t)GetDistanceSquareToTile(town_id, tile) <= t->cache.squared_town_zone_radius[HZB_TOWN_EDGE]); + return (static_cast(GetDistanceSquareToTile(town_id, tile)) <= t->cache.squared_town_zone_radius[HZB_TOWN_EDGE]); } /* static */ bool ScriptTown::HasStatue(TownID town_id) @@ -293,7 +293,7 @@ EnforcePrecondition(false, layout >= ROAD_LAYOUT_ORIGINAL && layout <= ROAD_LAYOUT_RANDOM); } else { /* The layout parameter is ignored for AIs when custom layouts is disabled. */ - layout = (RoadLayout) (uint8_t)_settings_game.economy.town_layout; + layout = static_cast(static_cast(_settings_game.economy.town_layout)); } std::string text; @@ -307,7 +307,7 @@ return false; } - return ScriptObject::Command::Do(tile, (::TownSize)size, city, (::TownLayout)layout, false, townnameparts, text); + return ScriptObject::Command::Do(tile, static_cast<::TownSize>(size), city, static_cast<::TownLayout>(layout), false, townnameparts, text); } /* static */ ScriptTown::TownRating ScriptTown::GetRating(TownID town_id, ScriptCompany::CompanyID company_id) @@ -384,5 +384,5 @@ { if (!IsValidTown(town_id)) return ROAD_LAYOUT_INVALID; - return (ScriptTown::RoadLayout)((TownLayout)::Town::Get(town_id)->layout); + return static_cast(::Town::Get(town_id)->layout); } diff --git a/src/script/api/script_vehicle.cpp b/src/script/api/script_vehicle.cpp index efce579f62..1452e7df06 100644 --- a/src/script/api/script_vehicle.cpp +++ b/src/script/api/script_vehicle.cpp @@ -408,7 +408,7 @@ if (!IsValidVehicle(vehicle_id)) return ScriptRoad::ROADTYPE_INVALID; if (GetVehicleType(vehicle_id) != VT_ROAD) return ScriptRoad::ROADTYPE_INVALID; - return (ScriptRoad::RoadType)(int)(::RoadVehicle::Get(vehicle_id))->roadtype; + return static_cast(static_cast((::RoadVehicle::Get(vehicle_id))->roadtype)); } /* static */ SQInteger ScriptVehicle::GetCapacity(VehicleID vehicle_id, CargoType cargo) diff --git a/src/script/api/script_vehiclelist.cpp b/src/script/api/script_vehiclelist.cpp index 68113654e5..a392c65241 100644 --- a/src/script/api/script_vehiclelist.cpp +++ b/src/script/api/script_vehiclelist.cpp @@ -126,6 +126,6 @@ ScriptVehicleList_DefaultGroup::ScriptVehicleList_DefaultGroup(ScriptVehicle::Ve ScriptList::FillList(this, [owner](const Vehicle *v) { return v->owner == owner && v->IsPrimaryVehicle(); }, - [vehicle_type](const Vehicle *v) { return v->type == (::VehicleType)vehicle_type && v->group_id == ScriptGroup::GROUP_DEFAULT; } + [vehicle_type](const Vehicle *v) { return v->type == static_cast<::VehicleType>(vehicle_type) && v->group_id == ScriptGroup::GROUP_DEFAULT; } ); } diff --git a/src/script/api/script_window.cpp b/src/script/api/script_window.cpp index 42b5614c03..85fe3034c7 100644 --- a/src/script/api/script_window.cpp +++ b/src/script/api/script_window.cpp @@ -20,13 +20,13 @@ if (ScriptGame::IsMultiplayer()) return; if (number == NUMBER_ALL) { - CloseWindowByClass((::WindowClass)window); + CloseWindowByClass(static_cast<::WindowClass>(window)); return; } number = Clamp(number, 0, INT32_MAX); - CloseWindowById((::WindowClass)window, number); + CloseWindowById(static_cast<::WindowClass>(window), number); } /* static */ bool ScriptWindow::IsOpen(WindowClass window, SQInteger number) @@ -34,12 +34,12 @@ if (ScriptGame::IsMultiplayer()) return false; if (number == NUMBER_ALL) { - return (FindWindowByClass((::WindowClass)window) != nullptr); + return (FindWindowByClass(static_cast<::WindowClass>(window)) != nullptr); } number = Clamp(number, 0, INT32_MAX); - return FindWindowById((::WindowClass)window, number) != nullptr; + return FindWindowById(static_cast<::WindowClass>(window), number) != nullptr; } /* static */ void ScriptWindow::Highlight(WindowClass window, SQInteger number, SQInteger widget, TextColour colour) @@ -47,11 +47,11 @@ if (ScriptGame::IsMultiplayer()) return; if (number == NUMBER_ALL) return; if (!IsOpen(window, number)) return; - if (colour != TC_INVALID && (::TextColour)colour >= ::TC_END) return; + if (colour != TC_INVALID && static_cast<::TextColour>(colour) >= ::TC_END) return; number = Clamp(number, 0, INT32_MAX); - Window *w = FindWindowById((::WindowClass)window, number); + Window *w = FindWindowById(static_cast<::WindowClass>(window), number); assert(w != nullptr); if (widget == WIDGET_ALL) { @@ -64,5 +64,5 @@ const NWidgetBase *wid = w->GetWidget(widget); if (wid == nullptr) return; - w->SetWidgetHighlight(widget, (::TextColour)colour); + w->SetWidgetHighlight(widget, static_cast<::TextColour>(colour)); } diff --git a/src/script/script_gui.cpp b/src/script/script_gui.cpp index 97c54cdc48..aff26cadfc 100644 --- a/src/script/script_gui.cpp +++ b/src/script/script_gui.cpp @@ -183,7 +183,7 @@ struct ScriptListWindow : public Window { switch (widget) { case WID_SCRL_LIST: { // Select one of the Scripts int sel = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_SCRL_LIST) - 1; - if (sel < (int)this->info_list->size()) { + if (sel < static_cast(this->info_list->size())) { this->selected = sel; this->SetDirty(); if (click_count > 1) { @@ -841,7 +841,7 @@ struct ScriptDebugWindow : public Window { void DrawWidgetCompanyButton(const Rect &r, WidgetID widget, int start) const { if (this->IsWidgetDisabled(widget)) return; - CompanyID cid = (CompanyID)(widget - start); + CompanyID cid = CompanyID(widget - start); Dimension sprite_size = GetSpriteSize(SPR_COMPANY_ICON); DrawCompanyIcon(cid, CenterBounds(r.left, r.right, sprite_size.width), CenterBounds(r.top, r.bottom, sprite_size.height)); } @@ -906,7 +906,7 @@ struct ScriptDebugWindow : public Window { ScriptLogTypes::LogData &log = this->GetLogData(); - int scroll_count = (int)log.size(); + int scroll_count = static_cast(log.size()); if (this->vscroll->GetCount() != scroll_count) { this->vscroll->SetCount(scroll_count); @@ -918,10 +918,10 @@ struct ScriptDebugWindow : public Window { /* Detect when the user scrolls the window. Enable autoscroll when the bottom-most line becomes visible. */ if (this->last_vscroll_pos != this->vscroll->GetPosition()) { - this->autoscroll = this->vscroll->GetPosition() + this->vscroll->GetCapacity() >= (int)log.size(); + this->autoscroll = this->vscroll->GetPosition() + this->vscroll->GetCapacity() >= static_cast(log.size()); } - if (this->autoscroll && this->vscroll->SetPosition((int)log.size())) { + if (this->autoscroll && this->vscroll->SetPosition(static_cast(log.size()))) { /* We need a repaint */ this->SetWidgetDirty(WID_SCRD_VSCROLLBAR); this->SetWidgetDirty(WID_SCRD_LOG_PANEL); @@ -1000,7 +1000,7 @@ struct ScriptDebugWindow : public Window { /* Check which button is clicked */ if (IsInsideMM(widget, WID_SCRD_COMPANY_BUTTON_START, WID_SCRD_COMPANY_BUTTON_END + 1)) { - ChangeToScript((CompanyID)(widget - WID_SCRD_COMPANY_BUTTON_START), _ctrl_pressed); + ChangeToScript(CompanyID(widget - WID_SCRD_COMPANY_BUTTON_START), _ctrl_pressed); } switch (widget) { @@ -1108,7 +1108,7 @@ struct ScriptDebugWindow : public Window { } /* Highlight row that matched */ - this->highlight_row = (int)(log.size() - 1); + this->highlight_row = static_cast(log.size() - 1); } } } diff --git a/src/script/script_info.cpp b/src/script/script_info.cpp index ffb74bea5f..ab3c85ae5f 100644 --- a/src/script/script_info.cpp +++ b/src/script/script_info.cpp @@ -34,7 +34,7 @@ bool ScriptInfo::CheckMethod(const char *name) const /* Make sure the instance stays alive over time */ sq_addref(vm, &info->SQ_instance); - info->scanner = (ScriptScanner *)Squirrel::GetGlobalPointer(vm); + info->scanner = static_cast(Squirrel::GetGlobalPointer(vm)); info->engine = info->scanner->GetEngine(); /* Ensure the mandatory functions exist */ @@ -148,7 +148,7 @@ SQInteger ScriptInfo::AddSetting(HSQUIRRELVM vm) } else if (key == "flags") { SQInteger res; if (SQ_FAILED(sq_getinteger(vm, -1, &res))) return SQ_ERROR; - config.flags = (ScriptConfigFlags)res; + config.flags = ScriptConfigFlags(res); items |= 0x100; } else { this->engine->ThrowError(fmt::format("unknown setting property '{}'", key)); diff --git a/src/script/script_instance.cpp b/src/script/script_instance.cpp index 0b0ee2934e..786416dc61 100644 --- a/src/script/script_instance.cpp +++ b/src/script/script_instance.cpp @@ -375,7 +375,7 @@ static const SaveLoad _script_byte[] = { SQInteger res; sq_getinteger(vm, index, &res); if (!test) { - int64_t value = (int64_t)res; + int64_t value = static_cast(res); SlCopy(&value, 1, SLE_INT64); } return true; @@ -394,7 +394,7 @@ static const SaveLoad _script_byte[] = { return false; } if (!test) { - _script_sl_byte = (uint8_t)len; + _script_sl_byte = static_cast(len); SlObject(nullptr, _script_byte); SlCopy(const_cast(buf), len, SLE_CHAR); } @@ -735,7 +735,7 @@ bool ScriptInstance::IsPaused() if (_script_sl_byte == 0) return nullptr; ScriptData *data = new ScriptData(); - data->push_back((SQInteger)version); + data->push_back(static_cast(version)); LoadObjects(data); return data; } diff --git a/src/script/squirrel.cpp b/src/script/squirrel.cpp index b933a3537a..01669c55dd 100644 --- a/src/script/squirrel.cpp +++ b/src/script/squirrel.cpp @@ -182,7 +182,7 @@ void Squirrel::CompileError(HSQUIRRELVM vm, const SQChar *desc, const SQChar *so std::string msg = fmt::format("Error {}:{}/{}: {}", source, line, column, desc); /* Check if we have a custom print function */ - Squirrel *engine = (Squirrel *)sq_getforeignptr(vm); + Squirrel *engine = static_cast(sq_getforeignptr(vm)); engine->crashed = true; SQPrintFunc *func = engine->print_func; if (func == nullptr) { @@ -195,7 +195,7 @@ void Squirrel::CompileError(HSQUIRRELVM vm, const SQChar *desc, const SQChar *so void Squirrel::ErrorPrintFunc(HSQUIRRELVM vm, const std::string &s) { /* Check if we have a custom print function */ - SQPrintFunc *func = ((Squirrel *)sq_getforeignptr(vm))->print_func; + SQPrintFunc *func = (static_cast(sq_getforeignptr(vm)))->print_func; if (func == nullptr) { fmt::print(stderr, "{}", s); } else { @@ -211,7 +211,7 @@ void Squirrel::RunError(HSQUIRRELVM vm, const SQChar *error) /* Check if we have a custom print function */ std::string msg = fmt::format("Your script made an error: {}\n", error); - Squirrel *engine = (Squirrel *)sq_getforeignptr(vm); + Squirrel *engine = static_cast(sq_getforeignptr(vm)); SQPrintFunc *func = engine->print_func; if (func == nullptr) { fmt::print(stderr, "{}", msg); @@ -243,7 +243,7 @@ SQInteger Squirrel::_RunError(HSQUIRRELVM vm) void Squirrel::PrintFunc(HSQUIRRELVM vm, const std::string &s) { /* Check if we have a custom print function */ - SQPrintFunc *func = ((Squirrel *)sq_getforeignptr(vm))->print_func; + SQPrintFunc *func = (static_cast(sq_getforeignptr(vm)))->print_func; if (func == nullptr) { fmt::print("{}", s); } else { @@ -434,7 +434,7 @@ bool Squirrel::CallBoolMethod(HSQOBJECT instance, const char *method_name, bool /* static */ bool Squirrel::CreateClassInstanceVM(HSQUIRRELVM vm, const std::string &class_name, void *real_instance, HSQOBJECT *instance, SQRELEASEHOOK release_hook, bool prepend_API_name) { - Squirrel *engine = (Squirrel *)sq_getforeignptr(vm); + Squirrel *engine = static_cast(sq_getforeignptr(vm)); int oldtop = sq_gettop(vm); @@ -564,7 +564,7 @@ public: static char32_t _io_file_lexfeed_ASCII(SQUserPointer file) { unsigned char c; - if (((SQFile *)file)->Read(&c, sizeof(c), 1) > 0) return c; + if ((static_cast(file))->Read(&c, sizeof(c), 1) > 0) return c; return 0; } @@ -573,12 +573,12 @@ static char32_t _io_file_lexfeed_UTF8(SQUserPointer file) char buffer[5]; /* Read the first character, and get the length based on UTF-8 specs. If invalid, bail out. */ - if (((SQFile *)file)->Read(buffer, sizeof(buffer[0]), 1) != 1) return 0; + if ((static_cast(file))->Read(buffer, sizeof(buffer[0]), 1) != 1) return 0; uint len = Utf8EncodedCharLen(buffer[0]); if (len == 0) return -1; /* Read the remaining bits. */ - if (len > 1 && ((SQFile *)file)->Read(buffer + 1, sizeof(buffer[0]), len - 1) != len - 1) return 0; + if (len > 1 && (static_cast(file))->Read(buffer + 1, sizeof(buffer[0]), len - 1) != len - 1) return 0; /* Convert the character, and when definitely invalid, bail out as well. */ char32_t c; @@ -590,23 +590,23 @@ static char32_t _io_file_lexfeed_UTF8(SQUserPointer file) static char32_t _io_file_lexfeed_UCS2_no_swap(SQUserPointer file) { unsigned short c; - if (((SQFile *)file)->Read(&c, sizeof(c), 1) > 0) return (char32_t)c; + if ((static_cast(file))->Read(&c, sizeof(c), 1) > 0) return static_cast(c); return 0; } static char32_t _io_file_lexfeed_UCS2_swap(SQUserPointer file) { unsigned short c; - if (((SQFile *)file)->Read(&c, sizeof(c), 1) > 0) { + if ((static_cast(file))->Read(&c, sizeof(c), 1) > 0) { c = ((c >> 8) & 0x00FF)| ((c << 8) & 0xFF00); - return (char32_t)c; + return static_cast(c); } return 0; } static SQInteger _io_file_read(SQUserPointer file, SQUserPointer buf, SQInteger size) { - SQInteger ret = ((SQFile *)file)->Read(buf, 1, size); + SQInteger ret = (static_cast(file))->Read(buf, 1, size); if (ret == 0) return -1; return ret; } diff --git a/src/script/squirrel_std.cpp b/src/script/squirrel_std.cpp index abcac023ec..8bc8ffac1e 100644 --- a/src/script/squirrel_std.cpp +++ b/src/script/squirrel_std.cpp @@ -63,7 +63,7 @@ SQInteger SquirrelStd::require(HSQUIRRELVM vm) std::transform(path.begin(), path.end(), path.begin(), [](char &c) { return c == '/' ? PATHSEPCHAR : c; }); #endif - Squirrel *engine = (Squirrel *)sq_getforeignptr(vm); + Squirrel *engine = static_cast(sq_getforeignptr(vm)); bool ret = engine->LoadScript(vm, path); /* Reset the top, so the stack stays correct */ diff --git a/src/settingentry_gui.cpp b/src/settingentry_gui.cpp index 5a4b97cf95..3ab9768463 100644 --- a/src/settingentry_gui.cpp +++ b/src/settingentry_gui.cpp @@ -93,7 +93,7 @@ uint BaseSettingEntry::Draw(GameSettings *settings_ptr, int left, int right, int if (cur_row >= max_row) return cur_row; bool rtl = _current_text_dir == TD_RTL; - int offset = (rtl ? -(int)_circle_size.width : (int)_circle_size.width) / 2; + int offset = (rtl ? -static_cast(_circle_size.width) : static_cast(_circle_size.width)) / 2; int level_width = rtl ? -WidgetDimensions::scaled.hsep_indent : WidgetDimensions::scaled.hsep_indent; int x = rtl ? right : left; diff --git a/src/settings.cpp b/src/settings.cpp index 6baf16c4f6..eedee16f87 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -174,7 +174,7 @@ enum IniFileVersion : uint32_t { IFV_MAX_VERSION, ///< Highest possible ini-file version. }; -const uint16_t INIFILE_VERSION = (IniFileVersion)(IFV_MAX_VERSION - 1); ///< Current ini-file version of OpenTTD. +const uint16_t INIFILE_VERSION = static_cast(IFV_MAX_VERSION - 1); ///< Current ini-file version of OpenTTD. /** * Find the index value of a ONEofMANY type in a string separated by | @@ -235,7 +235,7 @@ static size_t LookupManyOfMany(const std::vector &many, const char r = OneOfManySettingDesc::ParseSingleValue(str, s - str, many); if (r == SIZE_MAX) return r; - SetBit(res, (uint8_t)r); // value found, set it + SetBit(res, static_cast(r)); // value found, set it if (*s == 0) break; str = s + 1; } @@ -301,7 +301,7 @@ static bool LoadIntList(const char *str, void *array, int nelems, VarType type) } auto opt_items = ParseIntList(str); - if (!opt_items.has_value() || opt_items->size() != (size_t)nelems) return false; + if (!opt_items.has_value() || opt_items->size() != static_cast(nelems)) return false; char *p = static_cast(array); for (auto item : *opt_items) { @@ -329,12 +329,12 @@ std::string ListSettingDesc::FormatValue(const void *object) const int64_t v; switch (GetVarMemType(this->save.conv)) { case SLE_VAR_BL: - case SLE_VAR_I8: v = *(const int8_t *)p; p += 1; break; - case SLE_VAR_U8: v = *(const uint8_t *)p; p += 1; break; - case SLE_VAR_I16: v = *(const int16_t *)p; p += 2; break; - case SLE_VAR_U16: v = *(const uint16_t *)p; p += 2; break; - case SLE_VAR_I32: v = *(const int32_t *)p; p += 4; break; - case SLE_VAR_U32: v = *(const uint32_t *)p; p += 4; break; + case SLE_VAR_I8: v = *reinterpret_cast(p); p += 1; break; + case SLE_VAR_U8: v = *p; p += 1; break; + case SLE_VAR_I16: v = *reinterpret_cast(p); p += 2; break; + case SLE_VAR_U16: v = *reinterpret_cast(p); p += 2; break; + case SLE_VAR_I32: v = *reinterpret_cast(p); p += 4; break; + case SLE_VAR_U32: v = *reinterpret_cast(p); p += 4; break; default: NOT_REACHED(); } if (i != 0) result += ','; @@ -353,13 +353,13 @@ std::string OneOfManySettingDesc::FormatSingleValue(uint id) const std::string OneOfManySettingDesc::FormatValue(const void *object) const { - uint id = (uint)this->Read(object); + uint id = static_cast(this->Read(object)); return this->FormatSingleValue(id); } std::string ManyOfManySettingDesc::FormatValue(const void *object) const { - uint bitmask = (uint)this->Read(object); + uint bitmask = static_cast(this->Read(object)); if (bitmask == 0) { return {}; } @@ -568,7 +568,7 @@ void IntSettingDesc::MakeValueValid(int32_t &val) const void IntSettingDesc::Write(const void *object, int32_t val) const { void *ptr = GetVariableAddress(object, this->save); - WriteValue(ptr, this->save.conv, (int64_t)val); + WriteValue(ptr, this->save.conv, static_cast(val)); } /** @@ -579,7 +579,7 @@ void IntSettingDesc::Write(const void *object, int32_t val) const int32_t IntSettingDesc::Read(const void *object) const { void *ptr = GetVariableAddress(object, this->save); - return (int32_t)ReadValue(ptr, this->save.conv); + return static_cast(ReadValue(ptr, this->save.conv)); } /** @@ -673,7 +673,7 @@ static void IniLoadSettings(IniFile &ini, const SettingTable &settings_table, co void IntSettingDesc::ParseValue(const IniItem *item, void *object) const { size_t val = (item == nullptr) ? this->GetDefaultValue() : this->ParseValue(item->value.has_value() ? item->value->c_str() : ""); - this->MakeValueValidAndWrite(object, (int32_t)val); + this->MakeValueValidAndWrite(object, static_cast(val)); } void StringSettingDesc::ParseValue(const IniItem *item, void *object) const @@ -746,7 +746,7 @@ std::string IntSettingDesc::FormatValue(const void *object) const if (IsSignedVarMemType(this->save.conv)) { i = this->Read(object); } else { - i = (uint32_t)this->Read(object); + i = static_cast(this->Read(object)); } return std::to_string(i); } @@ -759,7 +759,7 @@ std::string BoolSettingDesc::FormatValue(const void *object) const bool IntSettingDesc::IsSameValue(const IniItem *item, void *object) const { - int32_t item_value = (int32_t)this->ParseValue(item->value->c_str()); + int32_t item_value = static_cast(this->ParseValue(item->value->c_str())); int32_t object_value = this->Read(object); return item_value == object_value; } @@ -1833,8 +1833,8 @@ void SyncCompanySettings() const void *new_object = &_settings_client.company; for (auto &desc : _company_settings) { const SettingDesc *sd = GetSettingDesc(desc); - uint32_t old_value = (uint32_t)sd->AsIntSetting()->Read(old_object); - uint32_t new_value = (uint32_t)sd->AsIntSetting()->Read(new_object); + uint32_t old_value = static_cast(sd->AsIntSetting()->Read(old_object)); + uint32_t new_value = static_cast(sd->AsIntSetting()->Read(new_object)); /* * This is called from a command, and since it contains local configuration information * that the rest of the clients do not know about, we need to circumvent the normal ::Post @@ -1903,7 +1903,7 @@ void IConsoleSetSetting(const char *name, const char *value, bool force_newgame) _settings_error_list.clear(); return; } - success = SetSettingValue(isd, (int32_t)val, force_newgame); + success = SetSettingValue(isd, static_cast(val), force_newgame); } if (!success) { diff --git a/src/settings_gui.cpp b/src/settings_gui.cpp index 2664fe25a0..e47f14a28f 100644 --- a/src/settings_gui.cpp +++ b/src/settings_gui.cpp @@ -640,19 +640,19 @@ struct GameOptionsWindow : Window { if (widget >= WID_GO_BASE_GRF_TEXTFILE && widget < WID_GO_BASE_GRF_TEXTFILE + TFT_CONTENT_END) { if (BaseGraphics::GetUsedSet() == nullptr) return; - ShowBaseSetTextfileWindow((TextfileType)(widget - WID_GO_BASE_GRF_TEXTFILE), BaseGraphics::GetUsedSet(), STR_CONTENT_TYPE_BASE_GRAPHICS); + ShowBaseSetTextfileWindow(static_cast(widget - WID_GO_BASE_GRF_TEXTFILE), BaseGraphics::GetUsedSet(), STR_CONTENT_TYPE_BASE_GRAPHICS); return; } if (widget >= WID_GO_BASE_SFX_TEXTFILE && widget < WID_GO_BASE_SFX_TEXTFILE + TFT_CONTENT_END) { if (BaseSounds::GetUsedSet() == nullptr) return; - ShowBaseSetTextfileWindow((TextfileType)(widget - WID_GO_BASE_SFX_TEXTFILE), BaseSounds::GetUsedSet(), STR_CONTENT_TYPE_BASE_SOUNDS); + ShowBaseSetTextfileWindow(static_cast(widget - WID_GO_BASE_SFX_TEXTFILE), BaseSounds::GetUsedSet(), STR_CONTENT_TYPE_BASE_SOUNDS); return; } if (widget >= WID_GO_BASE_MUSIC_TEXTFILE && widget < WID_GO_BASE_MUSIC_TEXTFILE + TFT_CONTENT_END) { if (BaseMusic::GetUsedSet() == nullptr) return; - ShowBaseSetTextfileWindow((TextfileType)(widget - WID_GO_BASE_MUSIC_TEXTFILE), BaseMusic::GetUsedSet(), STR_CONTENT_TYPE_BASE_MUSIC); + ShowBaseSetTextfileWindow(static_cast(widget - WID_GO_BASE_MUSIC_TEXTFILE), BaseMusic::GetUsedSet(), STR_CONTENT_TYPE_BASE_MUSIC); return; } switch (widget) { @@ -899,7 +899,7 @@ struct GameOptionsWindow : Window { break; case WID_GO_RESOLUTION_DROPDOWN: // Change resolution - if ((uint)index < _resolutions.size() && ChangeResInGame(_resolutions[index].width, _resolutions[index].height)) { + if (static_cast(index) < _resolutions.size() && ChangeResInGame(_resolutions[index].width, _resolutions[index].height)) { this->SetDirty(); } break; @@ -1227,7 +1227,7 @@ struct GameSettingsWindow : Window { GameSettingsWindow(WindowDesc &desc) : Window(desc), filter_editbox(50) { - this->filter.mode = (RestrictionMode)_settings_client.gui.settings_restriction_mode; + this->filter.mode = static_cast(_settings_client.gui.settings_restriction_mode); this->filter.min_cat = RM_ALL; this->filter.type = ST_ALL; this->filter.type_hides = false; @@ -1255,7 +1255,7 @@ struct GameSettingsWindow : Window { { switch (widget) { case WID_GS_OPTIONSPANEL: - resize.height = SETTING_HEIGHT = std::max({(int)_circle_size.height, SETTING_BUTTON_HEIGHT, GetCharacterHeight(FS_NORMAL)}) + WidgetDimensions::scaled.vsep_normal; + resize.height = SETTING_HEIGHT = std::max({static_cast(_circle_size.height), SETTING_BUTTON_HEIGHT, GetCharacterHeight(FS_NORMAL)}) + WidgetDimensions::scaled.vsep_normal; resize.width = 1; size.height = 5 * resize.height + WidgetDimensions::scaled.framerect.Vertical(); @@ -1635,7 +1635,7 @@ struct GameSettingsWindow : Window { { switch (widget) { case WID_GS_RESTRICT_DROPDOWN: - this->filter.mode = (RestrictionMode)index; + this->filter.mode = static_cast(index); if (this->filter.mode == RM_CHANGED_AGAINST_DEFAULT || this->filter.mode == RM_CHANGED_AGAINST_NEW) { @@ -1652,7 +1652,7 @@ struct GameSettingsWindow : Window { break; case WID_GS_TYPE_DROPDOWN: - this->filter.type = (SettingType)index; + this->filter.type = static_cast(index); this->InvalidateData(); break; @@ -1807,8 +1807,8 @@ void DrawArrowButtons(int x, int y, Colours button_colour, uint8_t state, bool c int colour = GetColourGradient(button_colour, SHADE_DARKER); Dimension dim = NWidgetScrollbar::GetHorizontalDimension(); - Rect lr = {x, y, x + (int)dim.width - 1, y + (int)dim.height - 1}; - Rect rr = {x + (int)dim.width, y, x + (int)dim.width * 2 - 1, y + (int)dim.height - 1}; + Rect lr = {x, y, x + static_cast(dim.width) - 1, y + static_cast(dim.height) - 1}; + Rect rr = {x + static_cast(dim.width), y, x + static_cast(dim.width) * 2 - 1, y + static_cast(dim.height) - 1}; DrawFrameRect(lr, button_colour, (state == 1) ? FrameFlag::Lowered : FrameFlags{}); DrawFrameRect(rr, button_colour, (state == 2) ? FrameFlag::Lowered : FrameFlags{}); @@ -1906,14 +1906,14 @@ struct CustomCurrencyWindow : Window { case WID_CC_RATE_UP: case WID_CC_YEAR_DOWN: case WID_CC_YEAR_UP: - size = maxdim(size, {(uint)SETTING_BUTTON_WIDTH / 2, (uint)SETTING_BUTTON_HEIGHT}); + size = maxdim(size, {static_castSETTING_BUTTON_WIDTH / 2, static_castSETTING_BUTTON_HEIGHT}); break; /* Set the appropriate width for the edit buttons. */ case WID_CC_SEPARATOR_EDIT: case WID_CC_PREFIX_EDIT: case WID_CC_SUFFIX_EDIT: - size = maxdim(size, {(uint)SETTING_BUTTON_WIDTH, (uint)SETTING_BUTTON_HEIGHT}); + size = maxdim(size, {static_castSETTING_BUTTON_WIDTH, static_castSETTING_BUTTON_HEIGHT}); break; /* Make sure the window is wide enough for the widest exchange rate */ diff --git a/src/settings_table.cpp b/src/settings_table.cpp index 9df8ff8065..c0d3614ce4 100644 --- a/src/settings_table.cpp +++ b/src/settings_table.cpp @@ -542,7 +542,7 @@ static bool CheckMaxHeightLevel(int32_t &new_value) /* Check if at least one mountain on the map is higher than the new value. * If yes, disallow the change. */ for (const auto t : Map::Iterate()) { - if ((int32_t)TileHeight(t) > new_value) { + if (static_cast(TileHeight(t)) > new_value) { ShowErrorMessage(GetEncodedString(STR_CONFIG_SETTING_TOO_HIGH_MOUNTAIN), {}, WL_ERROR); /* Return old, unchanged value */ return false; diff --git a/src/ship_cmd.cpp b/src/ship_cmd.cpp index c8bd310b5e..74cf1045e6 100644 --- a/src/ship_cmd.cpp +++ b/src/ship_cmd.cpp @@ -605,10 +605,10 @@ static int ShipTestUpDownOnLock(const Ship *v) if (DirToDiagDir(v->direction) == diagdir) { /* Move up */ - return (v->z_pos < GetTileMaxZ(v->tile) * (int)TILE_HEIGHT) ? 1 : 0; + return (v->z_pos < GetTileMaxZ(v->tile) * static_cast(TILE_HEIGHT)) ? 1 : 0; } else { /* Move down */ - return (v->z_pos > GetTileZ(v->tile) * (int)TILE_HEIGHT) ? -1 : 0; + return (v->z_pos > GetTileZ(v->tile) * static_cast(TILE_HEIGHT)) ? -1 : 0; } } diff --git a/src/signal.cpp b/src/signal.cpp index b88ca97161..4b814500bb 100644 --- a/src/signal.cpp +++ b/src/signal.cpp @@ -295,7 +295,7 @@ static SigFlags ExploreSegment(Owner owner) assert(IsValidDiagDirection(enterdir)); TrackBits tracks = GetTrackBits(tile); // trackbits of tile - TrackBits tracks_masked = (TrackBits)(tracks & _enterdir_to_trackbits[enterdir]); // only incidating trackbits + TrackBits tracks_masked = (tracks & _enterdir_to_trackbits[enterdir]); // only incidating trackbits if (tracks == TRACK_BIT_HORZ || tracks == TRACK_BIT_VERT) { // there is exactly one incidating track, no need to check tracks = tracks_masked; @@ -313,7 +313,7 @@ static SigFlags ExploreSegment(Owner owner) Track track = TrackBitsToTrack(tracks_masked); // mask TRACK_BIT_X and Y too if (HasSignalOnTrack(tile, track)) { // now check whole track, not trackdir SignalType sig = GetSignalType(tile, track); - Trackdir trackdir = (Trackdir)FindFirstBit((tracks * 0x101U) & _enterdir_to_trackdirbits[enterdir]); + Trackdir trackdir = static_cast(FindFirstBit((tracks * 0x101U) & _enterdir_to_trackdirbits[enterdir])); Trackdir reversedir = ReverseTrackdir(trackdir); /* add (tile, reversetrackdir) to 'to-be-updated' set when there is * ANY conventional signal in REVERSE direction diff --git a/src/signs_gui.cpp b/src/signs_gui.cpp index bcccad2cd4..d2b320dbc7 100644 --- a/src/signs_gui.cpp +++ b/src/signs_gui.cpp @@ -264,7 +264,7 @@ struct SignListWindow : Window, SignList { Dimension spr_dim = GetSpriteSize(SPR_COMPANY_ICON); this->text_offset = WidgetDimensions::scaled.frametext.left + spr_dim.width + 2; // 2 pixels space between icon and the sign text. resize.height = std::max(GetCharacterHeight(FS_NORMAL), spr_dim.height + 2); - Dimension d = {(uint)(this->text_offset + WidgetDimensions::scaled.frametext.right), padding.height + 5 * resize.height}; + Dimension d = {static_cast(this->text_offset + WidgetDimensions::scaled.frametext.right), padding.height + 5 * resize.height}; size = maxdim(size, d); break; } diff --git a/src/smallmap_gui.cpp b/src/smallmap_gui.cpp index e8ef37c65f..ff5e18a597 100644 --- a/src/smallmap_gui.cpp +++ b/src/smallmap_gui.cpp @@ -851,7 +851,7 @@ protected: sx = -hv.x; sub = 0; } - if (sx > (int)(Map::MaxX() * TILE_SIZE) - hv.x) { + if (sx > static_cast(Map::MaxX() * TILE_SIZE) - hv.x) { sx = Map::MaxX() * TILE_SIZE - hv.x; sub = 0; } @@ -859,7 +859,7 @@ protected: sy = -hv.y; sub = 0; } - if (sy > (int)(Map::MaxY() * TILE_SIZE) - hv.y) { + if (sy > static_cast(Map::MaxY() * TILE_SIZE) - hv.y) { sy = Map::MaxY() * TILE_SIZE - hv.y; sub = 0; } @@ -881,10 +881,10 @@ protected: Point upper_left_smallmap_coord = InverseRemapCoords2(vp->virtual_left, vp->virtual_top); Point lower_right_smallmap_coord = InverseRemapCoords2(vp->virtual_left + vp->virtual_width - 1, vp->virtual_top + vp->virtual_height - 1); - Point upper_left = this->RemapTile(upper_left_smallmap_coord.x / (int)TILE_SIZE, upper_left_smallmap_coord.y / (int)TILE_SIZE); + Point upper_left = this->RemapTile(upper_left_smallmap_coord.x / static_cast(TILE_SIZE), upper_left_smallmap_coord.y / static_cast(TILE_SIZE)); upper_left.x -= this->subscroll; - Point lower_right = this->RemapTile(lower_right_smallmap_coord.x / (int)TILE_SIZE, lower_right_smallmap_coord.y / (int)TILE_SIZE); + Point lower_right = this->RemapTile(lower_right_smallmap_coord.x / static_cast(TILE_SIZE), lower_right_smallmap_coord.y / static_cast(TILE_SIZE)); lower_right.x -= this->subscroll; SmallMapWindow::DrawVertMapIndicator(upper_left.x, upper_left.y, lower_right.y); @@ -932,7 +932,7 @@ protected: ta.ClampToMap(); // Clamp to map boundaries (may contain MP_VOID tiles!). uint32_t val = this->GetTileColours(ta); - uint8_t *val8 = (uint8_t *)&val; + uint8_t *val8 = reinterpret_cast(&val); int idx = std::max(0, -start_pos); for (int pos = std::max(0, start_pos); pos < end_pos; pos++) { blitter->SetPixel(dst, idx, 0, val8[idx]); @@ -954,7 +954,7 @@ protected: if (v->vehstatus.Any({VehState::Hidden, VehState::Unclickable})) continue; /* Remap into flat coordinates. */ - Point pt = this->RemapTile(v->x_pos / (int)TILE_SIZE, v->y_pos / (int)TILE_SIZE); + Point pt = this->RemapTile(v->x_pos / static_cast(TILE_SIZE), v->y_pos / static_cast(TILE_SIZE)); int y = pt.y - dpi->top; if (!IsInsideMM(y, 0, dpi->height)) continue; // y is out of bounds. @@ -1065,8 +1065,8 @@ protected: /* Which tile is displayed at (dpi->left, dpi->top)? */ int dx; Point tile = this->PixelToTile(dpi->left, dpi->top, &dx); - int tile_x = this->scroll_x / (int)TILE_SIZE + tile.x; - int tile_y = this->scroll_y / (int)TILE_SIZE + tile.y; + int tile_x = this->scroll_x / static_cast(TILE_SIZE) + tile.x; + int tile_y = this->scroll_y / static_cast(TILE_SIZE) + tile.y; void *ptr = blitter->MoveTo(dpi->dst_ptr, -dx - 4, 0); int x = - dx - 4; @@ -1123,8 +1123,8 @@ protected: */ Point RemapTile(int tile_x, int tile_y) const { - int x_offset = tile_x - this->scroll_x / (int)TILE_SIZE; - int y_offset = tile_y - this->scroll_y / (int)TILE_SIZE; + int x_offset = tile_x - this->scroll_x / static_cast(TILE_SIZE); + int y_offset = tile_y - this->scroll_y / static_cast(TILE_SIZE); if (this->zoom == 1) return SmallmapRemapCoords(x_offset, y_offset); @@ -1482,8 +1482,8 @@ public: int sub; const NWidgetBase *wid = this->GetWidget(WID_SM_MAP); - Point sxy = this->ComputeScroll(viewport_center.x / (int)TILE_SIZE, viewport_center.y / (int)TILE_SIZE, - std::max(0, (int)wid->current_x / 2 - 2), wid->current_y / 2, &sub); + Point sxy = this->ComputeScroll(viewport_center.x / static_cast(TILE_SIZE), viewport_center.y / static_cast(TILE_SIZE), + std::max(0, static_cast(wid->current_x) / 2 - 2), wid->current_y / 2, &sub); this->SetNewScroll(sxy.x, sxy.y, sub); this->SetDirty(); } @@ -1637,7 +1637,7 @@ public: if (tbl->col_break || ((this->map_type == SMT_INDUSTRY || this->map_type == SMT_OWNER || this->map_type == SMT_LINKSTATS) && i++ >= number_of_rows)) { /* Column break needed, continue at top, COLUMN_WIDTH pixels * (one "row") to the right. */ - int x = rtl ? -(int)this->column_width : this->column_width; + int x = rtl ? -static_cast(this->column_width) : this->column_width; int y = origin.top - text.top; text = text.Translate(x, y); icon = icon.Translate(x, y); @@ -1715,7 +1715,7 @@ public: case WID_SM_ZOOM_IN: case WID_SM_ZOOM_OUT: { const NWidgetBase *wid = this->GetWidget(WID_SM_MAP); - Point zoom_pt = { (int)wid->current_x / 2, (int)wid->current_y / 2}; + Point zoom_pt = { static_cast(wid->current_x) / 2, static_cast(wid->current_y) / 2}; this->SetZoomLevel((widget == WID_SM_ZOOM_IN) ? ZLC_ZOOM_IN : ZLC_ZOOM_OUT, &zoom_pt); if (_settings_client.sound.click_beep) SndPlayFx(SND_15_BEEP); break; @@ -1728,7 +1728,7 @@ public: case WID_SM_ROUTES: // Show transport routes case WID_SM_VEGETATION: // Show vegetation case WID_SM_OWNERS: // Show land owners - this->SwitchMapType((SmallMapType)(widget - WID_SM_CONTOUR)); + this->SwitchMapType(static_cast(widget - WID_SM_CONTOUR)); if (_settings_client.sound.click_beep) SndPlayFx(SND_15_BEEP); break; diff --git a/src/sound.cpp b/src/sound.cpp index 5960ee02d5..b317c8c56c 100644 --- a/src/sound.cpp +++ b/src/sound.cpp @@ -212,7 +212,7 @@ static void SndPlayScreenCoordFx(SoundID sound, int left, int right, int top, in top < vp->virtual_top + vp->virtual_height && bottom > vp->virtual_top) { int screen_x = (left + right) / 2 - vp->virtual_left; int width = (vp->virtual_width == 0 ? 1 : vp->virtual_width); - float panning = (float)screen_x / width; + float panning = static_cast(screen_x) / width; StartSound( sound, diff --git a/src/spritecache.cpp b/src/spritecache.cpp index a4eeb809ac..828d52bfc6 100644 --- a/src/spritecache.cpp +++ b/src/spritecache.cpp @@ -221,7 +221,7 @@ SpriteID GetMaxSpriteID() static bool ResizeSpriteIn(SpriteLoader::SpriteCollection &sprite, ZoomLevel src, ZoomLevel tgt) { - uint8_t scaled_1 = ScaleByZoom(1, (ZoomLevel)(src - tgt)); + uint8_t scaled_1 = ScaleByZoom(1, static_cast(src - tgt)); /* Check for possible memory overflow. */ if (sprite[src].width * scaled_1 > UINT16_MAX || sprite[src].height * scaled_1 > UINT16_MAX) return false; @@ -495,7 +495,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?"); - return (void*)GetRawSprite(SPR_IMG_QUERY, SpriteType::Normal, &allocator, encoder); + return GetRawSprite(SPR_IMG_QUERY, SpriteType::Normal, &allocator, encoder); } if (sprite_type == SpriteType::MapGen) { @@ -528,7 +528,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?"); - return (void*)GetRawSprite(SPR_IMG_QUERY, SpriteType::Normal, &allocator, encoder); + return GetRawSprite(SPR_IMG_QUERY, SpriteType::Normal, &allocator, encoder); } if (sprite[ZOOM_LVL_MIN].type == SpriteType::Font && _font_zoom != ZOOM_LVL_MIN) { @@ -723,7 +723,7 @@ static_assert((sizeof(size_t) & (sizeof(size_t) - 1)) == 0); static inline MemBlock *NextBlock(MemBlock *block) { - return (MemBlock*)((uint8_t*)block + (block->size & ~S_FREE_MASK)); + return reinterpret_cast(reinterpret_cast(block) + (block->size & ~S_FREE_MASK)); } static size_t GetSpriteCacheUsage() diff --git a/src/station_cmd.cpp b/src/station_cmd.cpp index b9f908a934..c576bd5cd4 100644 --- a/src/station_cmd.cpp +++ b/src/station_cmd.cpp @@ -238,7 +238,7 @@ struct StationNameInformation { static bool FindNearIndustryName(TileIndex tile, void *user_data) { /* All already found industry types */ - StationNameInformation *sni = (StationNameInformation*)user_data; + StationNameInformation *sni = static_cast(user_data); if (!IsTileType(tile, MP_INDUSTRY)) return false; /* If the station name is undefined it means that it doesn't name a station */ @@ -2074,8 +2074,8 @@ CommandCost CmdBuildRoadStop(DoCommandFlags flags, TileIndex tile, uint8_t width /* Update company infrastructure counts. If the current tile is a normal road tile, remove the old * bits first. */ if (IsNormalRoadTile(cur_tile)) { - UpdateCompanyRoadInfrastructure(road_rt, road_owner, -(int)CountBits(GetRoadBits(cur_tile, RTT_ROAD))); - UpdateCompanyRoadInfrastructure(tram_rt, tram_owner, -(int)CountBits(GetRoadBits(cur_tile, RTT_TRAM))); + UpdateCompanyRoadInfrastructure(road_rt, road_owner, -static_cast(CountBits(GetRoadBits(cur_tile, RTT_ROAD)))); + UpdateCompanyRoadInfrastructure(tram_rt, tram_owner, -static_cast(CountBits(GetRoadBits(cur_tile, RTT_TRAM)))); } if (road_rt == INVALID_ROADTYPE && RoadTypeIsRoad(rt)) road_rt = rt; @@ -2224,7 +2224,7 @@ static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlags flags, int repl if (replacement_spec_index < 0) st->AfterStationTileSetChange(false, is_truck ? StationType::Truck: StationType::Bus); st->RemoveRoadStopTileData(tile); - if ((int)specindex != replacement_spec_index) DeallocateSpecFromRoadStop(st, specindex); + if (static_cast(specindex) != replacement_spec_index) DeallocateSpecFromRoadStop(st, specindex); /* Update the tile area of the truck/bus stop */ if (is_truck) { @@ -2283,7 +2283,7 @@ CommandCost RemoveRoadWaypointStop(TileIndex tile, DoCommandFlags flags, int rep wp->rect.AfterRemoveTile(wp, tile); wp->RemoveRoadStopTileData(tile); - if ((int)specindex != replacement_spec_index) DeallocateSpecFromRoadStop(wp, specindex); + if (static_cast(specindex) != replacement_spec_index) DeallocateSpecFromRoadStop(wp, specindex); if (replacement_spec_index < 0) { MakeRoadWaypointStationAreaSmaller(wp, wp->road_waypoint_area); @@ -3062,7 +3062,7 @@ bool SplitGroundSpriteForOverlay(const TileInfo *ti, SpriteID *ground, RailTrack /* Decide snow/desert from tile */ switch (_settings_game.game_creation.landscape) { case LandscapeType::Arctic: - snow_desert = (uint)ti->z > GetSnowLine() * TILE_HEIGHT; + snow_desert = static_cast(ti->z) > GetSnowLine() * TILE_HEIGHT; break; case LandscapeType::Tropic: @@ -3110,7 +3110,7 @@ static void DrawTile_Station(TileInfo *ti) /* Ensure the chosen tile layout is valid for this custom station */ if (!statspec->renderdata.empty()) { - layout = &statspec->renderdata[tile_layout < statspec->renderdata.size() ? tile_layout : (uint)GetRailStationAxis(ti->tile)]; + layout = &statspec->renderdata[tile_layout < statspec->renderdata.size() ? tile_layout : static_cast(GetRailStationAxis(ti->tile))]; if (!layout->NeedsPreprocessing()) { t = layout; layout = nullptr; @@ -3711,7 +3711,7 @@ static VehicleEnterTileStatus VehicleEnter_Station(Vehicle *v, TileIndex tile, i * begin of the platform to the stop location is longer than the length * of the platform. Station ahead 'includes' the current tile where the * vehicle is on, so we need to subtract that. */ - if (stop + station_ahead - (int)TILE_SIZE >= station_length) return VETSB_CONTINUE; + if (stop + station_ahead - static_cast(TILE_SIZE) >= station_length) return VETSB_CONTINUE; DiagDirection dir = DirToDiagDir(v->direction); @@ -3733,7 +3733,7 @@ static VehicleEnterTileStatus VehicleEnter_Station(Vehicle *v, TileIndex tile, i } } else if (v->type == VEH_ROAD) { RoadVehicle *rv = RoadVehicle::From(v); - if (rv->state < RVSB_IN_ROAD_STOP && !IsReversingRoadTrackdir((Trackdir)rv->state) && rv->frame == 0) { + if (rv->state < RVSB_IN_ROAD_STOP && !IsReversingRoadTrackdir(static_cast(rv->state)) && rv->frame == 0) { if (IsStationRoadStop(tile) && rv->IsFrontEngine()) { /* Attempt to allocate a parking bay in a road stop */ return RoadStop::GetByTile(tile, GetRoadStopType(tile))->Enter(rv) ? VETSB_CONTINUE : VETSB_CANNOT_ENTER; @@ -3938,9 +3938,9 @@ static void UpdateStationRating(Station *st) /* if rating is <= 127 and there are any items waiting, maybe remove some goods. */ if (rating <= 127 && waiting != 0) { uint32_t r = Random(); - if (rating <= (int)GB(r, 0, 7)) { + if (rating <= static_cast(GB(r, 0, 7))) { /* Need to have int, otherwise it will just overflow etc. */ - waiting = std::max((int)waiting - (int)((GB(r, 8, 2) - 1) * num_dests), 0); + waiting = std::max(static_cast(waiting) - static_cast((GB(r, 8, 2) - 1) * num_dests), 0); waiting_changed = true; } } @@ -4877,16 +4877,16 @@ void FlowStat::ChangeShare(StationID st, int flow) if (it.second == st) { if (flow < 0) { uint share = it.first - last_share; - if (flow == INT_MIN || (uint)(-flow) >= share) { + if (flow == INT_MIN || static_cast(-flow) >= share) { removed_shares += share; if (it.first <= this->unrestricted) this->unrestricted -= share; if (flow != INT_MIN) flow += share; last_share = it.first; continue; // remove the whole share } - removed_shares += (uint)(-flow); + removed_shares += static_cast(-flow); } else { - added_shares += (uint)(flow); + added_shares += static_cast(flow); } if (it.first <= this->unrestricted) this->unrestricted += flow; @@ -4898,7 +4898,7 @@ void FlowStat::ChangeShare(StationID st, int flow) last_share = it.first; } if (flow > 0) { - new_shares[last_share + (uint)flow] = st; + new_shares[last_share + static_cast(flow)] = st; if (this->unrestricted < last_share) { this->ReleaseShare(st); } else { @@ -5047,8 +5047,8 @@ void FlowStatMap::FinalizeLocalConsumption(StationID self) fs.ChangeShare(StationID::Invalid(), -INT_MAX); local -= INT_MAX; } - fs.ChangeShare(self, -(int)local); - fs.ChangeShare(StationID::Invalid(), -(int)local); + fs.ChangeShare(self, -static_cast(local)); + fs.ChangeShare(StationID::Invalid(), -static_cast(local)); /* If the local share is used up there must be a share for some * remote station. */ diff --git a/src/station_gui.cpp b/src/station_gui.cpp index 30a961b7e7..f6b984e98e 100644 --- a/src/station_gui.cpp +++ b/src/station_gui.cpp @@ -1357,7 +1357,7 @@ struct StationViewWindow : public Window { this->SelectGroupBy(_settings_client.gui.station_gui_group_order); this->SelectSortBy(_settings_client.gui.station_gui_sort_by); this->sort_orders[0] = SO_ASCENDING; - this->SelectSortOrder((SortOrder)_settings_client.gui.station_gui_sort_order); + this->SelectSortOrder(static_cast(_settings_client.gui.station_gui_sort_order)); this->owner = Station::Get(window_number)->owner; } @@ -1938,7 +1938,7 @@ struct StationViewWindow : public Window { */ void HandleCargoWaitingClick(int row) { - if (row < 0 || (uint)row >= this->displayed_rows.size()) return; + if (row < 0 || static_cast(row) >= this->displayed_rows.size()) return; if (_ctrl_pressed) { this->scroll_to_row = row; } else { @@ -2000,7 +2000,7 @@ struct StationViewWindow : public Window { case WID_SV_SHIPS: // Show list of scheduled ships to this station case WID_SV_PLANES: { // Show list of scheduled aircraft to this station Owner owner = Station::Get(this->window_number)->owner; - ShowVehicleListWindow(owner, (VehicleType)(widget - WID_SV_TRAINS), static_cast(this->window_number)); + ShowVehicleListWindow(owner, static_cast(widget - WID_SV_TRAINS), static_cast(this->window_number)); break; } @@ -2146,7 +2146,7 @@ struct StationViewWindow : public Window { { if (gui_scope) { if (data >= 0 && data < NUM_CARGO) { - this->cached_destinations.Remove((CargoType)data); + this->cached_destinations.Remove(static_cast(data)); } else { this->ReInit(); } @@ -2190,7 +2190,7 @@ static std::vector _stations_nearby_list; template static bool AddNearbyStation(TileIndex tile, void *user_data) { - TileArea *ctx = (TileArea *)user_data; + TileArea *ctx = static_cast(user_data); /* First check if there were deleted stations here */ for (auto it = _deleted_stations_nearby.begin(); it != _deleted_stations_nearby.end(); /* nothing */) { diff --git a/src/story.cpp b/src/story.cpp index 89a2474811..e8af39a48d 100644 --- a/src/story.cpp +++ b/src/story.cpp @@ -69,9 +69,9 @@ static bool VerifyElementContentParameters(StoryPageID page_id, StoryPageElement if (!IsValidTile(tile)) return false; break; case SPET_GOAL: - if (!Goal::IsValidID((GoalID)reference)) return false; + if (!Goal::IsValidID(GoalID(reference))) return false; /* Reject company specific goals on global pages */ - if (StoryPage::Get(page_id)->company == CompanyID::Invalid() && Goal::Get((GoalID)reference)->company != CompanyID::Invalid()) return false; + if (StoryPage::Get(page_id)->company == CompanyID::Invalid() && Goal::Get(GoalID(reference))->company != CompanyID::Invalid()) return false; break; case SPET_BUTTON_PUSH: if (!button_data.ValidateColour()) return false; @@ -162,13 +162,13 @@ Colours StoryPageButtonData::GetColour() const StoryPageButtonFlags StoryPageButtonData::GetFlags() const { - return (StoryPageButtonFlags)GB(this->referenced_id, 24, 8); + return static_cast(GB(this->referenced_id, 24, 8)); } /** Get the mouse cursor used while waiting for input for the button. */ StoryPageButtonCursor StoryPageButtonData::GetCursor() const { - StoryPageButtonCursor cursor = (StoryPageButtonCursor)GB(this->referenced_id, 8, 8); + StoryPageButtonCursor cursor = static_cast(GB(this->referenced_id, 8, 8)); if (!IsValidStoryPageButtonCursor(cursor)) return INVALID_SPBC; return cursor; } @@ -176,7 +176,7 @@ StoryPageButtonCursor StoryPageButtonData::GetCursor() const /** Get the type of vehicles that are accepted by the button */ VehicleType StoryPageButtonData::GetVehicleType() const { - return (VehicleType)GB(this->referenced_id, 16, 8); + return static_cast(GB(this->referenced_id, 16, 8)); } /** Verify that the data stored a valid Colour value */ diff --git a/src/story_gui.cpp b/src/story_gui.cpp index c74e840185..c6c98a4cc6 100644 --- a/src/story_gui.cpp +++ b/src/story_gui.cpp @@ -299,7 +299,7 @@ protected: { switch (pe.type) { case SPET_GOAL: { - Goal *g = Goal::Get((GoalID) pe.referenced_id); + Goal *g = Goal::Get(GoalID(pe.referenced_id)); if (g == nullptr) return SPR_IMG_GOAL_BROKEN_REF; return g->completed ? SPR_IMG_GOAL_COMPLETED : SPR_IMG_GOAL; } @@ -513,7 +513,7 @@ protected: void DrawActionElement(int &y_offset, int width, int line_height, SpriteID action_sprite, const std::string &text) const { Dimension sprite_dim = GetSpriteSize(action_sprite); - uint element_height = std::max(sprite_dim.height, (uint)line_height); + uint element_height = std::max(sprite_dim.height, static_cast(line_height)); uint sprite_top = y_offset + (element_height - sprite_dim.height) / 2; uint text_top = y_offset + (element_height - line_height) / 2; @@ -537,9 +537,9 @@ protected: case SPET_LOCATION: if (_ctrl_pressed) { - ShowExtraViewportWindow((TileIndex)pe.referenced_id); + ShowExtraViewportWindow(TileIndex(pe.referenced_id)); } else { - ScrollMainWindowToTile((TileIndex)pe.referenced_id); + ScrollMainWindowToTile(TileIndex(pe.referenced_id)); } break; @@ -717,7 +717,7 @@ public: break; case SPET_GOAL: { - Goal *g = Goal::Get((GoalID) ce.pe->referenced_id); + Goal *g = Goal::Get(GoalID(ce.pe->referenced_id)); DrawActionElement(y_offset, ce.bounds.right - ce.bounds.left, line_height, GetPageElementSprite(*ce.pe), g == nullptr ? GetString(STR_STORY_BOOK_INVALID_GOAL_REF) : g->text.GetDecodedString()); break; @@ -1042,7 +1042,7 @@ static CursorID TranslateStoryPageButtonCursor(StoryPageButtonCursor cursor) */ void ShowStoryBook(CompanyID company, StoryPageID page_id, bool centered) { - if (!Company::IsValidID(company)) company = (CompanyID)CompanyID::Invalid(); + if (!Company::IsValidID(company)) company = static_cast(CompanyID::Invalid()); StoryBookWindow *w = AllocateWindowDescFront(centered ? _story_book_gs_desc : _story_book_desc, company); if (page_id != StoryPageID::Invalid()) w->SetSelectedPage(page_id); diff --git a/src/strgen/strgen.cpp b/src/strgen/strgen.cpp index c843f179fb..e0fba7a8e3 100644 --- a/src/strgen/strgen.cpp +++ b/src/strgen/strgen.cpp @@ -133,17 +133,17 @@ void FileStringReader::HandlePragma(char *str) } else if (!memcmp(str, "winlangid ", 10)) { const char *buf = str + 10; long langid = std::strtol(buf, nullptr, 16); - if (langid > (long)UINT16_MAX || langid < 0) { + if (langid > static_castUINT16_MAX || langid < 0) { FatalError("Invalid winlangid {}", buf); } - _lang.winlangid = (uint16_t)langid; + _lang.winlangid = static_cast(langid); } else if (!memcmp(str, "grflangid ", 10)) { const char *buf = str + 10; long langid = std::strtol(buf, nullptr, 16); if (langid >= 0x7F || langid < 0) { FatalError("Invalid grflangid {}", buf); } - _lang.newgrflangid = (uint8_t)langid; + _lang.newgrflangid = static_cast(langid); } else if (!memcmp(str, "gender ", 7)) { if (this->master) FatalError("Genders are not allowed in the base translation."); char *buf = str + 7; @@ -292,7 +292,7 @@ struct LanguageFileWriter : LanguageWriter, FileWriter { void WriteHeader(const LanguagePackHeader *header) override { - this->Write((const uint8_t *)header, sizeof(*header)); + this->Write(reinterpret_cast(header), sizeof(*header)); } void Finalise() override @@ -303,7 +303,7 @@ struct LanguageFileWriter : LanguageWriter, FileWriter { void Write(const uint8_t *buffer, size_t length) override { - this->output_stream.write((const char *)buffer, length); + this->output_stream.write(reinterpret_cast(buffer), length); } }; diff --git a/src/strgen/strgen_base.cpp b/src/strgen/strgen_base.cpp index b369415834..04990eeca9 100644 --- a/src/strgen/strgen_base.cpp +++ b/src/strgen/strgen_base.cpp @@ -553,7 +553,7 @@ ParsedCommandStruct ExtractCommandString(const char *s, bool) if (ar->consumes) { if (argno != -1) argidx = argno; - if (argidx < 0 || (uint)argidx >= p.consuming_commands.max_size()) StrgenFatal("invalid param idx {}", argidx); + if (argidx < 0 || static_cast(argidx) >= p.consuming_commands.max_size()) StrgenFatal("invalid param idx {}", argidx); if (p.consuming_commands[argidx] != nullptr && p.consuming_commands[argidx] != ar) StrgenFatal("duplicate param idx {}", argidx); p.consuming_commands[argidx++] = ar; @@ -787,8 +787,8 @@ void HeaderWriter::WriteHeader(const StringData &data) int last = 0; for (size_t i = 0; i < data.max_strings; i++) { if (data.strings[i] != nullptr) { - this->WriteStringID(data.strings[i]->name, (int)i); - last = (int)i; + this->WriteStringID(data.strings[i]->name, static_cast(i)); + last = static_cast(i); } } @@ -799,7 +799,7 @@ static int TranslateArgumentIdx(int argidx, int offset) { int sum; - if (argidx < 0 || (uint)argidx >= _cur_pcs.consuming_commands.max_size()) { + if (argidx < 0 || static_cast(argidx) >= _cur_pcs.consuming_commands.max_size()) { StrgenFatal("invalid argidx {}", argidx); } const CmdStruct *cs = _cur_pcs.consuming_commands[argidx]; @@ -884,7 +884,7 @@ void LanguageWriter::WriteLength(uint length) buffer[offs++] = (length >> 8) | 0xC0; } buffer[offs++] = length & 0xFF; - this->Write((uint8_t*)buffer, offs); + this->Write(reinterpret_cast(buffer), offs); } /** @@ -895,7 +895,7 @@ void LanguageWriter::WriteLang(const StringData &data) { std::vector in_use; for (size_t tab = 0; tab < data.tabs; tab++) { - uint n = data.CountInUse((uint)tab); + uint n = data.CountInUse(static_cast(tab)); in_use.push_back(n); _lang.offsets[tab] = TO_LE16(n); @@ -956,20 +956,20 @@ void LanguageWriter::WriteLang(const StringData &data) * <0x9E> * Each LEN is printed using 2 bytes in big endian order. */ buffer.AppendUtf8(SCC_SWITCH_CASE); - buffer.AppendByte((uint8_t)ls->translated_cases.size()); + buffer.AppendByte(static_cast(ls->translated_cases.size())); /* Write each case */ for (const Case &c : ls->translated_cases) { buffer.AppendByte(c.caseidx); /* Make some space for the 16-bit length */ - uint pos = (uint)buffer.size(); + uint pos = static_cast(buffer.size()); buffer.AppendByte(0); buffer.AppendByte(0); /* Write string */ PutCommandString(&buffer, c.string.c_str()); buffer.AppendByte(0); // terminate with a zero /* Fill in the length */ - uint size = (uint)buffer.size() - (pos + 2); + uint size = static_cast(buffer.size()) - (pos + 2); buffer[pos + 0] = GB(size, 8, 8); buffer[pos + 1] = GB(size, 0, 8); } @@ -977,7 +977,7 @@ void LanguageWriter::WriteLang(const StringData &data) if (!cmdp->empty()) PutCommandString(&buffer, cmdp->c_str()); - this->WriteLength((uint)buffer.size()); + this->WriteLength(static_cast(buffer.size())); this->Write(buffer.data(), buffer.size()); buffer.clear(); } diff --git a/src/string.cpp b/src/string.cpp index 59785cfe90..512eadd936 100644 --- a/src/string.cpp +++ b/src/string.cpp @@ -828,11 +828,11 @@ public: char32_t c = Utf8Consume(&s); if (c < 0x10000) { - this->utf16_str.push_back((UChar)c); + this->utf16_str.push_back(static_cast(c)); } else { /* Make a surrogate pair. */ - this->utf16_str.push_back((UChar)(0xD800 + ((c - 0x10000) >> 10))); - this->utf16_str.push_back((UChar)(0xDC00 + ((c - 0x10000) & 0x3FF))); + this->utf16_str.push_back(static_cast(0xD800 + ((c - 0x10000) >> 10))); + this->utf16_str.push_back(static_cast(0xDC00 + ((c - 0x10000) & 0x3FF))); this->utf16_to_utf8.push_back(idx); } this->utf16_to_utf8.push_back(idx); @@ -881,7 +881,7 @@ public: * break point, but we only want word starts. Move to the next location in * case the new position points to whitespace. */ while (pos != icu::BreakIterator::DONE && - IsWhitespace(Utf16DecodeChar((const uint16_t *)&this->utf16_str[pos]))) { + IsWhitespace(Utf16DecodeChar(reinterpret_cast(&this->utf16_str[pos])))) { int32_t new_pos = this->word_itr->next(); /* Don't set it to DONE if it was valid before. Otherwise we'll return END * even though the iterator wasn't at the end of the string before. */ @@ -913,7 +913,7 @@ public: * break point, but we only want word starts. Move to the previous location in * case the new position points to whitespace. */ while (pos != icu::BreakIterator::DONE && - IsWhitespace(Utf16DecodeChar((const uint16_t *)&this->utf16_str[pos]))) { + IsWhitespace(Utf16DecodeChar(reinterpret_cast(&this->utf16_str[pos])))) { int32_t new_pos = this->word_itr->previous(); /* Don't set it to DONE if it was valid before. Otherwise we'll return END * even though the iterator wasn't at the start of the string before. */ diff --git a/src/strings.cpp b/src/strings.cpp index 84496630d0..8e4c84d0c3 100644 --- a/src/strings.cpp +++ b/src/strings.cpp @@ -779,11 +779,11 @@ static int DeterminePluralForm(int64_t count, int plural_form) static const char *ParseStringChoice(const char *b, uint form, StringBuilder &builder) { /* {Length of each string} {each string} */ - uint n = (uint8_t)*b++; + uint n = static_cast(*b++); uint pos, i, mypos = 0; for (i = pos = 0; i != n; i++) { - uint len = (uint8_t)*b++; + uint len = static_cast(*b++); if (i == form) mypos = pos; pos += len; } @@ -805,8 +805,8 @@ struct UnitConversion { int64_t ToDisplay(int64_t input, bool round = true) const { return round - ? (int64_t)std::round(input * this->factor) - : (int64_t)(input * this->factor); + ? static_cast(std::round(input * this->factor)) + : static_cast(input * this->factor); } /** @@ -819,8 +819,8 @@ struct UnitConversion { int64_t FromDisplay(int64_t input, bool round = true, int64_t divider = 1) const { return round - ? (int64_t)std::round(input / this->factor / divider) - : (int64_t)(input / this->factor / divider); + ? static_cast(std::round(input / this->factor / divider)) + : static_cast(input / this->factor / divider); } }; @@ -1152,7 +1152,7 @@ static void FormatString(StringBuilder &builder, const char *str_arg, StringPara case SCC_GENDER_LIST: { // {G 0 Der Die Das} /* First read the meta data from the language file. */ - size_t offset = orig_offset + (uint8_t)*str++; + size_t offset = orig_offset + static_cast(*str++); int gender = 0; if (!dry_run && args.GetTypeAtOffset(offset) != 0) { /* Now we need to figure out what text to resolve, i.e. @@ -1175,7 +1175,7 @@ static void FormatString(StringBuilder &builder, const char *str_arg, StringPara const char *s = buffer.c_str(); char32_t c = Utf8Consume(&s); /* Does this string have a gender, if so, set it */ - if (c == SCC_GENDER_INDEX) gender = (uint8_t)s[0]; + if (c == SCC_GENDER_INDEX) gender = static_cast(s[0]); } str = ParseStringChoice(str, gender, builder); break; @@ -1194,7 +1194,7 @@ static void FormatString(StringBuilder &builder, const char *str_arg, StringPara case SCC_PLURAL_LIST: { // {P} int plural_form = *str++; // contains the plural form for this string - size_t offset = orig_offset + (uint8_t)*str++; + size_t offset = orig_offset + static_cast(*str++); const uint64_t *v = std::get_if(&args.GetParam(offset)); // contains the number that determines plural if (v != nullptr) { str = ParseStringChoice(str, DeterminePluralForm(static_cast(*v), plural_form), builder); @@ -1205,23 +1205,23 @@ static void FormatString(StringBuilder &builder, const char *str_arg, StringPara } case SCC_ARG_INDEX: { // Move argument pointer - args.SetOffset(orig_offset + (uint8_t)*str++); + args.SetOffset(orig_offset + static_cast(*str++)); break; } case SCC_SET_CASE: { // {SET_CASE} /* This is a pseudo command, it's outputted when someone does {STRING.ack} * The modifier is added to all subsequent GetStringWithArgs that accept the modifier. */ - next_substr_case_index = (uint8_t)*str++; + next_substr_case_index = static_cast(*str++); break; } case SCC_SWITCH_CASE: { // {Used to implement case switching} /* <0x9E> * Each LEN is printed using 2 bytes in big endian order. */ - uint num = (uint8_t)*str++; + uint num = static_cast(*str++); while (num) { - if ((uint8_t)str[0] == case_index) { + if (static_cast(str[0]) == case_index) { /* Found the case, adjust str pointer and continue */ str += 3; break; @@ -1788,7 +1788,7 @@ static void FormatString(StringBuilder &builder, const char *str_arg, StringPara } case SCC_COLOUR: { // {COLOUR} - StringControlCode scc = (StringControlCode)(SCC_BLUE + args.GetNextParameter()); + StringControlCode scc = static_cast(SCC_BLUE + args.GetNextParameter()); if (IsInsideMM(scc, SCC_BLUE, SCC_COLOUR)) builder.Utf8Encode(scc); break; } @@ -1989,7 +1989,7 @@ bool ReadLanguagePack(const LanguageMetadata *lang) if (!lang_pack) return false; /* End of read data (+ terminating zero added in ReadFileToMem()) */ - const char *end = (char *)lang_pack.get() + len + 1; + const char *end = reinterpret_cast(lang_pack.get()) + len + 1; /* We need at least one byte of lang_pack->data */ if (end <= lang_pack->data || !lang_pack->IsValid()) { @@ -2013,17 +2013,17 @@ bool ReadLanguagePack(const LanguageMetadata *lang) /* Fill offsets */ char *s = lang_pack->data; - len = (uint8_t)*s++; + len = static_cast(*s++); for (uint i = 0; i < count; i++) { if (s + len >= end) return false; if (len >= 0xC0) { - len = ((len & 0x3F) << 8) + (uint8_t)*s++; + len = ((len & 0x3F) << 8) + static_cast(*s++); if (s + len >= end) return false; } offs[i] = s; s += len; - len = (uint8_t)*s; + len = static_cast(*s); *s++ = '\0'; // zero terminate the string } @@ -2033,7 +2033,7 @@ bool ReadLanguagePack(const LanguageMetadata *lang) _langpack.langtab_start = tab_start; _current_language = lang; - _current_text_dir = (TextDirection)_current_language->text_dir; + _current_text_dir = static_cast(_current_language->text_dir); _config_language_file = FS2OTTD(_current_language->file.filename()); SetCurrentGrfLangID(_current_language->newgrflangid); _langpack.list_separator = GetString(STR_LIST_SEPARATOR); @@ -2250,7 +2250,7 @@ bool MissingGlyphSearcher::FindMissingGlyphs() char32_t c = Utf8Consume(src); if (c >= SCC_FIRST_FONT && c <= SCC_LAST_FONT) { - size = (FontSize)(c - SCC_FIRST_FONT); + size = static_cast(c - SCC_FIRST_FONT); fc = FontCache::Get(size); } else if (!IsInsideMM(c, SCC_SPRITE_START, SCC_SPRITE_END) && IsPrintable(c) && !IsTextDirectionChar(c) && fc->MapCharToGlyph(c, false) == 0) { /* The character is printable, but not in the normal font. This is the case we were testing for. */ diff --git a/src/terraform_cmd.cpp b/src/terraform_cmd.cpp index 9d2e6ecc70..efdff0802e 100644 --- a/src/terraform_cmd.cpp +++ b/src/terraform_cmd.cpp @@ -294,10 +294,10 @@ std::tuple CmdTerraformLand(DoCommandFlags flags, TileIndex t = it.first; int height = it.second; - SetTileHeight(t, (uint)height); + SetTileHeight(t, static_cast(height)); } - if (c != nullptr) c->terraform_limit -= (uint32_t)ts.tile_to_new_height.size() << 16; + if (c != nullptr) c->terraform_limit -= static_cast(ts.tile_to_new_height.size()) << 16; } return { total_cost, 0, total_cost.Succeeded() ? tile : INVALID_TILE }; } diff --git a/src/textbuf.cpp b/src/textbuf.cpp index 3fe748e8d0..8f57ef5d16 100644 --- a/src/textbuf.cpp +++ b/src/textbuf.cpp @@ -65,11 +65,11 @@ bool Textbuf::DeleteChar(uint16_t keycode) /* Delete a complete word. */ if (backspace) { /* Delete whitespace and word in front of the caret. */ - len = this->caretpos - (uint16_t)this->char_iter->Prev(StringIterator::ITER_WORD); + len = this->caretpos - static_cast(this->char_iter->Prev(StringIterator::ITER_WORD)); s -= len; } else { /* Delete word and following whitespace following the caret. */ - len = (uint16_t)this->char_iter->Next(StringIterator::ITER_WORD) - this->caretpos; + len = static_cast(this->char_iter->Next(StringIterator::ITER_WORD)) - this->caretpos; } /* Update character count. */ for (auto ss = s; ss < s + len; Utf8Consume(ss)) { @@ -81,11 +81,11 @@ bool Textbuf::DeleteChar(uint16_t keycode) /* Delete the last code point in front of the caret. */ s = Utf8PrevChar(s); char32_t c; - len = (uint16_t)Utf8Decode(&c, s); + len = static_cast(Utf8Decode(&c, s)); this->chars--; } else { /* Delete the complete character following the caret. */ - len = (uint16_t)this->char_iter->Next(StringIterator::ITER_CHARACTER) - this->caretpos; + len = static_cast(this->char_iter->Next(StringIterator::ITER_CHARACTER)) - this->caretpos; /* Update character count. */ for (auto ss = s; ss < s + len; Utf8Consume(ss)) { this->chars--; @@ -127,7 +127,7 @@ void Textbuf::DeleteAll() */ bool Textbuf::InsertChar(char32_t key) { - uint16_t len = (uint16_t)Utf8CharLen(key); + uint16_t len = static_cast(Utf8CharLen(key)); if (this->buf.size() + len < this->max_bytes && this->chars + 1 <= this->max_chars) { /* Make space in the string, then overwrite it with the Utf8 encoded character. */ auto pos = this->buf.begin() + this->caretpos; @@ -293,7 +293,7 @@ void Textbuf::UpdateStringIter() { this->char_iter->SetString(this->buf.c_str()); size_t pos = this->char_iter->SetCurPosition(this->caretpos); - this->caretpos = pos == StringIterator::END ? 0 : (uint16_t)pos; + this->caretpos = pos == StringIterator::END ? 0 : static_cast(pos); } /** Update pixel width of the text. */ diff --git a/src/textfile_gui.cpp b/src/textfile_gui.cpp index 0f7f3a4fe2..403214a993 100644 --- a/src/textfile_gui.cpp +++ b/src/textfile_gui.cpp @@ -535,7 +535,7 @@ void TextfileWindow::AfterLoadMarkdown() case WID_TF_JUMPLIST: { DropDownList list; for (size_t line : this->jumplist) { - list.push_back(MakeDropDownListStringItem(GetString(STR_TEXTFILE_JUMPLIST_ITEM, this->lines[line].text), (int)line)); + list.push_back(MakeDropDownListStringItem(GetString(STR_TEXTFILE_JUMPLIST_ITEM, this->lines[line].text), static_cast(line))); } ShowDropDownList(this, std::move(list), -1, widget); break; diff --git a/src/tgp.cpp b/src/tgp.cpp index 39a86b1435..2d90c4c887 100644 --- a/src/tgp.cpp +++ b/src/tgp.cpp @@ -300,7 +300,7 @@ static Amplitude GetAmplitude(int frequency) double extrapolation_factor = extrapolation_factors[smoothness]; int height_range = I2H(16); do { - amplitude = (Amplitude)(extrapolation_factor * (double)amplitude); + amplitude = static_cast(extrapolation_factor * static_cast(amplitude)); height_range <<= 1; index++; } while (index < 0); @@ -365,7 +365,7 @@ static void HeightMapGenerate() /* Trying to apply noise to uninitialized height map */ assert(!_height_map.h.empty()); - int start = std::max(MAX_TGP_FREQUENCIES - (int)std::min(Map::LogX(), Map::LogY()), 0); + int start = std::max(MAX_TGP_FREQUENCIES - static_cast(std::min(Map::LogX(), Map::LogY())), 0); bool first = true; for (int frequency = start; frequency < MAX_TGP_FREQUENCIES; frequency++) { @@ -434,7 +434,7 @@ static void HeightMapGetMinMaxAvg(Height *min_ptr, Height *max_ptr, Height *avg_ } /* Get average height */ - h_avg = (Height)(h_accu / (_height_map.size_x * _height_map.size_y)); + h_avg = static_cast(h_accu / (_height_map.size_x * _height_map.size_y)); /* Return required results */ if (min_ptr != nullptr) *min_ptr = h_min; @@ -465,7 +465,7 @@ static void HeightMapSineTransform(Height h_min, Height h_max) if (h < h_min) continue; /* Transform height into 0..1 space */ - fheight = (double)(h - h_min) / (double)(h_max - h_min); + fheight = static_cast(h - h_min) / static_cast(h_max - h_min); /* Apply sine transform depending on landscape type */ switch (_settings_game.game_creation.landscape) { case LandscapeType::Toyland: @@ -525,7 +525,7 @@ static void HeightMapSineTransform(Height h_min, Height h_max) break; } /* Transform it back into h_min..h_max space */ - h = (Height)(fheight * (h_max - h_min) + h_min); + h = static_cast(fheight * (h_max - h_min) + h_min); if (h < 0) h = I2H(0); if (h >= h_max) h = h_max - 1; } @@ -569,9 +569,9 @@ static void HeightMapCurves(uint level) std::array ht{}; /* Set up a grid to choose curve maps based on location; attempt to get a somewhat square grid */ - float factor = sqrt((float)_height_map.size_x / (float)_height_map.size_y); - uint sx = Clamp((int)(((1 << level) * factor) + 0.5), 1, 128); - uint sy = Clamp((int)(((1 << level) / factor) + 0.5), 1, 128); + float factor = sqrt(static_cast(_height_map.size_x) / static_cast(_height_map.size_y)); + uint sx = Clamp(static_cast(((1 << level) * factor) + 0.5), 1, 128); + uint sy = Clamp(static_cast(((1 << level) / factor) + 0.5), 1, 128); std::vector c(static_cast(sx) * sy); for (uint i = 0; i < sx * sy; i++) { @@ -582,8 +582,8 @@ static void HeightMapCurves(uint level) for (int x = 0; x < _height_map.size_x; x++) { /* Get our X grid positions and bi-linear ratio */ - float fx = (float)(sx * x) / _height_map.size_x + 1.0f; - uint x1 = (uint)fx; + float fx = static_cast(sx * x) / _height_map.size_x + 1.0f; + uint x1 = static_cast(fx); uint x2 = x1; float xr = 2.0f * (fx - x1) - 1.0f; xr = sin(xr * M_PI_2); @@ -599,8 +599,8 @@ static void HeightMapCurves(uint level) for (int y = 0; y < _height_map.size_y; y++) { /* Get our Y grid position and bi-linear ratio */ - float fy = (float)(sy * y) / _height_map.size_y + 1.0f; - uint y1 = (uint)fy; + float fy = static_cast(sy * y) / _height_map.size_y + 1.0f; + uint y1 = static_cast(fy); uint y2 = y1; float yr = 2.0f * (fy - y1) - 1.0f; yr = sin(yr * M_PI_2); @@ -656,7 +656,7 @@ static void HeightMapCurves(uint level) } /* Apply interpolation of curve map results. */ - *h = (Height)((ht[corner_a] * yri + ht[corner_b] * yr) * xri + (ht[corner_c] * yri + ht[corner_d] * yr) * xr); + *h = static_cast((ht[corner_a] * yri + ht[corner_b] * yr) * xri + (ht[corner_c] * yri + ht[corner_d] * yr) * xr); /* Re-add sea level */ *h += I2H(1); @@ -695,7 +695,7 @@ static void HeightMapAdjustWaterLevel(int64_t water_percent, Height h_max_new) */ for (Height &h : _height_map.h) { /* Transform height from range h_water_level..h_max into 0..h_max_new range */ - h = (Height)(((int)h_max_new) * (h - h_water_level) / (h_max - h_water_level)) + I2H(1); + h = static_cast((static_cast(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; @@ -841,8 +841,8 @@ static void HeightMapSmoothCoasts(BorderFlags water_borders) */ 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++) { + for (int y = 0; y <= _height_map.size_y; y++) { + for (int x = 0; x <= _height_map.size_x; x++) { 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; } @@ -900,7 +900,7 @@ static double int_noise(const long x, const long y, const int prime) n = (n << 13) ^ n; /* Pseudo-random number generator, using several large primes */ - return 1.0 - (double)((n * (n * n * 15731 + 789221) + 1376312589) & 0x7fffffff) / 1073741824.0; + return 1.0 - static_cast((n * (n * n * 15731 + 789221) + 1376312589) & 0x7fffffff) / 1073741824.0; } @@ -919,11 +919,11 @@ static inline double linear_interpolate(const double a, const double b, const do */ static double interpolated_noise(const double x, const double y, const int prime) { - const int integer_x = (int)x; - const int integer_y = (int)y; + const int integer_x = static_cast(x); + const int integer_y = static_cast(y); - const double fractional_x = x - (double)integer_x; - const double fractional_y = y - (double)integer_y; + const double fractional_x = x - static_cast(integer_x); + const double fractional_y = y - static_cast(integer_y); const double v1 = int_noise(integer_x, integer_y, prime); const double v2 = int_noise(integer_x + 1, integer_y, prime); @@ -948,8 +948,8 @@ static double perlin_coast_noise_2D(const double x, const double y, const double double total = 0.0; for (int i = 0; i < 6; i++) { - const double frequency = (double)(1 << i); - const double amplitude = pow(p, (double)i); + const double frequency = static_cast(1 << i); + const double amplitude = pow(p, static_cast(i)); total += interpolated_noise((x * frequency) / 64.0, (y * frequency) / 64.0, prime) * amplitude; } diff --git a/src/timetable_cmd.cpp b/src/timetable_cmd.cpp index 3dcff1f57c..c267665960 100644 --- a/src/timetable_cmd.cpp +++ b/src/timetable_cmd.cpp @@ -314,7 +314,7 @@ static bool VehicleTimetableSorter(Vehicle * const &a, Vehicle * const &b) { VehicleOrderID a_order = a->cur_real_order_index; VehicleOrderID b_order = b->cur_real_order_index; - int j = (int)b_order - (int)a_order; + int j = static_cast(b_order) - static_cast(a_order); /* Are we currently at an ordered station (un)loading? */ bool a_load = a->current_order.IsType(OT_LOADING) && a->current_order.GetNonStopType() != ONSF_STOP_EVERYWHERE; @@ -328,7 +328,7 @@ static bool VehicleTimetableSorter(Vehicle * const &a, Vehicle * const &b) if (!b_load) b_order--; /* First check the order index that accounted for loading, then just the raw one. */ - int i = (int)b_order - (int)a_order; + int i = static_cast(b_order) - static_cast(a_order); if (i != 0) return i < 0; if (j != 0) return j < 0; @@ -385,7 +385,7 @@ CommandCost CmdSetTimetableStart(DoCommandFlags flags, VehicleID veh_id, bool ti vehs.push_back(v); } - int num_vehs = (uint)vehs.size(); + int num_vehs = static_cast(vehs.size()); if (num_vehs >= 2) { std::sort(vehs.begin(), vehs.end(), &VehicleTimetableSorter); diff --git a/src/timetable_gui.cpp b/src/timetable_gui.cpp index 113f23baca..ab6c515f4f 100644 --- a/src/timetable_gui.cpp +++ b/src/timetable_gui.cpp @@ -317,7 +317,7 @@ struct TimetableWindow : Window { if (from == to) break; // no need to change anything /* if from == INVALID_VEH_ORDER_ID, one order was added; if to == INVALID_VEH_ORDER_ID, one order was removed */ - uint old_num_orders = this->vehicle->GetNumOrders() - (uint)(from == INVALID_VEH_ORDER_ID) + (uint)(to == INVALID_VEH_ORDER_ID); + uint old_num_orders = this->vehicle->GetNumOrders() - static_cast(from == INVALID_VEH_ORDER_ID) + static_cast(to == INVALID_VEH_ORDER_ID); VehicleOrderID selected_order = (this->sel_index + 1) / 2; if (selected_order == old_num_orders) selected_order = 0; // when last travel time is selected, it belongs to order 0 @@ -326,9 +326,9 @@ struct TimetableWindow : Window { if (from != selected_order) { /* Moving from preceding order? */ - selected_order -= (int)(from <= selected_order); + selected_order -= static_cast(from <= selected_order); /* Moving to preceding order? */ - selected_order += (int)(to <= selected_order); + selected_order += static_cast(to <= selected_order); } else { /* Now we are modifying the selected order */ if (to == INVALID_VEH_ORDER_ID) { @@ -343,7 +343,7 @@ struct TimetableWindow : Window { } /* recompute new sel_index */ - this->sel_index = 2 * selected_order - (int)travel; + this->sel_index = 2 * selected_order - static_cast(travel); /* travel time of first order needs special handling */ if (this->sel_index == -1) this->sel_index = this->vehicle->GetNumOrders() * 2 - 1; break; @@ -501,7 +501,7 @@ struct TimetableWindow : Window { std::vector arr_dep(v->GetNumOrders()); const VehicleOrderID cur_order = v->cur_real_order_index % v->GetNumOrders(); - VehicleOrderID earlyID = BuildArrivalDepartureList(v, arr_dep) ? cur_order : (VehicleOrderID)INVALID_VEH_ORDER_ID; + VehicleOrderID earlyID = BuildArrivalDepartureList(v, arr_dep) ? cur_order : INVALID_VEH_ORDER_ID; int selected = this->sel_index; Rect tr = r.Shrink(WidgetDimensions::scaled.framerect); diff --git a/src/toolbar_gui.cpp b/src/toolbar_gui.cpp index 9011172856..7c67f19b2d 100644 --- a/src/toolbar_gui.cpp +++ b/src/toolbar_gui.cpp @@ -538,7 +538,7 @@ static CallBackFunction ToolbarStationsClick(Window *w) */ static CallBackFunction MenuClickStations(int index) { - ShowCompanyStations((CompanyID)index); + ShowCompanyStations(CompanyID(index)); return CBF_NONE; } @@ -558,7 +558,7 @@ static CallBackFunction ToolbarFinancesClick(Window *w) */ static CallBackFunction MenuClickFinances(int index) { - ShowCompanyFinances((CompanyID)index); + ShowCompanyFinances(CompanyID(index)); return CBF_NONE; } @@ -594,7 +594,7 @@ static CallBackFunction MenuClickCompany(int index) return CBF_NONE; } } - ShowCompany((CompanyID)index); + ShowCompany(CompanyID(index)); return CBF_NONE; } @@ -614,7 +614,7 @@ static CallBackFunction ToolbarStoryClick(Window *w) */ static CallBackFunction MenuClickStory(int index) { - ShowStoryBook(index == CTMN_SPECTATOR ? CompanyID::Invalid() : (CompanyID)index); + ShowStoryBook(index == CTMN_SPECTATOR ? CompanyID::Invalid() : CompanyID(index)); return CBF_NONE; } @@ -634,7 +634,7 @@ static CallBackFunction ToolbarGoalClick(Window *w) */ static CallBackFunction MenuClickGoal(int index) { - ShowGoalsList(index == CTMN_SPECTATOR ? CompanyID::Invalid() : (CompanyID)index); + ShowGoalsList(index == CTMN_SPECTATOR ? CompanyID::Invalid() : CompanyID(index)); return CBF_NONE; } @@ -721,7 +721,7 @@ static CallBackFunction MenuClickGraphsOrLeague(int index) case LTMN_HIGHSCORE: ShowHighscoreTable(); break; default: { if (LeagueTable::IsValidID(index)) { - ShowScriptLeagueTable((LeagueTableID)index); + ShowScriptLeagueTable(LeagueTableID(index)); } } } @@ -786,7 +786,7 @@ static CallBackFunction ToolbarTrainClick(Window *w) */ static CallBackFunction MenuClickShowTrains(int index) { - ShowVehicleListWindow((CompanyID)index, VEH_TRAIN); + ShowVehicleListWindow(CompanyID(index), VEH_TRAIN); return CBF_NONE; } @@ -806,7 +806,7 @@ static CallBackFunction ToolbarRoadClick(Window *w) */ static CallBackFunction MenuClickShowRoad(int index) { - ShowVehicleListWindow((CompanyID)index, VEH_ROAD); + ShowVehicleListWindow(CompanyID(index), VEH_ROAD); return CBF_NONE; } @@ -826,7 +826,7 @@ static CallBackFunction ToolbarShipClick(Window *w) */ static CallBackFunction MenuClickShowShips(int index) { - ShowVehicleListWindow((CompanyID)index, VEH_SHIP); + ShowVehicleListWindow(CompanyID(index), VEH_SHIP); return CBF_NONE; } @@ -846,7 +846,7 @@ static CallBackFunction ToolbarAirClick(Window *w) */ static CallBackFunction MenuClickShowAir(int index) { - ShowVehicleListWindow((CompanyID)index, VEH_AIRCRAFT); + ShowVehicleListWindow(CompanyID(index), VEH_AIRCRAFT); return CBF_NONE; } @@ -855,7 +855,7 @@ static CallBackFunction MenuClickShowAir(int index) static CallBackFunction ToolbarZoomInClick(Window *w) { if (DoZoomInOutWindow(ZOOM_IN, GetMainWindow())) { - w->HandleButtonClick((_game_mode == GM_EDITOR) ? (WidgetID)WID_TE_ZOOM_IN : (WidgetID)WID_TN_ZOOM_IN); + w->HandleButtonClick((_game_mode == GM_EDITOR) ? static_cast(WID_TE_ZOOM_IN) : static_cast(WID_TN_ZOOM_IN)); if (_settings_client.sound.click_beep) SndPlayFx(SND_15_BEEP); } return CBF_NONE; @@ -866,7 +866,7 @@ static CallBackFunction ToolbarZoomInClick(Window *w) static CallBackFunction ToolbarZoomOutClick(Window *w) { if (DoZoomInOutWindow(ZOOM_OUT, GetMainWindow())) { - w->HandleButtonClick((_game_mode == GM_EDITOR) ? (WidgetID)WID_TE_ZOOM_OUT : (WidgetID)WID_TN_ZOOM_OUT); + w->HandleButtonClick((_game_mode == GM_EDITOR) ? static_cast(WID_TE_ZOOM_OUT) : static_cast(WID_TN_ZOOM_OUT)); if (_settings_client.sound.click_beep) SndPlayFx(SND_15_BEEP); } return CBF_NONE; @@ -889,7 +889,7 @@ static CallBackFunction ToolbarBuildRailClick(Window *w) */ static CallBackFunction MenuClickBuildRail(int index) { - _last_built_railtype = (RailType)index; + _last_built_railtype = static_cast(index); ShowBuildRailToolbar(_last_built_railtype); return CBF_NONE; } @@ -911,7 +911,7 @@ static CallBackFunction ToolbarBuildRoadClick(Window *w) */ static CallBackFunction MenuClickBuildRoad(int index) { - _last_built_roadtype = (RoadType)index; + _last_built_roadtype = static_cast(index); ShowBuildRoadToolbar(_last_built_roadtype); return CBF_NONE; } @@ -933,7 +933,7 @@ static CallBackFunction ToolbarBuildTramClick(Window *w) */ static CallBackFunction MenuClickBuildTram(int index) { - _last_built_tramtype = (RoadType)index; + _last_built_tramtype = static_cast(index); ShowBuildRoadToolbar(_last_built_tramtype); return CBF_NONE; } @@ -1015,7 +1015,7 @@ static CallBackFunction MenuClickForest(int index) static CallBackFunction ToolbarMusicClick(Window *w) { - PopupMainToolbarMenu(w, _game_mode == GM_EDITOR ? (WidgetID)WID_TE_MUSIC_SOUND : (WidgetID)WID_TN_MUSIC_SOUND, {STR_TOOLBAR_SOUND_MUSIC}); + PopupMainToolbarMenu(w, _game_mode == GM_EDITOR ? static_cast(WID_TE_MUSIC_SOUND) : static_cast(WID_TN_MUSIC_SOUND), {STR_TOOLBAR_SOUND_MUSIC}); return CBF_NONE; } @@ -1070,13 +1070,13 @@ static CallBackFunction PlaceLandBlockInfo() static CallBackFunction ToolbarHelpClick(Window *w) { if (_settings_client.gui.newgrf_developer_tools) { - PopupMainToolbarMenu(w, _game_mode == GM_EDITOR ? (WidgetID)WID_TE_HELP : (WidgetID)WID_TN_HELP, {STR_ABOUT_MENU_LAND_BLOCK_INFO, + PopupMainToolbarMenu(w, _game_mode == GM_EDITOR ? static_cast(WID_TE_HELP) : static_cast(WID_TN_HELP), {STR_ABOUT_MENU_LAND_BLOCK_INFO, STR_ABOUT_MENU_HELP, STR_NULL, STR_ABOUT_MENU_TOGGLE_CONSOLE, STR_ABOUT_MENU_AI_DEBUG, STR_ABOUT_MENU_SCREENSHOT, STR_ABOUT_MENU_SHOW_FRAMERATE, STR_ABOUT_MENU_ABOUT_OPENTTD, STR_ABOUT_MENU_SPRITE_ALIGNER, STR_ABOUT_MENU_TOGGLE_BOUNDING_BOXES, STR_ABOUT_MENU_TOGGLE_DIRTY_BLOCKS, STR_ABOUT_MENU_TOGGLE_WIDGET_OUTLINES}); } else { - PopupMainToolbarMenu(w, _game_mode == GM_EDITOR ? (WidgetID)WID_TE_HELP : (WidgetID)WID_TN_HELP, {STR_ABOUT_MENU_LAND_BLOCK_INFO, + PopupMainToolbarMenu(w, _game_mode == GM_EDITOR ? static_cast(WID_TE_HELP) : static_cast(WID_TN_HELP), {STR_ABOUT_MENU_LAND_BLOCK_INFO, STR_ABOUT_MENU_HELP, STR_NULL, STR_ABOUT_MENU_TOGGLE_CONSOLE, STR_ABOUT_MENU_AI_DEBUG, STR_ABOUT_MENU_SCREENSHOT, STR_ABOUT_MENU_SHOW_FRAMERATE, STR_ABOUT_MENU_ABOUT_OPENTTD}); } @@ -1186,7 +1186,7 @@ static CallBackFunction ToolbarSwitchClick(Window *w) } w->ReInit(); - w->SetWidgetLoweredState(_game_mode == GM_EDITOR ? (WidgetID)WID_TE_SWITCH_BAR : (WidgetID)WID_TN_SWITCH_BAR, _toolbar_mode == TB_LOWER); + w->SetWidgetLoweredState(_game_mode == GM_EDITOR ? static_cast(WID_TE_SWITCH_BAR) : static_cast(WID_TN_SWITCH_BAR), _toolbar_mode == TB_LOWER); if (_settings_client.sound.click_beep) SndPlayFx(SND_15_BEEP); return CBF_NONE; } @@ -1275,7 +1275,7 @@ static CallBackFunction ToolbarScenBuildRoadClick(Window *w) */ static CallBackFunction ToolbarScenBuildRoad(int index) { - _last_built_roadtype = (RoadType)index; + _last_built_roadtype = static_cast(index); ShowBuildRoadScenToolbar(_last_built_roadtype); return CBF_NONE; } @@ -1295,7 +1295,7 @@ static CallBackFunction ToolbarScenBuildTramClick(Window *w) */ static CallBackFunction ToolbarScenBuildTram(int index) { - _last_built_tramtype = (RoadType)index; + _last_built_tramtype = static_cast(index); ShowBuildRoadScenToolbar(_last_built_tramtype); return CBF_NONE; } @@ -1448,7 +1448,7 @@ public: /* Now assign the widgets to their rightful place */ uint position = 0; // Place to put next child relative to origin of the container. - uint spacer_space = std::max(0, (int)given_width - (int)(button_count * this->smallest_x)); // Remaining spacing for 'spacer' widgets + uint spacer_space = std::max(0, static_cast(given_width) - static_cast(button_count * this->smallest_x)); // Remaining spacing for 'spacer' widgets uint button_space = given_width - spacer_space; // Remaining spacing for the buttons uint spacer_i = 0; uint button_i = 0; diff --git a/src/town_cmd.cpp b/src/town_cmd.cpp index 1a47376d4e..8c7017aee1 100644 --- a/src/town_cmd.cpp +++ b/src/town_cmd.cpp @@ -197,7 +197,7 @@ void Town::InitializeLayout(TownLayout layout) /* static */ Town *Town::GetRandom() { if (Town::GetNumItems() == 0) return nullptr; - int num = RandomRange((uint16_t)Town::GetNumItems()); + int num = RandomRange(static_cast(Town::GetNumItems())); size_t index = std::numeric_limits::max(); while (num >= 0) { @@ -258,7 +258,7 @@ static TownDrawTileProc * const _town_draw_tile_procs[1] = { */ static inline DiagDirection RandomDiagDir() { - return (DiagDirection)(RandomRange(DIAGDIR_END)); + return static_cast(RandomRange(DIAGDIR_END)); } /** @@ -917,7 +917,7 @@ static bool GrowTown(Town *t); static void TownTickHandler(Town *t) { if (HasBit(t->flags, TOWN_IS_GROWING)) { - int i = (int)t->grow_counter - 1; + int i = static_cast(t->grow_counter) - 1; if (i < 0) { if (GrowTown(t)) { i = t->growth_rate; @@ -1325,7 +1325,7 @@ static bool RedundantBridgeExistsNearby(TileIndex tile, void *user_data) if (GetTunnelBridgeTransportType(tile) != TRANSPORT_ROAD) return false; /* If the bridge is facing the same direction as the proposed bridge, we've found a redundant bridge. */ - return (GetTileSlope(tile) & InclinedSlope(ReverseDiagDir(*(DiagDirection *)user_data))); + return (GetTileSlope(tile) & InclinedSlope(ReverseDiagDir(*static_cast(user_data)))); } /** @@ -1886,7 +1886,7 @@ static RoadBits GenRandomRoadBits() uint a = GB(r, 0, 2); uint b = GB(r, 8, 2); if (a == b) b ^= 2; - return (RoadBits)((ROAD_NW << a) + (ROAD_NW << b)); + return static_cast((ROAD_NW << a) + (ROAD_NW << b)); } /** @@ -2078,7 +2078,7 @@ static void DoCreateTown(Town *t, TileIndex tile, uint32_t townnameparts, TownSi t->larger_town = city; - int x = (int)size * 16 + 3; + int x = static_cast(size) * 16 + 3; if (size == TSZ_RANDOM) x = (Random() & 0xF) + 8; /* Don't create huge cities when founding town in-game */ if (city && (!manual || _game_mode == GM_EDITOR)) x *= _settings_game.economy.initial_city_size; @@ -2307,7 +2307,7 @@ struct SpotData { */ static bool FindFurthestFromWater(TileIndex tile, void *user_data) { - SpotData *sp = (SpotData*)user_data; + SpotData *sp = static_cast(user_data); uint dist = GetClosestWaterDistance(tile, true); if (IsTileType(tile, MP_CLEAR) && @@ -2421,7 +2421,7 @@ bool GenerateTowns(TownLayout layout) { uint current_number = 0; uint difficulty = (_game_mode != GM_EDITOR) ? _settings_game.difficulty.number_towns : 0; - uint total = (difficulty == (uint)CUSTOM_TOWN_NUMBER_DIFFICULTY) ? _settings_game.game_creation.custom_town_number : Map::ScaleBySize(_num_initial_towns[difficulty] + (Random() & 7)); + uint total = (difficulty == CUSTOM_TOWN_NUMBER_DIFFICULTY) ? _settings_game.game_creation.custom_town_number : Map::ScaleBySize(_num_initial_towns[difficulty] + (Random() & 7)); total = std::min(TownPool::MAX_SIZE, total); uint32_t townnameparts; TownNames town_names; @@ -3446,7 +3446,7 @@ static bool SearchTileForStatue(TileIndex tile, void *user_data) { static const int STATUE_NUMBER_INNER_TILES = 25; // Number of tiles int the center of the city, where we try to protect houses. - StatueBuildSearchData *statue_data = (StatueBuildSearchData *)user_data; + StatueBuildSearchData *statue_data = static_cast(user_data); statue_data->tile_count++; /* Statues can be build on slopes, just like houses. Only the steep slopes is a no go. */ @@ -3729,7 +3729,7 @@ static void UpdateTownRating(Town *t) /* Increase company ratings if they're low */ for (const Company *c : Company::Iterate()) { if (t->ratings[c->index] < RATING_GROWTH_MAXIMUM) { - t->ratings[c->index] = std::min((int)RATING_GROWTH_MAXIMUM, t->ratings[c->index] + RATING_GROWTH_UP_STEP); + t->ratings[c->index] = std::min(RATING_GROWTH_MAXIMUM, t->ratings[c->index] + RATING_GROWTH_UP_STEP); } } @@ -3769,7 +3769,7 @@ static void UpdateTownGrowCounter(Town *t, uint16_t prev_growth_rate) t->grow_counter = std::min(t->growth_rate, t->grow_counter); return; } - t->grow_counter = RoundDivSU((uint32_t)t->grow_counter * (t->growth_rate + 1), prev_growth_rate + 1); + t->grow_counter = RoundDivSU(static_cast(t->grow_counter) * (t->growth_rate + 1), prev_growth_rate + 1); } /** diff --git a/src/town_gui.cpp b/src/town_gui.cpp index 944ad4b5dd..8801212039 100644 --- a/src/town_gui.cpp +++ b/src/town_gui.cpp @@ -291,7 +291,7 @@ public: break; case WID_TA_RATING_INFO: - resize.height = std::max({this->icon_size.height + WidgetDimensions::scaled.vsep_normal, this->exclusive_size.height + WidgetDimensions::scaled.vsep_normal, (uint)GetCharacterHeight(FS_NORMAL)}); + resize.height = std::max({this->icon_size.height + WidgetDimensions::scaled.vsep_normal, this->exclusive_size.height + WidgetDimensions::scaled.vsep_normal, static_cast(GetCharacterHeight(FS_NORMAL))}); size.height = 9 * resize.height + padding.height; break; } @@ -440,7 +440,7 @@ public: bool rtl = _current_text_dir == TD_RTL; - const CargoSpec *cargo = FindFirstCargoWithTownAcceptanceEffect((TownAcceptanceEffect)i); + const CargoSpec *cargo = FindFirstCargoWithTownAcceptanceEffect(static_cast(i)); assert(cargo != nullptr); StringID string; @@ -1273,7 +1273,7 @@ public: break; case WID_TF_SIZE_SMALL: case WID_TF_SIZE_MEDIUM: case WID_TF_SIZE_LARGE: case WID_TF_SIZE_RANDOM: - this->town_size = (TownSize)(widget - WID_TF_SIZE_SMALL); + this->town_size = static_cast(widget - WID_TF_SIZE_SMALL); this->UpdateButtons(false); break; @@ -1285,7 +1285,7 @@ public: case WID_TF_LAYOUT_ORIGINAL: case WID_TF_LAYOUT_BETTER: case WID_TF_LAYOUT_GRID2: case WID_TF_LAYOUT_GRID3: case WID_TF_LAYOUT_RANDOM: - this->town_layout = (TownLayout)(widget - WID_TF_LAYOUT_ORIGINAL); + this->town_layout = static_cast(widget - WID_TF_LAYOUT_ORIGINAL); /* If we are in the editor, sync the settings of the current game to the chosen layout, * so that importing towns from file uses the selected layout. */ diff --git a/src/townname.cpp b/src/townname.cpp index fdef1a118d..3998592550 100644 --- a/src/townname.cpp +++ b/src/townname.cpp @@ -653,7 +653,7 @@ static void MakeCzechTownName(StringBuilder &builder, uint32_t seed) } /* Localize the array segment containing a good gender */ - for (ending = 0; ending < (int)std::size(_name_czech_subst_ending); ending++) { + for (ending = 0; ending < static_cast(std::size(_name_czech_subst_ending)); ending++) { const CzechNameSubst *e = &_name_czech_subst_ending[ending]; if (gender == CZG_FREE || @@ -684,7 +684,7 @@ static void MakeCzechTownName(StringBuilder &builder, uint32_t seed) assert(i > 0); /* Load the ending */ - ending = map[SeedModChance(16, (int)i, seed)]; + ending = map[SeedModChance(16, static_cast(i), seed)]; /* Override possible CZG_*FREE; this must be a real gender, * otherwise we get overflow when modifying the adjectivum. */ gender = _name_czech_subst_ending[ending].gender; diff --git a/src/train_cmd.cpp b/src/train_cmd.cpp index ad2a61df98..cc786d26be 100644 --- a/src/train_cmd.cpp +++ b/src/train_cmd.cpp @@ -445,7 +445,7 @@ int Train::GetCursorImageOffset() const reference_width = e->GetGRF()->traininfo_vehicle_width; } - return ScaleSpriteTrad((this->gcache.cached_veh_length - (int)VEHICLE_LENGTH) * reference_width / (int)VEHICLE_LENGTH); + return ScaleSpriteTrad((this->gcache.cached_veh_length - static_cast(VEHICLE_LENGTH)) * reference_width / static_cast(VEHICLE_LENGTH)); } return 0; } @@ -468,7 +468,7 @@ int Train::GetDisplayImageWidth(Point *offset) const if (offset != nullptr) { if (HasBit(this->flags, VRF_REVERSE_DIRECTION) && !EngInfo(this->engine_type)->misc_flags.Test(EngineMiscFlag::RailFlips)) { - offset->x = ScaleSpriteTrad(((int)this->gcache.cached_veh_length - (int)VEHICLE_LENGTH / 2) * reference_width / (int)VEHICLE_LENGTH); + offset->x = ScaleSpriteTrad((static_cast(this->gcache.cached_veh_length) - static_cast(VEHICLE_LENGTH) / 2) * reference_width / static_cast(VEHICLE_LENGTH)); } else { offset->x = ScaleSpriteTrad(reference_width) / 2; } @@ -1701,7 +1701,7 @@ static Vehicle *TrainApproachingCrossingEnum(Vehicle *v, void *data) Train *t = Train::From(v); if (!t->IsFrontEngine()) return nullptr; - TileIndex tile = *(TileIndex *)data; + TileIndex tile = *static_cast(data); if (TrainApproachingCrossingTile(t) != tile) return nullptr; @@ -2703,7 +2703,7 @@ static Track ChooseTrainTrack(Train *v, TileIndex tile, DiagDirection enterdir, if (got_reservation != nullptr) *got_reservation = false; /* Don't use tracks here as the setting to forbid 90 deg turns might have been switched between reservation and now. */ - TrackBits res_tracks = (TrackBits)(GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir)); + TrackBits res_tracks = (GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir)); /* Do we have a suitable reserved track? */ if (res_tracks != TRACK_BIT_NONE) return FindFirstTrack(res_tracks); @@ -2808,7 +2808,7 @@ static Track ChooseTrainTrack(Train *v, TileIndex tile, DiagDirection enterdir, /* Extend reservation until we have found a safe position. */ DiagDirection exitdir = TrackdirToExitdir(res_dest.trackdir); TileIndex next_tile = TileAddByDiagDir(res_dest.tile, exitdir); - TrackBits reachable = TrackdirBitsToTrackBits((TrackdirBits)(GetTileTrackStatus(next_tile, TRANSPORT_RAIL, 0))) & DiagdirReachesTracks(exitdir); + TrackBits reachable = TrackdirBitsToTrackBits(static_cast(GetTileTrackStatus(next_tile, TRANSPORT_RAIL, 0))) & DiagdirReachesTracks(exitdir); if (Rail90DegTurnDisallowed(GetTileRailType(res_dest.tile), GetTileRailType(next_tile))) { reachable &= ~TrackCrossesTracks(TrackdirToTrack(res_dest.trackdir)); } @@ -3177,7 +3177,7 @@ struct TrainCollideChecker { */ static Vehicle *FindTrainCollideEnum(Vehicle *v, void *data) { - TrainCollideChecker *tcc = (TrainCollideChecker*)data; + TrainCollideChecker *tcc = static_cast(data); /* not a train or in depot */ if (v->type != VEH_TRAIN || Train::From(v)->track == TRACK_BIT_DEPOT) return nullptr; @@ -3256,7 +3256,7 @@ static Vehicle *CheckTrainAtSignal(Vehicle *v, void *data) if (v->type != VEH_TRAIN || v->vehstatus.Test(VehState::Crashed)) return nullptr; Train *t = Train::From(v); - DiagDirection exitdir = *(DiagDirection *)data; + DiagDirection exitdir = *static_cast(data); /* not front engine of a train, inside wormhole or depot, crashed */ if (!t->IsFrontEngine() || !(t->track & TRACK_BIT_MASK)) return nullptr; @@ -3443,7 +3443,7 @@ bool TrainController(Train *v, Vehicle *nomove, bool reverse) const uint8_t *b = _initial_tile_subcoord[FindFirstBit(chosen_track)][enterdir]; gp.x = (gp.x & ~0xF) | b[0]; gp.y = (gp.y & ~0xF) | b[1]; - Direction chosen_dir = (Direction)b[2]; + Direction chosen_dir = static_cast(b[2]); /* Call the landscape function and tell it that the vehicle entered the tile */ uint32_t r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y); @@ -3596,7 +3596,7 @@ reverse_train_direction: */ static Vehicle *CollectTrackbitsFromCrashedVehiclesEnum(Vehicle *v, void *data) { - TrackBits *trackbits = (TrackBits *)data; + TrackBits *trackbits = static_cast(data); if (v->type == VEH_TRAIN && v->vehstatus.Test(VehState::Crashed)) { TrackBits train_tbits = Train::From(v)->track; diff --git a/src/train_gui.cpp b/src/train_gui.cpp index a0c5804e56..0ea6867166 100644 --- a/src/train_gui.cpp +++ b/src/train_gui.cpp @@ -327,10 +327,10 @@ int GetTrainDetailsWndVScroll(VehicleID veh_id, TrainDetailsWindowTabs det_tab) } else { for (const Train *v = Train::Get(veh_id); v != nullptr; v = v->GetNextVehicle()) { GetCargoSummaryOfArticulatedVehicle(v, _cargo_summary); - num += std::max(1u, (unsigned)_cargo_summary.size()); + num += std::max(1u, static_cast(_cargo_summary.size())); uint length = GetLengthOfArticulatedVehicle(v); - if (length > (uint)ScaleSpriteTrad(TRAIN_DETAILS_MAX_INDENT)) num++; + if (length > static_cast(ScaleSpriteTrad(TRAIN_DETAILS_MAX_INDENT))) num++; } } @@ -383,7 +383,7 @@ void DrawTrainDetails(const Train *v, const Rect &r, int vscroll_pos, uint16_t v u = u->Next(); } while (u != nullptr && u->IsArticulatedPart()); - bool separate_sprite_row = (dx > (uint)ScaleSpriteTrad(TRAIN_DETAILS_MAX_INDENT)); + bool separate_sprite_row = (dx > static_cast(ScaleSpriteTrad(TRAIN_DETAILS_MAX_INDENT))); if (separate_sprite_row) { vscroll_pos--; dx = 0; @@ -391,7 +391,7 @@ void DrawTrainDetails(const Train *v, const Rect &r, int vscroll_pos, uint16_t v int sprite_width = std::max(dx, ScaleSpriteTrad(TRAIN_DETAILS_MIN_INDENT)) + WidgetDimensions::scaled.hsep_normal; Rect dr = r.Indent(sprite_width, rtl); - uint num_lines = std::max(1u, (unsigned)_cargo_summary.size()); + uint num_lines = std::max(1u, static_cast(_cargo_summary.size())); for (uint i = 0; i < num_lines; i++) { if (vscroll_pos <= 0 && vscroll_pos > -vscroll_cap) { int py = r.top - line_height * vscroll_pos + text_y_offset; diff --git a/src/transparency_gui.cpp b/src/transparency_gui.cpp index 4591a610c8..ec5fc4cef6 100644 --- a/src/transparency_gui.cpp +++ b/src/transparency_gui.cpp @@ -75,11 +75,11 @@ public: if (widget >= WID_TT_BEGIN && widget < WID_TT_END) { if (_ctrl_pressed) { /* toggle the bit of the transparencies lock variable */ - ToggleTransparencyLock((TransparencyOption)(widget - WID_TT_BEGIN)); + ToggleTransparencyLock(static_cast(widget - WID_TT_BEGIN)); this->SetDirty(); } else { /* toggle the bit of the transparencies variable and play a sound */ - ToggleTransparency((TransparencyOption)(widget - WID_TT_BEGIN)); + ToggleTransparency(static_cast(widget - WID_TT_BEGIN)); if (_settings_client.sound.click_beep) SndPlayFx(SND_15_BEEP); MarkWholeScreenDirty(); } @@ -93,11 +93,11 @@ public: } if (i == WID_TT_TEXT|| i == WID_TT_END) return; - ToggleInvisibility((TransparencyOption)(i - WID_TT_BEGIN)); + ToggleInvisibility(static_cast(i - WID_TT_BEGIN)); if (_settings_client.sound.click_beep) SndPlayFx(SND_15_BEEP); /* Redraw whole screen only if transparency is set */ - if (IsTransparencySet((TransparencyOption)(i - WID_TT_BEGIN))) { + if (IsTransparencySet(static_cast(i - WID_TT_BEGIN))) { MarkWholeScreenDirty(); } else { this->SetWidgetDirty(WID_TT_BUTTONS); @@ -121,7 +121,7 @@ public: { if (!gui_scope) return; for (WidgetID i = WID_TT_BEGIN; i < WID_TT_END; i++) { - this->SetWidgetLoweredState(i, IsTransparencySet((TransparencyOption)(i - WID_TT_BEGIN))); + this->SetWidgetLoweredState(i, IsTransparencySet(static_cast(i - WID_TT_BEGIN))); } } }; diff --git a/src/tree_cmd.cpp b/src/tree_cmd.cpp index 7df13e934b..c06b0c6e31 100644 --- a/src/tree_cmd.cpp +++ b/src/tree_cmd.cpp @@ -179,7 +179,7 @@ static void PlaceTree(TileIndex tile, uint32_t r) /* Rerandomize ground, if neither snow nor shore */ TreeGround ground = GetTreeGround(tile); if (ground != TREE_GROUND_SNOW_DESERT && ground != TREE_GROUND_ROUGH_SNOW && ground != TREE_GROUND_SHORE) { - SetTreeGroundDensity(tile, (TreeGround)GB(r, 28, 1), 3); + SetTreeGroundDensity(tile, static_cast(GB(r, 28, 1)), 3); } } } @@ -559,7 +559,7 @@ CommandCost CmdPlantTree(DoCommandFlags flags, TileIndex tile, TileIndex start_t continue; } - TreeType treetype = (TreeType)tree_to_plant; + TreeType treetype = static_cast(tree_to_plant); /* Be a bit picky about which trees go where. */ if (_settings_game.game_creation.landscape == LandscapeType::Tropic && treetype != TREE_INVALID && ( /* No cacti outside the desert */ @@ -693,7 +693,7 @@ static void DrawTile_Trees(TileInfo *ti) uint mi = 0; for (uint i = 1; i < trees; i++) { - if ((uint)(te[i].x + te[i].y) < min) { + if (static_cast(te[i].x + te[i].y) < min) { min = te[i].x + te[i].y; mi = i; } diff --git a/src/tree_gui.cpp b/src/tree_gui.cpp index e177146cd9..94426f1f50 100644 --- a/src/tree_gui.cpp +++ b/src/tree_gui.cpp @@ -64,7 +64,7 @@ static Dimension GetMaxTreeSpriteSize() offset.y = 0; for (int i = base; i < base + count; i++) { - if (i >= (int)lengthof(tree_sprites)) return size; + if (i >= static_castlengthof(tree_sprites)) return size; this_size = GetSpriteSize(tree_sprites[i].sprite, &offset); size.width = std::max(size.width, 2 * std::max(this_size.width, -offset.x)); size.height = std::max(size.height, std::max(this_size.height, -offset.y)); @@ -128,9 +128,9 @@ class BuildTreesWindow : public Window void DoPlantForest(TileIndex tile) { - TreeType treetype = (TreeType)this->tree_to_plant; + TreeType treetype = static_cast(this->tree_to_plant); if (this->tree_to_plant == TREE_INVALID) { - treetype = (TreeType)(InteractiveRandomRange(_tree_count_by_landscape[to_underlying(_settings_game.game_creation.landscape)]) + _tree_base_by_landscape[to_underlying(_settings_game.game_creation.landscape)]); + treetype = static_cast(InteractiveRandomRange(_tree_count_by_landscape[to_underlying(_settings_game.game_creation.landscape)]) + _tree_base_by_landscape[to_underlying(_settings_game.game_creation.landscape)]); } const uint radius = this->mode == PM_FOREST_LG ? 12 : 5; const uint count = this->mode == PM_FOREST_LG ? 12 : 5; diff --git a/src/tunnelbridge_cmd.cpp b/src/tunnelbridge_cmd.cpp index cfcae74c6d..ec51790eff 100644 --- a/src/tunnelbridge_cmd.cpp +++ b/src/tunnelbridge_cmd.cpp @@ -257,12 +257,12 @@ CommandCost CmdBuildBridge(DoCommandFlags flags, TileIndex tile_end, TileIndex t /* type of bridge */ switch (transport_type) { case TRANSPORT_ROAD: - roadtype = (RoadType)road_rail_type; + roadtype = static_cast(road_rail_type); if (!ValParamRoadType(roadtype)) return CMD_ERROR; break; case TRANSPORT_RAIL: - railtype = (RailType)road_rail_type; + railtype = static_cast(road_rail_type); if (!ValParamRailType(railtype)) return CMD_ERROR; break; @@ -587,10 +587,10 @@ CommandCost CmdBuildBridge(DoCommandFlags flags, TileIndex tile_end, TileIndex t if (c != nullptr) bridge_len = CalcBridgeLenCostFactor(bridge_len); if (transport_type != TRANSPORT_WATER) { - cost.AddCost((int64_t)bridge_len * _price[PR_BUILD_BRIDGE] * GetBridgeSpec(bridge_type)->price >> 8); + cost.AddCost(static_cast(bridge_len) * _price[PR_BUILD_BRIDGE] * GetBridgeSpec(bridge_type)->price >> 8); } else { /* Aqueducts use a separate base cost. */ - cost.AddCost((int64_t)bridge_len * _price[PR_BUILD_AQUEDUCT]); + cost.AddCost(static_cast(bridge_len) * _price[PR_BUILD_AQUEDUCT]); } } @@ -616,12 +616,12 @@ CommandCost CmdBuildTunnel(DoCommandFlags flags, TileIndex start_tile, Transport _build_tunnel_endtile = TileIndex{}; switch (transport_type) { case TRANSPORT_RAIL: - railtype = (RailType)road_rail_type; + railtype = static_cast(road_rail_type); if (!ValParamRailType(railtype)) return CMD_ERROR; break; case TRANSPORT_ROAD: - roadtype = (RoadType)road_rail_type; + roadtype = static_cast(road_rail_type); if (!ValParamRoadType(roadtype)) return CMD_ERROR; break; @@ -740,7 +740,7 @@ CommandCost CmdBuildTunnel(DoCommandFlags flags, TileIndex start_tile, Transport coa = nullptr; ret = std::get<0>(Command::Do(flags, end_tile, end_tileh & start_tileh, false)); - _cleared_object_areas[(uint)coa_index].first_tile = old_first_tile; + _cleared_object_areas[static_cast(coa_index)].first_tile = old_first_tile; if (ret.Failed()) return CommandCost(STR_ERROR_UNABLE_TO_EXCAVATE_LAND); cost.AddCost(ret); } @@ -891,8 +891,8 @@ static CommandCost DoClearTunnel(TileIndex tile, DoCommandFlags flags) if (v != nullptr) TryPathReserve(v); } else { /* A full diagonal road tile has two road bits. */ - UpdateCompanyRoadInfrastructure(GetRoadTypeRoad(tile), GetRoadOwner(tile, RTT_ROAD), -(int)(len * 2 * TUNNELBRIDGE_TRACKBIT_FACTOR)); - UpdateCompanyRoadInfrastructure(GetRoadTypeTram(tile), GetRoadOwner(tile, RTT_TRAM), -(int)(len * 2 * TUNNELBRIDGE_TRACKBIT_FACTOR)); + UpdateCompanyRoadInfrastructure(GetRoadTypeRoad(tile), GetRoadOwner(tile, RTT_ROAD), -static_cast(len * 2 * TUNNELBRIDGE_TRACKBIT_FACTOR)); + UpdateCompanyRoadInfrastructure(GetRoadTypeTram(tile), GetRoadOwner(tile, RTT_TRAM), -static_cast(len * 2 * TUNNELBRIDGE_TRACKBIT_FACTOR)); DoClearSquare(tile); DoClearSquare(endtile); @@ -958,8 +958,8 @@ static CommandCost DoClearBridge(TileIndex tile, DoCommandFlags flags) if (Company::IsValidID(owner)) Company::Get(owner)->infrastructure.rail[GetRailType(tile)] -= len * TUNNELBRIDGE_TRACKBIT_FACTOR; } else if (GetTunnelBridgeTransportType(tile) == TRANSPORT_ROAD) { /* A full diagonal road tile has two road bits. */ - UpdateCompanyRoadInfrastructure(GetRoadTypeRoad(tile), GetRoadOwner(tile, RTT_ROAD), -(int)(len * 2 * TUNNELBRIDGE_TRACKBIT_FACTOR)); - UpdateCompanyRoadInfrastructure(GetRoadTypeTram(tile), GetRoadOwner(tile, RTT_TRAM), -(int)(len * 2 * TUNNELBRIDGE_TRACKBIT_FACTOR)); + UpdateCompanyRoadInfrastructure(GetRoadTypeRoad(tile), GetRoadOwner(tile, RTT_ROAD), -static_cast(len * 2 * TUNNELBRIDGE_TRACKBIT_FACTOR)); + UpdateCompanyRoadInfrastructure(GetRoadTypeTram(tile), GetRoadOwner(tile, RTT_TRAM), -static_cast(len * 2 * TUNNELBRIDGE_TRACKBIT_FACTOR)); } else { // Aqueduct if (Company::IsValidID(owner)) Company::Get(owner)->infrastructure.water -= len * TUNNELBRIDGE_TRACKBIT_FACTOR; } @@ -1097,7 +1097,7 @@ static void DrawBridgePillars(const PalSpriteID *psid, const TileInfo *ti, Axis if (z_front_south < z_front) DrawPillar(psid, x, y, bottom_z, w, h, &half_pillar_sub_sprite[axis][1]); /* Draw back pillars, skip top two parts, which are hidden by the bridge */ - int z_bridge_back = z_bridge - 2 * (int)TILE_HEIGHT; + int z_bridge_back = z_bridge - 2 * static_cast(TILE_HEIGHT); if (drawfarpillar && (z_back_north <= z_bridge_back || z_back_south <= z_bridge_back)) { bottom_z = DrawPillarColumn(z_back, z_bridge_back, psid, x_back, y_back, w, h); if (z_back_north < z_back) DrawPillar(psid, x_back, y_back, bottom_z, w, h, &half_pillar_sub_sprite[axis][0]); diff --git a/src/vehicle.cpp b/src/vehicle.cpp index 06103c8197..f82cdaf3d8 100644 --- a/src/vehicle.cpp +++ b/src/vehicle.cpp @@ -527,7 +527,7 @@ bool HasVehicleOnPos(TileIndex tile, void *data, VehicleFromPosProc *proc) */ static Vehicle *EnsureNoVehicleProcZ(Vehicle *v, void *data) { - int z = *(int*)data; + int z = *static_cast(data); if (v->type == VEH_DISASTER || (v->type == VEH_AIRCRAFT && v->subtype == AIR_SHADOW)) return nullptr; if (v->z_pos > z) return nullptr; @@ -557,7 +557,7 @@ CommandCost EnsureNoVehicleOnGround(TileIndex tile) static Vehicle *GetVehicleTunnelBridgeProc(Vehicle *v, void *data) { if (v->type != VEH_TRAIN && v->type != VEH_ROAD && v->type != VEH_SHIP) return nullptr; - if (v == (const Vehicle *)data) return nullptr; + if (v == static_cast(data)) return nullptr; return v; } @@ -584,7 +584,7 @@ CommandCost TunnelBridgeIsFree(TileIndex tile, TileIndex endtile, const Vehicle static Vehicle *EnsureNoTrainOnTrackProc(Vehicle *v, void *data) { - TrackBits rail_bits = *(TrackBits *)data; + TrackBits rail_bits = *static_cast(data); if (v->type != VEH_TRAIN) return nullptr; @@ -1082,9 +1082,9 @@ void CallVehicleTicks() int z = v->z_pos; const Company *c = Company::Get(_current_company); - SubtractMoneyFromCompany(CommandCost(EXPENSES_NEW_VEHICLES, (Money)c->settings.engine_renew_money)); + SubtractMoneyFromCompany(CommandCost(EXPENSES_NEW_VEHICLES, Money(c->settings.engine_renew_money))); CommandCost res = Command::Do(DoCommandFlag::Execute, v->index); - SubtractMoneyFromCompany(CommandCost(EXPENSES_NEW_VEHICLES, -(Money)c->settings.engine_renew_money)); + SubtractMoneyFromCompany(CommandCost(EXPENSES_NEW_VEHICLES, -Money(c->settings.engine_renew_money))); if (!IsLocalCompany()) continue; @@ -1244,7 +1244,7 @@ Vehicle *CheckClickOnVehicle(const Viewport *vp, int x, int y) Vehicle *found = nullptr; uint dist, best_dist = UINT_MAX; - if ((uint)(x -= vp->left) >= (uint)vp->width || (uint)(y -= vp->top) >= (uint)vp->height) return nullptr; + if (static_cast(x -= vp->left) >= static_cast(vp->width) || static_cast(y -= vp->top) >= static_cast(vp->height)) return nullptr; x = ScaleByZoom(x, vp->zoom) + vp->virtual_left; y = ScaleByZoom(y, vp->zoom) + vp->virtual_top; @@ -2109,7 +2109,7 @@ static PaletteID GetEngineColourMap(EngineID engine_type, CompanyID company, Eng bool twocc = e->info.misc_flags.Test(EngineMiscFlag::Uses2CC); - if (map == PAL_NONE) map = twocc ? (PaletteID)SPR_2CCMAP_BASE : (PaletteID)PALETTE_RECOLOUR_START; + if (map == PAL_NONE) map = twocc ? static_cast(SPR_2CCMAP_BASE) : PALETTE_RECOLOUR_START; /* Spectator has news shown too, but has invalid company ID - as well as dedicated server */ if (!Company::IsValidID(company)) return map; @@ -2732,7 +2732,7 @@ static void SpawnAdvancedVisualEffect(const Vehicle *v) int8_t l_center = 0; if (auto_center) { /* For road vehicles: Compute offset from vehicle position to vehicle center */ - if (v->type == VEH_ROAD) l_center = -(int)(VEHICLE_LENGTH - RoadVehicle::From(v)->gcache.cached_veh_length) / 2; + if (v->type == VEH_ROAD) l_center = -static_cast(VEHICLE_LENGTH - RoadVehicle::From(v)->gcache.cached_veh_length) / 2; } else { /* For trains: Compute offset from vehicle position to sprite position */ if (v->type == VEH_TRAIN) l_center = (VEHICLE_LENGTH - Train::From(v)->gcache.cached_veh_length) / 2; @@ -2815,14 +2815,14 @@ void Vehicle::ShowVisualEffect() const VisualEffectSpawnModel effect_model = VESM_NONE; if (advanced) { effect_offset = VE_OFFSET_CENTRE; - effect_model = (VisualEffectSpawnModel)GB(v->vcache.cached_vis_effect, 0, VE_ADVANCED_EFFECT); + effect_model = static_cast(GB(v->vcache.cached_vis_effect, 0, VE_ADVANCED_EFFECT)); if (effect_model >= VESM_END) effect_model = VESM_NONE; // unknown spawning model } else { - effect_model = (VisualEffectSpawnModel)GB(v->vcache.cached_vis_effect, VE_TYPE_START, VE_TYPE_COUNT); + effect_model = static_cast(GB(v->vcache.cached_vis_effect, VE_TYPE_START, VE_TYPE_COUNT)); assert(effect_model != (VisualEffectSpawnModel)VE_TYPE_DEFAULT); // should have been resolved by UpdateVisualEffect - static_assert((uint)VESM_STEAM == (uint)VE_TYPE_STEAM); - static_assert((uint)VESM_DIESEL == (uint)VE_TYPE_DIESEL); - static_assert((uint)VESM_ELECTRIC == (uint)VE_TYPE_ELECTRIC); + static_assert(static_cast(VESM_STEAM) == static_cast(VE_TYPE_STEAM)); + static_assert(static_cast(VESM_DIESEL) == static_cast(VE_TYPE_DIESEL)); + static_assert(static_cast(VESM_ELECTRIC) == static_cast(VE_TYPE_ELECTRIC)); } /* Show no smoke when: diff --git a/src/vehicle_cmd.cpp b/src/vehicle_cmd.cpp index 8193c85927..682b3145b7 100644 --- a/src/vehicle_cmd.cpp +++ b/src/vehicle_cmd.cpp @@ -804,7 +804,7 @@ static void CloneVehicleName(const Vehicle *src, Vehicle *dst) buf = src->name.substr(0, number_position); auto num_str = src->name.substr(number_position); - padding = (uint8_t)num_str.length(); + padding = static_cast(num_str.length()); std::istringstream iss(num_str); iss >> num; diff --git a/src/vehicle_gui.cpp b/src/vehicle_gui.cpp index c801a91a75..15a529fa8c 100644 --- a/src/vehicle_gui.cpp +++ b/src/vehicle_gui.cpp @@ -960,7 +960,7 @@ struct RefitWindow : public Window { /* Calculate sprite position. */ NWidgetCore *vehicle_panel_display = this->GetWidget(WID_VR_VEHICLE_PANEL_DISPLAY); - int sprite_width = std::max(0, ((int)vehicle_panel_display->current_x - this->vehicle_width) / 2); + int sprite_width = std::max(0, (static_cast(vehicle_panel_display->current_x) - this->vehicle_width) / 2); this->sprite_left = vehicle_panel_display->pos_x; this->sprite_right = vehicle_panel_display->pos_x + vehicle_panel_display->current_x - 1; if (_current_text_dir == TD_RTL) { @@ -2296,7 +2296,7 @@ void ShowVehicleListWindow(CompanyID company, VehicleType vehicle_type) * if _ctrl_pressed, do the opposite action (Advanced list x Normal list) */ - if ((_settings_client.gui.advanced_vehicle_list > (uint)(company != _local_company)) != _ctrl_pressed) { + if ((_settings_client.gui.advanced_vehicle_list > static_cast(company != _local_company)) != _ctrl_pressed) { ShowCompanyGroup(company, vehicle_type); } else { ShowVehicleListWindowLocal(company, VL_STANDARD, vehicle_type, company.base()); @@ -2747,7 +2747,7 @@ struct VehicleDetailsWindow : Window { WID_VD_DETAILS_CAPACITY_OF_EACH, WID_VD_DETAILS_TOTAL_CARGO); - this->tab = (TrainDetailsWindowTabs)(widget - WID_VD_DETAILS_CARGO_CARRIED); + this->tab = static_cast(widget - WID_VD_DETAILS_CARGO_CARRIED); this->SetDirty(); break; } @@ -3062,7 +3062,7 @@ public: const Vehicle *v = Vehicle::Get(this->window_number); switch (widget) { case WID_VV_START_STOP: - size.height = std::max({size.height, (uint)GetCharacterHeight(FS_NORMAL), GetScaledSpriteSize(SPR_WARNING_SIGN).height, GetScaledSpriteSize(SPR_FLAG_VEH_STOPPED).height, GetScaledSpriteSize(SPR_FLAG_VEH_RUNNING).height}) + padding.height; + size.height = std::max({size.height, static_cast(GetCharacterHeight(FS_NORMAL)), GetScaledSpriteSize(SPR_WARNING_SIGN).height, GetScaledSpriteSize(SPR_FLAG_VEH_STOPPED).height, GetScaledSpriteSize(SPR_FLAG_VEH_RUNNING).height}) + padding.height; break; case WID_VV_FORCE_PROCEED: @@ -3555,7 +3555,7 @@ void SetMouseCursorVehicle(const Vehicle *v, EngineImageType image_type) bool is_ground_vehicle = v->IsGroundVehicle(); while (v != nullptr) { - if (total_width >= ScaleSpriteTrad(2 * (int)VEHICLEINFO_FULL_VEHICLE_WIDTH)) break; + if (total_width >= ScaleSpriteTrad(2 * static_cast(VEHICLEINFO_FULL_VEHICLE_WIDTH))) break; PaletteID pal = v->vehstatus.Test(VehState::Crashed) ? PALETTE_CRASH : GetVehiclePalette(v); VehicleSpriteSeq seq; diff --git a/src/video/opengl.cpp b/src/video/opengl.cpp index 561324d6f1..61c087736e 100644 --- a/src/video/opengl.cpp +++ b/src/video/opengl.cpp @@ -171,7 +171,7 @@ static bool IsOpenGLExtensionSupported(const char *extension) /* Starting with OpenGL 3.0 the preferred API to get the extensions * has changed. Try to load the required function once. */ if (!glGetStringi_loaded) { - if (IsOpenGLVersionAtLeast(3, 0)) glGetStringi = (PFNGLGETSTRINGIPROC)GetOGLProcAddress("glGetStringi"); + if (IsOpenGLVersionAtLeast(3, 0)) glGetStringi = reinterpret_cast(GetOGLProcAddress("glGetStringi")); glGetStringi_loaded = true; } @@ -181,12 +181,12 @@ static bool IsOpenGLExtensionSupported(const char *extension) _glGetIntegerv(GL_NUM_EXTENSIONS, &num_exts); for (GLint i = 0; i < num_exts; i++) { - const char *entry = (const char *)glGetStringi(GL_EXTENSIONS, i); + const char *entry = reinterpret_cast(glGetStringi(GL_EXTENSIONS, i)); if (strcmp(entry, extension) == 0) return true; } } else { /* Old style: A single, space-delimited string for all extensions. */ - return FindStringInExtensionList((const char *)_glGetString(GL_EXTENSIONS), extension) != nullptr; + return FindStringInExtensionList(reinterpret_cast(_glGetString(GL_EXTENSIONS)), extension) != nullptr; } return false; @@ -525,9 +525,9 @@ std::optional OpenGLBackend::Init(const Dimension &screen_res) if (!BindBasicInfoProcs()) return "OpenGL not supported"; /* Always query the supported OpenGL version as the current context might have changed. */ - const char *ver = (const char *)_glGetString(GL_VERSION); - const char *vend = (const char *)_glGetString(GL_VENDOR); - const char *renderer = (const char *)_glGetString(GL_RENDERER); + const char *ver = reinterpret_cast(_glGetString(GL_VERSION)); + const char *vend = reinterpret_cast(_glGetString(GL_VENDOR)); + const char *renderer = reinterpret_cast(_glGetString(GL_RENDERER)); if (ver == nullptr || vend == nullptr || renderer == nullptr) return "OpenGL not supported"; @@ -587,7 +587,7 @@ std::optional OpenGLBackend::Init(const Dimension &screen_res) /* Check maximum texture size against screen resolution. */ GLint max_tex_size = 0; _glGetIntegerv(GL_MAX_TEXTURE_SIZE, &max_tex_size); - if (std::max(screen_res.width, screen_res.height) > (uint)max_tex_size) return "Max supported texture size is too small"; + if (std::max(screen_res.width, screen_res.height) > static_cast(max_tex_size)) return "Max supported texture size is too small"; /* Check available texture units. */ GLint max_tex_units = 0; @@ -801,7 +801,7 @@ static bool VerifyProgram(GLuint program) */ bool OpenGLBackend::InitShaders() { - const char *ver = (const char *)_glGetString(GL_SHADING_LANGUAGE_VERSION); + const char *ver = reinterpret_cast(_glGetString(GL_SHADING_LANGUAGE_VERSION)); if (ver == nullptr) return false; int glsl_major = ver[0] - '0'; @@ -1007,7 +1007,7 @@ bool OpenGLBackend::Resize(int w, int h, bool force) /* Update screen size in remap shader program. */ _glUseProgram(this->remap_program); - _glUniform2f(this->remap_screen_loc, (float)_screen.width, (float)_screen.height); + _glUniform2f(this->remap_screen_loc, static_cast(_screen.width), static_cast(_screen.height)); _glClear(GL_COLOR_BUFFER_BIT); @@ -1100,7 +1100,7 @@ void OpenGLBackend::PopulateCursorCache() if (this->clear_cursor_cache) { /* We have a pending cursor cache clear to do first. */ this->clear_cursor_cache = false; - this->last_sprite_pal = (PaletteID)-1; + this->last_sprite_pal = static_cast(-1); this->InternalClearCursorCache(); } @@ -1181,7 +1181,7 @@ uint8_t *OpenGLBackend::GetAnimBuffer() this->anim_buffer = _glMapBufferRange(GL_PIXEL_UNPACK_BUFFER, 0, static_cast(_screen.pitch) * _screen.height, GL_MAP_READ_BIT | GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT); } - return (uint8_t *)this->anim_buffer; + return static_cast(this->anim_buffer); } /** @@ -1211,9 +1211,9 @@ void OpenGLBackend::ReleaseVideoBuffer(const Rect &update_rect) _glBindTexture(GL_TEXTURE_2D, this->vid_texture); _glPixelStorei(GL_UNPACK_ROW_LENGTH, _screen.pitch); if (BlitterFactory::GetCurrentBlitter()->GetScreenDepth() == 8) { - _glTexSubImage2D(GL_TEXTURE_2D, 0, update_rect.left, update_rect.top, update_rect.right - update_rect.left, update_rect.bottom - update_rect.top, GL_RED, GL_UNSIGNED_BYTE, (GLvoid*)(size_t)(update_rect.top * _screen.pitch + update_rect.left)); + _glTexSubImage2D(GL_TEXTURE_2D, 0, update_rect.left, update_rect.top, update_rect.right - update_rect.left, update_rect.bottom - update_rect.top, GL_RED, GL_UNSIGNED_BYTE, (GLvoid*)static_cast(update_rect.top * _screen.pitch + update_rect.left)); } else { - _glTexSubImage2D(GL_TEXTURE_2D, 0, update_rect.left, update_rect.top, update_rect.right - update_rect.left, update_rect.bottom - update_rect.top, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, (GLvoid*)(size_t)(update_rect.top * _screen.pitch * 4 + update_rect.left * 4)); + _glTexSubImage2D(GL_TEXTURE_2D, 0, update_rect.left, update_rect.top, update_rect.right - update_rect.left, update_rect.bottom - update_rect.top, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, (GLvoid*)static_cast(update_rect.top * _screen.pitch * 4 + update_rect.left * 4)); } #ifndef NO_GL_BUFFER_SYNC @@ -1248,7 +1248,7 @@ void OpenGLBackend::ReleaseAnimBuffer(const Rect &update_rect) _glActiveTexture(GL_TEXTURE0); _glBindTexture(GL_TEXTURE_2D, this->anim_texture); _glPixelStorei(GL_UNPACK_ROW_LENGTH, _screen.pitch); - _glTexSubImage2D(GL_TEXTURE_2D, 0, update_rect.left, update_rect.top, update_rect.right - update_rect.left, update_rect.bottom - update_rect.top, GL_RED, GL_UNSIGNED_BYTE, (GLvoid *)(size_t)(update_rect.top * _screen.pitch + update_rect.left)); + _glTexSubImage2D(GL_TEXTURE_2D, 0, update_rect.left, update_rect.top, update_rect.right - update_rect.left, update_rect.bottom - update_rect.top, GL_RED, GL_UNSIGNED_BYTE, (GLvoid *)static_cast(update_rect.top * _screen.pitch + update_rect.left)); #ifndef NO_GL_BUFFER_SYNC if (this->persistent_mapping_supported) this->sync_anim_mapping = _glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0); @@ -1302,9 +1302,9 @@ void OpenGLBackend::RenderOglSprite(OpenGLSprite *gl_sprite, PaletteID pal, int /* Set up shader program. */ Dimension dim = gl_sprite->GetSize(zoom); _glUseProgram(this->sprite_program); - _glUniform4f(this->sprite_sprite_loc, (float)x, (float)y, (float)dim.width, (float)dim.height); - _glUniform1f(this->sprite_zoom_loc, (float)zoom); - _glUniform2f(this->sprite_screen_loc, (float)_screen.width, (float)_screen.height); + _glUniform4f(this->sprite_sprite_loc, static_cast(x), static_cast(y), static_cast(dim.width), static_cast(dim.height)); + _glUniform1f(this->sprite_zoom_loc, static_cast(zoom)); + _glUniform2f(this->sprite_screen_loc, static_cast(_screen.width), static_cast(_screen.height)); _glUniform1i(this->sprite_rgb_loc, rgb ? 1 : 0); _glUniform1i(this->sprite_crash_loc, pal == PALETTE_CRASH ? 1 : 0); @@ -1502,7 +1502,7 @@ void OpenGLSprite::Update(uint width, uint height, uint level, const SpriteLoade */ inline Dimension OpenGLSprite::GetSize(ZoomLevel level) const { - Dimension sd = { (uint)UnScaleByZoomLower(this->dim.width, level), (uint)UnScaleByZoomLower(this->dim.height, level) }; + Dimension sd = { static_cast(UnScaleByZoomLower(this->dim.width, level)), static_cast(UnScaleByZoomLower(this->dim.height, level)) }; return sd; } diff --git a/src/viewport.cpp b/src/viewport.cpp index c0f74f4c95..b3f5ad7d0b 100644 --- a/src/viewport.cpp +++ b/src/viewport.cpp @@ -1123,7 +1123,7 @@ static void DrawTileSelection(const TileInfo *ti) if ((_thd.drawstyle & HT_DRAG_MASK) == HT_NONE) return; if (_thd.diagonal) { // We're drawing a 45 degrees rotated (diagonal) rectangle - if (IsInsideRotatedRectangle((int)ti->x, (int)ti->y)) goto draw_inner; + if (IsInsideRotatedRectangle(ti->x, ti->y)) goto draw_inner; return; } @@ -1191,7 +1191,7 @@ draw_inner: static int GetViewportY(Point tile) { /* Each increment in X or Y direction moves down by half a tile, i.e. TILE_PIXELS / 2. */ - return (tile.y * (int)(TILE_PIXELS / 2) + tile.x * (int)(TILE_PIXELS / 2) - TilePixelHeightOutsideMap(tile.x, tile.y)) << ZOOM_BASE_SHIFT; + return (tile.y * static_cast(TILE_PIXELS / 2) + tile.x * static_cast(TILE_PIXELS / 2) - TilePixelHeightOutsideMap(tile.x, tile.y)) << ZOOM_BASE_SHIFT; } /** @@ -1218,8 +1218,8 @@ static void ViewportAddLandscape() * - Right column is column of upper_right (rounded up) and one column to the right. * Note: Integer-division does not round down for negative numbers, so ensure rounding with another increment/decrement. */ - int left_column = (upper_left.y - upper_left.x) / (int)TILE_SIZE - 2; - int right_column = (upper_right.y - upper_right.x) / (int)TILE_SIZE + 2; + int left_column = (upper_left.y - upper_left.x) / static_cast(TILE_SIZE) - 2; + int right_column = (upper_right.y - upper_right.x) / static_cast(TILE_SIZE) + 2; int potential_bridge_height = ZOOM_BASE * TILE_HEIGHT * _settings_game.construction.max_bridge_height; @@ -1227,7 +1227,7 @@ static void ViewportAddLandscape() * The first row that could possibly be visible is the row above upper_left (if it is at height 0). * Due to integer-division not rounding down for negative numbers, we need another decrement. */ - int row = (upper_left.x + upper_left.y) / (int)TILE_SIZE - 2; + int row = (upper_left.x + upper_left.y) / static_cast(TILE_SIZE) - 2; bool last_row = false; for (; !last_row; row++) { last_row = true; @@ -1746,7 +1746,7 @@ static void ViewportDrawDirtyBlocks() uint8_t bo = UnScaleByZoom(dpi->left + dpi->top, dpi->zoom) & 1; do { - for (int i = (bo ^= 1); i < right; i += 2) blitter->SetPixel(dst, i, 0, (uint8_t)colour); + for (int i = (bo ^= 1); i < right; i += 2) blitter->SetPixel(dst, i, 0, static_cast(colour)); dst = blitter->MoveTo(dst, 0, 1); } while (--bottom > 0); } @@ -2216,8 +2216,8 @@ static void SetSelectionTilesDirty() /* a_size, b_size describe a rectangle with rotated coordinates */ int a_size = x_size + y_size, b_size = x_size - y_size; - int interval_a = a_size < 0 ? -(int)TILE_SIZE : (int)TILE_SIZE; - int interval_b = b_size < 0 ? -(int)TILE_SIZE : (int)TILE_SIZE; + int interval_a = a_size < 0 ? -static_cast(TILE_SIZE) : static_cast(TILE_SIZE); + int interval_b = b_size < 0 ? -static_cast(TILE_SIZE) : static_cast(TILE_SIZE); for (int a = -interval_a; a != a_size + interval_a; a += interval_a) { for (int b = -interval_b; b != b_size + interval_b; b += interval_b) { @@ -2521,11 +2521,11 @@ bool ScrollWindowTo(int x, int y, int z, Window *w, bool instant) { /* The slope cannot be acquired outside of the map, so make sure we are always within the map. */ if (z == -1) { - if ( x >= 0 && x <= (int)Map::SizeX() * (int)TILE_SIZE - 1 - && y >= 0 && y <= (int)Map::SizeY() * (int)TILE_SIZE - 1) { + if ( x >= 0 && x <= static_cast(Map::SizeX()) * static_cast(TILE_SIZE) - 1 + && y >= 0 && y <= static_cast(Map::SizeY()) * static_cast(TILE_SIZE) - 1) { z = GetSlopePixelZ(x, y); } else { - z = TileHeightOutsideMap(x / (int)TILE_SIZE, y / (int)TILE_SIZE); + z = TileHeightOutsideMap(x / static_cast(TILE_SIZE), y / static_cast(TILE_SIZE)); } } @@ -3008,7 +3008,7 @@ static int CalcHeightdiff(HighLightStyle style, uint distance, TileIndex start_t } if (swap) Swap(h0, h1); - return (int)(h1 - h0) * TILE_HEIGHT_STEP; + return static_cast(h1 - h0) * TILE_HEIGHT_STEP; } /** @@ -3074,7 +3074,7 @@ static void CalcRaildirsDrawstyle(int x, int y, int method) } else { /* We are not on a straight line. Determine the rail to build * based on whether we are above or below it. */ - b = dx + dy >= (int)TILE_SIZE ? HT_LINE | HT_DIR_HU : HT_LINE | HT_DIR_HL; + b = dx + dy >= static_cast(TILE_SIZE) ? HT_LINE | HT_DIR_HU : HT_LINE | HT_DIR_HL; /* Calculate where a horizontal line through the start point and * a vertical line from the selected end point intersect and @@ -3085,10 +3085,10 @@ static void CalcRaildirsDrawstyle(int x, int y, int method) /* 'Build' the last half rail tile if needed */ if ((offset & TILE_UNIT_MASK) > (TILE_SIZE / 2)) { - if (dx + dy >= (int)TILE_SIZE) { - x -= (int)TILE_SIZE; + if (dx + dy >= static_cast(TILE_SIZE)) { + x -= static_cast(TILE_SIZE); } else { - y += (int)TILE_SIZE; + y += static_cast(TILE_SIZE); } } @@ -3114,16 +3114,16 @@ static void CalcRaildirsDrawstyle(int x, int y, int method) /* Calculate where a vertical line through the start point and * a horizontal line from the selected end point intersect and * use that point as the end point. */ - int offset = (raw_dx + raw_dy + (int)TILE_SIZE) / 2; + int offset = (raw_dx + raw_dy + static_cast(TILE_SIZE)) / 2; x = _thd.selstart.x - (offset & ~TILE_UNIT_MASK); y = _thd.selstart.y - (offset & ~TILE_UNIT_MASK); /* 'Build' the last half rail tile if needed */ if ((offset & TILE_UNIT_MASK) > (TILE_SIZE / 2)) { if (dx < dy) { - y -= (int)TILE_SIZE; + y -= static_cast(TILE_SIZE); } else { - x -= (int)TILE_SIZE; + x -= static_cast(TILE_SIZE); } } @@ -3146,18 +3146,18 @@ static void CalcRaildirsDrawstyle(int x, int y, int method) b = HT_RECT; } } else if (h == TILE_SIZE) { // Is this in X direction? - if (dx == (int)TILE_SIZE) { // 2x1 special handling + if (dx == static_cast(TILE_SIZE)) { // 2x1 special handling b = (Check2x1AutoRail(3)) | HT_LINE; - } else if (dx == -(int)TILE_SIZE) { + } else if (dx == -static_cast(TILE_SIZE)) { b = (Check2x1AutoRail(2)) | HT_LINE; } else { b = HT_LINE | HT_DIR_X; } y = _thd.selstart.y; } else if (w == TILE_SIZE) { // Or Y direction? - if (dy == (int)TILE_SIZE) { // 2x1 special handling + if (dy == static_cast(TILE_SIZE)) { // 2x1 special handling b = (Check2x1AutoRail(1)) | HT_LINE; - } else if (dy == -(int)TILE_SIZE) { // 2x1 other direction + } else if (dy == -static_cast(TILE_SIZE)) { // 2x1 other direction b = (Check2x1AutoRail(0)) | HT_LINE; } else { b = HT_LINE | HT_DIR_Y; @@ -3363,7 +3363,7 @@ calc_heightdiff_single_direction:; /* If dragging an area (eg dynamite tool) and it is actually a single * row/column, change the type to 'line' to get proper calculation for height */ - style = (HighLightStyle)_thd.next_drawstyle; + style = _thd.next_drawstyle; if (_thd.IsDraggingDiagonal()) { /* Determine the "area" of the diagonal dragged selection. * We assume the area is the number of tiles along the X @@ -3602,10 +3602,10 @@ CommandCost CmdScrollViewport(DoCommandFlags flags, TileIndex tile, ViewportScro case VST_EVERYONE: break; case VST_COMPANY: - if (_local_company != (CompanyID)ref) return CommandCost(); + if (_local_company != CompanyID(ref)) return CommandCost(); break; case VST_CLIENT: - if (_network_own_client_id != (ClientID)ref) return CommandCost(); + if (_network_own_client_id != static_cast(ref)) return CommandCost(); break; default: return CMD_ERROR; diff --git a/src/viewport_sprite_sorter_sse4.cpp b/src/viewport_sprite_sorter_sse4.cpp index a5ce747dc1..011cf50263 100644 --- a/src/viewport_sprite_sorter_sse4.cpp +++ b/src/viewport_sprite_sorter_sse4.cpp @@ -99,8 +99,8 @@ void ViewportSortParentSpritesSSE41(ParentSpriteToSortVector *psdv) prev = x++; /* Check that p->xmin <= s->xmax && p->ymin <= s->ymax && p->zmin <= s->zmax */ - __m128i s_max = LOAD_128((__m128i*) &s->xmax); - __m128i p_min = LOAD_128((__m128i*) &p->xmin); + __m128i s_max = LOAD_128(reinterpret_cast<__m128i*>(&s->xmax)); + __m128i p_min = LOAD_128(reinterpret_cast<__m128i*>(&p->xmin)); __m128i r1 = _mm_cmplt_epi32(s_max, p_min); if (!_mm_testz_si128(mask_ptest, r1)) continue; @@ -108,8 +108,8 @@ void ViewportSortParentSpritesSSE41(ParentSpriteToSortVector *psdv) /* Check if sprites overlap, i.e. * s->xmin <= p->xmax && s->ymin <= p->ymax && s->zmin <= p->zmax */ - __m128i s_min = LOAD_128((__m128i*) &s->xmin); - __m128i p_max = LOAD_128((__m128i*) &p->xmax); + __m128i s_min = LOAD_128(reinterpret_cast<__m128i*>(&s->xmin)); + __m128i p_max = LOAD_128(reinterpret_cast<__m128i*>(&p->xmax)); __m128i r2 = _mm_cmplt_epi32(p_max, s_min); if (_mm_testz_si128(mask_ptest, r2)) { /* Use X+Y+Z as the sorting order, so sprites closer to the bottom of diff --git a/src/water_cmd.cpp b/src/water_cmd.cpp index cd47c33c46..879afe4c46 100644 --- a/src/water_cmd.cpp +++ b/src/water_cmd.cpp @@ -1041,7 +1041,7 @@ static Vehicle *FloodVehicleProc(Vehicle *v, void *data) case VEH_TRAIN: case VEH_ROAD: { - int z = *(int*)data; + int z = *static_cast(data); if (v->z_pos > z) break; FloodVehicle(v->First()); break; diff --git a/src/waypoint_cmd.cpp b/src/waypoint_cmd.cpp index fe75aeb072..ef8ef6ae03 100644 --- a/src/waypoint_cmd.cpp +++ b/src/waypoint_cmd.cpp @@ -438,8 +438,8 @@ CommandCost CmdBuildRoadWaypoint(DoCommandFlags flags, TileIndex start_tile, Axi /* Update company infrastructure counts. If the current tile is a normal road tile, remove the old * bits first. */ if (IsNormalRoadTile(cur_tile)) { - UpdateCompanyRoadInfrastructure(road_rt, road_owner, -(int)CountBits(GetRoadBits(cur_tile, RTT_ROAD))); - UpdateCompanyRoadInfrastructure(tram_rt, tram_owner, -(int)CountBits(GetRoadBits(cur_tile, RTT_TRAM))); + UpdateCompanyRoadInfrastructure(road_rt, road_owner, -static_cast(CountBits(GetRoadBits(cur_tile, RTT_ROAD)))); + UpdateCompanyRoadInfrastructure(tram_rt, tram_owner, -static_cast(CountBits(GetRoadBits(cur_tile, RTT_TRAM)))); } UpdateCompanyRoadInfrastructure(road_rt, road_owner, ROAD_STOP_TRACKBIT_FACTOR); diff --git a/src/widget.cpp b/src/widget.cpp index 622785e635..f33bfcfedb 100644 --- a/src/widget.cpp +++ b/src/widget.cpp @@ -47,7 +47,7 @@ static std::string GetStringForWidget(const Window *w, const NWidgetCore *nwid, */ static inline RectPadding ScaleGUITrad(const RectPadding &r) { - return {(uint8_t)ScaleGUITrad(r.left), (uint8_t)ScaleGUITrad(r.top), (uint8_t)ScaleGUITrad(r.right), (uint8_t)ScaleGUITrad(r.bottom)}; + return {static_cast(ScaleGUITrad(r.left)), static_cast(ScaleGUITrad(r.top)), static_cast(ScaleGUITrad(r.right)), static_cast(ScaleGUITrad(r.bottom))}; } /** @@ -57,7 +57,7 @@ static inline RectPadding ScaleGUITrad(const RectPadding &r) */ static inline Dimension ScaleGUITrad(const Dimension &dim) { - return {(uint)ScaleGUITrad(dim.width), (uint)ScaleGUITrad(dim.height)}; + return {static_cast(ScaleGUITrad(dim.width)), static_cast(ScaleGUITrad(dim.height))}; } /** @@ -2007,7 +2007,7 @@ void NWidgetMatrix::SetupSmallestSize(Window *w) this->children.front()->SetupSmallestSize(w); - Dimension padding = { (uint)this->pip_pre + this->pip_post, (uint)this->pip_pre + this->pip_post}; + Dimension padding = { static_cast(this->pip_pre) + this->pip_post, static_cast(this->pip_pre) + this->pip_post}; Dimension size = {this->children.front()->smallest_x + padding.width, this->children.front()->smallest_y + padding.height}; Dimension fill = {0, 0}; Dimension resize = {this->pip_inter + this->children.front()->smallest_x, this->pip_inter + this->children.front()->smallest_y}; @@ -2064,11 +2064,11 @@ NWidgetCore *NWidgetMatrix::GetWidgetFromPos(int x, int y) bool rtl = _current_text_dir == TD_RTL; int widget_col = (rtl ? - -x + (int)this->pip_post + this->pos_x + base_offs_x + this->widget_w - 1 - (int)this->pip_inter : - x - (int)this->pip_pre - this->pos_x - base_offs_x + -x + static_cast(this->pip_post) + this->pos_x + base_offs_x + this->widget_w - 1 - static_cast(this->pip_inter) : + x - static_cast(this->pip_pre) - this->pos_x - base_offs_x ) / this->widget_w; - int widget_row = (y - base_offs_y - (int)this->pip_pre - this->pos_y) / this->widget_h; + int widget_row = (y - base_offs_y - static_cast(this->pip_pre) - this->pos_y) / this->widget_h; this->current_element = (widget_row + start_y) * this->widgets_x + start_x + widget_col; if (this->current_element >= this->count) return nullptr; @@ -2106,7 +2106,7 @@ NWidgetCore *NWidgetMatrix::GetWidgetFromPos(int x, int y) for (int y = start_y; y < start_y + this->widgets_y + 1; y++, offs_y += this->widget_h) { /* Are we within bounds? */ if (offs_y + child->smallest_y <= 0) continue; - if (offs_y >= (int)this->current_y) break; + if (offs_y >= static_cast(this->current_y)) break; /* We've passed our amount of widgets. */ if (y * this->widgets_x >= this->count) break; @@ -2115,7 +2115,7 @@ NWidgetCore *NWidgetMatrix::GetWidgetFromPos(int x, int y) for (int x = start_x; x < start_x + this->widgets_x + 1; x++, offs_x += rtl ? -this->widget_w : this->widget_w) { /* Are we within bounds? */ if (offs_x + child->smallest_x <= 0) continue; - if (offs_x >= (int)this->current_x) continue; + if (offs_x >= static_cast(this->current_x)) continue; /* Do we have this many widgets? */ this->current_element = y * this->widgets_x + x; @@ -2522,9 +2522,9 @@ void Scrollbar::SetCapacityFromWidget(Window *w, WidgetID widget, int padding) { NWidgetBase *nwid = w->GetWidget(widget); if (this->IsVertical()) { - this->SetCapacity(((int)nwid->current_y - padding) / (int)nwid->resize_y); + this->SetCapacity((static_cast(nwid->current_y) - padding) / static_cast(nwid->resize_y)); } else { - this->SetCapacity(((int)nwid->current_x - padding) / (int)nwid->resize_x); + this->SetCapacity((static_cast(nwid->current_x) - padding) / static_cast(nwid->resize_x)); } } diff --git a/src/window.cpp b/src/window.cpp index d6df71359a..779d472b0f 100644 --- a/src/window.cpp +++ b/src/window.cpp @@ -693,8 +693,8 @@ static void DispatchLeftClickEvent(Window *w, int x, int y, int click_count) int dy = (w->resize.step_height == 0) ? 0 : def_height - w->height; /* dx and dy has to go by step.. calculate it. * The cast to int is necessary else dx/dy are implicitly casted to unsigned int, which won't work. */ - if (w->resize.step_width > 1) dx -= dx % (int)w->resize.step_width; - if (w->resize.step_height > 1) dy -= dy % (int)w->resize.step_height; + if (w->resize.step_width > 1) dx -= dx % static_cast(w->resize.step_width); + if (w->resize.step_height > 1) dy -= dy % static_cast(w->resize.step_height); ResizeWindow(w, dx, dy, false); } @@ -729,7 +729,7 @@ static void DispatchLeftClickEvent(Window *w, int x, int y, int click_count) /* Check if the widget is highlighted; if so, disable highlight and dispatch an event to the GameScript */ if (w->IsWidgetHighlighted(widget_index)) { w->SetWidgetHighlight(widget_index, TC_INVALID); - Game::NewEvent(new ScriptEventWindowWidgetClick((ScriptWindow::WindowClass)w->window_class, w->window_number, widget_index)); + Game::NewEvent(new ScriptEventWindowWidgetClick(static_cast(w->window_class), w->window_number, widget_index)); } w->OnClick(pt, widget_index, click_count); @@ -977,8 +977,8 @@ void Window::ReInit(int rx, int ry, bool reposition) int dy = (this->resize.step_height == 0) ? 0 : window_height - this->height; /* dx and dy has to go by step.. calculate it. * The cast to int is necessary else dx/dy are implicitly casted to unsigned int, which won't work. */ - 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 (this->resize.step_width > 1) dx -= dx % static_cast(this->resize.step_width); + if (this->resize.step_height > 1) dy -= dy % static_cast(this->resize.step_height); if (reposition) { Point pt = this->OnInitialPosition(this->nested_root->smallest_x, this->nested_root->smallest_y, window_number); @@ -1009,8 +1009,8 @@ void Window::SetShaded(bool make_shaded) this->ReInit(0, -this->height); } else { this->shade_select->SetDisplayedPlane(desired); - int dx = ((int)this->unshaded_size.width > this->width) ? (int)this->unshaded_size.width - this->width : 0; - int dy = ((int)this->unshaded_size.height > this->height) ? (int)this->unshaded_size.height - this->height : 0; + int dx = (static_cast(this->unshaded_size.width) > this->width) ? static_cast(this->unshaded_size.width) - this->width : 0; + int dy = (static_cast(this->unshaded_size.height) > this->height) ? static_cast(this->unshaded_size.height) - this->height : 0; this->ReInit(dx, dy); } } @@ -1443,8 +1443,8 @@ void Window::FindWindowPlacementAndResize(int def_width, int def_height) /* X and Y has to go by step.. calculate it. * The cast to int is necessary else x/y are implicitly casted to * unsigned int, which won't work. */ - if (this->resize.step_width > 1) enlarge_x -= enlarge_x % (int)this->resize.step_width; - if (this->resize.step_height > 1) enlarge_y -= enlarge_y % (int)this->resize.step_height; + if (this->resize.step_width > 1) enlarge_x -= enlarge_x % static_cast(this->resize.step_width); + if (this->resize.step_height > 1) enlarge_y -= enlarge_y % static_cast(this->resize.step_height); ResizeWindow(this, enlarge_x, enlarge_y, true, false); /* ResizeWindow() calls this->OnResize(). */ @@ -1604,7 +1604,7 @@ static Point GetAutoPlacePosition(int width, int height) * of the closebox */ int left = rtl ? _screen.width - width : 0, top = toolbar_y; - int offset_x = rtl ? -(int)NWidgetLeaf::closebox_dimension.width : (int)NWidgetLeaf::closebox_dimension.width; + int offset_x = rtl ? -static_cast(NWidgetLeaf::closebox_dimension.width) : static_cast(NWidgetLeaf::closebox_dimension.width); int offset_y = std::max(NWidgetLeaf::closebox_dimension.height, GetCharacterHeight(FS_NORMAL) + WidgetDimensions::scaled.captiontext.Vertical()); restart: @@ -2030,14 +2030,14 @@ void ResizeWindow(Window *w, int delta_x, int delta_y, bool clamp_to_screen, boo * the resolution clamp it in such a manner that it stays within the bounds. */ int new_right = w->left + w->width + delta_x; int new_bottom = w->top + w->height + delta_y; - if (new_right >= (int)_screen.width) delta_x -= Ceil(new_right - _screen.width, std::max(1U, w->nested_root->resize_x)); - if (new_bottom >= (int)_screen.height) delta_y -= Ceil(new_bottom - _screen.height, std::max(1U, w->nested_root->resize_y)); + if (new_right >= _screen.width) delta_x -= Ceil(new_right - _screen.width, std::max(1U, w->nested_root->resize_x)); + if (new_bottom >= _screen.height) delta_y -= Ceil(new_bottom - _screen.height, std::max(1U, w->nested_root->resize_y)); } w->SetDirty(); - uint new_xinc = std::max(0, (w->nested_root->resize_x == 0) ? 0 : (int)(w->nested_root->current_x - w->nested_root->smallest_x) + delta_x); - uint new_yinc = std::max(0, (w->nested_root->resize_y == 0) ? 0 : (int)(w->nested_root->current_y - w->nested_root->smallest_y) + delta_y); + uint new_xinc = std::max(0, (w->nested_root->resize_x == 0) ? 0 : static_cast(w->nested_root->current_x - w->nested_root->smallest_x) + delta_x); + uint new_yinc = std::max(0, (w->nested_root->resize_y == 0) ? 0 : static_cast(w->nested_root->current_y - w->nested_root->smallest_y) + delta_y); assert(w->nested_root->resize_x == 0 || new_xinc % w->nested_root->resize_x == 0); assert(w->nested_root->resize_y == 0 || new_yinc % w->nested_root->resize_y == 0); @@ -2218,14 +2218,14 @@ static EventState HandleWindowDragging() /* X and Y has to go by step.. calculate it. * The cast to int is necessary else x/y are implicitly casted to * unsigned int, which won't work. */ - if (w->resize.step_width > 1) x -= x % (int)w->resize.step_width; - if (w->resize.step_height > 1) y -= y % (int)w->resize.step_height; + if (w->resize.step_width > 1) x -= x % static_cast(w->resize.step_width); + if (w->resize.step_height > 1) y -= y % static_cast(w->resize.step_height); /* Check that we don't go below the minimum set size */ - if ((int)w->width + x < (int)w->nested_root->smallest_x) { + if (w->width + x < static_cast(w->nested_root->smallest_x)) { x = w->nested_root->smallest_x - w->width; } - if ((int)w->height + y < (int)w->nested_root->smallest_y) { + if (w->height + y < static_cast(w->nested_root->smallest_y)) { y = w->nested_root->smallest_y - w->height; }