1
0
Fork 0

Codechange: replace INVALID_X with XID::Invalid() for PoolIDs

pull/13585/head
Rubidium 2025-02-16 19:29:53 +01:00 committed by rubidium42
parent d13b0e0813
commit fd4adc55e3
157 changed files with 744 additions and 772 deletions

View File

@ -190,7 +190,7 @@
AI::scanner_info = nullptr; AI::scanner_info = nullptr;
AI::scanner_library = nullptr; AI::scanner_library = nullptr;
for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; ++c) { for (CompanyID c = CompanyID::Begin(); c < MAX_COMPANIES; ++c) {
if (_settings_game.ai_config[c] != nullptr) { if (_settings_game.ai_config[c] != nullptr) {
delete _settings_game.ai_config[c]; delete _settings_game.ai_config[c];
_settings_game.ai_config[c] = nullptr; _settings_game.ai_config[c] = nullptr;
@ -208,7 +208,7 @@
/* Check for both newgame as current game if we can reload the AIInfo inside /* Check for both newgame as current game if we can reload the AIInfo inside
* the AIConfig. If not, remove the AI from the list (which will assign * the AIConfig. If not, remove the AI from the list (which will assign
* a random new AI on reload). */ * a random new AI on reload). */
for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; ++c) { for (CompanyID c = CompanyID::Begin(); c < MAX_COMPANIES; ++c) {
if (_settings_game.ai_config[c] != nullptr && _settings_game.ai_config[c]->HasScript()) { if (_settings_game.ai_config[c] != nullptr && _settings_game.ai_config[c]->HasScript()) {
if (!_settings_game.ai_config[c]->ResetInfo(true)) { if (!_settings_game.ai_config[c]->ResetInfo(true)) {
Debug(script, 0, "After a reload, the AI by the name '{}' was no longer found, and removed from the list.", _settings_game.ai_config[c]->GetName()); Debug(script, 0, "After a reload, the AI by the name '{}' was no longer found, and removed from the list.", _settings_game.ai_config[c]->GetName());
@ -270,7 +270,7 @@
} }
/* Try to send the event to all AIs */ /* Try to send the event to all AIs */
for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; ++c) { for (CompanyID c = CompanyID::Begin(); c < MAX_COMPANIES; ++c) {
if (c != skip_company) AI::NewEvent(c, event); if (c != skip_company) AI::NewEvent(c, event);
} }
} }

View File

@ -93,7 +93,7 @@ static WindowDesc _ai_config_desc(
* Window to configure which AIs will start. * Window to configure which AIs will start.
*/ */
struct AIConfigWindow : public Window { struct AIConfigWindow : public Window {
CompanyID selected_slot; ///< The currently selected AI slot or \c INVALID_COMPANY. CompanyID selected_slot; ///< The currently selected AI slot or \c CompanyID::Invalid().
int line_height; ///< Height of a single AI-name line. int line_height; ///< Height of a single AI-name line.
Scrollbar *vscroll; ///< Cache of the vertical scrollbar. Scrollbar *vscroll; ///< Cache of the vertical scrollbar.
@ -101,7 +101,7 @@ struct AIConfigWindow : public Window {
{ {
this->InitNested(WN_GAME_OPTIONS_AI); // Initializes 'this->line_height' as a side effect. this->InitNested(WN_GAME_OPTIONS_AI); // Initializes 'this->line_height' as a side effect.
this->vscroll = this->GetScrollbar(WID_AIC_SCROLLBAR); this->vscroll = this->GetScrollbar(WID_AIC_SCROLLBAR);
this->selected_slot = INVALID_COMPANY; this->selected_slot = CompanyID::Invalid();
NWidgetCore *nwi = this->GetWidget<NWidgetCore>(WID_AIC_LIST); NWidgetCore *nwi = this->GetWidget<NWidgetCore>(WID_AIC_LIST);
this->vscroll->SetCapacity(nwi->current_y / this->line_height); this->vscroll->SetCapacity(nwi->current_y / this->line_height);
this->vscroll->SetCount(MAX_COMPANIES); this->vscroll->SetCount(MAX_COMPANIES);
@ -169,7 +169,7 @@ struct AIConfigWindow : public Window {
for (const Company *c : Company::Iterate()) { for (const Company *c : Company::Iterate()) {
if (c->is_ai) max_slot--; if (c->is_ai) max_slot--;
} }
for (CompanyID cid = COMPANY_FIRST; cid < max_slot && cid < MAX_COMPANIES; ++cid) { for (CompanyID cid = CompanyID::Begin(); cid < max_slot && cid < MAX_COMPANIES; ++cid) {
if (Company::IsValidID(cid)) max_slot++; if (Company::IsValidID(cid)) max_slot++;
} }
} else { } else {
@ -206,7 +206,7 @@ struct AIConfigWindow : public Window {
void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
{ {
if (widget >= WID_AIC_TEXTFILE && widget < WID_AIC_TEXTFILE + TFT_CONTENT_END) { if (widget >= WID_AIC_TEXTFILE && widget < WID_AIC_TEXTFILE + TFT_CONTENT_END) {
if (this->selected_slot == INVALID_COMPANY || AIConfig::GetConfig(this->selected_slot) == nullptr) return; if (this->selected_slot == CompanyID::Invalid() || AIConfig::GetConfig(this->selected_slot) == nullptr) return;
ShowScriptTextfileWindow((TextfileType)(widget - WID_AIC_TEXTFILE), this->selected_slot); ShowScriptTextfileWindow((TextfileType)(widget - WID_AIC_TEXTFILE), this->selected_slot);
return; return;
@ -266,7 +266,7 @@ struct AIConfigWindow : public Window {
case WID_AIC_OPEN_URL: { case WID_AIC_OPEN_URL: {
const AIConfig *config = AIConfig::GetConfig(this->selected_slot); const AIConfig *config = AIConfig::GetConfig(this->selected_slot);
if (this->selected_slot == INVALID_COMPANY || config == nullptr || config->GetInfo() == nullptr) return; if (this->selected_slot == CompanyID::Invalid() || config == nullptr || config->GetInfo() == nullptr) return;
OpenBrowser(config->GetInfo()->GetURL()); OpenBrowser(config->GetInfo()->GetURL());
break; break;
} }
@ -297,25 +297,25 @@ struct AIConfigWindow : public Window {
void OnInvalidateData([[maybe_unused]] int data = 0, [[maybe_unused]] bool gui_scope = true) override void OnInvalidateData([[maybe_unused]] int data = 0, [[maybe_unused]] bool gui_scope = true) override
{ {
if (!IsEditable(this->selected_slot) && !Company::IsValidAiID(this->selected_slot)) { if (!IsEditable(this->selected_slot) && !Company::IsValidAiID(this->selected_slot)) {
this->selected_slot = INVALID_COMPANY; this->selected_slot = CompanyID::Invalid();
} }
if (!gui_scope) return; if (!gui_scope) return;
AIConfig *config = this->selected_slot == INVALID_COMPANY ? nullptr : AIConfig::GetConfig(this->selected_slot); AIConfig *config = this->selected_slot == CompanyID::Invalid() ? nullptr : AIConfig::GetConfig(this->selected_slot);
this->SetWidgetDisabledState(WID_AIC_DECREASE_NUMBER, GetGameSettings().difficulty.max_no_competitors == 0); this->SetWidgetDisabledState(WID_AIC_DECREASE_NUMBER, GetGameSettings().difficulty.max_no_competitors == 0);
this->SetWidgetDisabledState(WID_AIC_INCREASE_NUMBER, GetGameSettings().difficulty.max_no_competitors == MAX_COMPANIES - 1); this->SetWidgetDisabledState(WID_AIC_INCREASE_NUMBER, GetGameSettings().difficulty.max_no_competitors == MAX_COMPANIES - 1);
this->SetWidgetDisabledState(WID_AIC_DECREASE_INTERVAL, GetGameSettings().difficulty.competitors_interval == MIN_COMPETITORS_INTERVAL); this->SetWidgetDisabledState(WID_AIC_DECREASE_INTERVAL, GetGameSettings().difficulty.competitors_interval == MIN_COMPETITORS_INTERVAL);
this->SetWidgetDisabledState(WID_AIC_INCREASE_INTERVAL, GetGameSettings().difficulty.competitors_interval == MAX_COMPETITORS_INTERVAL); 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_CHANGE, !IsEditable(this->selected_slot));
this->SetWidgetDisabledState(WID_AIC_CONFIGURE, this->selected_slot == INVALID_COMPANY || config->GetConfigList()->empty()); 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_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_DOWN, !IsEditable(this->selected_slot) || !IsEditable((CompanyID)(this->selected_slot + 1)));
this->SetWidgetDisabledState(WID_AIC_OPEN_URL, this->selected_slot == INVALID_COMPANY || config->GetInfo() == nullptr || config->GetInfo()->GetURL().empty()); 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++) { for (TextfileType tft = TFT_CONTENT_BEGIN; tft < TFT_CONTENT_END; tft++) {
this->SetWidgetDisabledState(WID_AIC_TEXTFILE + tft, this->selected_slot == INVALID_COMPANY || !config->GetTextfile(tft, this->selected_slot).has_value()); this->SetWidgetDisabledState(WID_AIC_TEXTFILE + tft, this->selected_slot == CompanyID::Invalid() || !config->GetTextfile(tft, this->selected_slot).has_value());
} }
} }
}; };

View File

@ -116,15 +116,15 @@ enum HelicopterRotorStates : uint8_t {
/** /**
* Find the nearest hangar to v * Find the nearest hangar to v
* INVALID_STATION is returned, if the company does not have any suitable * StationID::Invalid() is returned, if the company does not have any suitable
* airports (like helipads only) * airports (like helipads only)
* @param v vehicle looking for a hangar * @param v vehicle looking for a hangar
* @return the StationID if one is found, otherwise, INVALID_STATION * @return the StationID if one is found, otherwise, StationID::Invalid()
*/ */
static StationID FindNearestHangar(const Aircraft *v) static StationID FindNearestHangar(const Aircraft *v)
{ {
uint best = 0; uint best = 0;
StationID index = INVALID_STATION; StationID index = StationID::Invalid();
TileIndex vtile = TileVirtXY(v->x_pos, v->y_pos); TileIndex vtile = TileVirtXY(v->x_pos, v->y_pos);
const AircraftVehicleInfo *avi = AircraftVehInfo(v->engine_type); const AircraftVehicleInfo *avi = AircraftVehInfo(v->engine_type);
uint max_range = v->acache.cached_max_range_sqr; uint max_range = v->acache.cached_max_range_sqr;
@ -163,7 +163,7 @@ static StationID FindNearestHangar(const Aircraft *v)
/* v->tile can't be used here, when aircraft is flying v->tile is set to 0 */ /* v->tile can't be used here, when aircraft is flying v->tile is set to 0 */
uint distance = DistanceSquare(vtile, st->airport.tile); uint distance = DistanceSquare(vtile, st->airport.tile);
if (distance < best || index == INVALID_STATION) { if (distance < best || index == StationID::Invalid()) {
best = distance; best = distance;
index = st->index; index = st->index;
} }
@ -318,8 +318,8 @@ CommandCost CmdBuildAircraft(DoCommandFlags flags, TileIndex tile, const Engine
} }
v->name.clear(); v->name.clear();
v->last_station_visited = INVALID_STATION; v->last_station_visited = StationID::Invalid();
v->last_loading_station = INVALID_STATION; v->last_loading_station = StationID::Invalid();
v->acceleration = avi->acceleration; v->acceleration = avi->acceleration;
v->engine_type = e->index; v->engine_type = e->index;
@ -404,7 +404,7 @@ ClosestDepot Aircraft::FindClosestDepot()
/* the aircraft has to search for a hangar on its own */ /* the aircraft has to search for a hangar on its own */
StationID station = FindNearestHangar(this); StationID station = FindNearestHangar(this);
if (station == INVALID_STATION) return ClosestDepot(); if (station == StationID::Invalid()) return ClosestDepot();
st = Station::Get(station); st = Station::Get(station);
} }
@ -1357,7 +1357,7 @@ static void CrashAirplane(Aircraft *v)
newstype = NewsType::AccidentOther; newstype = NewsType::AccidentOther;
} }
AddTileNewsItem(newsitem, newstype, vt, st != nullptr ? st->index : INVALID_STATION); AddTileNewsItem(newsitem, newstype, vt, st != nullptr ? st->index : StationID::Invalid());
ModifyStationRatingAround(vt, v->owner, -160, 30); ModifyStationRatingAround(vt, v->owner, -160, 30);
if (_settings_client.sound.disaster) SndPlayVehicleFx(SND_12_EXPLOSION, v); if (_settings_client.sound.disaster) SndPlayVehicleFx(SND_12_EXPLOSION, v);

View File

@ -70,7 +70,7 @@ static void PlaceAirport(TileIndex tile)
auto proc = [=](bool test, StationID to_join) -> bool { auto proc = [=](bool test, StationID to_join) -> bool {
if (test) { if (test) {
return Command<CMD_BUILD_AIRPORT>::Do(CommandFlagsToDCFlags(GetCommandFlags<CMD_BUILD_AIRPORT>()), tile, airport_type, layout, INVALID_STATION, adjacent).Succeeded(); return Command<CMD_BUILD_AIRPORT>::Do(CommandFlagsToDCFlags(GetCommandFlags<CMD_BUILD_AIRPORT>()), tile, airport_type, layout, StationID::Invalid(), adjacent).Succeeded();
} else { } else {
return Command<CMD_BUILD_AIRPORT>::Post(STR_ERROR_CAN_T_BUILD_AIRPORT_HERE, CcBuildAirport, tile, airport_type, layout, to_join, adjacent); return Command<CMD_BUILD_AIRPORT>::Post(STR_ERROR_CAN_T_BUILD_AIRPORT_HERE, CcBuildAirport, tile, airport_type, layout, to_join, adjacent);
} }

View File

@ -29,7 +29,7 @@ static const uint MAX_ARTICULATED_PARTS = 100; ///< Maximum of articulated parts
* @param front_type Front engine type * @param front_type Front engine type
* @param front Front engine * @param front Front engine
* @param mirrored Returns whether the part shall be flipped. * @param mirrored Returns whether the part shall be flipped.
* @return engine to add or INVALID_ENGINE * @return engine to add or EngineID::Invalid()
*/ */
static EngineID GetNextArticulatedPart(uint index, EngineID front_type, Vehicle *front = nullptr, bool *mirrored = nullptr) static EngineID GetNextArticulatedPart(uint index, EngineID front_type, Vehicle *front = nullptr, bool *mirrored = nullptr)
{ {
@ -38,17 +38,17 @@ static EngineID GetNextArticulatedPart(uint index, EngineID front_type, Vehicle
const Engine *front_engine = Engine::Get(front_type); const Engine *front_engine = Engine::Get(front_type);
uint16_t callback = GetVehicleCallback(CBID_VEHICLE_ARTIC_ENGINE, index, 0, front_type, front); uint16_t callback = GetVehicleCallback(CBID_VEHICLE_ARTIC_ENGINE, index, 0, front_type, front);
if (callback == CALLBACK_FAILED) return INVALID_ENGINE; if (callback == CALLBACK_FAILED) return EngineID::Invalid();
if (front_engine->GetGRF()->grf_version < 8) { if (front_engine->GetGRF()->grf_version < 8) {
/* 8 bits, bit 7 for mirroring */ /* 8 bits, bit 7 for mirroring */
callback = GB(callback, 0, 8); callback = GB(callback, 0, 8);
if (callback == 0xFF) return INVALID_ENGINE; if (callback == 0xFF) return EngineID::Invalid();
if (mirrored != nullptr) *mirrored = HasBit(callback, 7); if (mirrored != nullptr) *mirrored = HasBit(callback, 7);
callback = GB(callback, 0, 7); callback = GB(callback, 0, 7);
} else { } else {
/* 15 bits, bit 14 for mirroring */ /* 15 bits, bit 14 for mirroring */
if (callback == 0x7FFF) return INVALID_ENGINE; if (callback == 0x7FFF) return EngineID::Invalid();
if (mirrored != nullptr) *mirrored = HasBit(callback, 14); if (mirrored != nullptr) *mirrored = HasBit(callback, 14);
callback = GB(callback, 0, 14); callback = GB(callback, 0, 14);
} }
@ -89,7 +89,7 @@ uint CountArticulatedParts(EngineID engine_type, bool purchase_window)
uint i; uint i;
for (i = 1; i < MAX_ARTICULATED_PARTS; i++) { for (i = 1; i < MAX_ARTICULATED_PARTS; i++) {
if (GetNextArticulatedPart(i, engine_type, v) == INVALID_ENGINE) break; if (GetNextArticulatedPart(i, engine_type, v) == EngineID::Invalid()) break;
} }
delete v; delete v;
@ -150,7 +150,7 @@ CargoArray GetCapacityOfArticulatedParts(EngineID engine)
for (uint i = 1; i < MAX_ARTICULATED_PARTS; i++) { for (uint i = 1; i < MAX_ARTICULATED_PARTS; i++) {
EngineID artic_engine = GetNextArticulatedPart(i, engine); EngineID artic_engine = GetNextArticulatedPart(i, engine);
if (artic_engine == INVALID_ENGINE) break; if (artic_engine == EngineID::Invalid()) break;
if (auto [cargo, cap] = GetVehicleDefaultCapacity(artic_engine); IsValidCargoType(cargo)) { if (auto [cargo, cap] = GetVehicleDefaultCapacity(artic_engine); IsValidCargoType(cargo)) {
capacity[cargo] += cap; capacity[cargo] += cap;
@ -180,7 +180,7 @@ CargoTypes GetCargoTypesOfArticulatedParts(EngineID engine)
for (uint i = 1; i < MAX_ARTICULATED_PARTS; i++) { for (uint i = 1; i < MAX_ARTICULATED_PARTS; i++) {
EngineID artic_engine = GetNextArticulatedPart(i, engine); EngineID artic_engine = GetNextArticulatedPart(i, engine);
if (artic_engine == INVALID_ENGINE) break; if (artic_engine == EngineID::Invalid()) break;
if (auto [cargo, cap] = GetVehicleDefaultCapacity(artic_engine); IsValidCargoType(cargo) && cap > 0) { if (auto [cargo, cap] = GetVehicleDefaultCapacity(artic_engine); IsValidCargoType(cargo) && cap > 0) {
SetBit(cargoes, cargo); SetBit(cargoes, cargo);
@ -206,7 +206,7 @@ bool IsArticulatedVehicleRefittable(EngineID engine)
for (uint i = 1; i < MAX_ARTICULATED_PARTS; i++) { for (uint i = 1; i < MAX_ARTICULATED_PARTS; i++) {
EngineID artic_engine = GetNextArticulatedPart(i, engine); EngineID artic_engine = GetNextArticulatedPart(i, engine);
if (artic_engine == INVALID_ENGINE) break; if (artic_engine == EngineID::Invalid()) break;
if (IsEngineRefittable(artic_engine)) return true; if (IsEngineRefittable(artic_engine)) return true;
} }
@ -233,7 +233,7 @@ void GetArticulatedRefitMasks(EngineID engine, bool include_initial_cargo_type,
for (uint i = 1; i < MAX_ARTICULATED_PARTS; i++) { for (uint i = 1; i < MAX_ARTICULATED_PARTS; i++) {
EngineID artic_engine = GetNextArticulatedPart(i, engine); EngineID artic_engine = GetNextArticulatedPart(i, engine);
if (artic_engine == INVALID_ENGINE) break; if (artic_engine == EngineID::Invalid()) break;
veh_cargoes = GetAvailableVehicleCargoTypes(artic_engine, include_initial_cargo_type); veh_cargoes = GetAvailableVehicleCargoTypes(artic_engine, include_initial_cargo_type);
*union_mask |= veh_cargoes; *union_mask |= veh_cargoes;
@ -344,7 +344,7 @@ void AddArticulatedParts(Vehicle *first)
for (uint i = 1; i < MAX_ARTICULATED_PARTS; i++) { for (uint i = 1; i < MAX_ARTICULATED_PARTS; i++) {
bool flip_image; bool flip_image;
EngineID engine_type = GetNextArticulatedPart(i, first->engine_type, first, &flip_image); EngineID engine_type = GetNextArticulatedPart(i, first->engine_type, first, &flip_image);
if (engine_type == INVALID_ENGINE) return; if (engine_type == EngineID::Invalid()) return;
/* In the (very rare) case the GRF reported wrong number of articulated parts /* In the (very rare) case the GRF reported wrong number of articulated parts
* and we run out of available vehicles, bail out. */ * and we run out of available vehicles, bail out. */

View File

@ -59,7 +59,7 @@ void RemoveAllEngineReplacement(EngineRenewList *erl)
* @param engine Engine type to be replaced. * @param engine Engine type to be replaced.
* @param group The group related to this replacement. * @param group The group related to this replacement.
* @param[out] replace_when_old Set to true if the replacement should be done when old. * @param[out] replace_when_old Set to true if the replacement should be done when old.
* @return The engine type to replace with, or INVALID_ENGINE if no * @return The engine type to replace with, or EngineID::Invalid() if no
* replacement is in the list. * replacement is in the list.
*/ */
EngineID EngineReplacement(EngineRenewList erl, EngineID engine, GroupID group, bool *replace_when_old) EngineID EngineReplacement(EngineRenewList erl, EngineID engine, GroupID group, bool *replace_when_old)
@ -81,7 +81,7 @@ EngineID EngineReplacement(EngineRenewList erl, EngineID engine, GroupID group,
*replace_when_old = er->replace_when_old; *replace_when_old = er->replace_when_old;
} }
} }
return er == nullptr ? INVALID_ENGINE : er->to; return er == nullptr ? EngineID::Invalid() : er->to;
} }
/** /**

View File

@ -37,7 +37,7 @@ struct EngineRenew : EngineRenewPool::PoolItem<&_enginerenew_pool> {
GroupID group_id; GroupID group_id;
bool replace_when_old; ///< Do replacement only when vehicle is old. bool replace_when_old; ///< Do replacement only when vehicle is old.
EngineRenew(EngineID from = INVALID_ENGINE, EngineID to = INVALID_ENGINE) : from(from), to(to) {} EngineRenew(EngineID from = EngineID::Invalid(), EngineID to = EngineID::Invalid()) : from(from), to(to) {}
~EngineRenew() {} ~EngineRenew() {}
}; };

View File

@ -276,14 +276,14 @@ static CargoType GetNewCargoTypeForReplace(Vehicle *v, EngineID engine_type, boo
* @param v The vehicle to find a replacement for * @param v The vehicle to find a replacement for
* @param c The vehicle's owner (it's faster to forward the pointer than refinding it) * @param c The vehicle's owner (it's faster to forward the pointer than refinding it)
* @param always_replace Always replace, even if not old. * @param always_replace Always replace, even if not old.
* @param[out] e the EngineID of the replacement. INVALID_ENGINE if no replacement is found * @param[out] e the EngineID of the replacement. EngineID::Invalid() if no replacement is found
* @return Error if the engine to build is not available * @return Error if the engine to build is not available
*/ */
static CommandCost GetNewEngineType(const Vehicle *v, const Company *c, bool always_replace, EngineID &e) static CommandCost GetNewEngineType(const Vehicle *v, const Company *c, bool always_replace, EngineID &e)
{ {
assert(v->type != VEH_TRAIN || !v->IsArticulatedPart()); assert(v->type != VEH_TRAIN || !v->IsArticulatedPart());
e = INVALID_ENGINE; e = EngineID::Invalid();
if (v->type == VEH_TRAIN && Train::From(v)->IsRearDualheaded()) { if (v->type == VEH_TRAIN && Train::From(v)->IsRearDualheaded()) {
/* we build the rear ends of multiheaded trains with the front ones */ /* we build the rear ends of multiheaded trains with the front ones */
@ -292,10 +292,10 @@ static CommandCost GetNewEngineType(const Vehicle *v, const Company *c, bool alw
bool replace_when_old; bool replace_when_old;
e = EngineReplacementForCompany(c, v->engine_type, v->group_id, &replace_when_old); e = EngineReplacementForCompany(c, v->engine_type, v->group_id, &replace_when_old);
if (!always_replace && replace_when_old && !v->NeedsAutorenewing(c, false)) e = INVALID_ENGINE; if (!always_replace && replace_when_old && !v->NeedsAutorenewing(c, false)) e = EngineID::Invalid();
/* Autoreplace, if engine is available */ /* Autoreplace, if engine is available */
if (e != INVALID_ENGINE && IsEngineBuildable(e, v->type, _current_company)) { if (e != EngineID::Invalid() && IsEngineBuildable(e, v->type, _current_company)) {
return CommandCost(); return CommandCost();
} }
@ -303,7 +303,7 @@ static CommandCost GetNewEngineType(const Vehicle *v, const Company *c, bool alw
if (v->NeedsAutorenewing(c)) e = v->engine_type; if (v->NeedsAutorenewing(c)) e = v->engine_type;
/* Nothing to do or all is fine? */ /* Nothing to do or all is fine? */
if (e == INVALID_ENGINE || IsEngineBuildable(e, v->type, _current_company)) return CommandCost(); if (e == EngineID::Invalid() || IsEngineBuildable(e, v->type, _current_company)) return CommandCost();
/* The engine we need is not available. Report error to user */ /* The engine we need is not available. Report error to user */
return CommandCost(STR_ERROR_RAIL_VEHICLE_NOT_AVAILABLE + v->type); return CommandCost(STR_ERROR_RAIL_VEHICLE_NOT_AVAILABLE + v->type);
@ -327,7 +327,7 @@ static CommandCost BuildReplacementVehicle(Vehicle *old_veh, Vehicle **new_vehic
EngineID e; EngineID e;
CommandCost cost = GetNewEngineType(old_veh, c, true, e); CommandCost cost = GetNewEngineType(old_veh, c, true, e);
if (cost.Failed()) return cost; if (cost.Failed()) return cost;
if (e == INVALID_ENGINE) return CommandCost(); // neither autoreplace is set, nor autorenew is triggered if (e == EngineID::Invalid()) return CommandCost(); // neither autoreplace is set, nor autorenew is triggered
/* Does it need to be refitted */ /* Does it need to be refitted */
CargoType refit_cargo = GetNewCargoTypeForReplace(old_veh, e, part_of_chain); CargoType refit_cargo = GetNewCargoTypeForReplace(old_veh, e, part_of_chain);
@ -397,7 +397,7 @@ static inline CommandCost DoCmdStartStopVehicle(const Vehicle *v, bool evaluate_
*/ */
static inline CommandCost CmdMoveVehicle(const Vehicle *v, const Vehicle *after, DoCommandFlags flags, bool whole_chain) static inline CommandCost CmdMoveVehicle(const Vehicle *v, const Vehicle *after, DoCommandFlags flags, bool whole_chain)
{ {
return Command<CMD_MOVE_RAIL_VEHICLE>::Do(flags.Set(DoCommandFlag::NoCargoCapacityCheck), v->index, after != nullptr ? after->index : INVALID_VEHICLE, whole_chain); return Command<CMD_MOVE_RAIL_VEHICLE>::Do(flags.Set(DoCommandFlag::NoCargoCapacityCheck), v->index, after != nullptr ? after->index : VehicleID::Invalid(), whole_chain);
} }
/** /**
@ -763,7 +763,7 @@ CommandCost CmdAutoreplaceVehicle(DoCommandFlags flags, VehicleID veh_id)
EngineID e; EngineID e;
CommandCost cost = GetNewEngineType(w, c, false, e); CommandCost cost = GetNewEngineType(w, c, false, e);
if (cost.Failed()) return cost; if (cost.Failed()) return cost;
any_replacements |= (e != INVALID_ENGINE); any_replacements |= (e != EngineID::Invalid());
w = (!free_wagon && w->type == VEH_TRAIN ? Train::From(w)->GetNextUnit() : nullptr); w = (!free_wagon && w->type == VEH_TRAIN ? Train::From(w)->GetNextUnit() : nullptr);
} }
@ -828,7 +828,7 @@ CommandCost CmdSetAutoReplace(DoCommandFlags flags, GroupID id_g, EngineID old_e
if (!Engine::IsValidID(old_engine_type)) return CMD_ERROR; if (!Engine::IsValidID(old_engine_type)) return CMD_ERROR;
if (Group::IsValidID(id_g) && Group::Get(id_g)->vehicle_type != Engine::Get(old_engine_type)->type) return CMD_ERROR; if (Group::IsValidID(id_g) && Group::Get(id_g)->vehicle_type != Engine::Get(old_engine_type)->type) return CMD_ERROR;
if (new_engine_type != INVALID_ENGINE) { if (new_engine_type != EngineID::Invalid()) {
if (!Engine::IsValidID(new_engine_type)) return CMD_ERROR; if (!Engine::IsValidID(new_engine_type)) return CMD_ERROR;
if (!CheckAutoreplaceValidity(old_engine_type, new_engine_type, _current_company)) return CMD_ERROR; if (!CheckAutoreplaceValidity(old_engine_type, new_engine_type, _current_company)) return CMD_ERROR;

View File

@ -33,7 +33,7 @@ inline void RemoveAllEngineReplacementForCompany(Company *c)
* @param engine Engine type. * @param engine Engine type.
* @param group The group related to this replacement. * @param group The group related to this replacement.
* @param[out] replace_when_old Set to true if the replacement should be done when old. * @param[out] replace_when_old Set to true if the replacement should be done when old.
* @return The engine type to replace with, or INVALID_ENGINE if no * @return The engine type to replace with, or EngineID::Invalid() if no
* replacement is in the list. * replacement is in the list.
*/ */
inline EngineID EngineReplacementForCompany(const Company *c, EngineID engine, GroupID group, bool *replace_when_old = nullptr) inline EngineID EngineReplacementForCompany(const Company *c, EngineID engine, GroupID group, bool *replace_when_old = nullptr)
@ -50,7 +50,7 @@ inline EngineID EngineReplacementForCompany(const Company *c, EngineID engine, G
*/ */
inline bool EngineHasReplacementForCompany(const Company *c, EngineID engine, GroupID group) inline bool EngineHasReplacementForCompany(const Company *c, EngineID engine, GroupID group)
{ {
return EngineReplacementForCompany(c, engine, group) != INVALID_ENGINE; return EngineReplacementForCompany(c, engine, group) != EngineID::Invalid();
} }
/** /**

View File

@ -118,7 +118,7 @@ class ReplaceVehicleWindow : public Window {
void GenerateReplaceVehList(bool draw_left) void GenerateReplaceVehList(bool draw_left)
{ {
std::vector<EngineID> variants; std::vector<EngineID> variants;
EngineID selected_engine = INVALID_ENGINE; EngineID selected_engine = EngineID::Invalid();
VehicleType type = this->window_number; VehicleType type = this->window_number;
uint8_t side = draw_left ? 0 : 1; uint8_t side = draw_left ? 0 : 1;
@ -147,7 +147,7 @@ class ReplaceVehicleWindow : public Window {
const uint num_engines = GetGroupNumEngines(_local_company, this->sel_group, eid); const uint num_engines = GetGroupNumEngines(_local_company, this->sel_group, eid);
/* Skip drawing the engines we don't have any of and haven't set for replacement */ /* Skip drawing the engines we don't have any of and haven't set for replacement */
if (num_engines == 0 && EngineReplacementForCompany(Company::Get(_local_company), eid, this->sel_group) == INVALID_ENGINE) continue; if (num_engines == 0 && EngineReplacementForCompany(Company::Get(_local_company), eid, this->sel_group) == EngineID::Invalid()) continue;
} else { } else {
if (!CheckAutoreplaceValidity(this->sel_engine[0], eid, _local_company)) continue; if (!CheckAutoreplaceValidity(this->sel_engine[0], eid, _local_company)) continue;
} }
@ -156,7 +156,7 @@ class ReplaceVehicleWindow : public Window {
if (side == 1) { if (side == 1) {
EngineID parent = e->info.variant_id; EngineID parent = e->info.variant_id;
while (parent != INVALID_ENGINE) { while (parent != EngineID::Invalid()) {
variants.push_back(parent); variants.push_back(parent);
parent = Engine::Get(parent)->info.variant_id; parent = Engine::Get(parent)->info.variant_id;
} }
@ -199,28 +199,28 @@ class ReplaceVehicleWindow : public Window {
/* We need to rebuild the left engines list */ /* We need to rebuild the left engines list */
this->GenerateReplaceVehList(true); this->GenerateReplaceVehList(true);
this->vscroll[0]->SetCount(this->engines[0].size()); this->vscroll[0]->SetCount(this->engines[0].size());
if (this->reset_sel_engine && this->sel_engine[0] == INVALID_ENGINE && !this->engines[0].empty()) { if (this->reset_sel_engine && this->sel_engine[0] == EngineID::Invalid() && !this->engines[0].empty()) {
this->sel_engine[0] = this->engines[0][0].engine_id; this->sel_engine[0] = this->engines[0][0].engine_id;
} }
} }
if (this->engines[1].NeedRebuild() || e != this->sel_engine[0]) { if (this->engines[1].NeedRebuild() || e != this->sel_engine[0]) {
/* Either we got a request to rebuild the right engines list, or the left engines list selected a different engine */ /* Either we got a request to rebuild the right engines list, or the left engines list selected a different engine */
if (this->sel_engine[0] == INVALID_ENGINE) { if (this->sel_engine[0] == EngineID::Invalid()) {
/* Always empty the right engines list when nothing is selected in the left engines list */ /* Always empty the right engines list when nothing is selected in the left engines list */
this->engines[1].clear(); this->engines[1].clear();
this->sel_engine[1] = INVALID_ENGINE; this->sel_engine[1] = EngineID::Invalid();
this->vscroll[1]->SetCount(this->engines[1].size()); this->vscroll[1]->SetCount(this->engines[1].size());
} else { } else {
if (this->reset_sel_engine && this->sel_engine[0] != INVALID_ENGINE) { if (this->reset_sel_engine && this->sel_engine[0] != EngineID::Invalid()) {
/* Select the current replacement for sel_engine[0]. */ /* Select the current replacement for sel_engine[0]. */
const Company *c = Company::Get(_local_company); const Company *c = Company::Get(_local_company);
this->sel_engine[1] = EngineReplacementForCompany(c, this->sel_engine[0], this->sel_group); this->sel_engine[1] = EngineReplacementForCompany(c, this->sel_engine[0], this->sel_group);
} }
/* Regenerate the list on the right. Note: This resets sel_engine[1] to INVALID_ENGINE, if it is no longer available. */ /* Regenerate the list on the right. Note: This resets sel_engine[1] to EngineID::Invalid(), if it is no longer available. */
this->GenerateReplaceVehList(false); this->GenerateReplaceVehList(false);
this->vscroll[1]->SetCount(this->engines[1].size()); this->vscroll[1]->SetCount(this->engines[1].size());
if (this->reset_sel_engine && this->sel_engine[1] != INVALID_ENGINE) { if (this->reset_sel_engine && this->sel_engine[1] != EngineID::Invalid()) {
int position = 0; int position = 0;
for (const auto &item : this->engines[1]) { for (const auto &item : this->engines[1]) {
if (item.engine_id == this->sel_engine[1]) break; if (item.engine_id == this->sel_engine[1]) break;
@ -272,8 +272,8 @@ public:
this->engines[1].ForceRebuild(); this->engines[1].ForceRebuild();
this->reset_sel_engine = true; this->reset_sel_engine = true;
this->details_height = ((vehicletype == VEH_TRAIN) ? 10 : 9); this->details_height = ((vehicletype == VEH_TRAIN) ? 10 : 9);
this->sel_engine[0] = INVALID_ENGINE; this->sel_engine[0] = EngineID::Invalid();
this->sel_engine[1] = INVALID_ENGINE; this->sel_engine[1] = EngineID::Invalid();
this->show_hidden_engines = _engine_sort_show_hidden_engines[vehicletype]; this->show_hidden_engines = _engine_sort_show_hidden_engines[vehicletype];
this->CreateNestedTree(); this->CreateNestedTree();
@ -441,7 +441,7 @@ public:
case WID_RV_INFO_TAB: { case WID_RV_INFO_TAB: {
const Company *c = Company::Get(_local_company); const Company *c = Company::Get(_local_company);
StringID str; StringID str;
if (this->sel_engine[0] != INVALID_ENGINE) { if (this->sel_engine[0] != EngineID::Invalid()) {
if (!EngineHasReplacementForCompany(c, this->sel_engine[0], this->sel_group)) { if (!EngineHasReplacementForCompany(c, this->sel_engine[0], this->sel_group)) {
str = STR_REPLACE_NOT_REPLACING; str = STR_REPLACE_NOT_REPLACING;
} else { } else {
@ -479,12 +479,12 @@ public:
* Either engines list is empty * Either engines list is empty
* or The selected replacement engine has a replacement (to prevent loops). */ * or The selected replacement engine has a replacement (to prevent loops). */
this->SetWidgetDisabledState(WID_RV_START_REPLACE, this->SetWidgetDisabledState(WID_RV_START_REPLACE,
this->sel_engine[0] == INVALID_ENGINE || this->sel_engine[1] == INVALID_ENGINE || EngineReplacementForCompany(c, this->sel_engine[1], this->sel_group) != INVALID_ENGINE); this->sel_engine[0] == EngineID::Invalid() || this->sel_engine[1] == EngineID::Invalid() || EngineReplacementForCompany(c, this->sel_engine[1], this->sel_group) != EngineID::Invalid());
/* Disable the "Stop Replacing" button if: /* Disable the "Stop Replacing" button if:
* The left engines list (existing vehicle) is empty * The left engines list (existing vehicle) is empty
* or The selected vehicle has no replacement set up */ * or The selected vehicle has no replacement set up */
this->SetWidgetDisabledState(WID_RV_STOP_REPLACE, this->sel_engine[0] == INVALID_ENGINE || !EngineHasReplacementForCompany(c, this->sel_engine[0], this->sel_group)); this->SetWidgetDisabledState(WID_RV_STOP_REPLACE, this->sel_engine[0] == EngineID::Invalid() || !EngineHasReplacementForCompany(c, this->sel_engine[0], this->sel_group));
this->DrawWidgets(); this->DrawWidgets();
@ -492,7 +492,7 @@ public:
int needed_height = this->details_height; int needed_height = this->details_height;
/* Draw details panels. */ /* Draw details panels. */
for (int side = 0; side < 2; side++) { for (int side = 0; side < 2; side++) {
if (this->sel_engine[side] != INVALID_ENGINE) { if (this->sel_engine[side] != EngineID::Invalid()) {
/* Use default engine details without refitting */ /* Use default engine details without refitting */
const Engine *e = Engine::Get(this->sel_engine[side]); const Engine *e = Engine::Get(this->sel_engine[side]);
TestedEngineDetails ted; TestedEngineDetails ted;
@ -575,7 +575,7 @@ public:
case WID_RV_STOP_REPLACE: { // Stop replacing case WID_RV_STOP_REPLACE: { // Stop replacing
EngineID veh_from = this->sel_engine[0]; EngineID veh_from = this->sel_engine[0];
Command<CMD_SET_AUTOREPLACE>::Post(this->sel_group, veh_from, INVALID_ENGINE, false); Command<CMD_SET_AUTOREPLACE>::Post(this->sel_group, veh_from, EngineID::Invalid(), false);
break; break;
} }
@ -588,14 +588,14 @@ public:
click_side = 1; click_side = 1;
} }
EngineID e = INVALID_ENGINE; EngineID e = EngineID::Invalid();
const auto it = this->vscroll[click_side]->GetScrolledItemFromWidget(this->engines[click_side], pt.y, this, widget); const auto it = this->vscroll[click_side]->GetScrolledItemFromWidget(this->engines[click_side], pt.y, this, widget);
if (it != this->engines[click_side].end()) { if (it != this->engines[click_side].end()) {
const auto &item = *it; const auto &item = *it;
const Rect r = this->GetWidget<NWidgetBase>(widget)->GetCurrentRect().Shrink(WidgetDimensions::scaled.matrix).WithWidth(WidgetDimensions::scaled.hsep_indent * (item.indent + 1), _current_text_dir == TD_RTL); const Rect r = this->GetWidget<NWidgetBase>(widget)->GetCurrentRect().Shrink(WidgetDimensions::scaled.matrix).WithWidth(WidgetDimensions::scaled.hsep_indent * (item.indent + 1), _current_text_dir == TD_RTL);
if (item.flags.Test(EngineDisplayFlag::HasVariants) && IsInsideMM(r.left, r.right, pt.x)) { if (item.flags.Test(EngineDisplayFlag::HasVariants) && IsInsideMM(r.left, r.right, pt.x)) {
/* toggle folded flag on engine */ /* toggle folded flag on engine */
assert(item.variant_id != INVALID_ENGINE); assert(item.variant_id != EngineID::Invalid());
Engine *engine = Engine::Get(item.variant_id); Engine *engine = Engine::Get(item.variant_id);
engine->display_flags.Flip(EngineDisplayFlag::IsFolded); engine->display_flags.Flip(EngineDisplayFlag::IsFolded);
@ -608,10 +608,10 @@ public:
/* If Ctrl is pressed on the left side and we don't have any engines of the selected type, stop autoreplacing. /* If Ctrl is pressed on the left side and we don't have any engines of the selected type, stop autoreplacing.
* This is most common when we have finished autoreplacing the engine and want to remove it from the list. */ * This is most common when we have finished autoreplacing the engine and want to remove it from the list. */
if (click_side == 0 && _ctrl_pressed && e != INVALID_ENGINE && if (click_side == 0 && _ctrl_pressed && e != EngineID::Invalid() &&
(GetGroupNumEngines(_local_company, sel_group, e) == 0 || GetGroupNumEngines(_local_company, ALL_GROUP, e) == 0)) { (GetGroupNumEngines(_local_company, sel_group, e) == 0 || GetGroupNumEngines(_local_company, ALL_GROUP, e) == 0)) {
EngineID veh_from = e; EngineID veh_from = e;
Command<CMD_SET_AUTOREPLACE>::Post(this->sel_group, veh_from, INVALID_ENGINE, false); Command<CMD_SET_AUTOREPLACE>::Post(this->sel_group, veh_from, EngineID::Invalid(), false);
break; break;
} }

View File

@ -132,7 +132,7 @@ static bool EngineIntroDateSorter(const GUIEngineListItem &a, const GUIEngineLis
} }
/* cached values for EngineNameSorter to spare many GetString() calls */ /* cached values for EngineNameSorter to spare many GetString() calls */
static EngineID _last_engine[2] = { INVALID_ENGINE, INVALID_ENGINE }; static EngineID _last_engine[2] = { EngineID::Invalid(), EngineID::Invalid() };
/** /**
* Determines order of engines by name * Determines order of engines by name
@ -1132,8 +1132,8 @@ void GUIEngineListAddChildren(GUIEngineList &dst, const GUIEngineList &src, Engi
const Engine *e = Engine::Get(item.engine_id); const Engine *e = Engine::Get(item.engine_id);
EngineDisplayFlags flags = item.flags; EngineDisplayFlags flags = item.flags;
if (e->display_last_variant != INVALID_ENGINE) flags.Reset(EngineDisplayFlag::Shaded); if (e->display_last_variant != EngineID::Invalid()) flags.Reset(EngineDisplayFlag::Shaded);
dst.emplace_back(e->display_last_variant == INVALID_ENGINE ? item.engine_id : e->display_last_variant, item.engine_id, flags, indent); dst.emplace_back(e->display_last_variant == EngineID::Invalid() ? item.engine_id : e->display_last_variant, item.engine_id, flags, indent);
/* Add variants if not folded */ /* Add variants if not folded */
if (item.flags.Test(EngineDisplayFlag::HasVariants) && !item.flags.Test(EngineDisplayFlag::IsFolded)) { if (item.flags.Test(EngineDisplayFlag::HasVariants) && !item.flags.Test(EngineDisplayFlag::IsFolded)) {
@ -1172,7 +1172,7 @@ struct BuildVehicleWindow : Window {
uint8_t sort_criteria; ///< Current sort criterium. uint8_t sort_criteria; ///< Current sort criterium.
bool show_hidden_engines; ///< State of the 'show hidden engines' button. bool show_hidden_engines; ///< State of the 'show hidden engines' button.
bool listview_mode; ///< If set, only display the available vehicles and do not show a 'build' button. bool listview_mode; ///< If set, only display the available vehicles and do not show a 'build' button.
EngineID sel_engine; ///< Currently selected engine, or #INVALID_ENGINE EngineID sel_engine; ///< Currently selected engine, or #EngineID::Invalid()
EngineID rename_engine; ///< Engine being renamed. EngineID rename_engine; ///< Engine being renamed.
GUIEngineList eng_list; GUIEngineList eng_list;
CargoType cargo_filter_criteria; ///< Selected cargo filter CargoType cargo_filter_criteria; ///< Selected cargo filter
@ -1187,7 +1187,7 @@ struct BuildVehicleWindow : Window {
{ {
NWidgetCore *widget = this->GetWidget<NWidgetCore>(WID_BV_BUILD); NWidgetCore *widget = this->GetWidget<NWidgetCore>(WID_BV_BUILD);
bool refit = this->sel_engine != INVALID_ENGINE && this->cargo_filter_criteria != CargoFilterCriteria::CF_ANY && this->cargo_filter_criteria != CargoFilterCriteria::CF_NONE && this->cargo_filter_criteria != CargoFilterCriteria::CF_ENGINES; bool refit = this->sel_engine != EngineID::Invalid() && this->cargo_filter_criteria != CargoFilterCriteria::CF_ANY && this->cargo_filter_criteria != CargoFilterCriteria::CF_NONE && this->cargo_filter_criteria != CargoFilterCriteria::CF_ENGINES;
if (refit) refit = Engine::Get(this->sel_engine)->GetDefaultCargoType() != this->cargo_filter_criteria; if (refit) refit = Engine::Get(this->sel_engine)->GetDefaultCargoType() != this->cargo_filter_criteria;
if (refit) { if (refit) {
@ -1203,7 +1203,7 @@ struct BuildVehicleWindow : Window {
this->listview_mode = tile == INVALID_TILE; this->listview_mode = tile == INVALID_TILE;
this->window_number = this->listview_mode ? (int)type : tile.base(); this->window_number = this->listview_mode ? (int)type : tile.base();
this->sel_engine = INVALID_ENGINE; this->sel_engine = EngineID::Invalid();
this->sort_criteria = _engine_sort_last_criteria[type]; this->sort_criteria = _engine_sort_last_criteria[type];
this->descending_sort_order = _engine_sort_last_order[type]; this->descending_sort_order = _engine_sort_last_order[type];
@ -1249,7 +1249,7 @@ struct BuildVehicleWindow : Window {
this->GenerateBuildList(); // generate the list, since we need it in the next line this->GenerateBuildList(); // generate the list, since we need it in the next line
/* Select the first unshaded engine in the list as default when opening the window */ /* Select the first unshaded engine in the list as default when opening the window */
EngineID engine = INVALID_ENGINE; EngineID engine = EngineID::Invalid();
auto it = std::ranges::find_if(this->eng_list, [](const GUIEngineListItem &item) { return !item.flags.Test(EngineDisplayFlag::Shaded); }); auto it = std::ranges::find_if(this->eng_list, [](const GUIEngineListItem &item) { return !item.flags.Test(EngineDisplayFlag::Shaded); });
if (it != this->eng_list.end()) engine = it->engine_id; if (it != this->eng_list.end()) engine = it->engine_id;
this->SelectEngine(engine); this->SelectEngine(engine);
@ -1314,7 +1314,7 @@ struct BuildVehicleWindow : Window {
this->sel_engine = engine; this->sel_engine = engine;
this->SetBuyVehicleText(); this->SetBuyVehicleText();
if (this->sel_engine == INVALID_ENGINE) return; if (this->sel_engine == EngineID::Invalid()) return;
const Engine *e = Engine::Get(this->sel_engine); const Engine *e = Engine::Get(this->sel_engine);
@ -1346,7 +1346,7 @@ struct BuildVehicleWindow : Window {
{ {
this->eng_list.Filter(this->cargo_filter_criteria); this->eng_list.Filter(this->cargo_filter_criteria);
if (0 == this->eng_list.size()) { // no engine passed through the filter, invalidate the previously selected engine if (0 == this->eng_list.size()) { // no engine passed through the filter, invalidate the previously selected engine
this->SelectEngine(INVALID_ENGINE); this->SelectEngine(EngineID::Invalid());
} else if (std::ranges::find(this->eng_list, this->sel_engine, &GUIEngineListItem::engine_id) == this->eng_list.end()) { // previously selected engine didn't pass the filter, select the first engine of the list } else if (std::ranges::find(this->eng_list, this->sel_engine, &GUIEngineListItem::engine_id) == this->eng_list.end()) { // previously selected engine didn't pass the filter, select the first engine of the list
this->SelectEngine(this->eng_list[0].engine_id); this->SelectEngine(this->eng_list[0].engine_id);
} }
@ -1380,14 +1380,14 @@ struct BuildVehicleWindow : Window {
void GenerateBuildTrainList(GUIEngineList &list) void GenerateBuildTrainList(GUIEngineList &list)
{ {
std::vector<EngineID> variants; std::vector<EngineID> variants;
EngineID sel_id = INVALID_ENGINE; EngineID sel_id = EngineID::Invalid();
size_t num_engines = 0; size_t num_engines = 0;
list.clear(); list.clear();
/* Make list of all available train engines and wagons. /* Make list of all available train engines and wagons.
* Also check to see if the previously selected engine is still available, * Also check to see if the previously selected engine is still available,
* and if not, reset selection to INVALID_ENGINE. This could be the case * and if not, reset selection to EngineID::Invalid(). This could be the case
* when engines become obsolete and are removed */ * when engines become obsolete and are removed */
for (const Engine *e : Engine::IterateType(VEH_TRAIN)) { for (const Engine *e : Engine::IterateType(VEH_TRAIN)) {
if (!this->show_hidden_engines && e->IsVariantHidden(_local_company)) continue; if (!this->show_hidden_engines && e->IsVariantHidden(_local_company)) continue;
@ -1409,7 +1409,7 @@ struct BuildVehicleWindow : Window {
/* Add all parent variants of this engine to the variant list */ /* Add all parent variants of this engine to the variant list */
EngineID parent = e->info.variant_id; EngineID parent = e->info.variant_id;
while (parent != INVALID_ENGINE) { while (parent != EngineID::Invalid()) {
variants.push_back(parent); variants.push_back(parent);
parent = Engine::Get(parent)->info.variant_id; parent = Engine::Get(parent)->info.variant_id;
} }
@ -1429,7 +1429,7 @@ struct BuildVehicleWindow : Window {
this->SelectEngine(sel_id); this->SelectEngine(sel_id);
/* invalidate cached values for name sorter - engine names could change */ /* invalidate cached values for name sorter - engine names could change */
_last_engine[0] = _last_engine[1] = INVALID_ENGINE; _last_engine[0] = _last_engine[1] = EngineID::Invalid();
/* make engines first, and then wagons, sorted by selected sort_criteria */ /* make engines first, and then wagons, sorted by selected sort_criteria */
_engine_sort_direction = false; _engine_sort_direction = false;
@ -1446,7 +1446,7 @@ struct BuildVehicleWindow : Window {
/* Figure out what road vehicle EngineIDs to put in the list */ /* Figure out what road vehicle EngineIDs to put in the list */
void GenerateBuildRoadVehList() void GenerateBuildRoadVehList()
{ {
EngineID sel_id = INVALID_ENGINE; EngineID sel_id = EngineID::Invalid();
this->eng_list.clear(); this->eng_list.clear();
@ -1469,7 +1469,7 @@ struct BuildVehicleWindow : Window {
/* Figure out what ship EngineIDs to put in the list */ /* Figure out what ship EngineIDs to put in the list */
void GenerateBuildShipList() void GenerateBuildShipList()
{ {
EngineID sel_id = INVALID_ENGINE; EngineID sel_id = EngineID::Invalid();
this->eng_list.clear(); this->eng_list.clear();
for (const Engine *e : Engine::IterateType(VEH_SHIP)) { for (const Engine *e : Engine::IterateType(VEH_SHIP)) {
@ -1490,7 +1490,7 @@ struct BuildVehicleWindow : Window {
/* Figure out what aircraft EngineIDs to put in the list */ /* Figure out what aircraft EngineIDs to put in the list */
void GenerateBuildAircraftList() void GenerateBuildAircraftList()
{ {
EngineID sel_id = INVALID_ENGINE; EngineID sel_id = EngineID::Invalid();
this->eng_list.clear(); this->eng_list.clear();
@ -1498,7 +1498,7 @@ struct BuildVehicleWindow : Window {
/* Make list of all available planes. /* Make list of all available planes.
* Also check to see if the previously selected plane is still available, * Also check to see if the previously selected plane is still available,
* and if not, reset selection to INVALID_ENGINE. This could be the case * and if not, reset selection to EngineID::Invalid(). This could be the case
* when planes become obsolete and are removed */ * when planes become obsolete and are removed */
for (const Engine *e : Engine::IterateType(VEH_AIRCRAFT)) { for (const Engine *e : Engine::IterateType(VEH_AIRCRAFT)) {
if (!this->show_hidden_engines && e->IsVariantHidden(_local_company)) continue; if (!this->show_hidden_engines && e->IsVariantHidden(_local_company)) continue;
@ -1554,7 +1554,7 @@ struct BuildVehicleWindow : Window {
std::vector<EngineID> variants; std::vector<EngineID> variants;
for (const auto &item : this->eng_list) { for (const auto &item : this->eng_list) {
EngineID parent = item.variant_id; EngineID parent = item.variant_id;
while (parent != INVALID_ENGINE) { while (parent != EngineID::Invalid()) {
variants.push_back(parent); variants.push_back(parent);
parent = Engine::Get(parent)->info.variant_id; parent = Engine::Get(parent)->info.variant_id;
} }
@ -1571,7 +1571,7 @@ struct BuildVehicleWindow : Window {
EngList_Sort(this->eng_list, _engine_sort_functions[this->vehicle_type][this->sort_criteria]); EngList_Sort(this->eng_list, _engine_sort_functions[this->vehicle_type][this->sort_criteria]);
this->eng_list.swap(list); this->eng_list.swap(list);
GUIEngineListAddChildren(this->eng_list, list, INVALID_ENGINE, 0); GUIEngineListAddChildren(this->eng_list, list, EngineID::Invalid(), 0);
this->eng_list.RebuildDone(); this->eng_list.RebuildDone();
} }
@ -1602,7 +1602,7 @@ struct BuildVehicleWindow : Window {
void BuildVehicle() void BuildVehicle()
{ {
EngineID sel_eng = this->sel_engine; EngineID sel_eng = this->sel_engine;
if (sel_eng == INVALID_ENGINE) return; if (sel_eng == EngineID::Invalid()) return;
CargoType cargo = this->cargo_filter_criteria; CargoType cargo = this->cargo_filter_criteria;
if (cargo == CargoFilterCriteria::CF_ANY || cargo == CargoFilterCriteria::CF_ENGINES || cargo == CargoFilterCriteria::CF_NONE) cargo = INVALID_CARGO; if (cargo == CargoFilterCriteria::CF_ANY || cargo == CargoFilterCriteria::CF_ENGINES || cargo == CargoFilterCriteria::CF_NONE) cargo = INVALID_CARGO;
@ -1615,7 +1615,7 @@ struct BuildVehicleWindow : Window {
/* Update last used variant in hierarchy and refresh if necessary. */ /* Update last used variant in hierarchy and refresh if necessary. */
bool refresh = false; bool refresh = false;
EngineID parent = sel_eng; EngineID parent = sel_eng;
while (parent != INVALID_ENGINE) { while (parent != EngineID::Invalid()) {
Engine *e = Engine::Get(parent); Engine *e = Engine::Get(parent);
refresh |= (e->display_last_variant != sel_eng); refresh |= (e->display_last_variant != sel_eng);
e->display_last_variant = sel_eng; e->display_last_variant = sel_eng;
@ -1647,14 +1647,14 @@ struct BuildVehicleWindow : Window {
break; break;
case WID_BV_LIST: { case WID_BV_LIST: {
EngineID e = INVALID_ENGINE; EngineID e = EngineID::Invalid();
const auto it = this->vscroll->GetScrolledItemFromWidget(this->eng_list, pt.y, this, WID_BV_LIST); const auto it = this->vscroll->GetScrolledItemFromWidget(this->eng_list, pt.y, this, WID_BV_LIST);
if (it != this->eng_list.end()) { if (it != this->eng_list.end()) {
const auto &item = *it; const auto &item = *it;
const Rect r = this->GetWidget<NWidgetBase>(widget)->GetCurrentRect().Shrink(WidgetDimensions::scaled.matrix).WithWidth(WidgetDimensions::scaled.hsep_indent * (item.indent + 1), _current_text_dir == TD_RTL); const Rect r = this->GetWidget<NWidgetBase>(widget)->GetCurrentRect().Shrink(WidgetDimensions::scaled.matrix).WithWidth(WidgetDimensions::scaled.hsep_indent * (item.indent + 1), _current_text_dir == TD_RTL);
if (item.flags.Test(EngineDisplayFlag::HasVariants) && IsInsideMM(r.left, r.right, pt.x)) { if (item.flags.Test(EngineDisplayFlag::HasVariants) && IsInsideMM(r.left, r.right, pt.x)) {
/* toggle folded flag on engine */ /* toggle folded flag on engine */
assert(item.variant_id != INVALID_ENGINE); assert(item.variant_id != EngineID::Invalid());
Engine *engine = Engine::Get(item.variant_id); Engine *engine = Engine::Get(item.variant_id);
engine->display_flags.Flip(EngineDisplayFlag::IsFolded); engine->display_flags.Flip(EngineDisplayFlag::IsFolded);
@ -1683,7 +1683,7 @@ struct BuildVehicleWindow : Window {
break; break;
case WID_BV_SHOW_HIDE: { case WID_BV_SHOW_HIDE: {
const Engine *e = (this->sel_engine == INVALID_ENGINE) ? nullptr : Engine::Get(this->sel_engine); const Engine *e = (this->sel_engine == EngineID::Invalid()) ? nullptr : Engine::Get(this->sel_engine);
if (e != nullptr) { if (e != nullptr) {
Command<CMD_SET_VEHICLE_VISIBILITY>::Post(this->sel_engine, !e->IsHidden(_current_company)); Command<CMD_SET_VEHICLE_VISIBILITY>::Post(this->sel_engine, !e->IsHidden(_current_company));
} }
@ -1696,7 +1696,7 @@ struct BuildVehicleWindow : Window {
case WID_BV_RENAME: { case WID_BV_RENAME: {
EngineID sel_eng = this->sel_engine; EngineID sel_eng = this->sel_engine;
if (sel_eng != INVALID_ENGINE) { if (sel_eng != EngineID::Invalid()) {
this->rename_engine = sel_eng; this->rename_engine = sel_eng;
ShowQueryString(GetString(STR_ENGINE_NAME, PackEngineNameDParam(sel_eng, EngineNameContext::Generic)), STR_QUERY_RENAME_TRAIN_TYPE_CAPTION + this->vehicle_type, MAX_LENGTH_ENGINE_NAME_CHARS, this, CS_ALPHANUMERAL, QSF_ENABLE_DEFAULT | QSF_LEN_IN_CHARS); ShowQueryString(GetString(STR_ENGINE_NAME, PackEngineNameDParam(sel_eng, EngineNameContext::Generic)), STR_QUERY_RENAME_TRAIN_TYPE_CAPTION + this->vehicle_type, MAX_LENGTH_ENGINE_NAME_CHARS, this, CS_ALPHANUMERAL, QSF_ENABLE_DEFAULT | QSF_LEN_IN_CHARS);
} }
@ -1747,7 +1747,7 @@ struct BuildVehicleWindow : Window {
break; break;
case WID_BV_SHOW_HIDE: { case WID_BV_SHOW_HIDE: {
const Engine *e = (this->sel_engine == INVALID_ENGINE) ? nullptr : Engine::Get(this->sel_engine); const Engine *e = (this->sel_engine == EngineID::Invalid()) ? nullptr : Engine::Get(this->sel_engine);
if (e != nullptr && e->IsHidden(_local_company)) { if (e != nullptr && e->IsHidden(_local_company)) {
SetDParam(0, STR_BUY_VEHICLE_TRAIN_SHOW_TOGGLE_BUTTON + this->vehicle_type); SetDParam(0, STR_BUY_VEHICLE_TRAIN_SHOW_TOGGLE_BUTTON + this->vehicle_type);
} else { } else {
@ -1825,17 +1825,17 @@ struct BuildVehicleWindow : Window {
this->GenerateBuildList(); this->GenerateBuildList();
this->vscroll->SetCount(this->eng_list.size()); this->vscroll->SetCount(this->eng_list.size());
this->SetWidgetsDisabledState(this->sel_engine == INVALID_ENGINE, WID_BV_SHOW_HIDE, WID_BV_BUILD); this->SetWidgetsDisabledState(this->sel_engine == EngineID::Invalid(), WID_BV_SHOW_HIDE, WID_BV_BUILD);
/* Disable renaming engines in network games if you are not the server. */ /* Disable renaming engines in network games if you are not the server. */
this->SetWidgetDisabledState(WID_BV_RENAME, this->sel_engine == INVALID_ENGINE || (_networking && !_network_server)); this->SetWidgetDisabledState(WID_BV_RENAME, this->sel_engine == EngineID::Invalid() || (_networking && !_network_server));
this->DrawWidgets(); this->DrawWidgets();
if (!this->IsShaded()) { if (!this->IsShaded()) {
int needed_height = this->details_height; int needed_height = this->details_height;
/* Draw details panels. */ /* Draw details panels. */
if (this->sel_engine != INVALID_ENGINE) { if (this->sel_engine != EngineID::Invalid()) {
const Rect r = this->GetWidget<NWidgetBase>(WID_BV_PANEL)->GetCurrentRect().Shrink(WidgetDimensions::scaled.framerect); const Rect r = this->GetWidget<NWidgetBase>(WID_BV_PANEL)->GetCurrentRect().Shrink(WidgetDimensions::scaled.framerect);
int text_end = DrawVehiclePurchaseInfo(r.left, r.right, r.top, this->sel_engine, this->te); int text_end = DrawVehiclePurchaseInfo(r.left, r.right, r.top, this->sel_engine, this->te);
needed_height = std::max(needed_height, (text_end - r.top) / GetCharacterHeight(FS_NORMAL)); needed_height = std::max(needed_height, (text_end - r.top) / GetCharacterHeight(FS_NORMAL));

View File

@ -120,22 +120,22 @@ inline bool MonitorMonitorsIndustry(CargoMonitorID num)
/** /**
* Extract the industry number from the cargo monitor. * Extract the industry number from the cargo monitor.
* @param num Cargo monitoring number to decode. * @param num Cargo monitoring number to decode.
* @return The extracted industry id, or #INVALID_INDUSTRY if the number does not monitor an industry. * @return The extracted industry id, or #IndustryID::Invalid() if the number does not monitor an industry.
*/ */
inline IndustryID DecodeMonitorIndustry(CargoMonitorID num) inline IndustryID DecodeMonitorIndustry(CargoMonitorID num)
{ {
if (!MonitorMonitorsIndustry(num)) return INVALID_INDUSTRY; if (!MonitorMonitorsIndustry(num)) return IndustryID::Invalid();
return static_cast<IndustryID>(GB(num, CCB_TOWN_IND_NUMBER_START, CCB_TOWN_IND_NUMBER_LENGTH)); return static_cast<IndustryID>(GB(num, CCB_TOWN_IND_NUMBER_START, CCB_TOWN_IND_NUMBER_LENGTH));
} }
/** /**
* Extract the town number from the cargo monitor. * Extract the town number from the cargo monitor.
* @param num Cargo monitoring number to decode. * @param num Cargo monitoring number to decode.
* @return The extracted town id, or #INVALID_TOWN if the number does not monitor a town. * @return The extracted town id, or #TownID::Invalid() if the number does not monitor a town.
*/ */
inline TownID DecodeMonitorTown(CargoMonitorID num) inline TownID DecodeMonitorTown(CargoMonitorID num)
{ {
if (MonitorMonitorsIndustry(num)) return INVALID_TOWN; if (MonitorMonitorsIndustry(num)) return TownID::Invalid();
return static_cast<TownID>(GB(num, CCB_TOWN_IND_NUMBER_START, CCB_TOWN_IND_NUMBER_LENGTH)); return static_cast<TownID>(GB(num, CCB_TOWN_IND_NUMBER_START, CCB_TOWN_IND_NUMBER_LENGTH));
} }
@ -143,6 +143,6 @@ void ClearCargoPickupMonitoring(CompanyID company = INVALID_OWNER);
void ClearCargoDeliveryMonitoring(CompanyID company = INVALID_OWNER); void ClearCargoDeliveryMonitoring(CompanyID company = INVALID_OWNER);
int32_t GetDeliveryAmount(CargoMonitorID monitor, bool keep_monitoring); int32_t GetDeliveryAmount(CargoMonitorID monitor, bool keep_monitoring);
int32_t GetPickupAmount(CargoMonitorID monitor, bool keep_monitoring); int32_t GetPickupAmount(CargoMonitorID monitor, bool keep_monitoring);
void AddCargoDelivery(CargoType cargo_type, CompanyID company, uint32_t amount, Source src, const Station *st, IndustryID dest = INVALID_INDUSTRY); void AddCargoDelivery(CargoType cargo_type, CompanyID company, uint32_t amount, Source src, const Station *st, IndustryID dest = IndustryID::Invalid());
#endif /* CARGOMONITOR_H */ #endif /* CARGOMONITOR_H */

View File

@ -137,13 +137,13 @@ void CargoPacket::Reduce(uint count)
} }
/** /**
* Invalidates (sets source to INVALID_STATION) all cargo packets from given station. * Invalidates (sets source to StationID::Invalid()) all cargo packets from given station.
* @param sid Station that gets removed. * @param sid Station that gets removed.
*/ */
/* static */ void CargoPacket::InvalidateAllFrom(StationID sid) /* static */ void CargoPacket::InvalidateAllFrom(StationID sid)
{ {
for (CargoPacket *cp : CargoPacket::Iterate()) { for (CargoPacket *cp : CargoPacket::Iterate()) {
if (cp->first_station == sid) cp->first_station = INVALID_STATION; if (cp->first_station == sid) cp->first_station = StationID::Invalid();
} }
} }
@ -406,7 +406,7 @@ void VehicleCargoList::AgeCargo()
/* static */ VehicleCargoList::MoveToAction VehicleCargoList::ChooseAction(const CargoPacket *cp, StationID cargo_next, /* static */ VehicleCargoList::MoveToAction VehicleCargoList::ChooseAction(const CargoPacket *cp, StationID cargo_next,
StationID current_station, bool accepted, StationIDStack next_station) StationID current_station, bool accepted, StationIDStack next_station)
{ {
if (cargo_next == INVALID_STATION) { if (cargo_next == StationID::Invalid()) {
return (accepted && cp->first_station != current_station) ? MTA_DELIVER : MTA_KEEP; return (accepted && cp->first_station != current_station) ? MTA_DELIVER : MTA_KEEP;
} else if (cargo_next == current_station) { } else if (cargo_next == current_station) {
return MTA_DELIVER; return MTA_DELIVER;
@ -452,7 +452,7 @@ bool VehicleCargoList::Stage(bool accepted, StationID current_station, StationID
CargoPacket *cp = *it; CargoPacket *cp = *it;
this->packets.erase(it++); this->packets.erase(it++);
StationID cargo_next = INVALID_STATION; StationID cargo_next = StationID::Invalid();
MoveToAction action = MTA_LOAD; MoveToAction action = MTA_LOAD;
if (force_keep) { if (force_keep) {
action = MTA_KEEP; action = MTA_KEEP;
@ -464,7 +464,7 @@ bool VehicleCargoList::Stage(bool accepted, StationID current_station, StationID
* also not to the current station. */ * also not to the current station. */
FlowStatMap::const_iterator flow_it(flows.find(cp->first_station)); FlowStatMap::const_iterator flow_it(flows.find(cp->first_station));
if (flow_it == flows.end()) { if (flow_it == flows.end()) {
cargo_next = INVALID_STATION; cargo_next = StationID::Invalid();
} else { } else {
FlowStat new_shares = flow_it->second; FlowStat new_shares = flow_it->second;
new_shares.ChangeShare(current_station, INT_MIN); new_shares.ChangeShare(current_station, INT_MIN);
@ -473,7 +473,7 @@ bool VehicleCargoList::Stage(bool accepted, StationID current_station, StationID
new_shares.ChangeShare(StationID{excluded.Pop()}, INT_MIN); new_shares.ChangeShare(StationID{excluded.Pop()}, INT_MIN);
} }
if (new_shares.GetShares()->empty()) { if (new_shares.GetShares()->empty()) {
cargo_next = INVALID_STATION; cargo_next = StationID::Invalid();
} else { } else {
cargo_next = new_shares.GetVia(); cargo_next = new_shares.GetVia();
} }
@ -481,13 +481,13 @@ bool VehicleCargoList::Stage(bool accepted, StationID current_station, StationID
} else { } else {
/* Rewrite an invalid source station to some random other one to /* Rewrite an invalid source station to some random other one to
* avoid keeping the cargo in the vehicle forever. */ * avoid keeping the cargo in the vehicle forever. */
if (cp->first_station == INVALID_STATION && !flows.empty()) { if (cp->first_station == StationID::Invalid() && !flows.empty()) {
cp->first_station = flows.begin()->first; cp->first_station = flows.begin()->first;
} }
bool restricted = false; bool restricted = false;
FlowStatMap::const_iterator flow_it(flows.find(cp->first_station)); FlowStatMap::const_iterator flow_it(flows.find(cp->first_station));
if (flow_it == flows.end()) { if (flow_it == flows.end()) {
cargo_next = INVALID_STATION; cargo_next = StationID::Invalid();
} else { } else {
cargo_next = flow_it->second.GetViaWithRestricted(restricted); cargo_next = flow_it->second.GetViaWithRestricted(restricted);
} }
@ -577,7 +577,7 @@ uint VehicleCargoList::Reassign<VehicleCargoList::MTA_DELIVER, VehicleCargoList:
sum -= cp_split->Count(); sum -= cp_split->Count();
this->packets.insert(it, cp_split); this->packets.insert(it, cp_split);
} }
cp->next_hop = INVALID_STATION; cp->next_hop = StationID::Invalid();
} }
this->action_counts[MTA_DELIVER] -= max_move; this->action_counts[MTA_DELIVER] -= max_move;
@ -734,7 +734,7 @@ bool StationCargoList::ShiftCargo(Taction &action, StationID next)
* will be kept and the loop will be aborted. * will be kept and the loop will be aborted.
* @param action Action instance to be applied. * @param action Action instance to be applied.
* @param next Next hop the cargo wants to visit. * @param next Next hop the cargo wants to visit.
* @param include_invalid If cargo from the INVALID_STATION list should be * @param include_invalid If cargo from the StationID::Invalid() list should be
* used if necessary. * used if necessary.
* @return Amount of cargo actually moved. * @return Amount of cargo actually moved.
*/ */
@ -747,7 +747,7 @@ uint StationCargoList::ShiftCargo(Taction action, StationIDStack next, bool incl
if (action.MaxMove() == 0) break; if (action.MaxMove() == 0) break;
} }
if (include_invalid && action.MaxMove() > 0) { if (include_invalid && action.MaxMove() > 0) {
this->ShiftCargo(action, INVALID_STATION); this->ShiftCargo(action, StationID::Invalid());
} }
return max_move - action.MaxMove(); return max_move - action.MaxMove();
} }

View File

@ -60,8 +60,8 @@ private:
bool in_vehicle = false; ///< NOSAVE: Whether this cargo is in a vehicle or not. bool in_vehicle = false; ///< NOSAVE: Whether this cargo is in a vehicle or not.
#endif /* WITH_ASSERT */ #endif /* WITH_ASSERT */
StationID first_station = INVALID_STATION; ///< The station where the cargo came from first. StationID first_station = StationID::Invalid(); ///< The station where the cargo came from first.
StationID next_hop = INVALID_STATION; ///< Station where the cargo wants to go next. StationID next_hop = StationID::Invalid(); ///< Station where the cargo wants to go next.
/** The CargoList caches, thus needs to know about it. */ /** The CargoList caches, thus needs to know about it. */
template <class Tinst, class Tcont> friend class CargoList; template <class Tinst, class Tcont> friend class CargoList;
@ -395,7 +395,7 @@ public:
*/ */
inline StationID GetFirstStation() const inline StationID GetFirstStation() const
{ {
return this->count == 0 ? INVALID_STATION : this->packets.front()->first_station; return this->count == 0 ? StationID::Invalid() : this->packets.front()->first_station;
} }
/** /**
@ -557,8 +557,8 @@ public:
while (!next.IsEmpty()) { while (!next.IsEmpty()) {
if (this->packets.find(StationID{next.Pop()}) != this->packets.end()) return true; if (this->packets.find(StationID{next.Pop()}) != this->packets.end()) return true;
} }
/* Packets for INVALID_STATION can go anywhere. */ /* Packets for StationID::Invalid() can go anywhere. */
return this->packets.find(INVALID_STATION) != this->packets.end(); return this->packets.find(StationID::Invalid()) != this->packets.end();
} }
/** /**
@ -567,7 +567,7 @@ public:
*/ */
inline StationID GetFirstStation() const inline StationID GetFirstStation() const
{ {
return this->count == 0 ? INVALID_STATION : this->packets.begin()->second.front()->first_station; return this->count == 0 ? StationID::Invalid() : this->packets.begin()->second.front()->first_station;
} }
/** /**

View File

@ -265,7 +265,7 @@ static void TileLoop_Clear(TileIndex tile)
SetClearCounter(tile, 0); SetClearCounter(tile, 0);
} }
if (GetIndustryIndexOfField(tile) == INVALID_INDUSTRY && GetFieldType(tile) >= 7) { if (GetIndustryIndexOfField(tile) == IndustryID::Invalid() && GetFieldType(tile) >= 7) {
/* This farmfield is no longer farmfield, so make it grass again */ /* This farmfield is no longer farmfield, so make it grass again */
MakeClear(tile, CLEAR_GRASS, 2); MakeClear(tile, CLEAR_GRASS, 2);
} else { } else {

View File

@ -26,7 +26,7 @@ class CommandCost {
StringID message; ///< Warning message for when success is unset StringID message; ///< Warning message for when success is unset
ExpensesType expense_type; ///< the type of expence as shown on the finances view ExpensesType expense_type; ///< the type of expence as shown on the finances view
bool success; ///< Whether the command went fine up to this moment bool success; ///< Whether the command went fine up to this moment
Owner owner = INVALID_COMPANY; ///< Originator owner of error. Owner owner = CompanyID::Invalid(); ///< Originator owner of error.
const GRFFile *textref_stack_grffile = nullptr; ///< NewGRF providing the #TextRefStack content. const GRFFile *textref_stack_grffile = nullptr; ///< NewGRF providing the #TextRefStack content.
uint textref_stack_size = 0; ///< Number of uint32_t values to put on the #TextRefStack for the error message. uint textref_stack_size = 0; ///< Number of uint32_t values to put on the #TextRefStack for the error message.
StringID extra_message = INVALID_STRING_ID; ///< Additional warning message for when success is unset StringID extra_message = INVALID_STRING_ID; ///< Additional warning message for when success is unset

View File

@ -73,7 +73,7 @@ Company::Company(StringID name_1, bool is_ai)
this->tree_limit = (uint32_t)_settings_game.construction.tree_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->build_object_limit = (uint32_t)_settings_game.construction.build_object_frame_burst << 16;
InvalidateWindowData(WC_PERFORMANCE_DETAIL, 0, INVALID_COMPANY); InvalidateWindowData(WC_PERFORMANCE_DETAIL, 0, CompanyID::Invalid());
} }
/** Destructor. */ /** Destructor. */
@ -574,7 +574,7 @@ void ResetCompanyLivery(Company *c)
* @param company CompanyID to use for the new company * @param company CompanyID to use for the new company
* @return the company struct * @return the company struct
*/ */
Company *DoStartupNewCompany(bool is_ai, CompanyID company = INVALID_COMPANY) Company *DoStartupNewCompany(bool is_ai, CompanyID company = CompanyID::Invalid())
{ {
if (!Company::CanAllocateItem()) return nullptr; if (!Company::CanAllocateItem()) return nullptr;
@ -582,7 +582,7 @@ Company *DoStartupNewCompany(bool is_ai, CompanyID company = INVALID_COMPANY)
Colours colour = GenerateCompanyColour(); Colours colour = GenerateCompanyColour();
Company *c; Company *c;
if (company == INVALID_COMPANY) { if (company == CompanyID::Invalid()) {
c = new Company(STR_SV_UNNAMED, is_ai); c = new Company(STR_SV_UNNAMED, is_ai);
} else { } else {
if (Company::IsValidID(company)) return nullptr; if (Company::IsValidID(company)) return nullptr;
@ -644,7 +644,7 @@ TimeoutTimer<TimerGameTick> _new_competitor_timeout({ TimerGameTick::Priority::C
/* Send a command to all clients to start up a new AI. /* Send a command to all clients to start up a new AI.
* Works fine for Multiplayer and Singleplayer */ * Works fine for Multiplayer and Singleplayer */
Command<CMD_COMPANY_CTRL>::Post(CCA_NEW_AI, INVALID_COMPANY, CRR_NONE, INVALID_CLIENT_ID); Command<CMD_COMPANY_CTRL>::Post(CCA_NEW_AI, CompanyID::Invalid(), CRR_NONE, INVALID_CLIENT_ID);
}); });
/** Start of a new game. */ /** Start of a new game. */
@ -764,7 +764,7 @@ void OnTick_Companies()
for (auto i = 0; i < _settings_game.difficulty.max_no_competitors; i++) { for (auto i = 0; i < _settings_game.difficulty.max_no_competitors; i++) {
if (_networking && Company::GetNumItems() >= _settings_client.network.max_companies) break; if (_networking && Company::GetNumItems() >= _settings_client.network.max_companies) break;
if (n++ >= _settings_game.difficulty.max_no_competitors) break; if (n++ >= _settings_game.difficulty.max_no_competitors) break;
Command<CMD_COMPANY_CTRL>::Post(CCA_NEW_AI, INVALID_COMPANY, CRR_NONE, INVALID_CLIENT_ID); Command<CMD_COMPANY_CTRL>::Post(CCA_NEW_AI, CompanyID::Invalid(), CRR_NONE, INVALID_CLIENT_ID);
} }
timeout = 10 * 60 * Ticks::TICKS_PER_SECOND; timeout = 10 * 60 * Ticks::TICKS_PER_SECOND;
} }
@ -906,15 +906,15 @@ CommandCost CmdCompanyCtrl(DoCommandFlags flags, CompanyCtrlAction cca, CompanyI
} }
case CCA_NEW_AI: { // Make a new AI company case CCA_NEW_AI: { // Make a new AI company
if (company_id != INVALID_COMPANY && company_id >= MAX_COMPANIES) return CMD_ERROR; if (company_id != CompanyID::Invalid() && company_id >= MAX_COMPANIES) return CMD_ERROR;
/* For network games, company deletion is delayed. */ /* For network games, company deletion is delayed. */
if (!_networking && company_id != INVALID_COMPANY && Company::IsValidID(company_id)) return CMD_ERROR; if (!_networking && company_id != CompanyID::Invalid() && Company::IsValidID(company_id)) return CMD_ERROR;
if (!flags.Test(DoCommandFlag::Execute)) return CommandCost(); if (!flags.Test(DoCommandFlag::Execute)) return CommandCost();
/* For network game, just assume deletion happened. */ /* For network game, just assume deletion happened. */
assert(company_id == INVALID_COMPANY || !Company::IsValidID(company_id)); assert(company_id == CompanyID::Invalid() || !Company::IsValidID(company_id));
Company *c = DoStartupNewCompany(true, company_id); Company *c = DoStartupNewCompany(true, company_id);
if (c != nullptr) { if (c != nullptr) {
@ -1325,7 +1325,7 @@ CommandCost CmdGiveMoney(DoCommandFlags flags, Money money, CompanyID dest_compa
* to get the index of the company: * to get the index of the company:
* 1st - get the first existing human company. * 1st - get the first existing human company.
* 2nd - get the first non-existing company. * 2nd - get the first non-existing company.
* 3rd - get COMPANY_FIRST. * 3rd - get CompanyID::Begin().
* @return the index of the first available company. * @return the index of the first available company.
*/ */
CompanyID GetFirstPlayableCompanyID() CompanyID GetFirstPlayableCompanyID()
@ -1337,12 +1337,12 @@ CompanyID GetFirstPlayableCompanyID()
} }
if (Company::CanAllocateItem()) { if (Company::CanAllocateItem()) {
for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; ++c) { for (CompanyID c = CompanyID::Begin(); c < MAX_COMPANIES; ++c) {
if (!Company::IsValidID(c)) { if (!Company::IsValidID(c)) {
return c; return c;
} }
} }
} }
return COMPANY_FIRST; return CompanyID::Begin();
} }

View File

@ -634,7 +634,7 @@ private:
} else { } else {
const Group *g = Group::Get(this->sel); const Group *g = Group::Get(this->sel);
livery = &g->livery; livery = &g->livery;
if (g->parent == INVALID_GROUP) { if (g->parent == GroupID::Invalid()) {
default_livery = &c->livery[LS_DEFAULT]; default_livery = &c->livery[LS_DEFAULT];
} else { } else {
const Group *pg = Group::Get(g->parent); const Group *pg = Group::Get(g->parent);
@ -697,7 +697,7 @@ public:
this->CreateNestedTree(); this->CreateNestedTree();
this->vscroll = this->GetScrollbar(WID_SCL_MATRIX_SCROLLBAR); this->vscroll = this->GetScrollbar(WID_SCL_MATRIX_SCROLLBAR);
if (group == INVALID_GROUP) { if (group == GroupID::Invalid()) {
this->livery_class = LC_OTHER; this->livery_class = LC_OTHER;
this->sel = 1; this->sel = 1;
this->LowerWidget(WID_SCL_CLASS_GENERAL); this->LowerWidget(WID_SCL_CLASS_GENERAL);
@ -796,7 +796,7 @@ public:
bool local = this->window_number == _local_company; bool local = this->window_number == _local_company;
/* Disable dropdown controls if no scheme is selected */ /* Disable dropdown controls if no scheme is selected */
bool disabled = this->livery_class < LC_GROUP_RAIL ? (this->sel == 0) : (this->sel == INVALID_GROUP); bool disabled = this->livery_class < LC_GROUP_RAIL ? (this->sel == 0) : (this->sel == GroupID::Invalid());
this->SetWidgetDisabledState(WID_SCL_PRI_COL_DROPDOWN, !local || disabled); this->SetWidgetDisabledState(WID_SCL_PRI_COL_DROPDOWN, !local || disabled);
this->SetWidgetDisabledState(WID_SCL_SEC_COL_DROPDOWN, !local || disabled); this->SetWidgetDisabledState(WID_SCL_SEC_COL_DROPDOWN, !local || disabled);
@ -831,7 +831,7 @@ public:
} }
} }
} else { } else {
if (this->sel != INVALID_GROUP) { if (this->sel != GroupID::Invalid()) {
const Group *g = Group::Get(this->sel); const Group *g = Group::Get(this->sel);
const Livery *livery = &g->livery; const Livery *livery = &g->livery;
if (HasBit(livery->in_use, primary ? 0 : 1)) { if (HasBit(livery->in_use, primary ? 0 : 1)) {
@ -944,7 +944,7 @@ public:
} }
} }
} else { } else {
this->sel = INVALID_GROUP.base(); this->sel = GroupID::Invalid().base();
this->groups.ForceRebuild(); this->groups.ForceRebuild();
this->BuildGroupList(this->window_number); this->BuildGroupList(this->window_number);
@ -1038,7 +1038,7 @@ public:
this->SetRows(); this->SetRows();
if (!Group::IsValidID(this->sel)) { if (!Group::IsValidID(this->sel)) {
this->sel = INVALID_GROUP.base(); this->sel = GroupID::Invalid().base();
if (!this->groups.empty()) this->sel = this->groups[0].group->index.base(); if (!this->groups.empty()) this->sel = this->groups[0].group->index.base();
} }
@ -1112,7 +1112,7 @@ void ShowCompanyLiveryWindow(CompanyID company, GroupID group)
SelectCompanyLiveryWindow *w = (SelectCompanyLiveryWindow *)BringWindowToFrontById(WC_COMPANY_COLOUR, company); SelectCompanyLiveryWindow *w = (SelectCompanyLiveryWindow *)BringWindowToFrontById(WC_COMPANY_COLOUR, company);
if (w == nullptr) { if (w == nullptr) {
new SelectCompanyLiveryWindow(_select_company_livery_desc, company, group); new SelectCompanyLiveryWindow(_select_company_livery_desc, company, group);
} else if (group != INVALID_GROUP) { } else if (group != GroupID::Invalid()) {
w->SetSelectedGroup(company, group); w->SetSelectedGroup(company, group);
} }
} }
@ -2452,7 +2452,7 @@ struct CompanyWindow : Window
case WID_C_NEW_FACE: DoSelectCompanyManagerFace(this); break; case WID_C_NEW_FACE: DoSelectCompanyManagerFace(this); break;
case WID_C_COLOUR_SCHEME: case WID_C_COLOUR_SCHEME:
ShowCompanyLiveryWindow(this->window_number, INVALID_GROUP); ShowCompanyLiveryWindow(this->window_number, GroupID::Invalid());
break; break;
case WID_C_PRESIDENT_NAME: case WID_C_PRESIDENT_NAME:

View File

@ -14,8 +14,6 @@
#include "core/pool_type.hpp" #include "core/pool_type.hpp"
using CompanyID = PoolID<uint8_t, struct CompanyIDTag, 0xF, 0xFF>; using CompanyID = PoolID<uint8_t, struct CompanyIDTag, 0xF, 0xFF>;
static constexpr CompanyID COMPANY_FIRST = CompanyID::Begin();
static constexpr CompanyID INVALID_COMPANY = CompanyID::Invalid(); ///< An invalid company
/* 'Fake' companies used for networks */ /* 'Fake' companies used for networks */
static constexpr CompanyID COMPANY_INACTIVE_CLIENT{253}; ///< The client is joining static constexpr CompanyID COMPANY_INACTIVE_CLIENT{253}; ///< The client is joining

View File

@ -40,7 +40,7 @@ void IConsoleInit()
{ {
_iconsole_output_file = std::nullopt; _iconsole_output_file = std::nullopt;
_redirect_console_to_client = INVALID_CLIENT_ID; _redirect_console_to_client = INVALID_CLIENT_ID;
_redirect_console_to_admin = INVALID_ADMIN_ID; _redirect_console_to_admin = AdminID::Invalid();
IConsoleGUIInit(); IConsoleGUIInit();
@ -96,7 +96,7 @@ void IConsolePrint(TextColour colour_code, const std::string &string)
return; return;
} }
if (_redirect_console_to_admin != INVALID_ADMIN_ID) { if (_redirect_console_to_admin != AdminID::Invalid()) {
NetworkServerSendAdminRcon(_redirect_console_to_admin, colour_code, string); NetworkServerSendAdminRcon(_redirect_console_to_admin, colour_code, string);
return; return;
} }

View File

@ -1088,7 +1088,7 @@ DEF_CONSOLE_CMD(ConNetworkReconnect)
default: default:
/* From a user pov 0 is a new company, internally it's different and all /* From a user pov 0 is a new company, internally it's different and all
* companies are offset by one to ease up on users (eg companies 1-8 not 0-7) */ * companies are offset by one to ease up on users (eg companies 1-8 not 0-7) */
if (playas < COMPANY_FIRST + 1 || playas > MAX_COMPANIES + 1) return false; if (playas < CompanyID::Begin() + 1 || playas > MAX_COMPANIES + 1) return false;
break; break;
} }
@ -1451,7 +1451,7 @@ DEF_CONSOLE_CMD(ConStartAI)
} }
/* Start a new AI company */ /* Start a new AI company */
Command<CMD_COMPANY_CTRL>::Post(CCA_NEW_AI, INVALID_COMPANY, CRR_NONE, INVALID_CLIENT_ID); Command<CMD_COMPANY_CTRL>::Post(CCA_NEW_AI, CompanyID::Invalid(), CRR_NONE, INVALID_CLIENT_ID);
return true; return true;
} }
@ -1898,7 +1898,7 @@ DEF_CONSOLE_CMD(ConSay)
if (!_network_server) { if (!_network_server) {
NetworkClientSendChat(NETWORK_ACTION_CHAT, DESTTYPE_BROADCAST, 0 /* param does not matter */, argv[1]); NetworkClientSendChat(NETWORK_ACTION_CHAT, DESTTYPE_BROADCAST, 0 /* param does not matter */, argv[1]);
} else { } else {
bool from_admin = (_redirect_console_to_admin < INVALID_ADMIN_ID); bool from_admin = (_redirect_console_to_admin < AdminID::Invalid());
NetworkServerSendChat(NETWORK_ACTION_CHAT, DESTTYPE_BROADCAST, 0, argv[1], CLIENT_ID_SERVER, from_admin); NetworkServerSendChat(NETWORK_ACTION_CHAT, DESTTYPE_BROADCAST, 0, argv[1], CLIENT_ID_SERVER, from_admin);
} }
@ -1924,7 +1924,7 @@ DEF_CONSOLE_CMD(ConSayCompany)
if (!_network_server) { if (!_network_server) {
NetworkClientSendChat(NETWORK_ACTION_CHAT_COMPANY, DESTTYPE_TEAM, company_id.base(), argv[2]); NetworkClientSendChat(NETWORK_ACTION_CHAT_COMPANY, DESTTYPE_TEAM, company_id.base(), argv[2]);
} else { } else {
bool from_admin = (_redirect_console_to_admin < INVALID_ADMIN_ID); bool from_admin = (_redirect_console_to_admin < AdminID::Invalid());
NetworkServerSendChat(NETWORK_ACTION_CHAT_COMPANY, DESTTYPE_TEAM, company_id.base(), argv[2], CLIENT_ID_SERVER, from_admin); NetworkServerSendChat(NETWORK_ACTION_CHAT_COMPANY, DESTTYPE_TEAM, company_id.base(), argv[2], CLIENT_ID_SERVER, from_admin);
} }
@ -1944,7 +1944,7 @@ DEF_CONSOLE_CMD(ConSayClient)
if (!_network_server) { if (!_network_server) {
NetworkClientSendChat(NETWORK_ACTION_CHAT_CLIENT, DESTTYPE_CLIENT, atoi(argv[1]), argv[2]); NetworkClientSendChat(NETWORK_ACTION_CHAT_CLIENT, DESTTYPE_CLIENT, atoi(argv[1]), argv[2]);
} else { } else {
bool from_admin = (_redirect_console_to_admin < INVALID_ADMIN_ID); bool from_admin = (_redirect_console_to_admin < AdminID::Invalid());
NetworkServerSendChat(NETWORK_ACTION_CHAT_CLIENT, DESTTYPE_CLIENT, atoi(argv[1]), argv[2], CLIENT_ID_SERVER, from_admin); NetworkServerSendChat(NETWORK_ACTION_CHAT_CLIENT, DESTTYPE_CLIENT, atoi(argv[1]), argv[2], CLIENT_ID_SERVER, from_admin);
} }
@ -1964,7 +1964,7 @@ enum ConNetworkAuthorizedKeyAction : uint8_t {
CNAKA_REMOVE, CNAKA_REMOVE,
}; };
static void PerformNetworkAuthorizedKeyAction(std::string_view name, NetworkAuthorizedKeys *authorized_keys, ConNetworkAuthorizedKeyAction action, const std::string &authorized_key, CompanyID company = INVALID_COMPANY) static void PerformNetworkAuthorizedKeyAction(std::string_view name, NetworkAuthorizedKeys *authorized_keys, ConNetworkAuthorizedKeyAction action, const std::string &authorized_key, CompanyID company = CompanyID::Invalid())
{ {
switch (action) { switch (action) {
case CNAKA_LIST: case CNAKA_LIST:
@ -1978,7 +1978,7 @@ static void PerformNetworkAuthorizedKeyAction(std::string_view name, NetworkAuth
return; return;
} }
if (company == INVALID_COMPANY) { if (company == CompanyID::Invalid()) {
authorized_keys->Add(authorized_key); authorized_keys->Add(authorized_key);
} else { } else {
AutoRestoreBackup backup(_current_company, company); AutoRestoreBackup backup(_current_company, company);
@ -1993,7 +1993,7 @@ static void PerformNetworkAuthorizedKeyAction(std::string_view name, NetworkAuth
return; return;
} }
if (company == INVALID_COMPANY) { if (company == CompanyID::Invalid()) {
authorized_keys->Remove(authorized_key); authorized_keys->Remove(authorized_key);
} else { } else {
AutoRestoreBackup backup(_current_company, company); AutoRestoreBackup backup(_current_company, company);

View File

@ -144,7 +144,7 @@ static void TrainDepotMoveVehicle(const Vehicle *wagon, VehicleID sel, const Veh
if (wagon == v) return; if (wagon == v) return;
Command<CMD_MOVE_RAIL_VEHICLE>::Post(STR_ERROR_CAN_T_MOVE_VEHICLE, v->tile, v->index, wagon == nullptr ? INVALID_VEHICLE : wagon->index, _ctrl_pressed); Command<CMD_MOVE_RAIL_VEHICLE>::Post(STR_ERROR_CAN_T_MOVE_VEHICLE, v->tile, v->index, wagon == nullptr ? VehicleID::Invalid() : wagon->index, _ctrl_pressed);
} }
static VehicleCellSize _base_block_sizes_depot[VEH_COMPANY_END]; ///< Cell size for vehicle images in the depot view. static VehicleCellSize _base_block_sizes_depot[VEH_COMPANY_END]; ///< Cell size for vehicle images in the depot view.
@ -255,7 +255,7 @@ const Sprite *GetAircraftSprite(EngineID engine);
struct DepotWindow : Window { struct DepotWindow : Window {
VehicleID sel; VehicleID sel;
VehicleID vehicle_over; ///< Rail vehicle over which another one is dragged, \c INVALID_VEHICLE if none. VehicleID vehicle_over; ///< Rail vehicle over which another one is dragged, \c VehicleID::Invalid() if none.
VehicleType type; VehicleType type;
bool generate_list; bool generate_list;
bool check_unitnumber_digits; bool check_unitnumber_digits;
@ -271,8 +271,8 @@ struct DepotWindow : Window {
{ {
assert(IsCompanyBuildableVehicleType(type)); // ensure that we make the call with a valid type assert(IsCompanyBuildableVehicleType(type)); // ensure that we make the call with a valid type
this->sel = INVALID_VEHICLE; this->sel = VehicleID::Invalid();
this->vehicle_over = INVALID_VEHICLE; this->vehicle_over = VehicleID::Invalid();
this->generate_list = true; this->generate_list = true;
this->check_unitnumber_digits = true; this->check_unitnumber_digits = true;
this->hovered_widget = -1; this->hovered_widget = -1;
@ -558,8 +558,8 @@ struct DepotWindow : Window {
VehicleID sel = this->sel; VehicleID sel = this->sel;
if (this->type == VEH_TRAIN && sel != INVALID_VEHICLE) { if (this->type == VEH_TRAIN && sel != VehicleID::Invalid()) {
this->sel = INVALID_VEHICLE; this->sel = VehicleID::Invalid();
TrainDepotMoveVehicle(v, sel, gdvp.head); TrainDepotMoveVehicle(v, sel, gdvp.head);
} else if (v != nullptr) { } else if (v != nullptr) {
SetObjectToPlaceWnd(SPR_CURSOR_MOUSE, PAL_NONE, HT_DRAG, this); SetObjectToPlaceWnd(SPR_CURSOR_MOUSE, PAL_NONE, HT_DRAG, this);
@ -980,8 +980,8 @@ struct DepotWindow : Window {
this->SetWidgetDirty(WID_D_CLONE); this->SetWidgetDirty(WID_D_CLONE);
/* abort drag & drop */ /* abort drag & drop */
this->sel = INVALID_VEHICLE; this->sel = VehicleID::Invalid();
this->vehicle_over = INVALID_VEHICLE; this->vehicle_over = VehicleID::Invalid();
this->SetWidgetDirty(WID_D_MATRIX); this->SetWidgetDirty(WID_D_MATRIX);
if (this->hovered_widget != -1) { if (this->hovered_widget != -1) {
@ -1002,7 +1002,7 @@ struct DepotWindow : Window {
void OnMouseDrag(Point pt, WidgetID widget) override void OnMouseDrag(Point pt, WidgetID widget) override
{ {
if (this->sel == INVALID_VEHICLE) return; if (this->sel == VehicleID::Invalid()) return;
if (widget != this->hovered_widget) { if (widget != this->hovered_widget) {
if (this->hovered_widget == WID_D_SELL || this->hovered_widget == WID_D_SELL_CHAIN) { if (this->hovered_widget == WID_D_SELL || this->hovered_widget == WID_D_SELL_CHAIN) {
this->SetWidgetLoweredState(this->hovered_widget, false); this->SetWidgetLoweredState(this->hovered_widget, false);
@ -1018,8 +1018,8 @@ struct DepotWindow : Window {
/* A rail vehicle is dragged.. */ /* A rail vehicle is dragged.. */
if (widget != WID_D_MATRIX) { // ..outside of the depot matrix. if (widget != WID_D_MATRIX) { // ..outside of the depot matrix.
if (this->vehicle_over != INVALID_VEHICLE) { if (this->vehicle_over != VehicleID::Invalid()) {
this->vehicle_over = INVALID_VEHICLE; this->vehicle_over = VehicleID::Invalid();
this->SetWidgetDirty(WID_D_MATRIX); this->SetWidgetDirty(WID_D_MATRIX);
} }
return; return;
@ -1030,7 +1030,7 @@ struct DepotWindow : Window {
if (this->GetVehicleFromDepotWndPt(pt.x, pt.y, &v, &gdvp) != MODE_DRAG_VEHICLE) return; if (this->GetVehicleFromDepotWndPt(pt.x, pt.y, &v, &gdvp) != MODE_DRAG_VEHICLE) return;
VehicleID new_vehicle_over = INVALID_VEHICLE; VehicleID new_vehicle_over = VehicleID::Invalid();
if (gdvp.head != nullptr) { if (gdvp.head != nullptr) {
if (gdvp.wagon == nullptr && gdvp.head->Last()->index != this->sel) { // ..at the end of the train. if (gdvp.wagon == nullptr && gdvp.head->Last()->index != this->sel) { // ..at the end of the train.
/* NOTE: As a wagon can't be moved at the begin of a train, head index isn't used to mark a drag-and-drop /* NOTE: As a wagon can't be moved at the begin of a train, head index isn't used to mark a drag-and-drop
@ -1058,17 +1058,17 @@ struct DepotWindow : Window {
const Vehicle *v = nullptr; const Vehicle *v = nullptr;
VehicleID sel = this->sel; VehicleID sel = this->sel;
this->sel = INVALID_VEHICLE; this->sel = VehicleID::Invalid();
this->SetDirty(); this->SetDirty();
if (this->type == VEH_TRAIN) { if (this->type == VEH_TRAIN) {
GetDepotVehiclePtData gdvp = { nullptr, nullptr }; GetDepotVehiclePtData gdvp = { nullptr, nullptr };
if (this->GetVehicleFromDepotWndPt(pt.x, pt.y, &v, &gdvp) == MODE_DRAG_VEHICLE && sel != INVALID_VEHICLE) { if (this->GetVehicleFromDepotWndPt(pt.x, pt.y, &v, &gdvp) == MODE_DRAG_VEHICLE && sel != VehicleID::Invalid()) {
if (gdvp.wagon != nullptr && gdvp.wagon->index == sel && _ctrl_pressed) { if (gdvp.wagon != nullptr && gdvp.wagon->index == sel && _ctrl_pressed) {
Command<CMD_REVERSE_TRAIN_DIRECTION>::Post(STR_ERROR_CAN_T_REVERSE_DIRECTION_RAIL_VEHICLE, Vehicle::Get(sel)->tile, Vehicle::Get(sel)->index, true); Command<CMD_REVERSE_TRAIN_DIRECTION>::Post(STR_ERROR_CAN_T_REVERSE_DIRECTION_RAIL_VEHICLE, Vehicle::Get(sel)->tile, Vehicle::Get(sel)->index, true);
} else if (gdvp.wagon == nullptr || gdvp.wagon->index != sel) { } else if (gdvp.wagon == nullptr || gdvp.wagon->index != sel) {
this->vehicle_over = INVALID_VEHICLE; this->vehicle_over = VehicleID::Invalid();
TrainDepotMoveVehicle(gdvp.wagon, sel, gdvp.head); TrainDepotMoveVehicle(gdvp.wagon, sel, gdvp.head);
} else if (gdvp.head != nullptr && gdvp.head->IsFrontEngine()) { } else if (gdvp.head != nullptr && gdvp.head->IsFrontEngine()) {
ShowVehicleViewWindow(gdvp.head); ShowVehicleViewWindow(gdvp.head);
@ -1082,12 +1082,12 @@ struct DepotWindow : Window {
case WID_D_SELL: case WID_D_SELL_CHAIN: { case WID_D_SELL: case WID_D_SELL_CHAIN: {
if (this->IsWidgetDisabled(widget)) return; if (this->IsWidgetDisabled(widget)) return;
if (this->sel == INVALID_VEHICLE) return; if (this->sel == VehicleID::Invalid()) return;
this->HandleButtonClick(widget); this->HandleButtonClick(widget);
const Vehicle *v = Vehicle::Get(this->sel); const Vehicle *v = Vehicle::Get(this->sel);
this->sel = INVALID_VEHICLE; this->sel = VehicleID::Invalid();
this->SetDirty(); this->SetDirty();
bool sell_cmd = (v->type == VEH_TRAIN && (widget == WID_D_SELL_CHAIN || _ctrl_pressed)); bool sell_cmd = (v->type == VEH_TRAIN && (widget == WID_D_SELL_CHAIN || _ctrl_pressed));
@ -1096,7 +1096,7 @@ struct DepotWindow : Window {
} }
default: default:
this->sel = INVALID_VEHICLE; this->sel = VehicleID::Invalid();
this->SetDirty(); this->SetDirty();
break; break;
} }
@ -1129,7 +1129,7 @@ struct DepotWindow : Window {
EventState OnCTRLStateChange() override EventState OnCTRLStateChange() override
{ {
if (this->sel != INVALID_VEHICLE) { if (this->sel != VehicleID::Invalid()) {
_cursor.vehchain = _ctrl_pressed; _cursor.vehchain = _ctrl_pressed;
this->SetWidgetDirty(WID_D_MATRIX); this->SetWidgetDirty(WID_D_MATRIX);
return ES_HANDLED; return ES_HANDLED;

View File

@ -15,8 +15,6 @@
using DepotID = PoolID<uint16_t, struct DepotIDTag, 64000, 0xFFFF>; ///< Type for the unique identifier of depots. using DepotID = PoolID<uint16_t, struct DepotIDTag, 64000, 0xFFFF>; ///< Type for the unique identifier of depots.
struct Depot; struct Depot;
static constexpr DepotID INVALID_DEPOT = DepotID::Invalid();
static const uint MAX_LENGTH_DEPOT_NAME_CHARS = 32; ///< The maximum length of a depot name in characters including '\0' static const uint MAX_LENGTH_DEPOT_NAME_CHARS = 32; ///< The maximum length of a depot name in characters including '\0'
#endif /* DEPOT_TYPE_H */ #endif /* DEPOT_TYPE_H */

View File

@ -348,7 +348,7 @@ static bool DisasterTick_Ufo(DisasterVehicle *v)
for (RoadVehicle *u : RoadVehicle::Iterate()) { for (RoadVehicle *u : RoadVehicle::Iterate()) {
/* Find (n+1)-th road vehicle. */ /* Find (n+1)-th road vehicle. */
if (u->IsFrontEngine() && (n-- == 0)) { if (u->IsFrontEngine() && (n-- == 0)) {
if (u->crashed_ctr != 0 || u->disaster_vehicle != INVALID_VEHICLE) { if (u->crashed_ctr != 0 || u->disaster_vehicle != VehicleID::Invalid()) {
/* Targetted vehicle is crashed or already a target, destroy the UFO. */ /* Targetted vehicle is crashed or already a target, destroy the UFO. */
delete v; delete v;
return false; return false;
@ -385,7 +385,7 @@ static bool DisasterTick_Ufo(DisasterVehicle *v)
v->age++; v->age++;
if (u->crashed_ctr == 0) { if (u->crashed_ctr == 0) {
uint victims = u->Crash(); uint victims = u->Crash();
u->disaster_vehicle = INVALID_VEHICLE; u->disaster_vehicle = VehicleID::Invalid();
AddTileNewsItem(STR_NEWS_DISASTER_SMALL_UFO, NewsType::Accident, u->tile); AddTileNewsItem(STR_NEWS_DISASTER_SMALL_UFO, NewsType::Accident, u->tile);

View File

@ -42,7 +42,7 @@ struct DisasterVehicle final : public SpecializedVehicle<DisasterVehicle, VEH_DI
/** For use by saveload. */ /** For use by saveload. */
DisasterVehicle() : SpecializedVehicleBase() {} DisasterVehicle() : SpecializedVehicleBase() {}
DisasterVehicle(int x, int y, Direction direction, DisasterSubType subtype, VehicleID big_ufo_destroyer_target = INVALID_VEHICLE); DisasterVehicle(int x, int y, Direction direction, DisasterSubType subtype, VehicleID big_ufo_destroyer_target = VehicleID::Invalid());
/** We want to 'destruct' the right class. */ /** We want to 'destruct' the right class. */
virtual ~DisasterVehicle() = default; virtual ~DisasterVehicle() = default;

View File

@ -220,7 +220,7 @@ struct BuildDocksToolbarWindow : Window {
bool adjacent = _ctrl_pressed; bool adjacent = _ctrl_pressed;
auto proc = [=](bool test, StationID to_join) -> bool { auto proc = [=](bool test, StationID to_join) -> bool {
if (test) { if (test) {
return Command<CMD_BUILD_DOCK>::Do(CommandFlagsToDCFlags(GetCommandFlags<CMD_BUILD_DOCK>()), tile, INVALID_STATION, adjacent).Succeeded(); return Command<CMD_BUILD_DOCK>::Do(CommandFlagsToDCFlags(GetCommandFlags<CMD_BUILD_DOCK>()), tile, StationID::Invalid(), adjacent).Succeeded();
} else { } else {
return Command<CMD_BUILD_DOCK>::Post(STR_ERROR_CAN_T_BUILD_DOCK_HERE, CcBuildDocks, tile, to_join, adjacent); return Command<CMD_BUILD_DOCK>::Post(STR_ERROR_CAN_T_BUILD_DOCK_HERE, CcBuildDocks, tile, to_join, adjacent);
} }

View File

@ -399,7 +399,7 @@ void ChangeOwnershipOfCompanyItems(Owner old_owner, Owner new_owner)
t->exclusivity = new_owner; t->exclusivity = new_owner;
} else { } else {
t->exclusive_counter = 0; t->exclusive_counter = 0;
t->exclusivity = INVALID_COMPANY; t->exclusivity = CompanyID::Invalid();
} }
} }
} }
@ -1114,7 +1114,7 @@ static Money DeliverGoods(int num_pieces, CargoType cargo_type, StationID dest,
Station *st = Station::Get(dest); Station *st = Station::Get(dest);
/* Give the goods to the industry. */ /* Give the goods to the industry. */
uint accepted_ind = DeliverGoodsToIndustry(st, cargo_type, num_pieces, src.type == SourceType::Industry ? src.ToIndustryID() : INVALID_INDUSTRY, company->index); uint accepted_ind = DeliverGoodsToIndustry(st, cargo_type, num_pieces, src.type == SourceType::Industry ? src.ToIndustryID() : IndustryID::Invalid(), company->index);
/* If this cargo type is always accepted, accept all */ /* If this cargo type is always accepted, accept all */
uint accepted_total = HasBit(st->always_accepted, cargo_type) ? num_pieces : accepted_ind; uint accepted_total = HasBit(st->always_accepted, cargo_type) ? num_pieces : accepted_ind;
@ -1507,7 +1507,7 @@ static void HandleStationRefit(Vehicle *v, CargoArray &consist_capleft, Station
bool is_auto_refit = new_cargo_type == CARGO_AUTO_REFIT; bool is_auto_refit = new_cargo_type == CARGO_AUTO_REFIT;
if (is_auto_refit) { if (is_auto_refit) {
/* Get a refittable cargo type with waiting cargo for next_station or INVALID_STATION. */ /* Get a refittable cargo type with waiting cargo for next_station or StationID::Invalid(). */
new_cargo_type = v_start->cargo_type; new_cargo_type = v_start->cargo_type;
for (CargoType cargo_type : SetCargoBitIterator(refit_mask)) { for (CargoType cargo_type : SetCargoBitIterator(refit_mask)) {
if (st->goods[cargo_type].HasData() && st->goods[cargo_type].GetData().cargo.HasCargoFor(next_station)) { if (st->goods[cargo_type].HasData() && st->goods[cargo_type].GetData().cargo.HasCargoFor(next_station)) {
@ -1531,11 +1531,11 @@ static void HandleStationRefit(Vehicle *v, CargoArray &consist_capleft, Station
/* Refit if given a valid cargo. */ /* Refit if given a valid cargo. */
if (new_cargo_type < NUM_CARGO && new_cargo_type != v_start->cargo_type) { if (new_cargo_type < NUM_CARGO && new_cargo_type != v_start->cargo_type) {
/* INVALID_STATION because in the DT_MANUAL case that's correct and in the DT_(A)SYMMETRIC /* StationID::Invalid() because in the DT_MANUAL case that's correct and in the DT_(A)SYMMETRIC
* cases the next hop of the vehicle doesn't really tell us anything if the cargo had been * cases the next hop of the vehicle doesn't really tell us anything if the cargo had been
* "via any station" before reserving. We rather produce some more "any station" cargo than * "via any station" before reserving. We rather produce some more "any station" cargo than
* misrouting it. */ * misrouting it. */
IterateVehicleParts(v_start, ReturnCargoAction(st, INVALID_STATION)); IterateVehicleParts(v_start, ReturnCargoAction(st, StationID::Invalid()));
CommandCost cost = std::get<0>(Command<CMD_REFIT_VEHICLE>::Do(DoCommandFlag::Execute, v_start->index, new_cargo_type, 0xFF, true, false, 1)); // Auto-refit and only this vehicle including artic parts. CommandCost cost = std::get<0>(Command<CMD_REFIT_VEHICLE>::Do(DoCommandFlag::Execute, v_start->index, new_cargo_type, 0xFF, true, false, 1)); // Auto-refit and only this vehicle including artic parts.
if (cost.Succeeded()) v->First()->profit_this_year -= cost.GetCost() << 8; if (cost.Succeeded()) v->First()->profit_this_year -= cost.GetCost() << 8;
} }
@ -1700,7 +1700,7 @@ static void LoadUnloadVehicle(Vehicle *front)
uint new_remaining = v->cargo.RemainingCount() + v->cargo.ActionCount(VehicleCargoList::MTA_DELIVER); uint new_remaining = v->cargo.RemainingCount() + v->cargo.ActionCount(VehicleCargoList::MTA_DELIVER);
if (v->cargo_cap < new_remaining) { if (v->cargo_cap < new_remaining) {
/* Return some of the reserved cargo to not overload the vehicle. */ /* Return some of the reserved cargo to not overload the vehicle. */
v->cargo.Return(new_remaining - v->cargo_cap, &ge->GetOrCreateData().cargo, INVALID_STATION, v->GetCargoTile()); v->cargo.Return(new_remaining - v->cargo_cap, &ge->GetOrCreateData().cargo, StationID::Invalid(), v->GetCargoTile());
} }
/* Keep instead of delivering. This may lead to no cargo being unloaded, so ...*/ /* Keep instead of delivering. This may lead to no cargo being unloaded, so ...*/

View File

@ -73,8 +73,8 @@ Engine::Engine(VehicleType type, uint16_t local_id)
this->type = type; this->type = type;
this->grf_prop.local_id = local_id; this->grf_prop.local_id = local_id;
this->list_position = local_id; this->list_position = local_id;
this->preview_company = INVALID_COMPANY; this->preview_company = CompanyID::Invalid();
this->display_last_variant = INVALID_ENGINE; this->display_last_variant = EngineID::Invalid();
/* Check if this base engine is within the original engine data range */ /* Check if this base engine is within the original engine data range */
if (local_id >= _engine_counts[type]) { if (local_id >= _engine_counts[type]) {
@ -99,7 +99,7 @@ Engine::Engine(VehicleType type, uint16_t local_id)
/* Set cargo aging period to the default value. */ /* Set cargo aging period to the default value. */
this->info.cargo_age_period = Ticks::CARGO_AGING_TICKS; this->info.cargo_age_period = Ticks::CARGO_AGING_TICKS;
/* Not a variant */ /* Not a variant */
this->info.variant_id = INVALID_ENGINE; this->info.variant_id = EngineID::Invalid();
return; return;
} }
@ -496,7 +496,7 @@ bool Engine::IsVariantHidden(CompanyID c) const
* the last display variant rather than the actual parent variant. */ * the last display variant rather than the actual parent variant. */
const Engine *re = this; const Engine *re = this;
const Engine *ve = re->GetDisplayVariant(); const Engine *ve = re->GetDisplayVariant();
while (!(ve->IsHidden(c)) && re->info.variant_id != INVALID_ENGINE) { while (!(ve->IsHidden(c)) && re->info.variant_id != EngineID::Invalid()) {
re = Engine::Get(re->info.variant_id); re = Engine::Get(re->info.variant_id);
ve = re->GetDisplayVariant(); ve = re->GetDisplayVariant();
} }
@ -525,14 +525,14 @@ void EngineOverrideManager::ResetToDefaultMapping()
* @param grfid The GrfID that defines the scope of grf_local_id. * @param grfid The GrfID that defines the scope of grf_local_id.
* If a newgrf overrides the engines of another newgrf, the "scope grfid" is the ID of the overridden newgrf. * If a newgrf overrides the engines of another newgrf, the "scope grfid" is the ID of the overridden newgrf.
* If dynnamic_engines is disabled, all newgrf share the same ID scope identified by INVALID_GRFID. * If dynnamic_engines is disabled, all newgrf share the same ID scope identified by INVALID_GRFID.
* @return The engine ID if present, or INVALID_ENGINE if not. * @return The engine ID if present, or EngineID::Invalid() if not.
*/ */
EngineID EngineOverrideManager::GetID(VehicleType type, uint16_t grf_local_id, uint32_t grfid) EngineID EngineOverrideManager::GetID(VehicleType type, uint16_t grf_local_id, uint32_t grfid)
{ {
const auto &map = this->mappings[type]; const auto &map = this->mappings[type];
const auto key = EngineIDMapping::Key(grfid, grf_local_id); const auto key = EngineIDMapping::Key(grfid, grf_local_id);
auto it = std::ranges::lower_bound(map, key, std::less{}, EngineIDMappingKeyProjection{}); auto it = std::ranges::lower_bound(map, key, std::less{}, EngineIDMappingKeyProjection{});
if (it == std::end(map) || it->Key() != key) return INVALID_ENGINE; if (it == std::end(map) || it->Key() != key) return EngineID::Invalid();
return it->engine; return it->engine;
} }
@ -544,14 +544,14 @@ EngineID EngineOverrideManager::GetID(VehicleType type, uint16_t grf_local_id, u
* If a newgrf overrides the engines of another newgrf, the "scope grfid" is the ID of the overridden newgrf. * If a newgrf overrides the engines of another newgrf, the "scope grfid" is the ID of the overridden newgrf.
* If dynnamic_engines is disabled, all newgrf share the same ID scope identified by INVALID_GRFID. * If dynnamic_engines is disabled, all newgrf share the same ID scope identified by INVALID_GRFID.
* @param static_access Whether to actually reserve the EngineID. * @param static_access Whether to actually reserve the EngineID.
* @return The engine ID if present and now reserved, or INVALID_ENGINE if not. * @return The engine ID if present and now reserved, or EngineID::Invalid() if not.
*/ */
EngineID EngineOverrideManager::UseUnreservedID(VehicleType type, uint16_t grf_local_id, uint32_t grfid, bool static_access) EngineID EngineOverrideManager::UseUnreservedID(VehicleType type, uint16_t grf_local_id, uint32_t grfid, bool static_access)
{ {
auto &map = _engine_mngr.mappings[type]; auto &map = _engine_mngr.mappings[type];
const auto key = EngineIDMapping::Key(INVALID_GRFID, grf_local_id); const auto key = EngineIDMapping::Key(INVALID_GRFID, grf_local_id);
auto it = std::ranges::lower_bound(map, key, std::less{}, EngineIDMappingKeyProjection{}); auto it = std::ranges::lower_bound(map, key, std::less{}, EngineIDMappingKeyProjection{});
if (it == std::end(map) || it->Key() != key) return INVALID_ENGINE; if (it == std::end(map) || it->Key() != key) return EngineID::Invalid();
if (!static_access && grfid != INVALID_GRFID) { if (!static_access && grfid != INVALID_GRFID) {
/* Reserve the engine slot for the new grfid. */ /* Reserve the engine slot for the new grfid. */
@ -636,7 +636,7 @@ static bool IsWagon(EngineID index)
static void ClearLastVariant(EngineID engine_id, VehicleType type) static void ClearLastVariant(EngineID engine_id, VehicleType type)
{ {
for (Engine *e : Engine::IterateType(type)) { for (Engine *e : Engine::IterateType(type)) {
if (e->display_last_variant == engine_id) e->display_last_variant = INVALID_ENGINE; if (e->display_last_variant == engine_id) e->display_last_variant = EngineID::Invalid();
} }
} }
@ -648,7 +648,7 @@ void CalcEngineReliability(Engine *e, bool new_month)
{ {
/* Get source engine for reliability age. This is normally our engine unless variant reliability syncing is requested. */ /* Get source engine for reliability age. This is normally our engine unless variant reliability syncing is requested. */
Engine *re = e; Engine *re = e;
while (re->info.variant_id != INVALID_ENGINE && re->info.extra_flags.Test(ExtraEngineFlag::SyncReliability)) { while (re->info.variant_id != EngineID::Invalid() && re->info.extra_flags.Test(ExtraEngineFlag::SyncReliability)) {
re = Engine::Get(re->info.variant_id); re = Engine::Get(re->info.variant_id);
} }
@ -750,7 +750,7 @@ void StartupOneEngine(Engine *e, const TimerGameCalendar::YearMonthDay &aging_ym
/* Get parent variant index for syncing reliability via random seed. */ /* Get parent variant index for syncing reliability via random seed. */
const Engine *re = e; const Engine *re = e;
while (re->info.variant_id != INVALID_ENGINE && re->info.extra_flags.Test(ExtraEngineFlag::SyncReliability)) { while (re->info.variant_id != EngineID::Invalid() && re->info.extra_flags.Test(ExtraEngineFlag::SyncReliability)) {
re = Engine::Get(re->info.variant_id); re = Engine::Get(re->info.variant_id);
} }
@ -884,7 +884,7 @@ static void AcceptEnginePreview(EngineID eid, CompanyID company, int recursion_d
{ {
Engine *e = Engine::Get(eid); Engine *e = Engine::Get(eid);
e->preview_company = INVALID_COMPANY; e->preview_company = CompanyID::Invalid();
e->preview_asked.Set(); e->preview_asked.Set();
EnableEngineForCompany(eid, company); EnableEngineForCompany(eid, company);
@ -910,11 +910,11 @@ static void AcceptEnginePreview(EngineID eid, CompanyID company, int recursion_d
/** /**
* Get the best company for an engine preview. * Get the best company for an engine preview.
* @param e Engine to preview. * @param e Engine to preview.
* @return Best company if it exists, #INVALID_COMPANY otherwise. * @return Best company if it exists, #CompanyID::Invalid() otherwise.
*/ */
static CompanyID GetPreviewCompany(Engine *e) static CompanyID GetPreviewCompany(Engine *e)
{ {
CompanyID best_company = INVALID_COMPANY; CompanyID best_company = CompanyID::Invalid();
/* For trains the cargomask has no useful meaning, since you can attach other wagons */ /* For trains the cargomask has no useful meaning, since you can attach other wagons */
CargoTypes cargomask = e->type != VEH_TRAIN ? GetUnionOfArticulatedRefitMasks(e->index, true) : ALL_CARGOTYPES; CargoTypes cargomask = e->type != VEH_TRAIN ? GetUnionOfArticulatedRefitMasks(e->index, true) : ALL_CARGOTYPES;
@ -971,15 +971,15 @@ static IntervalTimer<TimerGameCalendar> _calendar_engines_daily({TimerGameCalend
for (Engine *e : Engine::Iterate()) { for (Engine *e : Engine::Iterate()) {
EngineID i = e->index; EngineID i = e->index;
if (e->flags.Test(EngineFlag::ExclusivePreview)) { if (e->flags.Test(EngineFlag::ExclusivePreview)) {
if (e->preview_company != INVALID_COMPANY) { if (e->preview_company != CompanyID::Invalid()) {
if (!--e->preview_wait) { if (!--e->preview_wait) {
CloseWindowById(WC_ENGINE_PREVIEW, i); CloseWindowById(WC_ENGINE_PREVIEW, i);
e->preview_company = INVALID_COMPANY; e->preview_company = CompanyID::Invalid();
} }
} else if (CountBits(e->preview_asked.base()) < MAX_COMPANIES) { } else if (CountBits(e->preview_asked.base()) < MAX_COMPANIES) {
e->preview_company = GetPreviewCompany(e); e->preview_company = GetPreviewCompany(e);
if (e->preview_company == INVALID_COMPANY) { if (e->preview_company == CompanyID::Invalid()) {
e->preview_asked.Set(); e->preview_asked.Set();
continue; continue;
} }
@ -1177,7 +1177,7 @@ void CalendarEnginesMonthlyLoop()
/* Show preview dialog to one of the companies. */ /* Show preview dialog to one of the companies. */
e->flags.Set(EngineFlag::ExclusivePreview); e->flags.Set(EngineFlag::ExclusivePreview);
e->preview_company = INVALID_COMPANY; e->preview_company = CompanyID::Invalid();
e->preview_asked = CompanyMask{}; e->preview_asked = CompanyMask{};
} }
} }

View File

@ -55,7 +55,7 @@ struct Engine : EnginePool::PoolItem<&_engine_pool> {
uint16_t duration_phase_3; ///< Third reliability phase in months, decaying to #reliability_final. uint16_t duration_phase_3; ///< Third reliability phase in months, decaying to #reliability_final.
EngineFlags flags; ///< Flags of the engine. @see EngineFlags EngineFlags flags; ///< Flags of the engine. @see EngineFlags
CompanyID preview_company; ///< Company which is currently being offered a preview \c INVALID_COMPANY means no company. CompanyID preview_company; ///< Company which is currently being offered a preview \c CompanyID::Invalid() means no company.
uint8_t preview_wait; ///< Daily countdown timer for timeout of offering the engine to the #preview_company company. uint8_t preview_wait; ///< Daily countdown timer for timeout of offering the engine to the #preview_company company.
uint8_t original_image_index; ///< Original vehicle image index, thus the image index of the overridden vehicle uint8_t original_image_index; ///< Original vehicle image index, thus the image index of the overridden vehicle
VehicleType type; ///< %Vehicle type, ie #VEH_ROAD, #VEH_TRAIN, etc. VehicleType type; ///< %Vehicle type, ie #VEH_ROAD, #VEH_TRAIN, etc.
@ -149,7 +149,7 @@ struct Engine : EnginePool::PoolItem<&_engine_pool> {
*/ */
const Engine *GetDisplayVariant() const const Engine *GetDisplayVariant() const
{ {
if (this->display_last_variant == this->index || this->display_last_variant == INVALID_ENGINE) return this; if (this->display_last_variant == this->index || this->display_last_variant == EngineID::Invalid()) return this;
return Engine::Get(this->display_last_variant); return Engine::Get(this->display_last_variant);
} }

View File

@ -53,6 +53,6 @@ extern EngList_SortTypeFunction * const _engine_sort_functions[][11];
uint GetEngineListHeight(VehicleType type); uint GetEngineListHeight(VehicleType type);
void DisplayVehicleSortDropDown(Window *w, VehicleType vehicle_type, int selected, WidgetID button); void DisplayVehicleSortDropDown(Window *w, VehicleType vehicle_type, int selected, WidgetID button);
void DrawEngineList(VehicleType type, const Rect &r, const GUIEngineList &eng_list, const Scrollbar &sb, EngineID selected_id, bool show_count, GroupID selected_group); void DrawEngineList(VehicleType type, const Rect &r, const GUIEngineList &eng_list, const Scrollbar &sb, EngineID selected_id, bool show_count, GroupID selected_group);
void GUIEngineListAddChildren(GUIEngineList &dst, const GUIEngineList &src, EngineID parent = INVALID_ENGINE, uint8_t indent = 0); void GUIEngineListAddChildren(GUIEngineList &dst, const GUIEngineList &src, EngineID parent = EngineID::Invalid(), uint8_t indent = 0);
#endif /* ENGINE_GUI_H */ #endif /* ENGINE_GUI_H */

View File

@ -22,7 +22,6 @@
/** Unique identification number of an engine. */ /** Unique identification number of an engine. */
using EngineID = PoolID<uint16_t, struct EngineIDTag, 64000, 0xFFFF>; using EngineID = PoolID<uint16_t, struct EngineIDTag, 64000, 0xFFFF>;
static constexpr EngineID INVALID_ENGINE = EngineID::Invalid(); ///< Constant denoting an invalid engine.
struct Engine; struct Engine;

View File

@ -38,17 +38,17 @@ protected:
EncodedString detailed_msg; ///< Detailed error message showed in second line. Can be #INVALID_STRING_ID. EncodedString detailed_msg; ///< Detailed error message showed in second line. Can be #INVALID_STRING_ID.
EncodedString extra_msg; ///< Extra error message shown in third line. Can be #INVALID_STRING_ID. EncodedString extra_msg; ///< Extra error message shown in third line. Can be #INVALID_STRING_ID.
Point position; ///< Position of the error message window. Point position; ///< Position of the error message window.
CompanyID company; ///< Company belonging to the face being shown. #INVALID_COMPANY if no face present. CompanyID company; ///< Company belonging to the face being shown. #CompanyID::Invalid() if no face present.
public: public:
ErrorMessageData(const ErrorMessageData &data); ErrorMessageData(const ErrorMessageData &data);
ErrorMessageData(EncodedString &&summary_msg, EncodedString &&detailed_msg, bool is_critical = false, int x = 0, int y = 0, const GRFFile *textref_stack_grffile = nullptr, uint textref_stack_size = 0, const uint32_t *textref_stack = nullptr, EncodedString &&extra_msg = {}, CompanyID company = INVALID_COMPANY); ErrorMessageData(EncodedString &&summary_msg, EncodedString &&detailed_msg, bool is_critical = false, int x = 0, int y = 0, const GRFFile *textref_stack_grffile = nullptr, uint textref_stack_size = 0, const uint32_t *textref_stack = nullptr, EncodedString &&extra_msg = {}, CompanyID company = CompanyID::Invalid());
/* Remove the copy assignment, as the default implementation will not do the right thing. */ /* Remove the copy assignment, as the default implementation will not do the right thing. */
ErrorMessageData &operator=(ErrorMessageData &rhs) = delete; ErrorMessageData &operator=(ErrorMessageData &rhs) = delete;
/** Check whether error window shall display a company manager face */ /** Check whether error window shall display a company manager face */
bool HasFace() const { return company != INVALID_COMPANY; } bool HasFace() const { return company != CompanyID::Invalid(); }
}; };
/** Define a queue with errors. */ /** Define a queue with errors. */
@ -58,7 +58,7 @@ void ScheduleErrorMessage(ErrorList &datas);
void ScheduleErrorMessage(const ErrorMessageData &data); void ScheduleErrorMessage(const ErrorMessageData &data);
void ShowErrorMessage(EncodedString &&summary_msg, int x, int y, const CommandCost &cc); void ShowErrorMessage(EncodedString &&summary_msg, int x, int y, const CommandCost &cc);
void ShowErrorMessage(EncodedString &&summary_msg, EncodedString &&detailed_msg, WarningLevel wl, int x = 0, int y = 0, const GRFFile *textref_stack_grffile = nullptr, uint textref_stack_size = 0, const uint32_t *textref_stack = nullptr, EncodedString &&extra_msg = {}, CompanyID company = INVALID_COMPANY); void ShowErrorMessage(EncodedString &&summary_msg, EncodedString &&detailed_msg, WarningLevel wl, int x = 0, int y = 0, const GRFFile *textref_stack_grffile = nullptr, uint textref_stack_size = 0, const uint32_t *textref_stack = nullptr, EncodedString &&extra_msg = {}, CompanyID company = CompanyID::Invalid());
bool HideActiveErrorMessage(); bool HideActiveErrorMessage();
void ClearErrorMessages(); void ClearErrorMessages();

View File

@ -197,12 +197,12 @@ public:
void OnInvalidateData([[maybe_unused]] int data = 0, [[maybe_unused]] bool gui_scope = true) override void OnInvalidateData([[maybe_unused]] int data = 0, [[maybe_unused]] bool gui_scope = true) override
{ {
/* If company gets shut down, while displaying an error about it, remove the error message. */ /* If company gets shut down, while displaying an error about it, remove the error message. */
if (this->company != INVALID_COMPANY && !Company::IsValidID(this->company)) this->Close(); if (this->company != CompanyID::Invalid() && !Company::IsValidID(this->company)) this->Close();
} }
void SetStringParameters(WidgetID widget) const override void SetStringParameters(WidgetID widget) const override
{ {
if (widget == WID_EM_CAPTION && this->company != INVALID_COMPANY) SetDParam(0, this->company); if (widget == WID_EM_CAPTION && this->company != CompanyID::Invalid()) SetDParam(0, this->company);
} }
void DrawWidget(const Rect &r, WidgetID widget) const override void DrawWidget(const Rect &r, WidgetID widget) const override

View File

@ -373,7 +373,7 @@ static bool TryFoundTownNearby(TileIndex tile, void *user_data)
TownID id = std::get<TownID>(result); TownID id = std::get<TownID>(result);
/* Check if the command failed. */ /* Check if the command failed. */
if (id == INVALID_TOWN) return false; if (id == TownID::Invalid()) return false;
/* The command succeeded, send the ID back through user_data. */ /* The command succeeded, send the ID back through user_data. */
town.town_id = id; town.town_id = id;

View File

@ -57,7 +57,7 @@ INSTANTIATE_POOL_METHODS(Goal)
case GT_STORY_PAGE: { case GT_STORY_PAGE: {
if (!StoryPage::IsValidID(dest)) return false; if (!StoryPage::IsValidID(dest)) return false;
CompanyID story_company = StoryPage::Get(dest)->company; CompanyID story_company = StoryPage::Get(dest)->company;
if (company == INVALID_COMPANY ? story_company != INVALID_COMPANY : story_company != INVALID_COMPANY && story_company != company) return false; if (company == CompanyID::Invalid() ? story_company != CompanyID::Invalid() : story_company != CompanyID::Invalid() && story_company != company) return false;
break; break;
} }
@ -77,12 +77,12 @@ INSTANTIATE_POOL_METHODS(Goal)
*/ */
std::tuple<CommandCost, GoalID> CmdCreateGoal(DoCommandFlags flags, CompanyID company, GoalType type, GoalTypeID dest, const std::string &text) std::tuple<CommandCost, GoalID> CmdCreateGoal(DoCommandFlags flags, CompanyID company, GoalType type, GoalTypeID dest, const std::string &text)
{ {
if (!Goal::CanAllocateItem()) return { CMD_ERROR, INVALID_GOAL }; if (!Goal::CanAllocateItem()) return { CMD_ERROR, GoalID::Invalid() };
if (_current_company != OWNER_DEITY) return { CMD_ERROR, INVALID_GOAL }; if (_current_company != OWNER_DEITY) return { CMD_ERROR, GoalID::Invalid() };
if (text.empty()) return { CMD_ERROR, INVALID_GOAL }; if (text.empty()) return { CMD_ERROR, GoalID::Invalid() };
if (company != INVALID_COMPANY && !Company::IsValidID(company)) return { CMD_ERROR, INVALID_GOAL }; if (company != CompanyID::Invalid() && !Company::IsValidID(company)) return { CMD_ERROR, GoalID::Invalid() };
if (!Goal::IsValidGoalDestination(company, type, dest)) return { CMD_ERROR, INVALID_GOAL }; if (!Goal::IsValidGoalDestination(company, type, dest)) return { CMD_ERROR, GoalID::Invalid() };
if (flags.Test(DoCommandFlag::Execute)) { if (flags.Test(DoCommandFlag::Execute)) {
Goal *g = new Goal(); Goal *g = new Goal();
@ -92,7 +92,7 @@ std::tuple<CommandCost, GoalID> CmdCreateGoal(DoCommandFlags flags, CompanyID co
g->text = text; g->text = text;
g->completed = false; g->completed = false;
if (g->company == INVALID_COMPANY) { if (g->company == CompanyID::Invalid()) {
InvalidateWindowClassesData(WC_GOALS_LIST); InvalidateWindowClassesData(WC_GOALS_LIST);
} else { } else {
InvalidateWindowData(WC_GOALS_LIST, g->company); InvalidateWindowData(WC_GOALS_LIST, g->company);
@ -102,7 +102,7 @@ std::tuple<CommandCost, GoalID> CmdCreateGoal(DoCommandFlags flags, CompanyID co
return { CommandCost(), g->index }; return { CommandCost(), g->index };
} }
return { CommandCost(), INVALID_GOAL }; return { CommandCost(), GoalID::Invalid() };
} }
/** /**
@ -121,7 +121,7 @@ CommandCost CmdRemoveGoal(DoCommandFlags flags, GoalID goal)
CompanyID c = g->company; CompanyID c = g->company;
delete g; delete g;
if (c == INVALID_COMPANY) { if (c == CompanyID::Invalid()) {
InvalidateWindowClassesData(WC_GOALS_LIST); InvalidateWindowClassesData(WC_GOALS_LIST);
} else { } else {
InvalidateWindowData(WC_GOALS_LIST, c); InvalidateWindowData(WC_GOALS_LIST, c);
@ -172,7 +172,7 @@ CommandCost CmdSetGoalText(DoCommandFlags flags, GoalID goal, const std::string
Goal *g = Goal::Get(goal); Goal *g = Goal::Get(goal);
g->text = text; g->text = text;
if (g->company == INVALID_COMPANY) { if (g->company == CompanyID::Invalid()) {
InvalidateWindowClassesData(WC_GOALS_LIST); InvalidateWindowClassesData(WC_GOALS_LIST);
} else { } else {
InvalidateWindowData(WC_GOALS_LIST, g->company); InvalidateWindowData(WC_GOALS_LIST, g->company);
@ -198,7 +198,7 @@ CommandCost CmdSetGoalProgress(DoCommandFlags flags, GoalID goal, const std::str
Goal *g = Goal::Get(goal); Goal *g = Goal::Get(goal);
g->progress = text; g->progress = text;
if (g->company == INVALID_COMPANY) { if (g->company == CompanyID::Invalid()) {
InvalidateWindowClassesData(WC_GOALS_LIST); InvalidateWindowClassesData(WC_GOALS_LIST);
} else { } else {
InvalidateWindowData(WC_GOALS_LIST, g->company); InvalidateWindowData(WC_GOALS_LIST, g->company);
@ -224,7 +224,7 @@ CommandCost CmdSetGoalCompleted(DoCommandFlags flags, GoalID goal, bool complete
Goal *g = Goal::Get(goal); Goal *g = Goal::Get(goal);
g->completed = completed; g->completed = completed;
if (g->company == INVALID_COMPANY) { if (g->company == CompanyID::Invalid()) {
InvalidateWindowClassesData(WC_GOALS_LIST); InvalidateWindowClassesData(WC_GOALS_LIST);
} else { } else {
InvalidateWindowData(WC_GOALS_LIST, g->company); InvalidateWindowData(WC_GOALS_LIST, g->company);
@ -263,7 +263,7 @@ CommandCost CmdGoalQuestion(DoCommandFlags flags, uint16_t uniqueid, uint32_t ta
* fact the client is no longer here. */ * fact the client is no longer here. */
if (!flags.Test(DoCommandFlag::Execute) && _network_server && NetworkClientInfo::GetByClientID(client) == nullptr) return CMD_ERROR; if (!flags.Test(DoCommandFlag::Execute) && _network_server && NetworkClientInfo::GetByClientID(client) == nullptr) return CMD_ERROR;
} else { } else {
if (company != INVALID_COMPANY && !Company::IsValidID(company)) return CMD_ERROR; if (company != CompanyID::Invalid() && !Company::IsValidID(company)) return CMD_ERROR;
} }
uint min_buttons = (type == GQT_QUESTION ? 1 : 0); uint min_buttons = (type == GQT_QUESTION ? 1 : 0);
if (CountBits(button_mask) < min_buttons || CountBits(button_mask) > 3) return CMD_ERROR; if (CountBits(button_mask) < min_buttons || CountBits(button_mask) > 3) return CMD_ERROR;
@ -273,8 +273,8 @@ CommandCost CmdGoalQuestion(DoCommandFlags flags, uint16_t uniqueid, uint32_t ta
if (is_client) { if (is_client) {
if (client != _network_own_client_id) return CommandCost(); if (client != _network_own_client_id) return CommandCost();
} else { } else {
if (company == INVALID_COMPANY && !Company::IsValidID(_local_company)) return CommandCost(); if (company == CompanyID::Invalid() && !Company::IsValidID(_local_company)) return CommandCost();
if (company != INVALID_COMPANY && company != _local_company) return CommandCost(); if (company != CompanyID::Invalid() && company != _local_company) return CommandCost();
} }
ShowGoalQuestion(uniqueid, type, button_mask, text); ShowGoalQuestion(uniqueid, type, button_mask, text);
} }

View File

@ -19,7 +19,7 @@ extern GoalPool _goal_pool;
/** Struct about goals, current and completed */ /** Struct about goals, current and completed */
struct Goal : GoalPool::PoolItem<&_goal_pool> { struct Goal : GoalPool::PoolItem<&_goal_pool> {
CompanyID company; ///< Goal is for a specific company; INVALID_COMPANY if it is global CompanyID company; ///< Goal is for a specific company; CompanyID::Invalid() if it is global
GoalType type; ///< Type of the goal GoalType type; ///< Type of the goal
GoalTypeID dst; ///< Index of type GoalTypeID dst; ///< Index of type
std::string text; ///< Text of the goal. std::string text; ///< Text of the goal.

View File

@ -47,7 +47,7 @@ struct GoalListWindow : public Window {
this->FinishInitNested(window_number); this->FinishInitNested(window_number);
this->owner = this->window_number; this->owner = this->window_number;
NWidgetStacked *wi = this->GetWidget<NWidgetStacked>(WID_GOAL_SELECT_BUTTONS); NWidgetStacked *wi = this->GetWidget<NWidgetStacked>(WID_GOAL_SELECT_BUTTONS);
wi->SetDisplayedPlane(window_number == INVALID_COMPANY ? 1 : 0); wi->SetDisplayedPlane(window_number == CompanyID::Invalid() ? 1 : 0);
this->OnInvalidateData(0); this->OnInvalidateData(0);
} }
@ -55,7 +55,7 @@ struct GoalListWindow : public Window {
{ {
if (widget != WID_GOAL_CAPTION) return; if (widget != WID_GOAL_CAPTION) return;
if (this->window_number == INVALID_COMPANY) { if (this->window_number == CompanyID::Invalid()) {
SetDParam(0, STR_GOALS_SPECTATOR_CAPTION); SetDParam(0, STR_GOALS_SPECTATOR_CAPTION);
} else { } else {
SetDParam(0, STR_GOALS_CAPTION); SetDParam(0, STR_GOALS_CAPTION);
@ -67,7 +67,7 @@ struct GoalListWindow : public Window {
{ {
switch (widget) { switch (widget) {
case WID_GOAL_GLOBAL_BUTTON: case WID_GOAL_GLOBAL_BUTTON:
ShowGoalsList(INVALID_COMPANY); ShowGoalsList(CompanyID::Invalid());
break; break;
case WID_GOAL_COMPANY_BUTTON: case WID_GOAL_COMPANY_BUTTON:
@ -134,7 +134,7 @@ struct GoalListWindow : public Window {
*/ */
CompanyID goal_company = s->company; CompanyID goal_company = s->company;
CompanyID story_company = StoryPage::Get(s->dst)->company; CompanyID story_company = StoryPage::Get(s->dst)->company;
if (goal_company == INVALID_COMPANY ? story_company != INVALID_COMPANY : story_company != INVALID_COMPANY && story_company != goal_company) return; if (goal_company == CompanyID::Invalid() ? story_company != CompanyID::Invalid() : story_company != CompanyID::Invalid() && story_company != goal_company) return;
ShowStoryBook(static_cast<CompanyID>(this->window_number), static_cast<StoryPageID>(s->dst)); ShowStoryBook(static_cast<CompanyID>(this->window_number), static_cast<StoryPageID>(s->dst));
return; return;
@ -311,11 +311,11 @@ static WindowDesc _goals_list_desc(
/** /**
* Open a goal list window. * Open a goal list window.
* @param company %Company to display the goals for, use #INVALID_COMPANY to display global goals. * @param company %Company to display the goals for, use #CompanyID::Invalid() to display global goals.
*/ */
void ShowGoalsList(CompanyID company) void ShowGoalsList(CompanyID company)
{ {
if (!Company::IsValidID(company)) company = (CompanyID)INVALID_COMPANY; if (!Company::IsValidID(company)) company = (CompanyID)CompanyID::Invalid();
AllocateWindowDescFront<GoalListWindow>(_goals_list_desc, company); AllocateWindowDescFront<GoalListWindow>(_goals_list_desc, company);
} }

View File

@ -39,6 +39,5 @@ typedef uint32_t GoalTypeID; ///< Contains either tile, industry ID, town ID, co
using GoalID = PoolID<uint16_t, struct GoalIDTag, 64000, 0xFFFF>; using GoalID = PoolID<uint16_t, struct GoalIDTag, 64000, 0xFFFF>;
struct Goal; struct Goal;
static constexpr GoalID INVALID_GOAL = GoalID::Invalid(); ///< Constant representing a non-existing goal.
#endif /* GOAL_TYPE_H */ #endif /* GOAL_TYPE_H */

View File

@ -54,7 +54,7 @@ struct GraphLegendWindow : Window {
{ {
this->InitNested(window_number); this->InitNested(window_number);
for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; ++c) { for (CompanyID c = CompanyID::Begin(); c < MAX_COMPANIES; ++c) {
if (!_legend_excluded_companies.Test(c)) this->LowerWidget(WID_GL_FIRST_COMPANY + c); if (!_legend_excluded_companies.Test(c)) this->LowerWidget(WID_GL_FIRST_COMPANY + c);
this->OnInvalidateData(c.base()); this->OnInvalidateData(c.base());
@ -676,7 +676,7 @@ public:
CompanyMask excluded_companies = _legend_excluded_companies; CompanyMask excluded_companies = _legend_excluded_companies;
/* Exclude the companies which aren't valid */ /* Exclude the companies which aren't valid */
for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; ++c) { for (CompanyID c = CompanyID::Begin(); c < MAX_COMPANIES; ++c) {
if (!Company::IsValidID(c)) excluded_companies.Set(c); if (!Company::IsValidID(c)) excluded_companies.Set(c);
} }
@ -704,7 +704,7 @@ public:
this->month = mo; this->month = mo;
this->data.clear(); this->data.clear();
for (CompanyID k = COMPANY_FIRST; k < MAX_COMPANIES; ++k) { for (CompanyID k = CompanyID::Begin(); k < MAX_COMPANIES; ++k) {
const Company *c = Company::GetIfValid(k); const Company *c = Company::GetIfValid(k);
if (c == nullptr) continue; if (c == nullptr) continue;
@ -1269,7 +1269,7 @@ struct PerformanceRatingDetailWindow : Window {
this->UpdateCompanyStats(); this->UpdateCompanyStats();
this->InitNested(window_number); this->InitNested(window_number);
this->OnInvalidateData(INVALID_COMPANY.base()); this->OnInvalidateData(CompanyID::Invalid().base());
} }
void UpdateCompanyStats() void UpdateCompanyStats()
@ -1353,7 +1353,7 @@ struct PerformanceRatingDetailWindow : Window {
void DrawWidget(const Rect &r, WidgetID widget) const override void DrawWidget(const Rect &r, WidgetID widget) const override
{ {
/* No need to draw when there's nothing to draw */ /* No need to draw when there's nothing to draw */
if (this->company == INVALID_COMPANY) return; if (this->company == CompanyID::Invalid()) return;
if (IsInsideMM(widget, WID_PRD_COMPANY_FIRST, WID_PRD_COMPANY_LAST + 1)) { if (IsInsideMM(widget, WID_PRD_COMPANY_FIRST, WID_PRD_COMPANY_LAST + 1)) {
if (this->IsWidgetDisabled(widget)) return; if (this->IsWidgetDisabled(widget)) return;
@ -1460,18 +1460,18 @@ struct PerformanceRatingDetailWindow : Window {
{ {
if (!gui_scope) return; if (!gui_scope) return;
/* Disable the companies who are not active */ /* Disable the companies who are not active */
for (CompanyID i = COMPANY_FIRST; i < MAX_COMPANIES; ++i) { for (CompanyID i = CompanyID::Begin(); i < MAX_COMPANIES; ++i) {
this->SetWidgetDisabledState(WID_PRD_COMPANY_FIRST + i, !Company::IsValidID(i)); this->SetWidgetDisabledState(WID_PRD_COMPANY_FIRST + i, !Company::IsValidID(i));
} }
/* Check if the currently selected company is still active. */ /* Check if the currently selected company is still active. */
if (this->company != INVALID_COMPANY && !Company::IsValidID(this->company)) { if (this->company != CompanyID::Invalid() && !Company::IsValidID(this->company)) {
/* Raise the widget for the previous selection. */ /* Raise the widget for the previous selection. */
this->RaiseWidget(WID_PRD_COMPANY_FIRST + this->company); this->RaiseWidget(WID_PRD_COMPANY_FIRST + this->company);
this->company = INVALID_COMPANY; this->company = CompanyID::Invalid();
} }
if (this->company == INVALID_COMPANY) { if (this->company == CompanyID::Invalid()) {
for (const Company *c : Company::Iterate()) { for (const Company *c : Company::Iterate()) {
this->company = c->index; this->company = c->index;
break; break;
@ -1479,13 +1479,13 @@ struct PerformanceRatingDetailWindow : Window {
} }
/* Make sure the widget is lowered */ /* Make sure the widget is lowered */
if (this->company != INVALID_COMPANY) { if (this->company != CompanyID::Invalid()) {
this->LowerWidget(WID_PRD_COMPANY_FIRST + this->company); this->LowerWidget(WID_PRD_COMPANY_FIRST + this->company);
} }
} }
}; };
CompanyID PerformanceRatingDetailWindow::company = INVALID_COMPANY; CompanyID PerformanceRatingDetailWindow::company = CompanyID::Invalid();
/*******************************/ /*******************************/
/* INDUSTRY PRODUCTION HISTORY */ /* INDUSTRY PRODUCTION HISTORY */

View File

@ -41,7 +41,7 @@ struct GroundVehicleCache {
/* Cached NewGRF values, recalculated on load and each time a vehicle is added to/removed from the consist. */ /* Cached NewGRF values, recalculated on load and each time a vehicle is added to/removed from the consist. */
uint16_t cached_total_length; ///< Length of the whole vehicle (valid only for the first engine). uint16_t cached_total_length; ///< Length of the whole vehicle (valid only for the first engine).
EngineID first_engine; ///< Cached EngineID of the front vehicle. INVALID_ENGINE for the front vehicle itself. EngineID first_engine; ///< Cached EngineID of the front vehicle. EngineID::Invalid() for the front vehicle itself.
uint8_t cached_veh_length; ///< Length of this vehicle in units of 1/VEHICLE_LENGTH of normal length. It is cached because this can be set by a callback. uint8_t cached_veh_length; ///< Length of this vehicle in units of 1/VEHICLE_LENGTH of normal length. It is cached because this can be set by a callback.
/* Cached UI information. */ /* Cached UI information. */

View File

@ -83,7 +83,7 @@ struct Group : GroupPool::PoolItem<&_group_pool> {
GroupID parent; ///< Parent group GroupID parent; ///< Parent group
uint16_t number; ///< Per-company group number. uint16_t number; ///< Per-company group number.
Group(CompanyID owner = INVALID_COMPANY); Group(CompanyID owner = CompanyID::Invalid());
}; };

View File

@ -265,7 +265,7 @@ static inline void UpdateNumEngineGroup(const Vehicle *v, GroupID old_g, GroupID
const Livery *GetParentLivery(const Group *g) const Livery *GetParentLivery(const Group *g)
{ {
if (g->parent == INVALID_GROUP) { if (g->parent == GroupID::Invalid()) {
const Company *c = Company::Get(g->owner); const Company *c = Company::Get(g->owner);
return &c->livery[LS_DEFAULT]; return &c->livery[LS_DEFAULT];
} }
@ -311,7 +311,7 @@ static void PropagateChildLivery(const Group *g, bool reset_cache)
void UpdateCompanyGroupLiveries(const Company *c) void UpdateCompanyGroupLiveries(const Company *c)
{ {
for (Group *g : Group::Iterate()) { for (Group *g : Group::Iterate()) {
if (g->owner == c->index && g->parent == INVALID_GROUP) { if (g->owner == c->index && g->parent == GroupID::Invalid()) {
if (!HasBit(g->livery.in_use, 0)) g->livery.colour1 = c->livery[LS_DEFAULT].colour1; if (!HasBit(g->livery.in_use, 0)) g->livery.colour1 = c->livery[LS_DEFAULT].colour1;
if (!HasBit(g->livery.in_use, 1)) g->livery.colour2 = c->livery[LS_DEFAULT].colour2; if (!HasBit(g->livery.in_use, 1)) g->livery.colour2 = c->livery[LS_DEFAULT].colour2;
PropagateChildLivery(g, false); PropagateChildLivery(g, false);
@ -335,20 +335,20 @@ Group::Group(Owner owner)
*/ */
std::tuple<CommandCost, GroupID> CmdCreateGroup(DoCommandFlags flags, VehicleType vt, GroupID parent_group) std::tuple<CommandCost, GroupID> CmdCreateGroup(DoCommandFlags flags, VehicleType vt, GroupID parent_group)
{ {
if (!IsCompanyBuildableVehicleType(vt)) return { CMD_ERROR, INVALID_GROUP }; if (!IsCompanyBuildableVehicleType(vt)) return { CMD_ERROR, GroupID::Invalid() };
if (!Group::CanAllocateItem()) return { CMD_ERROR, INVALID_GROUP }; if (!Group::CanAllocateItem()) return { CMD_ERROR, GroupID::Invalid() };
const Group *pg = Group::GetIfValid(parent_group); const Group *pg = Group::GetIfValid(parent_group);
if (pg != nullptr) { if (pg != nullptr) {
if (pg->owner != _current_company) return { CMD_ERROR, INVALID_GROUP }; if (pg->owner != _current_company) return { CMD_ERROR, GroupID::Invalid() };
if (pg->vehicle_type != vt) return { CMD_ERROR, INVALID_GROUP }; if (pg->vehicle_type != vt) return { CMD_ERROR, GroupID::Invalid() };
} }
if (flags.Test(DoCommandFlag::Execute)) { if (flags.Test(DoCommandFlag::Execute)) {
Group *g = new Group(_current_company); Group *g = new Group(_current_company);
g->vehicle_type = vt; g->vehicle_type = vt;
g->parent = INVALID_GROUP; g->parent = GroupID::Invalid();
Company *c = Company::Get(g->owner); Company *c = Company::Get(g->owner);
g->number = c->freegroups.UseID(c->freegroups.NextID()); g->number = c->freegroups.UseID(c->freegroups.NextID());
@ -369,7 +369,7 @@ std::tuple<CommandCost, GroupID> CmdCreateGroup(DoCommandFlags flags, VehicleTyp
return { CommandCost(), g->index }; return { CommandCost(), g->index };
} }
return { CommandCost(), INVALID_GROUP}; return { CommandCost(), GroupID::Invalid()};
} }
@ -466,7 +466,7 @@ CommandCost CmdAlterGroup(DoCommandFlags flags, AlterGroupMode mode, GroupID gro
} }
if (flags.Test(DoCommandFlag::Execute)) { if (flags.Test(DoCommandFlag::Execute)) {
g->parent = (pg == nullptr) ? INVALID_GROUP : pg->index; g->parent = (pg == nullptr) ? GroupID::Invalid() : pg->index;
GroupStatistics::UpdateAutoreplace(g->owner); GroupStatistics::UpdateAutoreplace(g->owner);
if (!HasBit(g->livery.in_use, 0) || !HasBit(g->livery.in_use, 1)) { if (!HasBit(g->livery.in_use, 0) || !HasBit(g->livery.in_use, 1)) {
@ -537,30 +537,30 @@ static void AddVehicleToGroup(Vehicle *v, GroupID new_g)
std::tuple<CommandCost, GroupID> CmdAddVehicleGroup(DoCommandFlags flags, GroupID group_id, VehicleID veh_id, bool add_shared, const VehicleListIdentifier &vli) std::tuple<CommandCost, GroupID> CmdAddVehicleGroup(DoCommandFlags flags, GroupID group_id, VehicleID veh_id, bool add_shared, const VehicleListIdentifier &vli)
{ {
GroupID new_g = group_id; GroupID new_g = group_id;
if (!Group::IsValidID(new_g) && !IsDefaultGroupID(new_g) && new_g != NEW_GROUP) return { CMD_ERROR, INVALID_GROUP }; if (!Group::IsValidID(new_g) && !IsDefaultGroupID(new_g) && new_g != NEW_GROUP) return { CMD_ERROR, GroupID::Invalid() };
VehicleList list; VehicleList list;
if (veh_id == INVALID_VEHICLE && vli.Valid()) { if (veh_id == VehicleID::Invalid() && vli.Valid()) {
if (!GenerateVehicleSortList(&list, vli) || list.empty()) return { CMD_ERROR, INVALID_GROUP }; if (!GenerateVehicleSortList(&list, vli) || list.empty()) return { CMD_ERROR, GroupID::Invalid() };
} else { } else {
Vehicle *v = Vehicle::GetIfValid(veh_id); Vehicle *v = Vehicle::GetIfValid(veh_id);
if (v == nullptr) return { CMD_ERROR, INVALID_GROUP }; if (v == nullptr) return { CMD_ERROR, GroupID::Invalid() };
list.push_back(v); list.push_back(v);
} }
VehicleType vtype = list.front()->type; VehicleType vtype = list.front()->type;
for (const Vehicle *v : list) { for (const Vehicle *v : list) {
if (v->owner != _current_company || !v->IsPrimaryVehicle()) return { CMD_ERROR, INVALID_GROUP }; if (v->owner != _current_company || !v->IsPrimaryVehicle()) return { CMD_ERROR, GroupID::Invalid() };
} }
if (Group::IsValidID(new_g)) { if (Group::IsValidID(new_g)) {
Group *g = Group::Get(new_g); Group *g = Group::Get(new_g);
if (g->owner != _current_company || g->vehicle_type != vtype) return { CMD_ERROR, INVALID_GROUP }; if (g->owner != _current_company || g->vehicle_type != vtype) return { CMD_ERROR, GroupID::Invalid() };
} }
if (new_g == NEW_GROUP) { if (new_g == NEW_GROUP) {
/* Create new group. */ /* Create new group. */
auto [ret, new_group_id] = CmdCreateGroup(flags, vtype, INVALID_GROUP); auto [ret, new_group_id] = CmdCreateGroup(flags, vtype, GroupID::Invalid());
if (ret.Failed()) return { ret, new_group_id }; if (ret.Failed()) return { ret, new_group_id };
new_g = new_group_id; new_g = new_group_id;
@ -878,7 +878,7 @@ bool GroupIsInGroup(GroupID search, GroupID group)
do { do {
if (search == group) return true; if (search == group) return true;
search = Group::Get(search)->parent; search = Group::Get(search)->parent;
} while (search != INVALID_GROUP); } while (search != GroupID::Invalid());
return false; return false;
} }

View File

@ -118,7 +118,7 @@ static constexpr NWidgetPart _nested_group_widgets[] = {
* @param parent Current tree parent (set by self with recursion). * @param parent Current tree parent (set by self with recursion).
* @param indent Current tree indentation level (set by self with recursion). * @param indent Current tree indentation level (set by self with recursion).
*/ */
static void GuiGroupListAddChildren(GUIGroupList &dst, const GUIGroupList &src, bool fold, GroupID parent = INVALID_GROUP, uint8_t indent = 0) static void GuiGroupListAddChildren(GUIGroupList &dst, const GUIGroupList &src, bool fold, GroupID parent = GroupID::Invalid(), uint8_t indent = 0)
{ {
for (const auto &item : src) { for (const auto &item : src) {
if (item.group->parent != parent) continue; if (item.group->parent != parent) continue;
@ -182,7 +182,7 @@ void BuildGuiGroupList(GUIGroupList &dst, bool fold, Owner owner, VehicleType ve
return r < 0; return r < 0;
}); });
GuiGroupListAddChildren(dst, list, fold, INVALID_GROUP, 0); GuiGroupListAddChildren(dst, list, fold, GroupID::Invalid(), 0);
} }
class VehicleGroupWindow : public BaseVehicleListWindow { class VehicleGroupWindow : public BaseVehicleListWindow {
@ -200,8 +200,8 @@ private:
}; };
GroupID group_sel; ///< Selected group (for drag/drop) GroupID group_sel; ///< Selected group (for drag/drop)
GroupID group_rename; ///< Group being renamed, INVALID_GROUP if none GroupID group_rename; ///< Group being renamed, GroupID::Invalid() if none
GroupID group_over; ///< Group over which a vehicle is dragged, INVALID_GROUP if none GroupID group_over; ///< Group over which a vehicle is dragged, GroupID::Invalid() if none
GroupID group_confirm; ///< Group awaiting delete confirmation GroupID group_confirm; ///< Group awaiting delete confirmation
GUIGroupList groups; ///< List of groups GUIGroupList groups; ///< List of groups
uint tiny_step_height; ///< Step height for the group list uint tiny_step_height; ///< Step height for the group list
@ -374,7 +374,7 @@ private:
*/ */
void DirtyHighlightedGroupWidget() void DirtyHighlightedGroupWidget()
{ {
if (this->group_over == INVALID_GROUP) return; if (this->group_over == GroupID::Invalid()) return;
if (IsAllGroupID(this->group_over)) { if (IsAllGroupID(this->group_over)) {
this->SetWidgetDirty(WID_GL_ALL_VEHICLES); this->SetWidgetDirty(WID_GL_ALL_VEHICLES);
@ -394,9 +394,9 @@ public:
this->group_sb = this->GetScrollbar(WID_GL_LIST_GROUP_SCROLLBAR); this->group_sb = this->GetScrollbar(WID_GL_LIST_GROUP_SCROLLBAR);
this->vli.SetIndex(ALL_GROUP); this->vli.SetIndex(ALL_GROUP);
this->group_sel = INVALID_GROUP; this->group_sel = GroupID::Invalid();
this->group_rename = INVALID_GROUP; this->group_rename = GroupID::Invalid();
this->group_over = INVALID_GROUP; this->group_over = GroupID::Invalid();
this->groups.ForceRebuild(); this->groups.ForceRebuild();
this->groups.NeedResort(); this->groups.NeedResort();
@ -496,9 +496,9 @@ public:
} }
/* Process ID-invalidation in command-scope as well */ /* Process ID-invalidation in command-scope as well */
if (this->group_rename != INVALID_GROUP && !Group::IsValidID(this->group_rename)) { if (this->group_rename != GroupID::Invalid() && !Group::IsValidID(this->group_rename)) {
CloseWindowByClass(WC_QUERY_STRING); CloseWindowByClass(WC_QUERY_STRING);
this->group_rename = INVALID_GROUP; this->group_rename = GroupID::Invalid();
} }
GroupID group = this->vli.ToGroupID(); GroupID group = this->vli.ToGroupID();
@ -757,7 +757,7 @@ public:
this->vli.SetIndex(g); this->vli.SetIndex(g);
break; break;
} }
} while (g != INVALID_GROUP); } while (g != GroupID::Invalid());
} }
Group::Get(it->group->index)->folded = !it->group->folded; Group::Get(it->group->index)->folded = !it->group->folded;
@ -886,25 +886,25 @@ public:
switch (widget) { switch (widget) {
case WID_GL_ALL_VEHICLES: // All vehicles case WID_GL_ALL_VEHICLES: // All vehicles
case WID_GL_DEFAULT_VEHICLES: // Ungrouped vehicles case WID_GL_DEFAULT_VEHICLES: // Ungrouped vehicles
if (g->parent != INVALID_GROUP) { if (g->parent != GroupID::Invalid()) {
Command<CMD_ALTER_GROUP>::Post(STR_ERROR_GROUP_CAN_T_SET_PARENT, AlterGroupMode::SetParent, this->group_sel, INVALID_GROUP, {}); Command<CMD_ALTER_GROUP>::Post(STR_ERROR_GROUP_CAN_T_SET_PARENT, AlterGroupMode::SetParent, this->group_sel, GroupID::Invalid(), {});
} }
this->group_sel = INVALID_GROUP; this->group_sel = GroupID::Invalid();
this->group_over = INVALID_GROUP; this->group_over = GroupID::Invalid();
this->SetDirty(); this->SetDirty();
break; break;
case WID_GL_LIST_GROUP: { // Matrix group case WID_GL_LIST_GROUP: { // Matrix group
auto it = this->group_sb->GetScrolledItemFromWidget(this->groups, pt.y, this, WID_GL_LIST_GROUP); auto it = this->group_sb->GetScrolledItemFromWidget(this->groups, pt.y, this, WID_GL_LIST_GROUP);
GroupID new_g = it == this->groups.end() ? INVALID_GROUP : it->group->index; GroupID new_g = it == this->groups.end() ? GroupID::Invalid() : it->group->index;
if (this->group_sel != new_g && g->parent != new_g) { if (this->group_sel != new_g && g->parent != new_g) {
Command<CMD_ALTER_GROUP>::Post(STR_ERROR_GROUP_CAN_T_SET_PARENT, AlterGroupMode::SetParent, this->group_sel, new_g, {}); Command<CMD_ALTER_GROUP>::Post(STR_ERROR_GROUP_CAN_T_SET_PARENT, AlterGroupMode::SetParent, this->group_sel, new_g, {});
} }
this->group_sel = INVALID_GROUP; this->group_sel = GroupID::Invalid();
this->group_over = INVALID_GROUP; this->group_over = GroupID::Invalid();
this->SetDirty(); this->SetDirty();
break; break;
} }
@ -917,16 +917,16 @@ public:
case WID_GL_DEFAULT_VEHICLES: // Ungrouped vehicles case WID_GL_DEFAULT_VEHICLES: // Ungrouped vehicles
Command<CMD_ADD_VEHICLE_GROUP>::Post(STR_ERROR_GROUP_CAN_T_ADD_VEHICLE, DEFAULT_GROUP, this->vehicle_sel, _ctrl_pressed || this->grouping == GB_SHARED_ORDERS, VehicleListIdentifier{}); Command<CMD_ADD_VEHICLE_GROUP>::Post(STR_ERROR_GROUP_CAN_T_ADD_VEHICLE, DEFAULT_GROUP, this->vehicle_sel, _ctrl_pressed || this->grouping == GB_SHARED_ORDERS, VehicleListIdentifier{});
this->vehicle_sel = INVALID_VEHICLE; this->vehicle_sel = VehicleID::Invalid();
this->group_over = INVALID_GROUP; this->group_over = GroupID::Invalid();
this->SetDirty(); this->SetDirty();
break; break;
case WID_GL_LIST_GROUP: { // Matrix group case WID_GL_LIST_GROUP: { // Matrix group
const VehicleID vindex = this->vehicle_sel; const VehicleID vindex = this->vehicle_sel;
this->vehicle_sel = INVALID_VEHICLE; this->vehicle_sel = VehicleID::Invalid();
this->group_over = INVALID_GROUP; this->group_over = GroupID::Invalid();
this->SetDirty(); this->SetDirty();
auto it = this->group_sb->GetScrolledItemFromWidget(this->groups, pt.y, this, WID_GL_LIST_GROUP); auto it = this->group_sb->GetScrolledItemFromWidget(this->groups, pt.y, this, WID_GL_LIST_GROUP);
@ -938,8 +938,8 @@ public:
case WID_GL_LIST_VEHICLE: { // Matrix vehicle case WID_GL_LIST_VEHICLE: { // Matrix vehicle
const VehicleID vindex = this->vehicle_sel; const VehicleID vindex = this->vehicle_sel;
this->vehicle_sel = INVALID_VEHICLE; this->vehicle_sel = VehicleID::Invalid();
this->group_over = INVALID_GROUP; this->group_over = GroupID::Invalid();
this->SetDirty(); this->SetDirty();
auto it = this->vscroll->GetScrolledItemFromWidget(this->vehgroups, pt.y, this, WID_GL_LIST_VEHICLE); auto it = this->vscroll->GetScrolledItemFromWidget(this->vehgroups, pt.y, this, WID_GL_LIST_VEHICLE);
@ -979,16 +979,16 @@ public:
void OnDragDrop(Point pt, WidgetID widget) override void OnDragDrop(Point pt, WidgetID widget) override
{ {
if (this->vehicle_sel != INVALID_VEHICLE) OnDragDrop_Vehicle(pt, widget); if (this->vehicle_sel != VehicleID::Invalid()) OnDragDrop_Vehicle(pt, widget);
if (this->group_sel != INVALID_GROUP) OnDragDrop_Group(pt, widget); if (this->group_sel != GroupID::Invalid()) OnDragDrop_Group(pt, widget);
_cursor.vehchain = false; _cursor.vehchain = false;
} }
void OnQueryTextFinished(std::optional<std::string> str) override void OnQueryTextFinished(std::optional<std::string> str) override
{ {
if (str.has_value()) Command<CMD_ALTER_GROUP>::Post(STR_ERROR_GROUP_CAN_T_RENAME, AlterGroupMode::Rename, this->group_rename, INVALID_GROUP, *str); if (str.has_value()) Command<CMD_ALTER_GROUP>::Post(STR_ERROR_GROUP_CAN_T_RENAME, AlterGroupMode::Rename, this->group_rename, GroupID::Invalid(), *str);
this->group_rename = INVALID_GROUP; this->group_rename = GroupID::Invalid();
} }
void OnResize() override void OnResize() override
@ -1021,12 +1021,12 @@ public:
break; break;
case ADI_SERVICE: // Send for servicing case ADI_SERVICE: // Send for servicing
case ADI_DEPOT: { // Send to Depots case ADI_DEPOT: { // Send to Depots
Command<CMD_SEND_VEHICLE_TO_DEPOT>::Post(GetCmdSendToDepotMsg(this->vli.vtype), INVALID_VEHICLE, (index == ADI_SERVICE ? DepotCommandFlag::Service : DepotCommandFlags{}) | DepotCommandFlag::MassSend, this->vli); Command<CMD_SEND_VEHICLE_TO_DEPOT>::Post(GetCmdSendToDepotMsg(this->vli.vtype), VehicleID::Invalid(), (index == ADI_SERVICE ? DepotCommandFlag::Service : DepotCommandFlags{}) | DepotCommandFlag::MassSend, this->vli);
break; break;
} }
case ADI_CREATE_GROUP: // Create group case ADI_CREATE_GROUP: // Create group
Command<CMD_ADD_VEHICLE_GROUP>::Post(CcAddVehicleNewGroup, NEW_GROUP, INVALID_VEHICLE, false, this->vli); Command<CMD_ADD_VEHICLE_GROUP>::Post(CcAddVehicleNewGroup, NEW_GROUP, VehicleID::Invalid(), false, this->vli);
break; break;
case ADI_ADD_SHARED: // Add shared Vehicles case ADI_ADD_SHARED: // Add shared Vehicles
@ -1059,19 +1059,19 @@ public:
void OnPlaceObjectAbort() override void OnPlaceObjectAbort() override
{ {
/* abort drag & drop */ /* abort drag & drop */
this->vehicle_sel = INVALID_VEHICLE; this->vehicle_sel = VehicleID::Invalid();
this->DirtyHighlightedGroupWidget(); this->DirtyHighlightedGroupWidget();
this->group_sel = INVALID_GROUP; this->group_sel = GroupID::Invalid();
this->group_over = INVALID_GROUP; this->group_over = GroupID::Invalid();
this->SetWidgetDirty(WID_GL_LIST_VEHICLE); this->SetWidgetDirty(WID_GL_LIST_VEHICLE);
} }
void OnMouseDrag(Point pt, WidgetID widget) override void OnMouseDrag(Point pt, WidgetID widget) override
{ {
if (this->vehicle_sel == INVALID_VEHICLE && this->group_sel == INVALID_GROUP) return; if (this->vehicle_sel == VehicleID::Invalid() && this->group_sel == GroupID::Invalid()) return;
/* A vehicle is dragged over... */ /* A vehicle is dragged over... */
GroupID new_group_over = INVALID_GROUP; GroupID new_group_over = GroupID::Invalid();
switch (widget) { switch (widget) {
case WID_GL_DEFAULT_VEHICLES: // ... the 'default' group. case WID_GL_DEFAULT_VEHICLES: // ... the 'default' group.
new_group_over = DEFAULT_GROUP; new_group_over = DEFAULT_GROUP;
@ -1085,10 +1085,10 @@ public:
} }
/* Do not highlight when dragging over the current group */ /* Do not highlight when dragging over the current group */
if (this->vehicle_sel != INVALID_VEHICLE) { if (this->vehicle_sel != VehicleID::Invalid()) {
if (Vehicle::Get(vehicle_sel)->group_id == new_group_over) new_group_over = INVALID_GROUP; if (Vehicle::Get(vehicle_sel)->group_id == new_group_over) new_group_over = GroupID::Invalid();
} else if (this->group_sel != INVALID_GROUP) { } else if (this->group_sel != GroupID::Invalid()) {
if (this->group_sel == new_group_over || Group::Get(this->group_sel)->parent == new_group_over) new_group_over = INVALID_GROUP; if (this->group_sel == new_group_over || Group::Get(this->group_sel)->parent == new_group_over) new_group_over = GroupID::Invalid();
} }
/* Mark widgets as dirty if the group changed. */ /* Mark widgets as dirty if the group changed. */
@ -1128,7 +1128,7 @@ public:
*/ */
void SelectGroup(const GroupID g_id) void SelectGroup(const GroupID g_id)
{ {
if (g_id == INVALID_GROUP || g_id == this->vli.ToGroupID()) return; if (g_id == GroupID::Invalid() || g_id == this->vli.ToGroupID()) return;
this->vli.SetIndex(g_id); this->vli.SetIndex(g_id);
if (g_id != ALL_GROUP && g_id != DEFAULT_GROUP) { if (g_id != ALL_GROUP && g_id != DEFAULT_GROUP) {
@ -1184,7 +1184,7 @@ static WindowDesc _vehicle_group_desc[] = {
* Show the group window for the given company and vehicle type. * Show the group window for the given company and vehicle type.
* @param company The company to show the window for. * @param company The company to show the window for.
* @param vehicle_type The type of vehicle to show it for. * @param vehicle_type The type of vehicle to show it for.
* @param group The group to be selected. Defaults to INVALID_GROUP. * @param group The group to be selected. Defaults to GroupID::Invalid().
* @tparam Tneed_existing_window Whether the existing window is needed. * @tparam Tneed_existing_window Whether the existing window is needed.
*/ */
template <bool Tneed_existing_window> template <bool Tneed_existing_window>
@ -1202,7 +1202,7 @@ static void ShowCompanyGroupInternal(CompanyID company, VehicleType vehicle_type
* Show the group window for the given company and vehicle type. * Show the group window for the given company and vehicle type.
* @param company The company to show the window for. * @param company The company to show the window for.
* @param vehicle_type The type of vehicle to show it for. * @param vehicle_type The type of vehicle to show it for.
* @param group The group to be selected. Defaults to INVALID_GROUP. * @param group The group to be selected. Defaults to GroupID::Invalid().
*/ */
void ShowCompanyGroup(CompanyID company, VehicleType vehicle_type, GroupID group) void ShowCompanyGroup(CompanyID company, VehicleType vehicle_type, GroupID group)
{ {

View File

@ -13,7 +13,7 @@
#include "company_type.h" #include "company_type.h"
#include "vehicle_type.h" #include "vehicle_type.h"
void ShowCompanyGroup(CompanyID company, VehicleType veh, GroupID group = INVALID_GROUP); void ShowCompanyGroup(CompanyID company, VehicleType veh, GroupID group = GroupID::Invalid());
void ShowCompanyGroupForVehicle(const Vehicle *v); void ShowCompanyGroupForVehicle(const Vehicle *v);
void DeleteGroupHighlightOfVehicle(const Vehicle *v); void DeleteGroupHighlightOfVehicle(const Vehicle *v);

View File

@ -16,7 +16,6 @@ using GroupID = PoolID<uint16_t, struct GroupIDTag, 64000, 0xFFFF>;
static constexpr GroupID NEW_GROUP{0xFFFC}; ///< Sentinel for a to-be-created group. static constexpr GroupID NEW_GROUP{0xFFFC}; ///< Sentinel for a to-be-created group.
static constexpr GroupID ALL_GROUP{0xFFFD}; ///< All vehicles are in this group. static constexpr GroupID ALL_GROUP{0xFFFD}; ///< All vehicles are in this group.
static constexpr GroupID DEFAULT_GROUP{0xFFFE}; ///< Ungrouped vehicles are in this group. static constexpr GroupID DEFAULT_GROUP{0xFFFE}; ///< Ungrouped vehicles are in this group.
static constexpr GroupID INVALID_GROUP = GroupID::Invalid(); ///< Sentinel for invalid groups.
static const uint MAX_LENGTH_GROUP_NAME_CHARS = 32; ///< The maximum length of a group name in characters including '\0' static const uint MAX_LENGTH_GROUP_NAME_CHARS = 32; ///< The maximum length of a group name in characters including '\0'

View File

@ -65,7 +65,7 @@ void ShowGoalsList(CompanyID company);
void ShowGoalQuestion(uint16_t id, uint8_t type, uint32_t button_mask, const std::string &question); void ShowGoalQuestion(uint16_t id, uint8_t type, uint32_t button_mask, const std::string &question);
/* story_gui.cpp */ /* story_gui.cpp */
void ShowStoryBook(CompanyID company, StoryPageID page_id = INVALID_STORY_PAGE, bool centered = false); void ShowStoryBook(CompanyID company, StoryPageID page_id = StoryPageID::Invalid(), bool centered = false);
/* viewport_gui.cpp */ /* viewport_gui.cpp */
void ShowExtraViewportWindow(TileIndex tile = INVALID_TILE); void ShowExtraViewportWindow(TileIndex tile = INVALID_TILE);

View File

@ -178,7 +178,7 @@ Industry::~Industry()
for (TileIndex tile_cur : ta) { for (TileIndex tile_cur : ta) {
if (IsTileType(tile_cur, MP_CLEAR) && IsClearGround(tile_cur, CLEAR_FIELDS) && if (IsTileType(tile_cur, MP_CLEAR) && IsClearGround(tile_cur, CLEAR_FIELDS) &&
GetIndustryIndexOfField(tile_cur) == this->index) { GetIndustryIndexOfField(tile_cur) == this->index) {
SetIndustryIndexOfField(tile_cur, INVALID_INDUSTRY); SetIndustryIndexOfField(tile_cur, IndustryID::Invalid());
} }
} }
} }

View File

@ -11,7 +11,6 @@
#define INDUSTRY_TYPE_H #define INDUSTRY_TYPE_H
using IndustryID = PoolID<uint16_t, struct IndustryIDTag, 64000, 0xFFFF>; using IndustryID = PoolID<uint16_t, struct IndustryIDTag, 64000, 0xFFFF>;
static constexpr IndustryID INVALID_INDUSTRY = IndustryID::Invalid();
typedef uint16_t IndustryGfx; typedef uint16_t IndustryGfx;
typedef uint8_t IndustryType; typedef uint8_t IndustryType;

View File

@ -62,7 +62,7 @@ struct IntroGameViewportCommand {
int command_index = 0; ///< Sequence number of the command (order they are performed in). int command_index = 0; ///< Sequence number of the command (order they are performed in).
Point position{ 0, 0 }; ///< Calculated world coordinate to position viewport top-left at. Point position{ 0, 0 }; ///< Calculated world coordinate to position viewport top-left at.
VehicleID vehicle = INVALID_VEHICLE; ///< Vehicle to follow, or INVALID_VEHICLE if not following a vehicle. VehicleID vehicle = VehicleID::Invalid(); ///< Vehicle to follow, or VehicleID::Invalid() if not following a vehicle.
uint delay = 0; ///< Delay until next command. uint delay = 0; ///< Delay until next command.
int zoom_adjust = 0; ///< Adjustment to zoom level from base zoom level. int zoom_adjust = 0; ///< Adjustment to zoom level from base zoom level.
bool pan_to_next = false; ///< If true, do a smooth pan from this position to the next. bool pan_to_next = false; ///< If true, do a smooth pan from this position to the next.
@ -77,7 +77,7 @@ struct IntroGameViewportCommand {
*/ */
Point PositionForViewport(const Viewport *vp) Point PositionForViewport(const Viewport *vp)
{ {
if (this->vehicle != INVALID_VEHICLE) { if (this->vehicle != VehicleID::Invalid()) {
const Vehicle *v = Vehicle::Get(this->vehicle); const Vehicle *v = Vehicle::Get(this->vehicle);
this->position = RemapCoords(v->x_pos, v->y_pos, v->z_pos); this->position = RemapCoords(v->x_pos, v->y_pos, v->z_pos);
} }
@ -228,7 +228,7 @@ struct SelectGameWindow : public Window {
Viewport *vp = mw->viewport; Viewport *vp = mw->viewport;
/* Early exit if the current command hasn't elapsed and isn't animated. */ /* Early exit if the current command hasn't elapsed and isn't animated. */
if (!changed_command && !vc.pan_to_next && vc.vehicle == INVALID_VEHICLE) return; if (!changed_command && !vc.pan_to_next && vc.vehicle == VehicleID::Invalid()) return;
/* Suppress panning commands, while user interacts with GUIs. */ /* Suppress panning commands, while user interacts with GUIs. */
if (!changed_command && suppress_panning) return; if (!changed_command && suppress_panning) return;
@ -256,7 +256,7 @@ struct SelectGameWindow : public Window {
mw->SetDirty(); // Required during panning, otherwise logo graphics disappears mw->SetDirty(); // Required during panning, otherwise logo graphics disappears
/* If there is only one command, we just executed it and don't need to do any more */ /* If there is only one command, we just executed it and don't need to do any more */
if (intro_viewport_commands.size() == 1 && vc.vehicle == INVALID_VEHICLE) intro_viewport_commands.clear(); if (intro_viewport_commands.size() == 1 && vc.vehicle == VehicleID::Invalid()) intro_viewport_commands.clear();
} }
/** /**

View File

@ -31,7 +31,7 @@ extern LeagueTablePool _league_table_pool;
struct LeagueTableElement : LeagueTableElementPool::PoolItem<&_league_table_element_pool> { struct LeagueTableElement : LeagueTableElementPool::PoolItem<&_league_table_element_pool> {
LeagueTableID table; ///< Id of the table which this element belongs to LeagueTableID table; ///< Id of the table which this element belongs to
int64_t rating; ///< Value that determines ordering of elements in the table (higher=better) int64_t rating; ///< Value that determines ordering of elements in the table (higher=better)
CompanyID company; ///< Company Id to show the color blob for or INVALID_COMPANY CompanyID company; ///< Company Id to show the color blob for or CompanyID::Invalid()
std::string text; ///< Text of the element std::string text; ///< Text of the element
std::string score; ///< String representation of the score associated with the element std::string score; ///< String representation of the score associated with the element
Link link; ///< What opens when element is clicked Link link; ///< What opens when element is clicked

View File

@ -55,9 +55,9 @@ bool IsValidLink(Link link)
*/ */
std::tuple<CommandCost, LeagueTableID> CmdCreateLeagueTable(DoCommandFlags flags, const std::string &title, const std::string &header, const std::string &footer) std::tuple<CommandCost, LeagueTableID> CmdCreateLeagueTable(DoCommandFlags flags, const std::string &title, const std::string &header, const std::string &footer)
{ {
if (_current_company != OWNER_DEITY) return { CMD_ERROR, INVALID_LEAGUE_TABLE }; if (_current_company != OWNER_DEITY) return { CMD_ERROR, LeagueTableID::Invalid() };
if (!LeagueTable::CanAllocateItem()) return { CMD_ERROR, INVALID_LEAGUE_TABLE }; if (!LeagueTable::CanAllocateItem()) return { CMD_ERROR, LeagueTableID::Invalid() };
if (title.empty()) return { CMD_ERROR, INVALID_LEAGUE_TABLE }; if (title.empty()) return { CMD_ERROR, LeagueTableID::Invalid() };
if (flags.Test(DoCommandFlag::Execute)) { if (flags.Test(DoCommandFlag::Execute)) {
LeagueTable *lt = new LeagueTable(); LeagueTable *lt = new LeagueTable();
@ -67,7 +67,7 @@ std::tuple<CommandCost, LeagueTableID> CmdCreateLeagueTable(DoCommandFlags flags
return { CommandCost(), lt->index }; return { CommandCost(), lt->index };
} }
return { CommandCost(), INVALID_LEAGUE_TABLE }; return { CommandCost(), LeagueTableID::Invalid() };
} }
@ -76,7 +76,7 @@ std::tuple<CommandCost, LeagueTableID> CmdCreateLeagueTable(DoCommandFlags flags
* @param flags type of operation * @param flags type of operation
* @param table Id of the league table this element belongs to * @param table Id of the league table this element belongs to
* @param rating Value that elements are ordered by * @param rating Value that elements are ordered by
* @param company Company to show the color blob for or INVALID_COMPANY * @param company Company to show the color blob for or CompanyID::Invalid()
* @param text Text of the element * @param text Text of the element
* @param score String representation of the score associated with the element * @param score String representation of the score associated with the element
* @param link_type Type of the referenced object * @param link_type Type of the referenced object
@ -85,11 +85,11 @@ std::tuple<CommandCost, LeagueTableID> CmdCreateLeagueTable(DoCommandFlags flags
*/ */
std::tuple<CommandCost, LeagueTableElementID> CmdCreateLeagueTableElement(DoCommandFlags flags, LeagueTableID table, int64_t rating, CompanyID company, const std::string &text, const std::string &score, LinkType link_type, LinkTargetID link_target) std::tuple<CommandCost, LeagueTableElementID> CmdCreateLeagueTableElement(DoCommandFlags flags, LeagueTableID table, int64_t rating, CompanyID company, const std::string &text, const std::string &score, LinkType link_type, LinkTargetID link_target)
{ {
if (_current_company != OWNER_DEITY) return { CMD_ERROR, INVALID_LEAGUE_TABLE_ELEMENT }; if (_current_company != OWNER_DEITY) return { CMD_ERROR, LeagueTableElementID::Invalid() };
if (!LeagueTableElement::CanAllocateItem()) return { CMD_ERROR, INVALID_LEAGUE_TABLE_ELEMENT }; if (!LeagueTableElement::CanAllocateItem()) return { CMD_ERROR, LeagueTableElementID::Invalid() };
Link link{link_type, link_target}; Link link{link_type, link_target};
if (!IsValidLink(link)) return { CMD_ERROR, INVALID_LEAGUE_TABLE_ELEMENT }; if (!IsValidLink(link)) return { CMD_ERROR, LeagueTableElementID::Invalid() };
if (company != INVALID_COMPANY && !Company::IsValidID(company)) return { CMD_ERROR, INVALID_LEAGUE_TABLE_ELEMENT }; if (company != CompanyID::Invalid() && !Company::IsValidID(company)) return { CMD_ERROR, LeagueTableElementID::Invalid() };
if (flags.Test(DoCommandFlag::Execute)) { if (flags.Test(DoCommandFlag::Execute)) {
LeagueTableElement *lte = new LeagueTableElement(); LeagueTableElement *lte = new LeagueTableElement();
@ -102,14 +102,14 @@ std::tuple<CommandCost, LeagueTableElementID> CmdCreateLeagueTableElement(DoComm
InvalidateWindowData(WC_COMPANY_LEAGUE, table); InvalidateWindowData(WC_COMPANY_LEAGUE, table);
return { CommandCost(), lte->index }; return { CommandCost(), lte->index };
} }
return { CommandCost(), INVALID_LEAGUE_TABLE_ELEMENT }; return { CommandCost(), LeagueTableElementID::Invalid() };
} }
/** /**
* Update the attributes of a league table element. * Update the attributes of a league table element.
* @param flags type of operation * @param flags type of operation
* @param element Id of the element to update * @param element Id of the element to update
* @param company Company to show the color blob for or INVALID_COMPANY * @param company Company to show the color blob for or CompanyID::Invalid()
* @param text Text of the element * @param text Text of the element
* @param link_type Type of the referenced object * @param link_type Type of the referenced object
* @param link_target Id of the referenced object * @param link_target Id of the referenced object
@ -120,7 +120,7 @@ CommandCost CmdUpdateLeagueTableElementData(DoCommandFlags flags, LeagueTableEle
if (_current_company != OWNER_DEITY) return CMD_ERROR; if (_current_company != OWNER_DEITY) return CMD_ERROR;
auto lte = LeagueTableElement::GetIfValid(element); auto lte = LeagueTableElement::GetIfValid(element);
if (lte == nullptr) return CMD_ERROR; if (lte == nullptr) return CMD_ERROR;
if (company != INVALID_COMPANY && !Company::IsValidID(company)) return CMD_ERROR; if (company != CompanyID::Invalid() && !Company::IsValidID(company)) return CMD_ERROR;
Link link{link_type, link_target}; Link link{link_type, link_target};
if (!IsValidLink(link)) return CMD_ERROR; if (!IsValidLink(link)) return CMD_ERROR;

View File

@ -343,7 +343,7 @@ public:
for (auto [rank, lte] : this->rows) { for (auto [rank, lte] : this->rows) {
SetDParam(0, rank + 1); SetDParam(0, rank + 1);
DrawString(rank_rect.left, rank_rect.right, ir.top + text_y_offset, STR_COMPANY_LEAGUE_COMPANY_RANK); DrawString(rank_rect.left, rank_rect.right, ir.top + text_y_offset, STR_COMPANY_LEAGUE_COMPANY_RANK);
if (this->icon_size.width > 0 && lte->company != INVALID_COMPANY) DrawCompanyIcon(lte->company, icon_rect.left, ir.top + icon_y_offset); if (this->icon_size.width > 0 && lte->company != CompanyID::Invalid()) DrawCompanyIcon(lte->company, icon_rect.left, ir.top + icon_y_offset);
SetDParamStr(0, lte->text); SetDParamStr(0, lte->text);
DrawString(text_rect.left, text_rect.right, ir.top + text_y_offset, STR_JUST_RAW_STRING, TC_BLACK); DrawString(text_rect.left, text_rect.right, ir.top + text_y_offset, STR_JUST_RAW_STRING, TC_BLACK);
SetDParamStr(0, lte->score); SetDParamStr(0, lte->score);
@ -378,7 +378,7 @@ public:
this->text_width = std::max(this->text_width, GetStringBoundingBox(STR_JUST_RAW_STRING).width); this->text_width = std::max(this->text_width, GetStringBoundingBox(STR_JUST_RAW_STRING).width);
SetDParamStr(0, lte->score); SetDParamStr(0, lte->score);
this->score_width = std::max(this->score_width, GetStringBoundingBox(STR_JUST_RAW_STRING).width); this->score_width = std::max(this->score_width, GetStringBoundingBox(STR_JUST_RAW_STRING).width);
if (lte->company != INVALID_COMPANY) show_icon_column = true; if (lte->company != CompanyID::Invalid()) show_icon_column = true;
} }
if (!show_icon_column) this->icon_size.width = 0; if (!show_icon_column) this->icon_size.width = 0;

View File

@ -33,10 +33,8 @@ struct Link {
using LeagueTableID = PoolID<uint8_t, struct LeagueTableIDTag, 255, 0xFF>; ///< ID of a league table using LeagueTableID = PoolID<uint8_t, struct LeagueTableIDTag, 255, 0xFF>; ///< ID of a league table
struct LeagueTable; struct LeagueTable;
static constexpr LeagueTableID INVALID_LEAGUE_TABLE = LeagueTableID::Invalid(); ///< Invalid/unknown index of LeagueTable
using LeagueTableElementID = PoolID<uint16_t, struct LeagueTableElementIDTag, 64000, 0xFFFF>; ///< ID of a league table using LeagueTableElementID = PoolID<uint16_t, struct LeagueTableElementIDTag, 64000, 0xFFFF>; ///< ID of a league table
struct LeagueTableElement; struct LeagueTableElement;
static constexpr LeagueTableElementID INVALID_LEAGUE_TABLE_ELEMENT = LeagueTableElementID::Invalid(); ///< Invalid/unknown index of LeagueTableElement
#endif /* LEAGUE_TYPE_H */ #endif /* LEAGUE_TYPE_H */

View File

@ -96,7 +96,7 @@ public:
std::vector<BaseEdge> edges; ///< Sorted list of outgoing edges from this node. std::vector<BaseEdge> edges; ///< Sorted list of outgoing edges from this node.
BaseNode(TileIndex xy = INVALID_TILE, StationID st = INVALID_STATION, uint demand = 0); BaseNode(TileIndex xy = INVALID_TILE, StationID st = StationID::Invalid(), uint demand = 0);
/** /**
* Update the node's supply and set last_update to the current date. * Update the node's supply and set last_update to the current date.

View File

@ -561,7 +561,7 @@ void LinkGraphLegendWindow::SetOverlay(std::shared_ptr<LinkGraphOverlay> overlay
{ {
this->overlay = overlay; this->overlay = overlay;
CompanyMask companies = this->overlay->GetCompanyMask(); CompanyMask companies = this->overlay->GetCompanyMask();
for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; ++c) { for (CompanyID c = CompanyID::Begin(); c < MAX_COMPANIES; ++c) {
if (!this->IsWidgetDisabled(WID_LGL_COMPANY_FIRST + c)) { if (!this->IsWidgetDisabled(WID_LGL_COMPANY_FIRST + c)) {
this->SetWidgetLoweredState(WID_LGL_COMPANY_FIRST + c, companies.Test(c)); this->SetWidgetLoweredState(WID_LGL_COMPANY_FIRST + c, companies.Test(c));
} }
@ -658,7 +658,7 @@ bool LinkGraphLegendWindow::OnTooltip([[maybe_unused]] Point, WidgetID widget, T
void LinkGraphLegendWindow::UpdateOverlayCompanies() void LinkGraphLegendWindow::UpdateOverlayCompanies()
{ {
CompanyMask mask; CompanyMask mask;
for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; ++c) { for (CompanyID c = CompanyID::Begin(); c < MAX_COMPANIES; ++c) {
if (this->IsWidgetDisabled(WID_LGL_COMPANY_FIRST + c)) continue; if (this->IsWidgetDisabled(WID_LGL_COMPANY_FIRST + c)) continue;
if (!this->IsWidgetLowered(WID_LGL_COMPANY_FIRST + c)) continue; if (!this->IsWidgetLowered(WID_LGL_COMPANY_FIRST + c)) continue;
mask.Set(c); mask.Set(c);
@ -688,7 +688,7 @@ void LinkGraphLegendWindow::OnClick([[maybe_unused]] Point pt, WidgetID widget,
this->UpdateOverlayCompanies(); this->UpdateOverlayCompanies();
} }
} else if (widget == WID_LGL_COMPANIES_ALL || widget == WID_LGL_COMPANIES_NONE) { } else if (widget == WID_LGL_COMPANIES_ALL || widget == WID_LGL_COMPANIES_NONE) {
for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; ++c) { for (CompanyID c = CompanyID::Begin(); c < MAX_COMPANIES; ++c) {
if (this->IsWidgetDisabled(WID_LGL_COMPANY_FIRST + c)) continue; if (this->IsWidgetDisabled(WID_LGL_COMPANY_FIRST + c)) continue;
this->SetWidgetLoweredState(WID_LGL_COMPANY_FIRST + c, widget == WID_LGL_COMPANIES_ALL); this->SetWidgetLoweredState(WID_LGL_COMPANY_FIRST + c, widget == WID_LGL_COMPANIES_ALL);
} }
@ -719,7 +719,7 @@ void LinkGraphLegendWindow::OnInvalidateData([[maybe_unused]] int data, [[maybe_
} }
/* Disable the companies who are not active */ /* Disable the companies who are not active */
for (CompanyID i = COMPANY_FIRST; i < MAX_COMPANIES; ++i) { for (CompanyID i = CompanyID::Begin(); i < MAX_COMPANIES; ++i) {
this->SetWidgetDisabledState(WID_LGL_COMPANY_FIRST + i, !Company::IsValidID(i)); this->SetWidgetDisabledState(WID_LGL_COMPANY_FIRST + i, !Company::IsValidID(i));
} }
} }

View File

@ -13,10 +13,7 @@
#include "../core/pool_type.hpp" #include "../core/pool_type.hpp"
using LinkGraphID = PoolID<uint16_t, struct LinkGraphIDTag, 0xFFFF, 0xFFFF>; using LinkGraphID = PoolID<uint16_t, struct LinkGraphIDTag, 0xFFFF, 0xFFFF>;
static constexpr LinkGraphID INVALID_LINK_GRAPH = LinkGraphID::Invalid();
using LinkGraphJobID = PoolID<uint16_t, struct LinkGraphJobIDTag, 0xFFFF, 0xFFFF>; using LinkGraphJobID = PoolID<uint16_t, struct LinkGraphJobIDTag, 0xFFFF, 0xFFFF>;
static constexpr LinkGraphJobID INVALID_LINK_GRAPH_JOB = LinkGraphJobID::Invalid();
typedef uint16_t NodeID; typedef uint16_t NodeID;
static const NodeID INVALID_NODE = UINT16_MAX; static const NodeID INVALID_NODE = UINT16_MAX;

View File

@ -156,7 +156,7 @@ LinkGraphJob::~LinkGraphJob()
it->second.Invalidate(); it->second.Invalidate();
++it; ++it;
} else { } else {
FlowStat shares(INVALID_STATION, 1); FlowStat shares(StationID::Invalid(), 1);
it->second.SwapShares(shares); it->second.SwapShares(shares);
geflows.erase(it++); geflows.erase(it++);
for (FlowStat::SharesMap::const_iterator shares_it(shares.GetShares()->begin()); for (FlowStat::SharesMap::const_iterator shares_it(shares.GetShares()->begin());

View File

@ -35,7 +35,7 @@
HopSet seen_hops; HopSet seen_hops;
LinkRefresher refresher(v, &seen_hops, allow_merge, is_full_loading); LinkRefresher refresher(v, &seen_hops, allow_merge, is_full_loading);
refresher.RefreshLinks(first, first, v->last_loading_station != INVALID_STATION ? 1 << HAS_CARGO : 0); refresher.RefreshLinks(first, first, v->last_loading_station != StationID::Invalid() ? 1 << HAS_CARGO : 0);
} }
/** /**
@ -200,7 +200,7 @@ void LinkRefresher::RefreshStats(const Order *cur, const Order *next)
{ {
StationID next_station = next->GetDestination().ToStationID(); StationID next_station = next->GetDestination().ToStationID();
Station *st = Station::GetIfValid(cur->GetDestination().ToStationID()); Station *st = Station::GetIfValid(cur->GetDestination().ToStationID());
if (st != nullptr && next_station != INVALID_STATION && next_station != st->index) { if (st != nullptr && next_station != StationID::Invalid() && next_station != st->index) {
Station *st_to = Station::Get(next_station); Station *st_to = Station::Get(next_station);
for (CargoType c = 0; c < NUM_CARGO; c++) { for (CargoType c = 0; c < NUM_CARGO; c++) {
/* Refresh the link and give it a minimum capacity. */ /* Refresh the link and give it a minimum capacity. */

View File

@ -436,7 +436,7 @@ struct MainWindow : Window
bool in = wheel < 0; bool in = wheel < 0;
/* When following, only change zoom - otherwise zoom to the cursor. */ /* When following, only change zoom - otherwise zoom to the cursor. */
if (this->viewport->follow_vehicle != INVALID_VEHICLE) { if (this->viewport->follow_vehicle != VehicleID::Invalid()) {
DoZoomInOutWindow(in ? ZOOM_IN : ZOOM_OUT, this); DoZoomInOutWindow(in ? ZOOM_IN : ZOOM_OUT, this);
} else { } else {
ZoomInOrOutToCursorWindow(in, this); ZoomInOrOutToCursorWindow(in, this);

View File

@ -29,7 +29,7 @@
/* This file handles all the admin network commands. */ /* This file handles all the admin network commands. */
/** Redirection of the (remote) console to the admin. */ /** Redirection of the (remote) console to the admin. */
AdminID _redirect_console_to_admin = INVALID_ADMIN_ID; AdminID _redirect_console_to_admin = AdminID::Invalid();
/** The pool with sockets/clients. */ /** The pool with sockets/clients. */
NetworkAdminSocketPool _networkadminsocket_pool("NetworkAdminSocket"); NetworkAdminSocketPool _networkadminsocket_pool("NetworkAdminSocket");
@ -74,7 +74,7 @@ ServerNetworkAdminSocketHandler::ServerNetworkAdminSocketHandler(SOCKET s) : Net
ServerNetworkAdminSocketHandler::~ServerNetworkAdminSocketHandler() ServerNetworkAdminSocketHandler::~ServerNetworkAdminSocketHandler()
{ {
Debug(net, 3, "[admin] '{}' ({}) has disconnected", this->admin_name, this->admin_version); Debug(net, 3, "[admin] '{}' ({}) has disconnected", this->admin_name, this->admin_version);
if (_redirect_console_to_admin == this->index) _redirect_console_to_admin = INVALID_ADMIN_ID; if (_redirect_console_to_admin == this->index) _redirect_console_to_admin = AdminID::Invalid();
if (this->update_frequency[ADMIN_UPDATE_CONSOLE] & ADMIN_FREQUENCY_AUTOMATIC) { if (this->update_frequency[ADMIN_UPDATE_CONSOLE] & ADMIN_FREQUENCY_AUTOMATIC) {
this->update_frequency[ADMIN_UPDATE_CONSOLE] = (AdminUpdateFrequency)0; this->update_frequency[ADMIN_UPDATE_CONSOLE] = (AdminUpdateFrequency)0;
@ -492,7 +492,7 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::Receive_ADMIN_RCON(Packet &p)
_redirect_console_to_admin = this->index; _redirect_console_to_admin = this->index;
IConsoleCmdExec(command); IConsoleCmdExec(command);
_redirect_console_to_admin = INVALID_ADMIN_ID; _redirect_console_to_admin = AdminID::Invalid();
return this->SendRconEnd(command); return this->SendRconEnd(command);
} }

View File

@ -858,7 +858,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MAP_DONE(Packet
Debug(net, 9, "Client::join_status = REGISTERING"); Debug(net, 9, "Client::join_status = REGISTERING");
_network_join_status = NETWORK_JOIN_STATUS_REGISTERING; _network_join_status = NETWORK_JOIN_STATUS_REGISTERING;
ShowJoinStatusWindow(); ShowJoinStatusWindow();
Command<CMD_COMPANY_CTRL>::Post(CCA_NEW, INVALID_COMPANY, CRR_NONE, _network_own_client_id); Command<CMD_COMPANY_CTRL>::Post(CCA_NEW, CompanyID::Invalid(), CRR_NONE, _network_own_client_id);
} }
} else { } else {
/* take control over an existing company */ /* take control over an existing company */

View File

@ -57,7 +57,7 @@
static void ShowNetworkStartServerWindow(); static void ShowNetworkStartServerWindow();
static ClientID _admin_client_id = INVALID_CLIENT_ID; ///< For what client a confirmation window is open. static ClientID _admin_client_id = INVALID_CLIENT_ID; ///< For what client a confirmation window is open.
static CompanyID _admin_company_id = INVALID_COMPANY; ///< For what company a confirmation window is open. static CompanyID _admin_company_id = CompanyID::Invalid(); ///< For what company a confirmation window is open.
/** /**
* Update the network new window because a new server is * Update the network new window because a new server is
@ -1462,7 +1462,7 @@ private:
*/ */
static void OnClickCompanyNew([[maybe_unused]] NetworkClientListWindow *w, [[maybe_unused]] Point pt, CompanyID) static void OnClickCompanyNew([[maybe_unused]] NetworkClientListWindow *w, [[maybe_unused]] Point pt, CompanyID)
{ {
Command<CMD_COMPANY_CTRL>::Post(CCA_NEW, INVALID_COMPANY, CRR_NONE, _network_own_client_id); Command<CMD_COMPANY_CTRL>::Post(CCA_NEW, CompanyID::Invalid(), CRR_NONE, _network_own_client_id);
} }
/** /**

View File

@ -92,7 +92,7 @@ void UpdateNetworkGameWindow();
* Everything we need to know about a command to be able to execute it. * Everything we need to know about a command to be able to execute it.
*/ */
struct CommandPacket { struct CommandPacket {
CommandPacket() : company(INVALID_COMPANY), frame(0), my_cmd(false) {} CommandPacket() : company(CompanyID::Invalid()), frame(0), my_cmd(false) {}
CompanyID company; ///< company that is executing the command CompanyID company; ///< company that is executing the command
uint32_t frame; ///< the frame in which this packet is executed uint32_t frame; ///< the frame in which this packet is executed
bool my_cmd; ///< did the command originate from "me" bool my_cmd; ///< did the command originate from "me"

View File

@ -52,9 +52,6 @@ using ClientPoolID = PoolID<uint16_t, struct ClientPoolIDTag, MAX_CLIENTS + 1 /*
/** Indices into the admin tables. */ /** Indices into the admin tables. */
using AdminID = PoolID<uint8_t, struct AdminIDTag, 16, 0xFF>; using AdminID = PoolID<uint8_t, struct AdminIDTag, 16, 0xFF>;
/** An invalid admin marker. */
static constexpr AdminID INVALID_ADMIN_ID = AdminID::Invalid();
/** Simple calculated statistics of a company */ /** Simple calculated statistics of a company */
struct NetworkCompanyStats { struct NetworkCompanyStats {
uint16_t num_vehicle[NETWORK_VEH_END]; ///< How many vehicles are there of this type? uint16_t num_vehicle[NETWORK_VEH_END]; ///< How many vehicles are there of this type?

View File

@ -644,7 +644,7 @@ static Engine *GetNewEngine(const GRFFile *file, VehicleType type, uint16_t inte
/* Check if the engine is registered in the override manager */ /* Check if the engine is registered in the override manager */
EngineID engine = _engine_mngr.GetID(type, internal_id, scope_grfid); EngineID engine = _engine_mngr.GetID(type, internal_id, scope_grfid);
if (engine != INVALID_ENGINE) { if (engine != EngineID::Invalid()) {
Engine *e = Engine::Get(engine); Engine *e = Engine::Get(engine);
if (!e->grf_prop.HasGrfFile()) { if (!e->grf_prop.HasGrfFile()) {
e->grf_prop.grfid = file->grfid; e->grf_prop.grfid = file->grfid;
@ -656,7 +656,7 @@ static Engine *GetNewEngine(const GRFFile *file, VehicleType type, uint16_t inte
/* Check if there is an unreserved slot */ /* Check if there is an unreserved slot */
EngineID engine = _engine_mngr.UseUnreservedID(type, internal_id, scope_grfid, static_access); EngineID engine = _engine_mngr.UseUnreservedID(type, internal_id, scope_grfid, static_access);
if (engine != INVALID_ENGINE) { if (engine != EngineID::Invalid()) {
Engine *e = Engine::Get(engine); Engine *e = Engine::Get(engine);
if (!e->grf_prop.HasGrfFile()) { if (!e->grf_prop.HasGrfFile()) {
@ -9244,7 +9244,7 @@ static void FinaliseEngineArray()
} }
/* Do final mapping on variant engine ID. */ /* Do final mapping on variant engine ID. */
if (e->info.variant_id != INVALID_ENGINE) { if (e->info.variant_id != EngineID::Invalid()) {
e->info.variant_id = GetNewEngineID(e->grf_prop.grffile, e->type, e->info.variant_id.base()); e->info.variant_id = GetNewEngineID(e->grf_prop.grffile, e->type, e->info.variant_id.base());
} }
@ -9252,7 +9252,7 @@ static void FinaliseEngineArray()
/* Skip wagons, there livery is defined via the engine */ /* Skip wagons, there livery is defined via the engine */
if (e->type != VEH_TRAIN || e->u.rail.railveh_type != RAILVEH_WAGON) { if (e->type != VEH_TRAIN || e->u.rail.railveh_type != RAILVEH_WAGON) {
LiveryScheme ls = GetEngineLiveryScheme(e->index, INVALID_ENGINE, nullptr); LiveryScheme ls = GetEngineLiveryScheme(e->index, EngineID::Invalid(), nullptr);
SetBit(_loaded_newgrf_features.used_liveries, ls); SetBit(_loaded_newgrf_features.used_liveries, ls);
/* Note: For ships and roadvehicles we assume that they cannot be refitted between passenger and freight */ /* Note: For ships and roadvehicles we assume that they cannot be refitted between passenger and freight */
@ -9282,18 +9282,18 @@ static void FinaliseEngineArray()
* on variant engine. This is performed separately as all variant engines need to have been resolved. */ * on variant engine. This is performed separately as all variant engines need to have been resolved. */
for (Engine *e : Engine::Iterate()) { for (Engine *e : Engine::Iterate()) {
EngineID parent = e->info.variant_id; EngineID parent = e->info.variant_id;
while (parent != INVALID_ENGINE) { while (parent != EngineID::Invalid()) {
parent = Engine::Get(parent)->info.variant_id; parent = Engine::Get(parent)->info.variant_id;
if (parent != e->index) continue; if (parent != e->index) continue;
/* Engine looped back on itself, so clear the variant. */ /* Engine looped back on itself, so clear the variant. */
e->info.variant_id = INVALID_ENGINE; e->info.variant_id = EngineID::Invalid();
GrfMsg(1, "FinaliseEngineArray: Variant of engine {:x} in '{}' loops back on itself", e->grf_prop.local_id, e->GetGRF()->filename); GrfMsg(1, "FinaliseEngineArray: Variant of engine {:x} in '{}' loops back on itself", e->grf_prop.local_id, e->GetGRF()->filename);
break; break;
} }
if (e->info.variant_id != INVALID_ENGINE) { if (e->info.variant_id != EngineID::Invalid()) {
Engine::Get(e->info.variant_id)->display_flags.Set(EngineDisplayFlag::HasVariants).Set(EngineDisplayFlag::IsFolded); Engine::Get(e->info.variant_id)->display_flags.Set(EngineDisplayFlag::HasVariants).Set(EngineDisplayFlag::IsFolded);
} }
} }

View File

@ -437,7 +437,7 @@ struct NewGRFInspectWindow : Window {
GrfSpecFeature f = GetFeatureNum(this->window_number); GrfSpecFeature f = GetFeatureNum(this->window_number);
int h = GetVehicleImageCellSize((VehicleType)(VEH_TRAIN + (f - GSF_TRAINS)), EIT_IN_DEPOT).height; int h = GetVehicleImageCellSize((VehicleType)(VEH_TRAIN + (f - GSF_TRAINS)), EIT_IN_DEPOT).height;
int y = CenterBounds(br.top, br.bottom, h); int y = CenterBounds(br.top, br.bottom, h);
DrawVehicleImage(v->First(), br, INVALID_VEHICLE, EIT_IN_DETAILS, skip); DrawVehicleImage(v->First(), br, VehicleID::Invalid(), EIT_IN_DETAILS, skip);
/* Highlight the articulated part (this is different to the whole-vehicle highlighting of DrawVehicleImage */ /* Highlight the articulated part (this is different to the whole-vehicle highlighting of DrawVehicleImage */
if (_current_text_dir == TD_RTL) { if (_current_text_dir == TD_RTL) {

View File

@ -376,11 +376,11 @@ static const Livery *LiveryHelper(EngineID engine, const Vehicle *v)
if (v == nullptr) { if (v == nullptr) {
if (!Company::IsValidID(_current_company)) return nullptr; if (!Company::IsValidID(_current_company)) return nullptr;
l = GetEngineLivery(engine, _current_company, INVALID_ENGINE, nullptr, LIT_ALL); l = GetEngineLivery(engine, _current_company, EngineID::Invalid(), nullptr, LIT_ALL);
} else if (v->IsGroundVehicle()) { } else if (v->IsGroundVehicle()) {
l = GetEngineLivery(v->engine_type, v->owner, v->GetGroundVehicleCache()->first_engine, v, LIT_ALL); l = GetEngineLivery(v->engine_type, v->owner, v->GetGroundVehicleCache()->first_engine, v, LIT_ALL);
} else { } else {
l = GetEngineLivery(v->engine_type, v->owner, INVALID_ENGINE, v, LIT_ALL); l = GetEngineLivery(v->engine_type, v->owner, EngineID::Invalid(), v, LIT_ALL);
} }
return l; return l;
@ -839,7 +839,7 @@ static uint32_t VehicleGetVariable(Vehicle *v, const VehicleScopeResolver *objec
case 0x57: return GB(ClampTo<int32_t>(v->GetDisplayProfitLastYear()), 8, 24); case 0x57: return GB(ClampTo<int32_t>(v->GetDisplayProfitLastYear()), 8, 24);
case 0x58: return GB(ClampTo<int32_t>(v->GetDisplayProfitLastYear()), 16, 16); case 0x58: return GB(ClampTo<int32_t>(v->GetDisplayProfitLastYear()), 16, 16);
case 0x59: return GB(ClampTo<int32_t>(v->GetDisplayProfitLastYear()), 24, 8); case 0x59: return GB(ClampTo<int32_t>(v->GetDisplayProfitLastYear()), 24, 8);
case 0x5A: return (v->Next() == nullptr ? INVALID_VEHICLE : v->Next()->index).base(); case 0x5A: return (v->Next() == nullptr ? VehicleID::Invalid() : v->Next()->index).base();
case 0x5B: break; // not implemented case 0x5B: break; // not implemented
case 0x5C: return ClampTo<int32_t>(v->value); case 0x5C: return ClampTo<int32_t>(v->value);
case 0x5D: return GB(ClampTo<int32_t>(v->value), 8, 24); case 0x5D: return GB(ClampTo<int32_t>(v->value), 8, 24);
@ -964,7 +964,7 @@ static uint32_t VehicleGetVariable(Vehicle *v, const VehicleScopeResolver *objec
case 0xC4: return (Clamp(TimerGameCalendar::year, CalendarTime::ORIGINAL_BASE_YEAR, CalendarTime::ORIGINAL_MAX_YEAR) - CalendarTime::ORIGINAL_BASE_YEAR).base(); // Build year case 0xC4: return (Clamp(TimerGameCalendar::year, CalendarTime::ORIGINAL_BASE_YEAR, CalendarTime::ORIGINAL_MAX_YEAR) - CalendarTime::ORIGINAL_BASE_YEAR).base(); // Build year
case 0xC6: return Engine::Get(this->self_type)->grf_prop.local_id; case 0xC6: return Engine::Get(this->self_type)->grf_prop.local_id;
case 0xC7: return GB(Engine::Get(this->self_type)->grf_prop.local_id, 8, 8); case 0xC7: return GB(Engine::Get(this->self_type)->grf_prop.local_id, 8, 8);
case 0xDA: return INVALID_VEHICLE.base(); // Next vehicle case 0xDA: return VehicleID::Invalid().base(); // Next vehicle
case 0xF2: return 0; // Cargo subtype case 0xF2: return 0; // Cargo subtype
} }
@ -1345,7 +1345,7 @@ void CommitVehicleListOrderChanges()
if (engine_source->grf_prop.local_id == loc.target) continue; if (engine_source->grf_prop.local_id == loc.target) continue;
EngineID target = _engine_mngr.GetID(engine_source->type, loc.target, engine_source->grf_prop.grfid); EngineID target = _engine_mngr.GetID(engine_source->type, loc.target, engine_source->grf_prop.grfid);
if (target == INVALID_ENGINE) continue; if (target == EngineID::Invalid()) continue;
auto it_source = std::ranges::find(ordering, source); auto it_source = std::ranges::find(ordering, source);
auto it_target = std::ranges::find(ordering, target); auto it_target = std::ranges::find(ordering, target);

View File

@ -269,7 +269,7 @@ static uint32_t GetCountAndDistanceOfClosestInstance(uint8_t param_setID, uint8_
/* Land info of nearby tiles */ /* Land info of nearby tiles */
case 0x62: case 0x62:
if (this->tile == INVALID_TILE) break; if (this->tile == INVALID_TILE) break;
return GetNearbyIndustryTileInformation(parameter, this->tile, INVALID_INDUSTRY, false, this->ro.grffile->grf_version >= 8); return GetNearbyIndustryTileInformation(parameter, this->tile, IndustryID::Invalid(), false, this->ro.grffile->grf_version >= 8);
/* Animation stage of nearby tiles */ /* Animation stage of nearby tiles */
case 0x63: { case 0x63: {
@ -435,7 +435,7 @@ static uint32_t GetCountAndDistanceOfClosestInstance(uint8_t param_setID, uint8_
/* virtual */ void IndustriesScopeResolver::StorePSA(uint pos, int32_t value) /* virtual */ void IndustriesScopeResolver::StorePSA(uint pos, int32_t value)
{ {
if (this->industry->index == INVALID_INDUSTRY) return; if (this->industry->index == IndustryID::Invalid()) return;
if (this->industry->psa == nullptr) { if (this->industry->psa == nullptr) {
/* There is no need to create a storage if the value is zero. */ /* There is no need to create a storage if the value is zero. */
@ -490,7 +490,7 @@ TownScopeResolver *IndustriesResolverObject::GetTown()
bool readonly = true; bool readonly = true;
if (this->industries_scope.industry != nullptr) { if (this->industries_scope.industry != nullptr) {
t = this->industries_scope.industry->town; t = this->industries_scope.industry->town;
readonly = this->industries_scope.industry->index == INVALID_INDUSTRY; readonly = this->industries_scope.industry->index == IndustryID::Invalid();
} else if (this->industries_scope.tile != INVALID_TILE) { } else if (this->industries_scope.tile != INVALID_TILE) {
t = ClosestTownFromTile(this->industries_scope.tile, UINT_MAX); t = ClosestTownFromTile(this->industries_scope.tile, UINT_MAX);
} }
@ -542,7 +542,7 @@ CommandCost CheckIfCallBackAllowsCreation(TileIndex tile, IndustryType type, siz
const IndustrySpec *indspec = GetIndustrySpec(type); const IndustrySpec *indspec = GetIndustrySpec(type);
Industry ind; Industry ind;
ind.index = INVALID_INDUSTRY; ind.index = IndustryID::Invalid();
ind.location.tile = tile; ind.location.tile = tile;
ind.location.w = 0; // important to mark the industry invalid ind.location.w = 0; // important to mark the industry invalid
ind.type = type; ind.type = type;

View File

@ -78,7 +78,7 @@ uint32_t GetRelativePosition(TileIndex tile, TileIndex ind_tile)
/* Land info of nearby tiles */ /* Land info of nearby tiles */
case 0x60: return GetNearbyIndustryTileInformation(parameter, this->tile, case 0x60: return GetNearbyIndustryTileInformation(parameter, this->tile,
this->industry == nullptr ? (IndustryID)INVALID_INDUSTRY : this->industry->index, true, this->ro.grffile->grf_version >= 8); this->industry == nullptr ? (IndustryID)IndustryID::Invalid() : this->industry->index, true, this->ro.grffile->grf_version >= 8);
/* Animation stage of nearby tiles */ /* Animation stage of nearby tiles */
case 0x61: { case 0x61: {
@ -102,16 +102,16 @@ uint32_t GetRelativePosition(TileIndex tile, TileIndex ind_tile)
/* virtual */ uint32_t IndustryTileScopeResolver::GetRandomBits() const /* virtual */ uint32_t IndustryTileScopeResolver::GetRandomBits() const
{ {
assert(this->industry != nullptr && IsValidTile(this->tile)); assert(this->industry != nullptr && IsValidTile(this->tile));
assert(this->industry->index == INVALID_INDUSTRY || IsTileType(this->tile, MP_INDUSTRY)); assert(this->industry->index == IndustryID::Invalid() || IsTileType(this->tile, MP_INDUSTRY));
return (this->industry->index != INVALID_INDUSTRY) ? GetIndustryRandomBits(this->tile) : 0; return (this->industry->index != IndustryID::Invalid()) ? GetIndustryRandomBits(this->tile) : 0;
} }
/* virtual */ uint32_t IndustryTileScopeResolver::GetTriggers() const /* virtual */ uint32_t IndustryTileScopeResolver::GetTriggers() const
{ {
assert(this->industry != nullptr && IsValidTile(this->tile)); assert(this->industry != nullptr && IsValidTile(this->tile));
assert(this->industry->index == INVALID_INDUSTRY || IsTileType(this->tile, MP_INDUSTRY)); assert(this->industry->index == IndustryID::Invalid() || IsTileType(this->tile, MP_INDUSTRY));
if (this->industry->index == INVALID_INDUSTRY) return 0; if (this->industry->index == IndustryID::Invalid()) return 0;
return GetIndustryTriggers(this->tile); return GetIndustryTriggers(this->tile);
} }
@ -181,7 +181,7 @@ static void IndustryDrawTileLayout(const TileInfo *ti, const TileLayoutSpriteGro
uint16_t GetIndustryTileCallback(CallbackID callback, uint32_t param1, uint32_t param2, IndustryGfx gfx_id, Industry *industry, TileIndex tile) uint16_t GetIndustryTileCallback(CallbackID callback, uint32_t param1, uint32_t param2, IndustryGfx gfx_id, Industry *industry, TileIndex tile)
{ {
assert(industry != nullptr && IsValidTile(tile)); assert(industry != nullptr && IsValidTile(tile));
assert(industry->index == INVALID_INDUSTRY || IsTileType(tile, MP_INDUSTRY)); assert(industry->index == IndustryID::Invalid() || IsTileType(tile, MP_INDUSTRY));
IndustryTileResolverObject object(gfx_id, tile, industry, callback, param1, param2); IndustryTileResolverObject object(gfx_id, tile, industry, callback, param1, param2);
return object.ResolveCallback(); return object.ResolveCallback();
@ -230,7 +230,7 @@ extern bool IsSlopeRefused(Slope current, Slope refused);
CommandCost PerformIndustryTileSlopeCheck(TileIndex ind_base_tile, TileIndex ind_tile, const IndustryTileSpec *its, IndustryType type, IndustryGfx gfx, size_t layout_index, uint16_t initial_random_bits, Owner founder, IndustryAvailabilityCallType creation_type) CommandCost PerformIndustryTileSlopeCheck(TileIndex ind_base_tile, TileIndex ind_tile, const IndustryTileSpec *its, IndustryType type, IndustryGfx gfx, size_t layout_index, uint16_t initial_random_bits, Owner founder, IndustryAvailabilityCallType creation_type)
{ {
Industry ind; Industry ind;
ind.index = INVALID_INDUSTRY; ind.index = IndustryID::Invalid();
ind.location.tile = ind_base_tile; ind.location.tile = ind_base_tile;
ind.location.w = 0; ind.location.w = 0;
ind.type = type; ind.type = type;

View File

@ -346,7 +346,7 @@ static uint32_t GetCountAndDistanceOfClosestInstance(uint8_t local_id, uint32_t
} }
/* Land info of nearby tiles */ /* Land info of nearby tiles */
case 0x62: return GetNearbyObjectTileInformation(parameter, this->tile, this->obj == nullptr ? INVALID_OBJECT : this->obj->index, this->ro.grffile->grf_version >= 8); case 0x62: return GetNearbyObjectTileInformation(parameter, this->tile, this->obj == nullptr ? ObjectID::Invalid() : this->obj->index, this->ro.grffile->grf_version >= 8);
/* Animation counter of nearby tile */ /* Animation counter of nearby tile */
case 0x63: { case 0x63: {

View File

@ -457,7 +457,7 @@ uint32_t Station::GetNewGRFVariable(const ResolverObject &object, uint8_t variab
case 1: return GB(g->HasData() ? std::min(g->GetData().cargo.TotalCount(), 4095u) : 0, 0, 4) | (GB(g->status, GoodsEntry::GES_ACCEPTANCE, 1) << 7); case 1: return GB(g->HasData() ? std::min(g->GetData().cargo.TotalCount(), 4095u) : 0, 0, 4) | (GB(g->status, GoodsEntry::GES_ACCEPTANCE, 1) << 7);
case 2: return g->time_since_pickup; case 2: return g->time_since_pickup;
case 3: return g->rating; case 3: return g->rating;
case 4: return (g->HasData() ? g->GetData().cargo.GetFirstStation() : INVALID_STATION).base(); case 4: return (g->HasData() ? g->GetData().cargo.GetFirstStation() : StationID::Invalid()).base();
case 5: return g->HasData() ? g->GetData().cargo.PeriodsInTransit() : 0; case 5: return g->HasData() ? g->GetData().cargo.PeriodsInTransit() : 0;
case 6: return g->last_speed; case 6: return g->last_speed;
case 7: return g->last_age; case 7: return g->last_age;
@ -491,7 +491,7 @@ uint32_t Waypoint::GetNewGRFVariable(const ResolverObject &, uint8_t variable, [
if (variable >= 0x8C && variable <= 0xEC) { if (variable >= 0x8C && variable <= 0xEC) {
switch (GB(variable - 0x8C, 0, 3)) { switch (GB(variable - 0x8C, 0, 3)) {
case 3: return INITIAL_STATION_RATING; case 3: return INITIAL_STATION_RATING;
case 4: return INVALID_STATION.base(); case 4: return StationID::Invalid().base();
default: return 0; default: return 0;
} }
} }

View File

@ -27,9 +27,9 @@ inline void AddCompanyNewsItem(StringID string, std::unique_ptr<CompanyNewsInfor
* *
* @warning The DParams may not reference the vehicle due to autoreplace stuff. See AddVehicleAdviceNewsItem for how that can be done. * @warning The DParams may not reference the vehicle due to autoreplace stuff. See AddVehicleAdviceNewsItem for how that can be done.
*/ */
inline void AddVehicleNewsItem(StringID string, NewsType type, VehicleID vehicle, StationID station = INVALID_STATION) inline void AddVehicleNewsItem(StringID string, NewsType type, VehicleID vehicle, StationID station = StationID::Invalid())
{ {
AddNewsItem(string, type, NewsStyle::Thin, {NewsFlag::NoTransparency, NewsFlag::Shaded}, vehicle, station == INVALID_STATION ? NewsReference{} : station); AddNewsItem(string, type, NewsStyle::Thin, {NewsFlag::NoTransparency, NewsFlag::Shaded}, vehicle, station == StationID::Invalid() ? NewsReference{} : station);
} }
/** /**
@ -42,9 +42,9 @@ inline void AddVehicleAdviceNewsItem(AdviceType advice_type, StringID string, Ve
AddNewsItem(string, NewsType::Advice, NewsStyle::Small, {NewsFlag::InColour, NewsFlag::VehicleParam0}, vehicle, {}, nullptr, advice_type); AddNewsItem(string, NewsType::Advice, NewsStyle::Small, {NewsFlag::InColour, NewsFlag::VehicleParam0}, vehicle, {}, nullptr, advice_type);
} }
inline void AddTileNewsItem(StringID string, NewsType type, TileIndex tile, StationID station = INVALID_STATION) inline void AddTileNewsItem(StringID string, NewsType type, TileIndex tile, StationID station = StationID::Invalid())
{ {
AddNewsItem(string, type, NewsStyle::Thin, {NewsFlag::NoTransparency, NewsFlag::Shaded}, tile, station == INVALID_STATION ? NewsReference{} : station); AddNewsItem(string, type, NewsStyle::Thin, {NewsFlag::NoTransparency, NewsFlag::Shaded}, tile, station == StationID::Invalid() ? NewsReference{} : station);
} }
inline void AddIndustryNewsItem(StringID string, NewsType type, IndustryID industry) inline void AddIndustryNewsItem(StringID string, NewsType type, IndustryID industry)

View File

@ -32,6 +32,4 @@ using ObjectID = PoolID<uint32_t, struct ObjectIDTag, 0xFF0000, 0xFFFFFFFF>;
struct Object; struct Object;
struct ObjectSpec; struct ObjectSpec;
static constexpr ObjectID INVALID_OBJECT = ObjectID::Invalid(); ///< An invalid object
#endif /* OBJECT_TYPE_H */ #endif /* OBJECT_TYPE_H */

View File

@ -95,7 +95,7 @@ void CallWindowGameTickEvent();
bool HandleBootstrap(); bool HandleBootstrap();
extern void CheckCaches(); extern void CheckCaches();
extern Company *DoStartupNewCompany(bool is_ai, CompanyID company = INVALID_COMPANY); extern Company *DoStartupNewCompany(bool is_ai, CompanyID company = CompanyID::Invalid());
extern void OSOpenBrowser(const std::string &url); extern void OSOpenBrowser(const std::string &url);
extern void ShowOSErrorBox(const char *buf, bool system); extern void ShowOSErrorBox(const char *buf, bool system);
extern std::string _config_file; extern std::string _config_file;
@ -327,7 +327,7 @@ static void LoadIntroGame(bool load_newgrfs = true)
GenerateWorld(GWM_EMPTY, 64, 64); // if failed loading, make empty world. GenerateWorld(GWM_EMPTY, 64, 64); // if failed loading, make empty world.
SetLocalCompany(COMPANY_SPECTATOR); SetLocalCompany(COMPANY_SPECTATOR);
} else { } else {
SetLocalCompany(COMPANY_FIRST); SetLocalCompany(CompanyID::Begin());
} }
FixTitleGameZoom(); FixTitleGameZoom();
@ -341,7 +341,7 @@ static void LoadIntroGame(bool load_newgrfs = true)
void MakeNewgameSettingsLive() void MakeNewgameSettingsLive()
{ {
for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; ++c) { for (CompanyID c = CompanyID::Begin(); c < MAX_COMPANIES; ++c) {
if (_settings_game.ai_config[c] != nullptr) { if (_settings_game.ai_config[c] != nullptr) {
delete _settings_game.ai_config[c]; delete _settings_game.ai_config[c];
} }
@ -355,7 +355,7 @@ void MakeNewgameSettingsLive()
_settings_game = _settings_newgame; _settings_game = _settings_newgame;
_old_vds = _settings_client.company.vehicle; _old_vds = _settings_client.company.vehicle;
for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; ++c) { for (CompanyID c = CompanyID::Begin(); c < MAX_COMPANIES; ++c) {
_settings_game.ai_config[c] = nullptr; _settings_game.ai_config[c] = nullptr;
if (_settings_newgame.ai_config[c] != nullptr) { if (_settings_newgame.ai_config[c] != nullptr) {
_settings_game.ai_config[c] = new AIConfig(_settings_newgame.ai_config[c]); _settings_game.ai_config[c] = new AIConfig(_settings_newgame.ai_config[c]);
@ -865,7 +865,7 @@ static void MakeNewGameDone()
/* Create a single company */ /* Create a single company */
DoStartupNewCompany(false); DoStartupNewCompany(false);
Company *c = Company::Get(COMPANY_FIRST); Company *c = Company::Get(CompanyID::Begin());
c->settings = _settings_client.company; c->settings = _settings_client.company;
/* Overwrite color from settings if needed /* Overwrite color from settings if needed

View File

@ -381,7 +381,7 @@ const Order *OrderList::GetNextDecisionNode(const Order *next, uint hops) const
* @param v The vehicle we're looking at. * @param v The vehicle we're looking at.
* @param first Order to start searching at or nullptr to start at cur_implicit_order_index + 1. * @param first Order to start searching at or nullptr to start at cur_implicit_order_index + 1.
* @param hops Number of orders we have already looked at. * @param hops Number of orders we have already looked at.
* @return Next stopping station or INVALID_STATION. * @return Next stopping station or StationID::Invalid().
* @pre The vehicle is currently loading and v->last_station_visited is meaningful. * @pre The vehicle is currently loading and v->last_station_visited is meaningful.
* @note This function may draw a random number. Don't use it from the GUI. * @note This function may draw a random number. Don't use it from the GUI.
*/ */
@ -393,7 +393,7 @@ StationIDStack OrderList::GetNextStoppingStation(const Vehicle *v, const Order *
next = this->GetOrderAt(v->cur_implicit_order_index); next = this->GetOrderAt(v->cur_implicit_order_index);
if (next == nullptr) { if (next == nullptr) {
next = this->GetFirstOrder(); next = this->GetFirstOrder();
if (next == nullptr) return INVALID_STATION.base(); if (next == nullptr) return StationID::Invalid().base();
} else { } else {
/* GetNext never returns nullptr if there is a valid station in the list. /* GetNext never returns nullptr if there is a valid station in the list.
* As the given "next" is already valid and a station in the list, we * As the given "next" is already valid and a station in the list, we
@ -430,7 +430,7 @@ StationIDStack OrderList::GetNextStoppingStation(const Vehicle *v, const Order *
if (next == nullptr || ((next->IsType(OT_GOTO_STATION) || next->IsType(OT_IMPLICIT)) && if (next == nullptr || ((next->IsType(OT_GOTO_STATION) || next->IsType(OT_IMPLICIT)) &&
next->GetDestination() == v->last_station_visited && next->GetDestination() == v->last_station_visited &&
(next->GetUnloadType() & (OUFB_TRANSFER | OUFB_UNLOAD)) != 0)) { (next->GetUnloadType() & (OUFB_TRANSFER | OUFB_UNLOAD)) != 0)) {
return INVALID_STATION.base(); return StationID::Invalid().base();
} }
} while (next->IsType(OT_GOTO_DEPOT) || next->GetDestination() == v->last_station_visited); } while (next->IsType(OT_GOTO_DEPOT) || next->GetDestination() == v->last_station_visited);
@ -604,7 +604,7 @@ void OrderList::DebugCheckSanity() const
static inline bool OrderGoesToStation(const Vehicle *v, const Order *o) static inline bool OrderGoesToStation(const Vehicle *v, const Order *o)
{ {
return o->IsType(OT_GOTO_STATION) || return o->IsType(OT_GOTO_STATION) ||
(v->type == VEH_AIRCRAFT && o->IsType(OT_GOTO_DEPOT) && o->GetDestination() != INVALID_STATION); (v->type == VEH_AIRCRAFT && o->IsType(OT_GOTO_DEPOT) && o->GetDestination() != StationID::Invalid());
} }
/** /**
@ -634,7 +634,7 @@ TileIndex Order::GetLocation(const Vehicle *v, bool airport) const
return BaseStation::Get(this->GetDestination().ToStationID())->xy; return BaseStation::Get(this->GetDestination().ToStationID())->xy;
case OT_GOTO_DEPOT: case OT_GOTO_DEPOT:
if (this->GetDestination() == INVALID_DEPOT) return INVALID_TILE; if (this->GetDestination() == DepotID::Invalid()) return INVALID_TILE;
return (v->type == VEH_AIRCRAFT) ? Station::Get(this->GetDestination().ToStationID())->xy : Depot::Get(this->GetDestination().ToDepotID())->xy; return (v->type == VEH_AIRCRAFT) ? Station::Get(this->GetDestination().ToStationID())->xy : Depot::Get(this->GetDestination().ToDepotID())->xy;
default: default:

View File

@ -666,7 +666,7 @@ private:
Order order; Order order;
order.next = nullptr; order.next = nullptr;
order.index = OrderID::Begin(); order.index = OrderID::Begin();
order.MakeGoToDepot(INVALID_DEPOT, ODTFB_PART_OF_ORDERS, order.MakeGoToDepot(DepotID::Invalid(), ODTFB_PART_OF_ORDERS,
_settings_client.gui.new_nonstop && this->vehicle->IsGroundVehicle() ? ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS : ONSF_STOP_EVERYWHERE); _settings_client.gui.new_nonstop && this->vehicle->IsGroundVehicle() ? ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS : ONSF_STOP_EVERYWHERE);
order.SetDepotActionType(ODATFB_NEAREST_DEPOT); order.SetDepotActionType(ODATFB_NEAREST_DEPOT);

View File

@ -41,9 +41,6 @@ static const VehicleOrderID INVALID_VEH_ORDER_ID = 0xFF;
/** Last valid VehicleOrderID. */ /** Last valid VehicleOrderID. */
static const VehicleOrderID MAX_VEH_ORDER_ID = INVALID_VEH_ORDER_ID - 1; static const VehicleOrderID MAX_VEH_ORDER_ID = INVALID_VEH_ORDER_ID - 1;
/** Invalid order (sentinel) */
static constexpr OrderID INVALID_ORDER = OrderID::Invalid();
/** /**
* Maximum number of orders in implicit-only lists before we start searching * Maximum number of orders in implicit-only lists before we start searching
* harder for duplicates. * harder for duplicates.

View File

@ -159,7 +159,7 @@ public:
default: default:
this->dest_tile = v->dest_tile; this->dest_tile = v->dest_tile;
this->dest_station_id = INVALID_STATION; this->dest_station_id = StationID::Invalid();
this->dest_trackdirs = TrackStatusToTrackdirBits(GetTileTrackStatus(v->dest_tile, TRANSPORT_RAIL, 0)); this->dest_trackdirs = TrackStatusToTrackdirBits(GetTileTrackStatus(v->dest_tile, TRANSPORT_RAIL, 0));
break; break;
} }
@ -175,7 +175,7 @@ public:
/** Called by YAPF to detect if node ends in the desired destination */ /** Called by YAPF to detect if node ends in the desired destination */
inline bool PfDetectDestination(TileIndex tile, Trackdir td) inline bool PfDetectDestination(TileIndex tile, Trackdir td)
{ {
if (this->dest_station_id != INVALID_STATION) { if (this->dest_station_id != StationID::Invalid()) {
return HasStationTileRail(tile) return HasStationTileRail(tile)
&& (GetStationIndex(tile) == this->dest_station_id) && (GetStationIndex(tile) == this->dest_station_id)
&& (GetRailStationTrack(tile) == TrackdirToTrack(td)); && (GetRailStationTrack(tile) == TrackdirToTrack(td));

View File

@ -253,7 +253,7 @@ public:
this->non_artic = !v->HasArticulatedPart(); this->non_artic = !v->HasArticulatedPart();
this->dest_trackdirs = INVALID_TRACKDIR_BIT; this->dest_trackdirs = INVALID_TRACKDIR_BIT;
} else { } else {
this->dest_station = INVALID_STATION; this->dest_station = StationID::Invalid();
this->dest_tile = v->dest_tile; this->dest_tile = v->dest_tile;
this->dest_trackdirs = TrackStatusToTrackdirBits(GetTileTrackStatus(v->dest_tile, TRANSPORT_ROAD, GetRoadTramType(v->roadtype))); this->dest_trackdirs = TrackStatusToTrackdirBits(GetTileTrackStatus(v->dest_tile, TRANSPORT_ROAD, GetRoadTramType(v->roadtype)));
} }
@ -261,7 +261,7 @@ public:
const Station *GetDestinationStation() const const Station *GetDestinationStation() const
{ {
return this->dest_station != INVALID_STATION ? Station::GetIfValid(this->dest_station) : nullptr; return this->dest_station != StationID::Invalid() ? Station::GetIfValid(this->dest_station) : nullptr;
} }
protected: protected:
@ -280,7 +280,7 @@ public:
inline bool PfDetectDestinationTile(TileIndex tile, Trackdir trackdir) inline bool PfDetectDestinationTile(TileIndex tile, Trackdir trackdir)
{ {
if (this->dest_station != INVALID_STATION) { if (this->dest_station != StationID::Invalid()) {
return IsTileType(tile, MP_STATION) && return IsTileType(tile, MP_STATION) &&
GetStationIndex(tile) == this->dest_station && GetStationIndex(tile) == this->dest_station &&
(this->station_type == GetStationType(tile)) && (this->station_type == GetStationType(tile)) &&

View File

@ -49,7 +49,7 @@ public:
this->dest_tile = CalcClosestStationTile(this->dest_station, v->tile, StationType::Dock); this->dest_tile = CalcClosestStationTile(this->dest_station, v->tile, StationType::Dock);
this->dest_trackdirs = INVALID_TRACKDIR_BIT; this->dest_trackdirs = INVALID_TRACKDIR_BIT;
} else { } else {
this->dest_station = INVALID_STATION; this->dest_station = StationID::Invalid();
this->dest_tile = v->dest_tile; this->dest_tile = v->dest_tile;
this->dest_trackdirs = TrackStatusToTrackdirBits(GetTileTrackStatus(v->dest_tile, TRANSPORT_WATER, 0)); this->dest_trackdirs = TrackStatusToTrackdirBits(GetTileTrackStatus(v->dest_tile, TRANSPORT_WATER, 0));
} }
@ -84,7 +84,7 @@ public:
return GetWaterRegionPatchInfo(tile) == this->intermediate_dest_region_patch; return GetWaterRegionPatchInfo(tile) == this->intermediate_dest_region_patch;
} }
if (this->dest_station != INVALID_STATION) return IsDockingTile(tile) && IsShipDestinationTile(tile, this->dest_station); if (this->dest_station != StationID::Invalid()) return IsDockingTile(tile) && IsShipDestinationTile(tile, this->dest_station);
return tile == this->dest_tile && ((this->dest_trackdirs & TrackdirToTrackdirBits(trackdir)) != TRACKDIR_BIT_NONE); return tile == this->dest_tile && ((this->dest_trackdirs & TrackdirToTrackdirBits(trackdir)) != TRACKDIR_BIT_NONE);
} }

View File

@ -177,7 +177,7 @@ static void PlaceRail_Waypoint(TileIndex tile)
} else { } else {
/* Tile where we can't build rail waypoints. This is always going to fail, /* Tile where we can't build rail waypoints. This is always going to fail,
* but provides the user with a proper error message. */ * but provides the user with a proper error message. */
Command<CMD_BUILD_RAIL_WAYPOINT>::Post(STR_ERROR_CAN_T_BUILD_TRAIN_WAYPOINT, tile, AXIS_X, 1, 1, STAT_CLASS_WAYP, 0, INVALID_STATION, false); Command<CMD_BUILD_RAIL_WAYPOINT>::Post(STR_ERROR_CAN_T_BUILD_TRAIN_WAYPOINT, tile, AXIS_X, 1, 1, STAT_CLASS_WAYP, 0, StationID::Invalid(), false);
} }
} }
@ -215,7 +215,7 @@ static void PlaceRail_Station(TileIndex tile)
auto proc = [=](bool test, StationID to_join) -> bool { auto proc = [=](bool test, StationID to_join) -> bool {
if (test) { if (test) {
return Command<CMD_BUILD_RAIL_STATION>::Do(CommandFlagsToDCFlags(GetCommandFlags<CMD_BUILD_RAIL_STATION>()), tile, rt, params.axis, numtracks, platlength, params.sel_class, params.sel_type, INVALID_STATION, adjacent).Succeeded(); return Command<CMD_BUILD_RAIL_STATION>::Do(CommandFlagsToDCFlags(GetCommandFlags<CMD_BUILD_RAIL_STATION>()), tile, rt, params.axis, numtracks, platlength, params.sel_class, params.sel_type, StationID::Invalid(), adjacent).Succeeded();
} else { } else {
return Command<CMD_BUILD_RAIL_STATION>::Post(STR_ERROR_CAN_T_BUILD_RAILROAD_STATION, CcStation, tile, rt, params.axis, numtracks, platlength, params.sel_class, params.sel_type, to_join, adjacent); return Command<CMD_BUILD_RAIL_STATION>::Post(STR_ERROR_CAN_T_BUILD_RAILROAD_STATION, CcStation, tile, rt, params.axis, numtracks, platlength, params.sel_class, params.sel_type, to_join, adjacent);
} }
@ -776,7 +776,7 @@ struct BuildRailToolbarWindow : Window {
auto proc = [=](bool test, StationID to_join) -> bool { auto proc = [=](bool test, StationID to_join) -> bool {
if (test) { if (test) {
return Command<CMD_BUILD_RAIL_WAYPOINT>::Do(CommandFlagsToDCFlags(GetCommandFlags<CMD_BUILD_RAIL_WAYPOINT>()), ta.tile, axis, ta.w, ta.h, _waypoint_gui.sel_class, _waypoint_gui.sel_type, INVALID_STATION, adjacent).Succeeded(); return Command<CMD_BUILD_RAIL_WAYPOINT>::Do(CommandFlagsToDCFlags(GetCommandFlags<CMD_BUILD_RAIL_WAYPOINT>()), ta.tile, axis, ta.w, ta.h, _waypoint_gui.sel_class, _waypoint_gui.sel_type, StationID::Invalid(), adjacent).Succeeded();
} else { } else {
return Command<CMD_BUILD_RAIL_WAYPOINT>::Post(STR_ERROR_CAN_T_BUILD_TRAIN_WAYPOINT, CcPlaySound_CONSTRUCTION_RAIL, ta.tile, axis, ta.w, ta.h, _waypoint_gui.sel_class, _waypoint_gui.sel_type, to_join, adjacent); return Command<CMD_BUILD_RAIL_WAYPOINT>::Post(STR_ERROR_CAN_T_BUILD_TRAIN_WAYPOINT, CcPlaySound_CONSTRUCTION_RAIL, ta.tile, axis, ta.w, ta.h, _waypoint_gui.sel_class, _waypoint_gui.sel_type, to_join, adjacent);
} }
@ -943,7 +943,7 @@ static void HandleStationPlacement(TileIndex start, TileIndex end)
auto proc = [=](bool test, StationID to_join) -> bool { auto proc = [=](bool test, StationID to_join) -> bool {
if (test) { if (test) {
return Command<CMD_BUILD_RAIL_STATION>::Do(CommandFlagsToDCFlags(GetCommandFlags<CMD_BUILD_RAIL_STATION>()), ta.tile, rt, params.axis, numtracks, platlength, params.sel_class, params.sel_type, INVALID_STATION, adjacent).Succeeded(); return Command<CMD_BUILD_RAIL_STATION>::Do(CommandFlagsToDCFlags(GetCommandFlags<CMD_BUILD_RAIL_STATION>()), ta.tile, rt, params.axis, numtracks, platlength, params.sel_class, params.sel_type, StationID::Invalid(), adjacent).Succeeded();
} else { } else {
return Command<CMD_BUILD_RAIL_STATION>::Post(STR_ERROR_CAN_T_BUILD_RAILROAD_STATION, CcStation, ta.tile, rt, params.axis, numtracks, platlength, params.sel_class, params.sel_type, to_join, adjacent); return Command<CMD_BUILD_RAIL_STATION>::Post(STR_ERROR_CAN_T_BUILD_RAILROAD_STATION, CcStation, ta.tile, rt, params.axis, numtracks, platlength, params.sel_class, params.sel_type, to_join, adjacent);
} }

View File

@ -465,7 +465,7 @@ static CommandCost RemoveRoad(TileIndex tile, DoCommandFlags flags, RoadBits pie
if (rtt == RTT_ROAD && IsRoadOwner(tile, rtt, OWNER_TOWN)) { if (rtt == RTT_ROAD && IsRoadOwner(tile, rtt, OWNER_TOWN)) {
/* Update nearest-town index */ /* Update nearest-town index */
const Town *town = CalcClosestTownFromTile(tile); const Town *town = CalcClosestTownFromTile(tile);
SetTownIndex(tile, town == nullptr ? INVALID_TOWN : town->index); SetTownIndex(tile, town == nullptr ? TownID::Invalid() : town->index);
} }
if (rtt == RTT_ROAD) SetDisallowedRoadDirections(tile, DRD_NONE); if (rtt == RTT_ROAD) SetDisallowedRoadDirections(tile, DRD_NONE);
SetRoadBits(tile, ROAD_NONE, rtt); SetRoadBits(tile, ROAD_NONE, rtt);
@ -603,7 +603,7 @@ static CommandCost CheckRoadSlope(Slope tileh, RoadBits *pieces, RoadBits existi
* @param pieces road pieces to build (RoadBits) * @param pieces road pieces to build (RoadBits)
* @param rt road type * @param rt road type
* @param toggle_drd disallowed directions to toggle * @param toggle_drd disallowed directions to toggle
* @param town_id the town that is building the road (INVALID_TOWN if not applicable) * @param town_id the town that is building the road (TownID::Invalid() if not applicable)
* @return the cost of this operation or an error * @return the cost of this operation or an error
*/ */
CommandCost CmdBuildRoad(DoCommandFlags flags, TileIndex tile, RoadBits pieces, RoadType rt, DisallowedRoadDirections toggle_drd, TownID town_id) CommandCost CmdBuildRoad(DoCommandFlags flags, TileIndex tile, RoadBits pieces, RoadType rt, DisallowedRoadDirections toggle_drd, TownID town_id)
@ -616,10 +616,10 @@ CommandCost CmdBuildRoad(DoCommandFlags flags, TileIndex tile, RoadBits pieces,
/* Road pieces are max 4 bitset values (NE, NW, SE, SW) and town can only be non-zero /* Road pieces are max 4 bitset values (NE, NW, SE, SW) and town can only be non-zero
* if a non-company is building the road */ * if a non-company is building the road */
if ((Company::IsValidID(company) && town_id != INVALID_TOWN) || (company == OWNER_TOWN && !Town::IsValidID(town_id)) || (company == OWNER_DEITY && town_id != INVALID_TOWN)) return CMD_ERROR; if ((Company::IsValidID(company) && town_id != TownID::Invalid()) || (company == OWNER_TOWN && !Town::IsValidID(town_id)) || (company == OWNER_DEITY && town_id != TownID::Invalid())) return CMD_ERROR;
if (company != OWNER_TOWN) { if (company != OWNER_TOWN) {
const Town *town = CalcClosestTownFromTile(tile); const Town *town = CalcClosestTownFromTile(tile);
town_id = (town != nullptr) ? town->index : INVALID_TOWN; town_id = (town != nullptr) ? town->index : TownID::Invalid();
if (company == OWNER_DEITY) { if (company == OWNER_DEITY) {
company = OWNER_TOWN; company = OWNER_TOWN;
@ -1025,7 +1025,7 @@ CommandCost CmdBuildLongRoad(DoCommandFlags flags, TileIndex end_tile, TileIndex
if (tile == start_tile && start_half) bits &= DiagDirToRoadBits(dir); if (tile == start_tile && start_half) bits &= DiagDirToRoadBits(dir);
} }
CommandCost ret = Command<CMD_BUILD_ROAD>::Do(flags, tile, bits, rt, drd, INVALID_TOWN); CommandCost ret = Command<CMD_BUILD_ROAD>::Do(flags, tile, bits, rt, drd, TownID::Invalid());
if (ret.Failed()) { if (ret.Failed()) {
last_error = ret; last_error = ret;
if (last_error.GetErrorMessage() != STR_ERROR_ALREADY_BUILT) { if (last_error.GetErrorMessage() != STR_ERROR_ALREADY_BUILT) {
@ -1920,7 +1920,7 @@ void UpdateNearestTownForRoadTiles(bool invalidate)
for (const auto t : Map::Iterate()) { for (const auto t : Map::Iterate()) {
if (IsTileType(t, MP_ROAD) && !IsRoadDepot(t) && !HasTownOwnedRoad(t)) { if (IsTileType(t, MP_ROAD) && !IsRoadDepot(t) && !HasTownOwnedRoad(t)) {
TownID tid = INVALID_TOWN; TownID tid = TownID::Invalid();
if (!invalidate) { if (!invalidate) {
const Town *town = CalcClosestTownFromTile(t); const Town *town = CalcClosestTownFromTile(t);
if (town != nullptr) tid = town->index; if (town != nullptr) tid = town->index;

View File

@ -165,7 +165,7 @@ void ConnectRoadToStructure(TileIndex tile, DiagDirection direction)
/* if there is a roadpiece just outside of the station entrance, build a connecting route */ /* if there is a roadpiece just outside of the station entrance, build a connecting route */
if (IsNormalRoadTile(tile)) { if (IsNormalRoadTile(tile)) {
if (GetRoadBits(tile, GetRoadTramType(_cur_roadtype)) != ROAD_NONE) { if (GetRoadBits(tile, GetRoadTramType(_cur_roadtype)) != ROAD_NONE) {
Command<CMD_BUILD_ROAD>::Post(tile, DiagDirToRoadBits(ReverseDiagDir(direction)), _cur_roadtype, DRD_NONE, INVALID_TOWN); Command<CMD_BUILD_ROAD>::Post(tile, DiagDirToRoadBits(ReverseDiagDir(direction)), _cur_roadtype, DRD_NONE, TownID::Invalid());
} }
} }
} }
@ -237,7 +237,7 @@ static void PlaceRoadStop(TileIndex start_tile, TileIndex end_tile, RoadStopType
auto proc = [=](bool test, StationID to_join) -> bool { auto proc = [=](bool test, StationID to_join) -> bool {
if (test) { if (test) {
return Command<CMD_BUILD_ROAD_STOP>::Do(CommandFlagsToDCFlags(GetCommandFlags<CMD_BUILD_ROAD_STOP>()), ta.tile, ta.w, ta.h, stop_type, drive_through, return Command<CMD_BUILD_ROAD_STOP>::Do(CommandFlagsToDCFlags(GetCommandFlags<CMD_BUILD_ROAD_STOP>()), ta.tile, ta.w, ta.h, stop_type, drive_through,
ddir, rt, spec_class, spec_index, INVALID_STATION, adjacent).Succeeded(); ddir, rt, spec_class, spec_index, StationID::Invalid(), adjacent).Succeeded();
} else { } else {
return Command<CMD_BUILD_ROAD_STOP>::Post(err_msg, CcRoadStop, ta.tile, ta.w, ta.h, stop_type, drive_through, return Command<CMD_BUILD_ROAD_STOP>::Post(err_msg, CcRoadStop, ta.tile, ta.w, ta.h, stop_type, drive_through,
ddir, rt, spec_class, spec_index, to_join, adjacent); ddir, rt, spec_class, spec_index, to_join, adjacent);
@ -266,7 +266,7 @@ static void PlaceRoad_Waypoint(TileIndex tile)
} else { } else {
/* Tile where we can't build road waypoints. This is always going to fail, /* Tile where we can't build road waypoints. This is always going to fail,
* but provides the user with a proper error message. */ * but provides the user with a proper error message. */
Command<CMD_BUILD_ROAD_WAYPOINT>::Post(STR_ERROR_CAN_T_BUILD_ROAD_WAYPOINT, tile, AXIS_X, 1, 1, ROADSTOP_CLASS_WAYP, 0, INVALID_STATION, false); Command<CMD_BUILD_ROAD_WAYPOINT>::Post(STR_ERROR_CAN_T_BUILD_ROAD_WAYPOINT, tile, AXIS_X, 1, 1, ROADSTOP_CLASS_WAYP, 0, StationID::Invalid(), false);
} }
} }
@ -766,7 +766,7 @@ struct BuildRoadToolbarWindow : Window {
auto proc = [=](bool test, StationID to_join) -> bool { auto proc = [=](bool test, StationID to_join) -> bool {
if (test) { if (test) {
return Command<CMD_BUILD_ROAD_WAYPOINT>::Do(CommandFlagsToDCFlags(GetCommandFlags<CMD_BUILD_ROAD_WAYPOINT>()), ta.tile, axis, ta.w, ta.h, _waypoint_gui.sel_class, _waypoint_gui.sel_type, INVALID_STATION, adjacent).Succeeded(); return Command<CMD_BUILD_ROAD_WAYPOINT>::Do(CommandFlagsToDCFlags(GetCommandFlags<CMD_BUILD_ROAD_WAYPOINT>()), ta.tile, axis, ta.w, ta.h, _waypoint_gui.sel_class, _waypoint_gui.sel_type, StationID::Invalid(), adjacent).Succeeded();
} else { } else {
return Command<CMD_BUILD_ROAD_WAYPOINT>::Post(STR_ERROR_CAN_T_BUILD_ROAD_WAYPOINT, CcPlaySound_CONSTRUCTION_OTHER, ta.tile, axis, ta.w, ta.h, _waypoint_gui.sel_class, _waypoint_gui.sel_type, to_join, adjacent); return Command<CMD_BUILD_ROAD_WAYPOINT>::Post(STR_ERROR_CAN_T_BUILD_ROAD_WAYPOINT, CcPlaySound_CONSTRUCTION_OTHER, ta.tile, axis, ta.w, ta.h, _waypoint_gui.sel_class, _waypoint_gui.sel_type, to_join, adjacent);
} }

View File

@ -106,7 +106,7 @@ struct RoadVehicle final : public GroundVehicle<RoadVehicle, VEH_ROAD> {
uint8_t reverse_ctr; uint8_t reverse_ctr;
RoadType roadtype; ///< NOSAVE: Roadtype of this vehicle. RoadType roadtype; ///< NOSAVE: Roadtype of this vehicle.
VehicleID disaster_vehicle = INVALID_VEHICLE; ///< NOSAVE: Disaster vehicle targetting this vehicle. VehicleID disaster_vehicle = VehicleID::Invalid(); ///< NOSAVE: Disaster vehicle targetting this vehicle.
RoadTypes compatible_roadtypes; ///< NOSAVE: Roadtypes this consist is powered on. RoadTypes compatible_roadtypes; ///< NOSAVE: Roadtypes this consist is powered on.
/** We don't want GCC to zero our struct! It already is zeroed and has an index! */ /** We don't want GCC to zero our struct! It already is zeroed and has an index! */

View File

@ -229,7 +229,7 @@ void RoadVehUpdateCache(RoadVehicle *v, bool same_length)
assert(u->First() == v); assert(u->First() == v);
/* Update the 'first engine' */ /* Update the 'first engine' */
u->gcache.first_engine = (v == u) ? INVALID_ENGINE : v->engine_type; u->gcache.first_engine = (v == u) ? EngineID::Invalid() : v->engine_type;
/* Update the length of the vehicle. */ /* Update the length of the vehicle. */
uint veh_len = GetRoadVehLength(u); uint veh_len = GetRoadVehLength(u);
@ -289,10 +289,10 @@ CommandCost CmdBuildRoadVehicle(DoCommandFlags flags, TileIndex tile, const Engi
v->cargo_cap = rvi->capacity; v->cargo_cap = rvi->capacity;
v->refit_cap = 0; v->refit_cap = 0;
v->last_station_visited = INVALID_STATION; v->last_station_visited = StationID::Invalid();
v->last_loading_station = INVALID_STATION; v->last_loading_station = StationID::Invalid();
v->engine_type = e->index; v->engine_type = e->index;
v->gcache.first_engine = INVALID_ENGINE; // needs to be set before first callback v->gcache.first_engine = EngineID::Invalid(); // needs to be set before first callback
v->reliability = e->reliability; v->reliability = e->reliability;
v->reliability_spd_dec = e->reliability_spd_dec; v->reliability_spd_dec = e->reliability_spd_dec;
@ -582,7 +582,7 @@ static bool RoadVehCheckTrainCrash(RoadVehicle *v)
TileIndex RoadVehicle::GetOrderStationLocation(StationID station) TileIndex RoadVehicle::GetOrderStationLocation(StationID station)
{ {
if (station == this->last_station_visited) this->last_station_visited = INVALID_STATION; if (station == this->last_station_visited) this->last_station_visited = StationID::Invalid();
const Station *st = Station::Get(station); const Station *st = Station::Get(station);
if (!CanVehicleUseStation(this, st)) { if (!CanVehicleUseStation(this, st)) {
@ -1126,7 +1126,7 @@ static bool CanBuildTramTrackOnTile(CompanyID c, TileIndex t, RoadType rt, RoadB
/* The 'current' company is not necessarily the owner of the vehicle. */ /* The 'current' company is not necessarily the owner of the vehicle. */
Backup<CompanyID> cur_company(_current_company, c); Backup<CompanyID> cur_company(_current_company, c);
CommandCost ret = Command<CMD_BUILD_ROAD>::Do(DoCommandFlag::NoWater, t, r, rt, DRD_NONE, INVALID_TOWN); CommandCost ret = Command<CMD_BUILD_ROAD>::Do(DoCommandFlag::NoWater, t, r, rt, DRD_NONE, TownID::Invalid());
cur_company.Restore(); cur_company.Restore();
return ret.Succeeded(); return ret.Succeeded();

View File

@ -73,7 +73,7 @@
#include "../safeguards.h" #include "../safeguards.h"
extern Company *DoStartupNewCompany(bool is_ai, CompanyID company = INVALID_COMPANY); extern Company *DoStartupNewCompany(bool is_ai, CompanyID company = CompanyID::Invalid());
/** /**
* Makes a tile canal or water depending on the surroundings. * Makes a tile canal or water depending on the surroundings.
@ -179,7 +179,7 @@ static void ConvertTownOwner()
static void UpdateExclusiveRights() static void UpdateExclusiveRights()
{ {
for (Town *t : Town::Iterate()) { for (Town *t : Town::Iterate()) {
t->exclusivity = INVALID_COMPANY; t->exclusivity = CompanyID::Invalid();
} }
/* FIXME old exclusive rights status is not being imported (stored in s->blocked_months_obsolete) /* FIXME old exclusive rights status is not being imported (stored in s->blocked_months_obsolete)
@ -2285,7 +2285,7 @@ bool AfterLoadGame()
if (s->remaining < 12) { if (s->remaining < 12) {
/* Converting nonawarded subsidy */ /* Converting nonawarded subsidy */
s->remaining = 12 - s->remaining; // convert "age" to "remaining" s->remaining = 12 - s->remaining; // convert "age" to "remaining"
s->awarded = INVALID_COMPANY; // not awarded to anyone s->awarded = CompanyID::Invalid(); // not awarded to anyone
const CargoSpec *cs = CargoSpec::Get(s->cargo_type); const CargoSpec *cs = CargoSpec::Get(s->cargo_type);
switch (cs->town_acceptance_effect) { switch (cs->town_acceptance_effect) {
case TAE_PASSENGERS: case TAE_PASSENGERS:
@ -3416,7 +3416,7 @@ void ReloadNewGRFData()
/* Delete news referring to no longer existing entities */ /* Delete news referring to no longer existing entities */
DeleteInvalidEngineNews(); DeleteInvalidEngineNews();
/* Update livery selection windows */ /* Update livery selection windows */
for (CompanyID i = COMPANY_FIRST; i < MAX_COMPANIES; ++i) InvalidateWindowData(WC_COMPANY_COLOUR, i); for (CompanyID i = CompanyID::Begin(); i < MAX_COMPANIES; ++i) InvalidateWindowData(WC_COMPANY_COLOUR, i);
/* Update company infrastructure counts. */ /* Update company infrastructure counts. */
InvalidateWindowClassesData(WC_COMPANY_INFRASTRUCTURE); InvalidateWindowClassesData(WC_COMPANY_INFRASTRUCTURE);
InvalidateWindowClassesData(WC_BUILD_TOOLBAR); InvalidateWindowClassesData(WC_BUILD_TOOLBAR);

View File

@ -80,7 +80,7 @@ struct AIPLChunkHandler : ChunkHandler {
const std::vector<SaveLoad> slt = SlCompatTableHeader(_ai_company_desc, _ai_company_sl_compat); const std::vector<SaveLoad> slt = SlCompatTableHeader(_ai_company_desc, _ai_company_sl_compat);
/* Free all current data */ /* Free all current data */
for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; ++c) { for (CompanyID c = CompanyID::Begin(); c < MAX_COMPANIES; ++c) {
AIConfig::GetConfig(c, AIConfig::SSS_FORCE_GAME)->Change(std::nullopt); AIConfig::GetConfig(c, AIConfig::SSS_FORCE_GAME)->Change(std::nullopt);
} }
@ -160,7 +160,7 @@ struct AIPLChunkHandler : ChunkHandler {
{ {
SlTableHeader(_ai_company_desc); SlTableHeader(_ai_company_desc);
for (CompanyID i = COMPANY_FIRST; i < MAX_COMPANIES; ++i) { for (CompanyID i = CompanyID::Begin(); i < MAX_COMPANIES; ++i) {
SlSetArrayIndex(i); SlSetArrayIndex(i);
SlAutolength(SaveReal_AIPL, i.base()); SlAutolength(SaveReal_AIPL, i.base());
} }

View File

@ -55,9 +55,9 @@
} }
if (IsSavegameVersionBefore(SLV_120)) { if (IsSavegameVersionBefore(SLV_120)) {
/* CargoPacket's source should be either INVALID_STATION or a valid station */ /* CargoPacket's source should be either StationID::Invalid() or a valid station */
for (CargoPacket *cp : CargoPacket::Iterate()) { for (CargoPacket *cp : CargoPacket::Iterate()) {
if (!Station::IsValidID(cp->first_station)) cp->first_station = INVALID_STATION; if (!Station::IsValidID(cp->first_station)) cp->first_station = StationID::Invalid();
} }
} }

View File

@ -83,7 +83,7 @@ struct ENGNChunkHandler : ChunkHandler {
/* preview_company_rank was replaced with preview_company and preview_asked. /* preview_company_rank was replaced with preview_company and preview_asked.
* Just cancel any previews. */ * Just cancel any previews. */
e->flags.Reset(EngineFlag{4}); // ENGINE_OFFER_WINDOW_OPEN e->flags.Reset(EngineFlag{4}); // ENGINE_OFFER_WINDOW_OPEN
e->preview_company = INVALID_COMPANY; e->preview_company = CompanyID::Invalid();
e->preview_asked.Set(); e->preview_asked.Set();
} }
} }

View File

@ -53,7 +53,7 @@ struct GRPSChunkHandler : ChunkHandler {
Group *g = new (index) Group(); Group *g = new (index) Group();
SlObject(g, slt); SlObject(g, slt);
if (IsSavegameVersionBefore(SLV_189)) g->parent = INVALID_GROUP; if (IsSavegameVersionBefore(SLV_189)) g->parent = GroupID::Invalid();
} }
} }
}; };

View File

@ -437,7 +437,7 @@ static bool FixTTOEngines()
e->info.climates = LandscapeType::Temperate; e->info.climates = LandscapeType::Temperate;
} }
e->preview_company = INVALID_COMPANY; e->preview_company = CompanyID::Invalid();
e->preview_asked.Set(); e->preview_asked.Set();
e->preview_wait = 0; e->preview_wait = 0;
e->name = std::string{}; e->name = std::string{};
@ -724,8 +724,8 @@ static bool LoadOldGood(LoadgameState &ls, int num)
AssignBit(ge->status, GoodsEntry::GES_ACCEPTANCE, HasBit(_waiting_acceptance, 15)); AssignBit(ge->status, GoodsEntry::GES_ACCEPTANCE, HasBit(_waiting_acceptance, 15));
AssignBit(ge->status, GoodsEntry::GES_RATING, _cargo_source != 0xFF); AssignBit(ge->status, GoodsEntry::GES_RATING, _cargo_source != 0xFF);
if (GB(_waiting_acceptance, 0, 12) != 0 && CargoPacket::CanAllocateItem()) { if (GB(_waiting_acceptance, 0, 12) != 0 && CargoPacket::CanAllocateItem()) {
ge->GetOrCreateData().cargo.Append(new CargoPacket(GB(_waiting_acceptance, 0, 12), _cargo_periods, (_cargo_source == 0xFF) ? INVALID_STATION : StationID{_cargo_source}, INVALID_TILE, 0), ge->GetOrCreateData().cargo.Append(new CargoPacket(GB(_waiting_acceptance, 0, 12), _cargo_periods, (_cargo_source == 0xFF) ? StationID::Invalid() : StationID{_cargo_source}, INVALID_TILE, 0),
INVALID_STATION); StationID::Invalid());
} }
return true; return true;
@ -1372,8 +1372,8 @@ bool LoadOldVehicle(LoadgameState &ls, int num)
v->next = (Vehicle *)(size_t)_old_next_ptr; v->next = (Vehicle *)(size_t)_old_next_ptr;
if (_cargo_count != 0 && CargoPacket::CanAllocateItem()) { if (_cargo_count != 0 && CargoPacket::CanAllocateItem()) {
StationID source = (_cargo_source == 0xFF) ? INVALID_STATION : StationID{_cargo_source}; StationID source = (_cargo_source == 0xFF) ? StationID::Invalid() : StationID{_cargo_source};
TileIndex source_xy = (source != INVALID_STATION) ? 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)); v->cargo.Append(new CargoPacket(_cargo_count, _cargo_periods, source, source_xy, 0));
} }
} }

View File

@ -193,15 +193,15 @@ static void SwapPackets(GoodsEntry *ge)
StationCargoPacketMap &ge_packets = const_cast<StationCargoPacketMap &>(*ge->GetOrCreateData().cargo.Packets()); StationCargoPacketMap &ge_packets = const_cast<StationCargoPacketMap &>(*ge->GetOrCreateData().cargo.Packets());
if (_packets.empty()) { if (_packets.empty()) {
std::map<StationID, std::list<CargoPacket *> >::iterator it(ge_packets.find(INVALID_STATION)); std::map<StationID, std::list<CargoPacket *> >::iterator it(ge_packets.find(StationID::Invalid()));
if (it == ge_packets.end()) { if (it == ge_packets.end()) {
return; return;
} else { } else {
it->second.swap(_packets); it->second.swap(_packets);
} }
} else { } else {
assert(ge_packets[INVALID_STATION].empty()); assert(ge_packets[StationID::Invalid()].empty());
ge_packets[INVALID_STATION].swap(_packets); ge_packets[StationID::Invalid()].swap(_packets);
} }
} }
@ -322,7 +322,7 @@ public:
GoodsEntry::GoodsEntryData &data = ge->GetOrCreateData(); GoodsEntry::GoodsEntryData &data = ge->GetOrCreateData();
FlowSaveLoad flow{}; FlowSaveLoad flow{};
FlowStat *fs = nullptr; FlowStat *fs = nullptr;
StationID prev_source = INVALID_STATION; StationID prev_source = StationID::Invalid();
for (uint32_t j = 0; j < num_flows; ++j) { for (uint32_t j = 0; j < num_flows; ++j) {
SlObject(&flow, this->GetLoadDescription()); SlObject(&flow, this->GetLoadDescription());
if (fs == nullptr || prev_source != flow.source) { if (fs == nullptr || prev_source != flow.source) {
@ -416,8 +416,8 @@ public:
if (IsSavegameVersionBefore(SLV_68)) { if (IsSavegameVersionBefore(SLV_68)) {
AssignBit(ge.status, GoodsEntry::GES_ACCEPTANCE, HasBit(_waiting_acceptance, 15)); AssignBit(ge.status, GoodsEntry::GES_ACCEPTANCE, HasBit(_waiting_acceptance, 15));
if (GB(_waiting_acceptance, 0, 12) != 0) { if (GB(_waiting_acceptance, 0, 12) != 0) {
/* In old versions, enroute_from used 0xFF as INVALID_STATION */ /* In old versions, enroute_from used 0xFF as StationID::Invalid() */
StationID source = (IsSavegameVersionBefore(SLV_7) && _cargo_source == 0xFF) ? INVALID_STATION : static_cast<StationID>(_cargo_source); StationID source = (IsSavegameVersionBefore(SLV_7) && _cargo_source == 0xFF) ? StationID::Invalid() : static_cast<StationID>(_cargo_source);
/* Make sure we can allocate the CargoPacket. This is safe /* Make sure we can allocate the CargoPacket. This is safe
* as there can only be ~64k stations and 32 cargoes in these * as there can only be ~64k stations and 32 cargoes in these
@ -427,7 +427,7 @@ public:
/* Don't construct the packet with station here, because that'll fail with old savegames */ /* Don't construct the packet with station here, because that'll fail with old savegames */
CargoPacket *cp = new CargoPacket(GB(_waiting_acceptance, 0, 12), _cargo_periods, source, TileIndex{_cargo_source_xy}, _cargo_feeder_share); CargoPacket *cp = new CargoPacket(GB(_waiting_acceptance, 0, 12), _cargo_periods, source, TileIndex{_cargo_source_xy}, _cargo_feeder_share);
ge.GetOrCreateData().cargo.Append(cp, INVALID_STATION); ge.GetOrCreateData().cargo.Append(cp, StationID::Invalid());
SetBit(ge.status, GoodsEntry::GES_RATING); SetBit(ge.status, GoodsEntry::GES_RATING);
} }
} }

View File

@ -225,7 +225,7 @@ void UpdateOldAircraft()
static void CheckValidVehicles() static void CheckValidVehicles()
{ {
size_t total_engines = Engine::GetPoolSize(); size_t total_engines = Engine::GetPoolSize();
EngineID first_engine[4] = { INVALID_ENGINE, INVALID_ENGINE, INVALID_ENGINE, INVALID_ENGINE }; EngineID first_engine[4] = { EngineID::Invalid(), EngineID::Invalid(), EngineID::Invalid(), EngineID::Invalid() };
for (const Engine *e : Engine::IterateType(VEH_TRAIN)) { first_engine[VEH_TRAIN] = e->index; break; } for (const Engine *e : Engine::IterateType(VEH_TRAIN)) { first_engine[VEH_TRAIN] = e->index; break; }
for (const Engine *e : Engine::IterateType(VEH_ROAD)) { first_engine[VEH_ROAD] = e->index; break; } for (const Engine *e : Engine::IterateType(VEH_ROAD)) { first_engine[VEH_ROAD] = e->index; break; }
@ -262,7 +262,7 @@ void AfterLoadVehiclesPhase1(bool part_of_load)
if (part_of_load) v->fill_percent_te_id = INVALID_TE_ID; if (part_of_load) v->fill_percent_te_id = INVALID_TE_ID;
v->first = nullptr; v->first = nullptr;
if (v->IsGroundVehicle()) v->GetGroundVehicleCache()->first_engine = INVALID_ENGINE; if (v->IsGroundVehicle()) v->GetGroundVehicleCache()->first_engine = EngineID::Invalid();
} }
/* AfterLoadVehicles may also be called in case of NewGRF reload, in this /* AfterLoadVehicles may also be called in case of NewGRF reload, in this
@ -515,7 +515,7 @@ void AfterLoadVehiclesPhase2(bool part_of_load)
RoadVehicle *u = RoadVehicle::GetIfValid(v->dest_tile.base()); RoadVehicle *u = RoadVehicle::GetIfValid(v->dest_tile.base());
if (u != nullptr && u->IsFrontEngine()) { if (u != nullptr && u->IsFrontEngine()) {
/* Delete UFO targetting a vehicle which is already a target. */ /* Delete UFO targetting a vehicle which is already a target. */
if (u->disaster_vehicle != INVALID_VEHICLE && u->disaster_vehicle != dv->index) { if (u->disaster_vehicle != VehicleID::Invalid() && u->disaster_vehicle != dv->index) {
delete v; delete v;
continue; continue;
} else { } else {
@ -1144,10 +1144,10 @@ struct VEHSChunkHandler : ChunkHandler {
/* Old savegames used 'last_station_visited = 0xFF' */ /* Old savegames used 'last_station_visited = 0xFF' */
if (IsSavegameVersionBefore(SLV_5) && v->last_station_visited == 0xFF) { if (IsSavegameVersionBefore(SLV_5) && v->last_station_visited == 0xFF) {
v->last_station_visited = INVALID_STATION; v->last_station_visited = StationID::Invalid();
} }
if (IsSavegameVersionBefore(SLV_182)) v->last_loading_station = INVALID_STATION; if (IsSavegameVersionBefore(SLV_182)) v->last_loading_station = StationID::Invalid();
if (IsSavegameVersionBefore(SLV_5)) { if (IsSavegameVersionBefore(SLV_5)) {
/* Convert the current_order.type (which is a mix of type and flags, because /* Convert the current_order.type (which is a mix of type and flags, because

View File

@ -77,7 +77,7 @@
EnforcePrecondition(false, IsValidAirportType(type)); EnforcePrecondition(false, IsValidAirportType(type));
EnforcePrecondition(false, station_id == ScriptStation::STATION_NEW || station_id == ScriptStation::STATION_JOIN_ADJACENT || ScriptStation::IsValidStation(station_id)); EnforcePrecondition(false, station_id == ScriptStation::STATION_NEW || station_id == ScriptStation::STATION_JOIN_ADJACENT || ScriptStation::IsValidStation(station_id));
return ScriptObject::Command<CMD_BUILD_AIRPORT>::Do(tile, type, 0, (ScriptStation::IsValidStation(station_id) ? station_id : INVALID_STATION), station_id != ScriptStation::STATION_JOIN_ADJACENT); return ScriptObject::Command<CMD_BUILD_AIRPORT>::Do(tile, type, 0, (ScriptStation::IsValidStation(station_id) ? station_id : StationID::Invalid()), station_id != ScriptStation::STATION_JOIN_ADJACENT);
} }
/* static */ bool ScriptAirport::RemoveAirport(TileIndex tile) /* static */ bool ScriptAirport::RemoveAirport(TileIndex tile)
@ -148,11 +148,11 @@
/* static */ TownID ScriptAirport::GetNearestTown(TileIndex tile, AirportType type) /* static */ TownID ScriptAirport::GetNearestTown(TileIndex tile, AirportType type)
{ {
if (!::IsValidTile(tile)) return INVALID_TOWN; if (!::IsValidTile(tile)) return TownID::Invalid();
if (!IsAirportInformationAvailable(type)) return INVALID_TOWN; if (!IsAirportInformationAvailable(type)) return TownID::Invalid();
const AirportSpec *as = AirportSpec::Get(type); const AirportSpec *as = AirportSpec::Get(type);
if (!as->IsWithinMapBounds(0, tile)) return INVALID_TOWN; if (!as->IsWithinMapBounds(0, tile)) return TownID::Invalid();
uint dist; uint dist;
const auto &layout = as->layouts[0]; const auto &layout = as->layouts[0];

View File

@ -22,7 +22,7 @@ class ScriptBaseStation : public ScriptObject {
public: public:
static constexpr StationID STATION_NEW = ::NEW_STATION; ///< Build a new station static constexpr StationID STATION_NEW = ::NEW_STATION; ///< Build a new station
static constexpr StationID STATION_JOIN_ADJACENT = ::ADJACENT_STATION; ///< Join an neighbouring station if one exists static constexpr StationID STATION_JOIN_ADJACENT = ::ADJACENT_STATION; ///< Join an neighbouring station if one exists
static constexpr StationID STATION_INVALID = ::INVALID_STATION; ///< Invalid station id. static constexpr StationID STATION_INVALID = ::StationID::Invalid(); ///< Invalid station id.
/** /**
* Checks whether the given basestation is valid and owned by you. * Checks whether the given basestation is valid and owned by you.

View File

@ -105,7 +105,7 @@ static void _DoCommandReturnBuildBridge1(class ScriptInstance *instance)
DiagDirection dir_1 = ::DiagdirBetweenTiles(end, start); DiagDirection dir_1 = ::DiagdirBetweenTiles(end, start);
DiagDirection dir_2 = ::ReverseDiagDir(dir_1); DiagDirection dir_2 = ::ReverseDiagDir(dir_1);
return ScriptObject::Command<CMD_BUILD_ROAD>::Do(&::_DoCommandReturnBuildBridge2, start + ::TileOffsByDiagDir(dir_1), ::DiagDirToRoadBits(dir_2), (::RoadType)ScriptRoad::GetCurrentRoadType(), DRD_NONE, INVALID_TOWN); return ScriptObject::Command<CMD_BUILD_ROAD>::Do(&::_DoCommandReturnBuildBridge2, start + ::TileOffsByDiagDir(dir_1), ::DiagDirToRoadBits(dir_2), (::RoadType)ScriptRoad::GetCurrentRoadType(), DRD_NONE, TownID::Invalid());
} }
/* static */ bool ScriptBridge::_BuildBridgeRoad2() /* static */ bool ScriptBridge::_BuildBridgeRoad2()
@ -119,7 +119,7 @@ static void _DoCommandReturnBuildBridge1(class ScriptInstance *instance)
DiagDirection dir_1 = ::DiagdirBetweenTiles(end, start); DiagDirection dir_1 = ::DiagdirBetweenTiles(end, start);
DiagDirection dir_2 = ::ReverseDiagDir(dir_1); DiagDirection dir_2 = ::ReverseDiagDir(dir_1);
return ScriptObject::Command<CMD_BUILD_ROAD>::Do(end + ::TileOffsByDiagDir(dir_2), ::DiagDirToRoadBits(dir_1), (::RoadType)ScriptRoad::GetCurrentRoadType(), DRD_NONE, INVALID_TOWN); return ScriptObject::Command<CMD_BUILD_ROAD>::Do(end + ::TileOffsByDiagDir(dir_2), ::DiagDirToRoadBits(dir_1), (::RoadType)ScriptRoad::GetCurrentRoadType(), DRD_NONE, TownID::Invalid());
} }
/* static */ bool ScriptBridge::RemoveBridge(TileIndex tile) /* static */ bool ScriptBridge::RemoveBridge(TileIndex tile)

View File

@ -33,13 +33,13 @@
/* If this assert gets triggered, then ScriptCompany::ResolveCompanyID needed to be called before. */ /* If this assert gets triggered, then ScriptCompany::ResolveCompanyID needed to be called before. */
assert(company != ScriptCompany::COMPANY_SELF && company != ScriptCompany::COMPANY_SPECTATOR); assert(company != ScriptCompany::COMPANY_SELF && company != ScriptCompany::COMPANY_SPECTATOR);
if (company == ScriptCompany::COMPANY_INVALID) return ::INVALID_COMPANY; if (company == ScriptCompany::COMPANY_INVALID) return ::CompanyID::Invalid();
return static_cast<::CompanyID>(company); return static_cast<::CompanyID>(company);
} }
/* static */ ScriptCompany::CompanyID ScriptCompany::ToScriptCompanyID(::CompanyID company) /* static */ ScriptCompany::CompanyID ScriptCompany::ToScriptCompanyID(::CompanyID company)
{ {
if (company == ::INVALID_COMPANY) return ScriptCompany::COMPANY_INVALID; if (company == ::CompanyID::Invalid()) return ScriptCompany::COMPANY_INVALID;
return static_cast<::ScriptCompany::CompanyID>(company.base()); return static_cast<::ScriptCompany::CompanyID>(company.base());
} }

View File

@ -30,8 +30,8 @@ public:
/** Different constants related to CompanyID. */ /** Different constants related to CompanyID. */
enum CompanyID { enum CompanyID {
/* Note: these values represent part of the in-game Owner enum */ /* Note: these values represent part of the in-game Owner enum */
COMPANY_FIRST = ::COMPANY_FIRST.base(), ///< The first available company. COMPANY_FIRST = ::CompanyID::Begin().base(), ///< The first available company.
COMPANY_LAST = ::MAX_COMPANIES, ///< The last available company. COMPANY_LAST = ::CompanyID::End().base(), ///< The last available company.
/* Custom added value, only valid for this API */ /* Custom added value, only valid for this API */
COMPANY_INVALID = -1, ///< An invalid company. COMPANY_INVALID = -1, ///< An invalid company.

View File

@ -38,7 +38,7 @@
(type == GT_INDUSTRY && ScriptIndustry::IsValidIndustry(static_cast<IndustryID>(destination))) || (type == GT_INDUSTRY && ScriptIndustry::IsValidIndustry(static_cast<IndustryID>(destination))) ||
(type == GT_TOWN && ScriptTown::IsValidTown(static_cast<TownID>(destination))) || (type == GT_TOWN && ScriptTown::IsValidTown(static_cast<TownID>(destination))) ||
(type == GT_COMPANY && ScriptCompany::ResolveCompanyID(ScriptCompany::ToScriptCompanyID(static_cast<::CompanyID>(destination))) != ScriptCompany::COMPANY_INVALID) || (type == GT_COMPANY && ScriptCompany::ResolveCompanyID(ScriptCompany::ToScriptCompanyID(static_cast<::CompanyID>(destination))) != ScriptCompany::COMPANY_INVALID) ||
(type == GT_STORY_PAGE && story_page != nullptr && (c == INVALID_COMPANY ? story_page->company == INVALID_COMPANY : story_page->company == INVALID_COMPANY || story_page->company == c)); (type == GT_STORY_PAGE && story_page != nullptr && (c == CompanyID::Invalid() ? story_page->company == CompanyID::Invalid() : story_page->company == CompanyID::Invalid() || story_page->company == c));
} }
/* static */ GoalID ScriptGoal::New(ScriptCompany::CompanyID company, Text *goal, GoalType type, SQInteger destination) /* static */ GoalID ScriptGoal::New(ScriptCompany::CompanyID company, Text *goal, GoalType type, SQInteger destination)

View File

@ -25,7 +25,7 @@
*/ */
class ScriptGoal : public ScriptObject { class ScriptGoal : public ScriptObject {
public: public:
static constexpr GoalID GOAL_INVALID = ::INVALID_GOAL; ///< An invalid goal id. static constexpr GoalID GOAL_INVALID = ::GoalID::Invalid(); ///< An invalid goal id.
/** /**
* Goal types that can be given to a goal. * Goal types that can be given to a goal.

Some files were not shown because too many files have changed in this diff Show More