OpenTTD Source 20261112-master-gbcbec5e63f
engine.cpp
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
9
10#include "stdafx.h"
12#include "company_func.h"
13#include "command_func.h"
14#include "news_func.h"
15#include "newgrf.h"
16#include "newgrf_engine.h"
17#include "strings_func.h"
18#include "core/random_func.hpp"
19#include "window_func.h"
20#include "autoreplace_gui.h"
21#include "string_func.h"
22#include "ai/ai.hpp"
23#include "core/pool_func.hpp"
24#include "engine_gui.h"
25#include "engine_func.h"
26#include "engine_base.h"
27#include "company_base.h"
28#include "rail.h"
29#include "road_func.h"
30#include "vehicle_base.h"
31#include "vehicle_func.h"
33#include "error.h"
34#include "engine_base.h"
35#include "script/api/script_event_types.hpp"
36#include "timer/timer.h"
39
40#include "table/strings.h"
41#include "table/engines.h"
42
43#include "safeguards.h"
44
45EnginePool _engine_pool("Engine");
47
48EngineOverrideManager _engine_mngr;
49
55
62{
64 static constexpr VehicleTypeIndexArray<uint8_t> ENGINE_COUNTS = {
65 lengthof(_orig_rail_vehicle_info),
66 lengthof(_orig_road_vehicle_info),
67 lengthof(_orig_ship_vehicle_info),
68 lengthof(_orig_aircraft_vehicle_info),
69 };
70
72 return ENGINE_COUNTS[type];
73}
74
81{
83 static constexpr VehicleTypeIndexArray<uint8_t> ENGINE_OFFSETS = {
84 0,
85 lengthof(_orig_rail_vehicle_info),
86 lengthof(_orig_rail_vehicle_info) + lengthof(_orig_road_vehicle_info),
87 lengthof(_orig_rail_vehicle_info) + lengthof(_orig_road_vehicle_info) + lengthof(_orig_ship_vehicle_info),
88 };
89
91 return ENGINE_OFFSETS[type];
92}
93
94static_assert(lengthof(_orig_rail_vehicle_info) + lengthof(_orig_road_vehicle_info) + lengthof(_orig_ship_vehicle_info) + lengthof(_orig_aircraft_vehicle_info) == lengthof(_orig_engine_info));
95
96Engine::Engine(EngineID index, VehicleType type, uint16_t local_id) : EnginePool::PoolItem<&_engine_pool>(index)
97{
98 this->type = type;
99
100 /* Called in the context of loading a savegame. The rest comes from the loader. */
101 if (type == VehicleType::Invalid) return;
102
103 this->grf_prop.local_id = local_id;
104 this->list_position = local_id;
105 this->preview_company = CompanyID::Invalid();
106 this->display_last_variant = EngineID::Invalid();
107
108 /* Check if this base engine is within the original engine data range */
109 if (local_id >= GetOriginalEngineCount(type)) {
110 /* Initialise default type-specific information. */
111 switch (type) {
112 case VehicleType::Train: this->vehicle_info.emplace<RailVehicleInfo>(); break;
113 case VehicleType::Road: this->vehicle_info.emplace<RoadVehicleInfo>(); break;
114 case VehicleType::Ship: this->vehicle_info.emplace<ShipVehicleInfo>(); break;
115 case VehicleType::Aircraft: this->vehicle_info.emplace<AircraftVehicleInfo>(); break;
116 default: break;
117 }
118 /* Set model life to maximum to make wagons available */
119 this->info.base_life = TimerGameCalendar::Year{0xFF};
120 /* Aircraft must have CT_INVALID as default, as there is no property */
121 this->info.cargo_type = INVALID_CARGO;
122 this->info.cargo_label = (type == VehicleType::Aircraft) ? CT_INVALID : CT_PASSENGERS;
123 /* Set cargo aging period to the default value. */
124 this->info.cargo_age_period = Ticks::CARGO_AGING_TICKS;
125 /* Not a variant */
126 this->info.variant_id = EngineID::Invalid();
127 return;
128 }
129
130 /* Copy the original engine info for this slot */
131 this->info = _orig_engine_info[GetOriginalEngineOffset(type) + local_id];
132
133 /* Copy the original engine data for this slot */
134 switch (type) {
135 default: NOT_REACHED();
136
137 case VehicleType::Train: {
138 RailVehicleInfo &rvi = this->vehicle_info.emplace<RailVehicleInfo>(_orig_rail_vehicle_info[local_id]);
139 this->original_image_index = rvi.image_index;
140 this->info.string_id = STR_VEHICLE_NAME_TRAIN_ENGINE_RAIL_KIRBY_PAUL_TANK_STEAM + local_id;
141
142 /* Set the default model life of original wagons to "infinite" */
143 if (rvi.railveh_type == RailVehicleType::Wagon) this->info.base_life = TimerGameCalendar::Year{0xFF};
144
145 break;
146 }
147
148 case VehicleType::Road: {
149 RoadVehicleInfo &rvi = this->vehicle_info.emplace<RoadVehicleInfo>(_orig_road_vehicle_info[local_id]);
150 this->original_image_index = rvi.image_index;
151 this->info.string_id = STR_VEHICLE_NAME_ROAD_VEHICLE_MPS_REGAL_BUS + local_id;
152 break;
153 }
154
155 case VehicleType::Ship: {
156 ShipVehicleInfo &svi = this->vehicle_info.emplace<ShipVehicleInfo>(_orig_ship_vehicle_info[local_id]);
157 this->original_image_index = svi.image_index;
158 this->info.string_id = STR_VEHICLE_NAME_SHIP_MPS_OIL_TANKER + local_id;
159 break;
160 }
161
163 AircraftVehicleInfo &avi = this->vehicle_info.emplace<AircraftVehicleInfo>(_orig_aircraft_vehicle_info[local_id]);
164 this->original_image_index = avi.image_index;
165 this->info.string_id = STR_VEHICLE_NAME_AIRCRAFT_SAMPSON_U52 + local_id;
166 break;
167 }
168 }
169}
170
176{
177 return this->info.string_id != STR_NEWGRF_INVALID_ENGINE && this->info.climates.Test(_settings_game.game_creation.landscape);
178}
179
186{
187 const GRFFile *file = this->GetGRF();
188 return file == nullptr ? GrfID{} : file->grfid;
189}
190
197{
198 /* For engines that can appear in a consist (i.e. rail vehicles and (articulated) road vehicles), a capacity
199 * of zero is a special case, to define the vehicle to not carry anything. The default cargotype is still used
200 * for livery selection etc.
201 * Note: Only the property is tested. A capacity callback returning 0 does not have the same effect.
202 */
203 switch (this->type) {
205 if (this->VehInfo<RailVehicleInfo>().capacity == 0) return false;
206 break;
207
209 if (this->VehInfo<RoadVehicleInfo>().capacity == 0) return false;
210 break;
211
214 break;
215
216 default: NOT_REACHED();
217 }
219}
220
221
229uint Engine::DetermineCapacity(const Vehicle *v, uint16_t *mail_capacity) const
230{
231 assert(v == nullptr || this->index == v->engine_type);
232 if (mail_capacity != nullptr) *mail_capacity = 0;
233
234 if (!this->CanCarryCargo()) return 0;
235
236 bool new_multipliers = this->info.misc_flags.Test(EngineMiscFlag::NoDefaultCargoMultiplier);
237 CargoType default_cargo = this->GetDefaultCargoType();
238 CargoType cargo_type = (v != nullptr) ? v->cargo_type : default_cargo;
239
240 if (mail_capacity != nullptr && this->type == VehicleType::Aircraft && IsCargoInClass(cargo_type, CargoClass::Passengers)) {
241 *mail_capacity = GetEngineProperty(this->index, PROP_AIRCRAFT_MAIL_CAPACITY, this->VehInfo<AircraftVehicleInfo>().mail_capacity, v);
242 }
243
244 /* Check the refit capacity callback if we are not in the default configuration, or if we are using the new multiplier algorithm. */
245 if (this->info.callback_mask.Test(VehicleCallbackMask::RefitCapacity) &&
246 (new_multipliers || default_cargo != cargo_type || (v != nullptr && v->cargo_subtype != 0))) {
247 uint16_t callback = GetVehicleCallback(CBID_VEHICLE_REFIT_CAPACITY, 0, 0, this->index, v);
248 if (callback != CALLBACK_FAILED) return callback;
249 }
250
251 /* Get capacity according to property resp. CB */
252 uint capacity;
253 uint extra_mail_cap = 0;
254 switch (this->type) {
256 capacity = GetEngineProperty(this->index, PROP_TRAIN_CARGO_CAPACITY, this->VehInfo<RailVehicleInfo>().capacity, v);
257
258 /* In purchase list multiply the capacity by 2 for dual headed engines */
259 if (v == nullptr && this->VehInfo<RailVehicleInfo>().railveh_type == RailVehicleType::Multihead) capacity *= 2;
260 break;
261
263 capacity = GetEngineProperty(this->index, PROP_ROADVEH_CARGO_CAPACITY, this->VehInfo<RoadVehicleInfo>().capacity, v);
264 break;
265
267 capacity = GetEngineProperty(this->index, PROP_SHIP_CARGO_CAPACITY, this->VehInfo<ShipVehicleInfo>().capacity, v);
268 break;
269
271 capacity = GetEngineProperty(this->index, PROP_AIRCRAFT_PASSENGER_CAPACITY, this->VehInfo<AircraftVehicleInfo>().passenger_capacity, v);
272 if (!IsCargoInClass(cargo_type, CargoClass::Passengers)) {
273 extra_mail_cap = GetEngineProperty(this->index, PROP_AIRCRAFT_MAIL_CAPACITY, this->VehInfo<AircraftVehicleInfo>().mail_capacity, v);
274 }
276 if (!new_multipliers && cargo_type == GetCargoTypeByLabel(CT_MAIL)) return capacity + extra_mail_cap;
277 }
278 default_cargo = GetCargoTypeByLabel(CT_PASSENGERS); // Always use 'passengers' wrt. cargo multipliers
279 break;
280
281 default: NOT_REACHED();
282 }
283
284 if (!new_multipliers) {
285 /* Use the passenger multiplier for mail as well */
286 capacity += extra_mail_cap;
287 extra_mail_cap = 0;
288 }
289
290 /* Apply multipliers depending on cargo- and vehicletype. */
291 if (new_multipliers || (this->type != VehicleType::Ship && default_cargo != cargo_type)) {
292 uint16_t default_multiplier = new_multipliers ? 0x100 : CargoSpec::Get(default_cargo)->multiplier;
293 uint16_t cargo_multiplier = CargoSpec::Get(cargo_type)->multiplier;
294 capacity *= cargo_multiplier;
295 if (extra_mail_cap > 0 && IsValidCargoType(GetCargoTypeByLabel(CT_MAIL))) {
296 uint mail_multiplier = CargoSpec::Get(GetCargoTypeByLabel(CT_MAIL))->multiplier;
297 capacity += (default_multiplier * extra_mail_cap * cargo_multiplier + mail_multiplier / 2) / mail_multiplier;
298 }
299 capacity = (capacity + default_multiplier / 2) / default_multiplier;
300 }
301
302 return capacity;
303}
304
310{
311 Price base_price;
312 uint cost_factor;
313 switch (this->type) {
315 base_price = this->VehInfo<RoadVehicleInfo>().running_cost_class;
316 if (base_price == Price::Invalid) return 0;
317 cost_factor = GetEngineProperty(this->index, PROP_ROADVEH_RUNNING_COST_FACTOR, this->VehInfo<RoadVehicleInfo>().running_cost);
318 break;
319
321 base_price = this->VehInfo<RailVehicleInfo>().running_cost_class;
322 if (base_price == Price::Invalid) return 0;
323 cost_factor = GetEngineProperty(this->index, PROP_TRAIN_RUNNING_COST_FACTOR, this->VehInfo<RailVehicleInfo>().running_cost);
324 break;
325
327 base_price = Price::RunningShip;
328 cost_factor = GetEngineProperty(this->index, PROP_SHIP_RUNNING_COST_FACTOR, this->VehInfo<ShipVehicleInfo>().running_cost);
329 break;
330
332 base_price = Price::RunningAircraft;
333 cost_factor = GetEngineProperty(this->index, PROP_AIRCRAFT_RUNNING_COST_FACTOR, this->VehInfo<AircraftVehicleInfo>().running_cost);
334 break;
335
336 default: NOT_REACHED();
337 }
338
339 return GetPrice(base_price, cost_factor, this->GetGRF(), -8);
340}
341
346Money Engine::GetCost() const
347{
348 Price base_price;
349 uint cost_factor;
350 switch (this->type) {
352 base_price = Price::BuildVehicleRoad;
353 cost_factor = GetEngineProperty(this->index, PROP_ROADVEH_COST_FACTOR, this->VehInfo<RoadVehicleInfo>().cost_factor);
354 break;
355
357 if (this->VehInfo<RailVehicleInfo>().railveh_type == RailVehicleType::Wagon) {
358 base_price = Price::BuildVehicleWagon;
359 cost_factor = GetEngineProperty(this->index, PROP_TRAIN_COST_FACTOR, this->VehInfo<RailVehicleInfo>().cost_factor);
360 } else {
361 base_price = Price::BuildVehicleTrain;
362 cost_factor = GetEngineProperty(this->index, PROP_TRAIN_COST_FACTOR, this->VehInfo<RailVehicleInfo>().cost_factor);
363 }
364 break;
365
367 base_price = Price::BuildVehicleShip;
368 cost_factor = GetEngineProperty(this->index, PROP_SHIP_COST_FACTOR, this->VehInfo<ShipVehicleInfo>().cost_factor);
369 break;
370
372 base_price = Price::BuildVehicleAircraft;
373 cost_factor = GetEngineProperty(this->index, PROP_AIRCRAFT_COST_FACTOR, this->VehInfo<AircraftVehicleInfo>().cost_factor);
374 break;
375
376 default: NOT_REACHED();
377 }
378
379 return GetPrice(base_price, cost_factor, this->GetGRF(), -8);
380}
381
387{
388 switch (this->type) {
390 return GetEngineProperty(this->index, PROP_TRAIN_SPEED, this->VehInfo<RailVehicleInfo>().max_speed);
391
392 case VehicleType::Road: {
393 uint max_speed = GetEngineProperty(this->index, PROP_ROADVEH_SPEED, 0);
394 return (max_speed != 0) ? max_speed * 2 : this->VehInfo<RoadVehicleInfo>().max_speed / 2;
395 }
396
398 return GetEngineProperty(this->index, PROP_SHIP_SPEED, this->VehInfo<ShipVehicleInfo>().max_speed) / 2;
399
401 uint max_speed = GetEngineProperty(this->index, PROP_AIRCRAFT_SPEED, 0);
402 if (max_speed != 0) {
403 return (max_speed * 128) / 10;
404 }
405 return this->VehInfo<AircraftVehicleInfo>().max_speed;
406 }
407
408 default: NOT_REACHED();
409 }
410}
411
419{
420 /* Only trains and road vehicles have 'power'. */
421 switch (this->type) {
423 return GetEngineProperty(this->index, PROP_TRAIN_POWER, this->VehInfo<RailVehicleInfo>().power);
425 return GetEngineProperty(this->index, PROP_ROADVEH_POWER, this->VehInfo<RoadVehicleInfo>().power) * 10;
426
427 default: NOT_REACHED();
428 }
429}
430
437{
438 /* Only trains and road vehicles have 'weight'. */
439 switch (this->type) {
441 return GetEngineProperty(this->index, PROP_TRAIN_WEIGHT, this->VehInfo<RailVehicleInfo>().weight) << (this->VehInfo<RailVehicleInfo>().railveh_type == RailVehicleType::Multihead ? 1 : 0);
443 return GetEngineProperty(this->index, PROP_ROADVEH_WEIGHT, this->VehInfo<RoadVehicleInfo>().weight) / 4;
444
445 default: NOT_REACHED();
446 }
447}
448
455{
456 /* Only trains and road vehicles have 'tractive effort'. */
457 switch (this->type) {
459 return (GROUND_ACCELERATION * this->GetDisplayWeight() * GetEngineProperty(this->index, PROP_TRAIN_TRACTIVE_EFFORT, this->VehInfo<RailVehicleInfo>().tractive_effort)) / 256;
461 return (GROUND_ACCELERATION * this->GetDisplayWeight() * GetEngineProperty(this->index, PROP_ROADVEH_TRACTIVE_EFFORT, this->VehInfo<RoadVehicleInfo>().tractive_effort)) / 256;
462
463 default: NOT_REACHED();
464 }
465}
466
472{
473 /* Assume leap years; this gives the player a bit more than the given amount of years, but never less. */
474 return TimerGameCalendar::Date{(this->info.lifelength + _settings_game.vehicle.extend_vehicle_life).base() * CalendarTime::DAYS_IN_LEAP_YEAR};
475}
476
481uint16_t Engine::GetRange() const
482{
483 if (!_settings_game.vehicle.aircraft_range) return 0;
484 switch (this->type) {
486 return GetEngineProperty(this->index, PROP_AIRCRAFT_RANGE, this->VehInfo<AircraftVehicleInfo>().max_range);
487
488 default: NOT_REACHED();
489 }
490}
491
497{
498 switch (this->type) {
500 switch (this->VehInfo<AircraftVehicleInfo>().subtype) {
501 case AIR_HELI: return STR_LIVERY_HELICOPTER;
502 case AIR_CTOL: return STR_LIVERY_SMALL_PLANE;
503 case AIR_CTOL | AIR_FAST: return STR_LIVERY_LARGE_PLANE;
504 default: NOT_REACHED();
505 }
506
507 default: NOT_REACHED();
508 }
509}
510
516bool Engine::IsVariantHidden(CompanyID c) const
517{
518 /* In case company is spectator. */
519 if (c >= MAX_COMPANIES) return false;
520
521 /* Shortcut if this engine is explicitly hidden. */
522 if (this->IsHidden(c)) return true;
523
524 /* Check for hidden parent variants. This is a bit convoluted as we must check hidden status of
525 * the last display variant rather than the actual parent variant. */
526 const Engine *re = this;
527 const Engine *ve = re->GetDisplayVariant();
528 while (!(ve->IsHidden(c)) && re->info.variant_id != EngineID::Invalid()) {
529 re = Engine::Get(re->info.variant_id);
530 ve = re->GetDisplayVariant();
531 }
532 return ve->IsHidden(c);
533}
534
539{
540 EngineID id = EngineID::Begin();
542 auto &map = this->mappings[type];
543 map.clear();
544 for (uint internal_id = 0; internal_id < GetOriginalEngineCount(type); internal_id++, ++id) {
545 map.emplace_back(INVALID_GRFID, internal_id, type, internal_id, id);
546 }
547 }
548}
549
559EngineID EngineOverrideManager::GetID(VehicleType type, uint16_t grf_local_id, GrfID grfid)
560{
561 const auto &map = this->mappings[type];
562 const auto key = EngineIDMapping::Key(grfid, grf_local_id);
563 auto it = std::ranges::lower_bound(map, key, std::less{}, EngineIDMappingKeyProjection{});
564 if (it == std::end(map) || it->Key() != key) return EngineID::Invalid();
565 return it->engine;
566}
567
578EngineID EngineOverrideManager::UseUnreservedID(VehicleType type, uint16_t grf_local_id, GrfID grfid, bool static_access)
579{
580 auto &map = _engine_mngr.mappings[type];
581 const auto key = EngineIDMapping::Key(INVALID_GRFID, grf_local_id);
582 auto it = std::ranges::lower_bound(map, key, std::less{}, EngineIDMappingKeyProjection{});
583 if (it == std::end(map) || it->Key() != key) return EngineID::Invalid();
584
585 if (!static_access && grfid != INVALID_GRFID) {
586 /* Reserve the engine slot for the new grfid. */
587 it->grfid = grfid;
588
589 /* Relocate entry to its new position in the mapping list to keep it sorted. */
590 auto p = std::ranges::lower_bound(map, EngineIDMapping::Key(grfid, grf_local_id), std::less{}, EngineIDMappingKeyProjection{});
591 it = Slide(it, std::next(it), p).first;
592 }
593
594 return it->engine;
595}
596
605void EngineOverrideManager::SetID(VehicleType type, uint16_t grf_local_id, GrfID grfid, uint8_t substitute_id, EngineID engine)
606{
607 auto &map = this->mappings[type];
608 const auto key = EngineIDMapping::Key(grfid, grf_local_id);
609 auto it = std::ranges::lower_bound(map, key, std::less{}, EngineIDMappingKeyProjection{});
610 if (it == std::end(map) || it->Key() != key) {
611 map.emplace(it, grfid, grf_local_id, type, substitute_id, engine);
612 } else {
613 it->engine = engine;
614 }
615}
616
623{
624 for (const Vehicle *v : Vehicle::Iterate()) {
625 if (IsCompanyBuildableVehicleType(v)) return false;
626 }
627
628 /* Reset the engines, they will get new EngineIDs */
629 _engine_mngr.ResetToDefaultMapping();
631
632 return true;
633}
634
639{
640 CloseWindowByClass(WindowClass::EnginePreview);
641 _engine_pool.CleanPool();
642
644 const auto &mapping = _engine_mngr.mappings[type];
645
646 /* Verify that the engine override manager has at least been set up with the default engines. */
647 assert(std::size(mapping) >= GetOriginalEngineCount(type));
648
649 for (const EngineIDMapping &eid : mapping) {
650 Engine::CreateAtIndex(eid.engine, type, eid.internal_id);
651 }
652 }
653}
654
655void ShowEnginePreviewWindow(EngineID engine);
656
662static bool IsWagon(EngineID index)
663{
664 const Engine *e = Engine::Get(index);
665 return e->type == VehicleType::Train && e->VehInfo<RailVehicleInfo>().railveh_type == RailVehicleType::Wagon;
666}
667
673static void ClearLastVariant(EngineID engine_id, VehicleType type)
674{
675 for (Engine *e : Engine::IterateType(type)) {
676 if (e->display_last_variant == engine_id) e->display_last_variant = EngineID::Invalid();
677 }
678}
679
685void CalcEngineReliability(Engine *e, bool new_month)
686{
687 /* Get source engine for reliability age. This is normally our engine unless variant reliability syncing is requested. */
688 Engine *re = e;
689 while (re->info.variant_id != EngineID::Invalid() && re->info.extra_flags.Test(ExtraEngineFlag::SyncReliability)) {
690 re = Engine::Get(re->info.variant_id);
691 }
692
693 int age = re->age;
694 if (new_month && re->index > e->index && age != INT32_MAX) age++; /* parent variant's age has not yet updated. */
695
696 /* Check for early retirement */
697 if (e->company_avail.Any() && !_settings_game.vehicle.never_expire_vehicles && e->info.base_life != 0xFF) {
698 int retire_early = e->info.retire_early;
699 int retire_early_max_age = e->duration_phase_1 + e->duration_phase_2 - retire_early * 12;
700 if (retire_early != 0 && age >= retire_early_max_age) {
701 /* Early retirement is enabled and we're past the date... */
703 ClearLastVariant(e->index, e->type);
705 }
706 }
707
708 if (age < e->duration_phase_1) {
709 int start = e->reliability_start;
710 e->reliability = age * (e->reliability_max - start) / e->duration_phase_1 + start;
711 } else if ((age -= e->duration_phase_1) < e->duration_phase_2 || _settings_game.vehicle.never_expire_vehicles || e->info.base_life == 0xFF) {
712 /* We are at the peak of this engines life. It will have max reliability.
713 * This is also true if the engines never expire. They will not go bad over time */
715 } else if ((age -= e->duration_phase_2) < e->duration_phase_3) {
716 /* Linearly scale remaining age between the maximum and final reliability. */
717 int max = e->reliability_max;
718 e->reliability = age * (e->reliability_final - max) / e->duration_phase_3 + max;
719 } else {
720 /* time's up for this engine.
721 * We will now completely retire this design */
724 /* Kick this engine out of the lists */
725 ClearLastVariant(e->index, e->type);
727 }
728
729}
730
733{
734 /* Determine last engine aging year, default to 2050 as previously. */
736
737 for (const Engine *e : Engine::Iterate()) {
738 const EngineInfo *ei = &e->info;
739
740 /* Exclude certain engines */
741 if (!ei->climates.Test(_settings_game.game_creation.landscape)) continue;
742 if (e->type == VehicleType::Train && e->VehInfo<RailVehicleInfo>().railveh_type == RailVehicleType::Wagon) continue;
743
744 /* Base year ending date on half the model life */
745 TimerGameCalendar::YearMonthDay ymd = TimerGameCalendar::ConvertDateToYMD(ei->base_intro + (ei->lifelength.base() * CalendarTime::DAYS_IN_LEAP_YEAR) / 2);
746
748 }
749}
750
757void StartupOneEngine(Engine *e, const TimerGameCalendar::YearMonthDay &aging_ymd, uint32_t seed)
758{
759 const EngineInfo *ei = &e->info;
760
761 e->age = 0;
762 e->flags = {};
765
766 /* Vehicles with the same base_intro date shall be introduced at the same time.
767 * Make sure they use the same randomisation of the date. */
768 SavedRandomSeeds saved_seeds;
769 SaveRandomSeeds(&saved_seeds);
770 SetRandomSeed(_settings_game.game_creation.generation_seed ^ seed ^
771 ei->base_intro.base() ^
772 to_underlying(e->type) ^
774 uint32_t r = Random();
775
776 /* Don't randomise the start-date in the first two years after gamestart to ensure availability
777 * of engines in early starting games.
778 * Note: TTDP uses fixed 1922 */
779 e->intro_date = ei->base_intro <= TimerGameCalendar::ConvertYMDToDate(_settings_game.game_creation.starting_year + 2, 0, 1) ? ei->base_intro : (TimerGameCalendar::Date)GB(r, 0, 9) + ei->base_intro;
781 TimerGameCalendar::YearMonthDay intro_ymd = TimerGameCalendar::ConvertDateToYMD(e->intro_date);
782 int aging_months = aging_ymd.year.base() * 12 + aging_ymd.month;
783 int intro_months = intro_ymd.year.base() * 12 + intro_ymd.month;
784 if (intro_ymd.day > 1) intro_months++; // Engines are introduced at the first month start at/after intro date.
785 e->age = aging_months - intro_months;
786 e->company_avail.Set();
788 }
789
790 /* Get parent variant index for syncing reliability via random seed. */
791 const Engine *re = e;
792 while (re->info.variant_id != EngineID::Invalid() && re->info.extra_flags.Test(ExtraEngineFlag::SyncReliability)) {
793 re = Engine::Get(re->info.variant_id);
794 }
795
796 SetRandomSeed(_settings_game.game_creation.generation_seed ^ seed ^
797 (re->index.base() << 16) ^ (re->info.base_intro.base() << 12) ^ (re->info.decay_speed << 8) ^
798 (re->info.lifelength.base() << 4) ^ re->info.retire_early ^
799 to_underlying(e->type) ^
801
802 /* Base reliability defined as a percentage of UINT16_MAX. */
803 const uint16_t RELIABILITY_START = UINT16_MAX * 48 / 100;
804 const uint16_t RELIABILITY_MAX = UINT16_MAX * 75 / 100;
805 const uint16_t RELIABILITY_FINAL = UINT16_MAX * 25 / 100;
806
807 static_assert(RELIABILITY_START == 0x7AE0);
808 static_assert(RELIABILITY_MAX == 0xBFFF);
809 static_assert(RELIABILITY_FINAL == 0x3FFF);
810
811 r = Random();
812 /* 14 bits gives a value between 0 and 16383, which is up to an additional 25%p reliability on top of the base reliability. */
813 e->reliability_start = GB(r, 16, 14) + RELIABILITY_START;
814 e->reliability_max = GB(r, 0, 14) + RELIABILITY_MAX;
815
816 r = Random();
817 e->reliability_final = GB(r, 16, 14) + RELIABILITY_FINAL;
818
819 e->duration_phase_1 = GB(r, 0, 5) + 7;
820 e->duration_phase_2 = std::max(0, int(GB(r, 5, 4)) + ei->base_life.base() * 12 - 96);
821 e->duration_phase_3 = GB(r, 9, 7) + 120;
822
823 RestoreRandomSeeds(saved_seeds);
824
825 e->reliability_spd_dec = ei->decay_speed << 2;
826
827 /* prevent certain engines from ever appearing. */
828 if (!ei->climates.Test(_settings_game.game_creation.landscape)) {
831 }
832}
833
839{
840 /* Aging of vehicles stops, so account for that when starting late */
842 TimerGameCalendar::YearMonthDay aging_ymd = TimerGameCalendar::ConvertDateToYMD(aging_date);
843 uint32_t seed = Random();
844
845 for (Engine *e : Engine::Iterate()) {
846 StartupOneEngine(e, aging_ymd, seed);
847 }
848 for (Engine *e : Engine::Iterate()) {
849 CalcEngineReliability(e, false);
850 }
851
852 /* Update the bitmasks for the vehicle lists */
853 for (Company *c : Company::Iterate()) {
854 c->avail_railtypes = GetCompanyRailTypes(c->index);
855 c->avail_roadtypes = GetCompanyRoadTypes(c->index);
856 }
857
858 /* Invalidate any open purchase lists */
859 InvalidateWindowClassesData(WindowClass::BuildVehicle);
860
861 SetWindowClassesDirty(WindowClass::BuildVehicle);
862 SetWindowClassesDirty(WindowClass::ReplaceVehicle);
863}
864
870static void EnableEngineForCompany(EngineID eid, CompanyID company)
871{
872 Engine *e = Engine::Get(eid);
873 Company *c = Company::Get(company);
874
875 e->company_avail.Set(company);
876 if (e->type == VehicleType::Train) {
878 } else if (e->type == VehicleType::Road) {
880 }
881
882 if (company == _local_company) {
884
885 /* Update the toolbar. */
886 InvalidateWindowData(WindowClass::MainToolbar, 0);
887 if (e->type == VehicleType::Road) InvalidateWindowData(WindowClass::BuildToolbar, TransportType::Road);
888 if (e->type == VehicleType::Ship) InvalidateWindowData(WindowClass::BuildToolbar, TransportType::Water);
889 if (e->type == VehicleType::Aircraft) InvalidateWindowData(WindowClass::BuildToolbar, TransportType::Air);
890 }
891}
892
898static void DisableEngineForCompany(EngineID eid, CompanyID company)
899{
900 Engine *e = Engine::Get(eid);
901 Company *c = Company::Get(company);
902
903 e->company_avail.Reset(company);
904 if (e->type == VehicleType::Train) {
906 } else if (e->type == VehicleType::Road) {
908 }
909
910 if (company == _local_company) {
911 ClearLastVariant(e->index, e->type);
913 }
914}
915
922static void AcceptEnginePreview(EngineID eid, CompanyID company, int recursion_depth = 0)
923{
924 Engine *e = Engine::Get(eid);
925
926 e->preview_company = CompanyID::Invalid();
927 e->preview_asked.Set();
928
929 EnableEngineForCompany(eid, company);
930
931 /* Notify preview window to remove this engine.
932 * Note: We cannot directly close the window.
933 * In singleplayer this function is called from the preview window, so
934 * we have to use the GUI-scope scheduling of InvalidateWindowData.
935 */
936 InvalidateWindowClassesData(WindowClass::EnginePreview);
937
938 /* Don't search for variants to include if we are 10 levels deep already. */
939 if (recursion_depth >= 10) return;
940
941 /* Find variants to be included in preview. */
942 for (Engine *ve : Engine::IterateType(e->type)) {
943 if (ve->index != eid && ve->info.variant_id == eid && ve->info.extra_flags.Test(ExtraEngineFlag::JoinPreview)) {
944 AcceptEnginePreview(ve->index, company, recursion_depth + 1);
945 }
946 }
947}
948
954static CompanyID GetPreviewCompany(Engine *e)
955{
956 CompanyID best_company = CompanyID::Invalid();
957
958 /* For trains the cargomask has no useful meaning, since you can attach other wagons */
959 CargoTypes cargomask = e->type != VehicleType::Train ? GetUnionOfArticulatedRefitMasks(e->index, true) : ALL_CARGOTYPES;
960
961 int32_t best_hist = -1;
962 for (const Company *c : Company::Iterate()) {
963 if (c->block_preview == 0 && !e->preview_asked.Test(c->index) &&
964 c->old_economy[0].performance_history > best_hist) {
965
966 /* Check whether the company uses similar vehicles */
967 for (const Vehicle *v : Vehicle::Iterate()) {
968 if (v->owner != c->index || v->type != e->type) continue;
969 if (!v->GetEngine()->CanCarryCargo() || !cargomask.Test(v->cargo_type)) continue;
970
971 best_hist = c->old_economy[0].performance_history;
972 best_company = c->index;
973 break;
974 }
975 }
976 }
977
978 return best_company;
979}
980
988static bool IsVehicleTypeDisabled(VehicleType type, bool ai)
989{
990 switch (type) {
991 case VehicleType::Train: return _settings_game.vehicle.max_trains == 0 || (ai && _settings_game.ai.ai_disable_veh_train);
992 case VehicleType::Road: return _settings_game.vehicle.max_roadveh == 0 || (ai && _settings_game.ai.ai_disable_veh_roadveh);
993 case VehicleType::Ship: return _settings_game.vehicle.max_ships == 0 || (ai && _settings_game.ai.ai_disable_veh_ship);
994 case VehicleType::Aircraft: return _settings_game.vehicle.max_aircraft == 0 || (ai && _settings_game.ai.ai_disable_veh_aircraft);
995
996 default: NOT_REACHED();
997 }
998}
999
1001static const IntervalTimer<TimerGameCalendar> _calendar_engines_daily({TimerGameCalendar::Trigger::Day, TimerGameCalendar::Priority::Engine}, [](auto)
1002{
1003 for (Company *c : Company::Iterate()) {
1004 c->avail_railtypes = AddDateIntroducedRailTypes(c->avail_railtypes, TimerGameCalendar::date);
1005 c->avail_roadtypes = AddDateIntroducedRoadTypes(c->avail_roadtypes, TimerGameCalendar::date);
1006 }
1007
1009
1010 for (Engine *e : Engine::Iterate()) {
1011 EngineID i = e->index;
1012 if (e->flags.Test(EngineFlag::ExclusivePreview)) {
1013 if (e->preview_company != CompanyID::Invalid()) {
1014 if (!--e->preview_wait) {
1015 InvalidateWindowClassesData(WindowClass::EnginePreview);
1016 e->preview_company = CompanyID::Invalid();
1017 }
1018 } else if (e->preview_asked.Count() < MAX_COMPANIES) {
1019 e->preview_company = GetPreviewCompany(e);
1020
1021 if (e->preview_company == CompanyID::Invalid()) {
1022 e->preview_asked.Set();
1023 continue;
1024 }
1025
1026 e->preview_asked.Set(e->preview_company);
1027 e->preview_wait = 20;
1028 /* AIs are intentionally not skipped for preview even if they cannot build a certain
1029 * vehicle type. This is done to not give poor performing human companies an "unfair"
1030 * boost that they wouldn't have gotten against other human companies. The check on
1031 * the line below is just to make AIs not notice that they have a preview if they
1032 * cannot build the vehicle. */
1033 if (!IsVehicleTypeDisabled(e->type, true)) AI::NewEvent(e->preview_company, new ScriptEventEnginePreview(i));
1034 if (IsInteractiveCompany(e->preview_company)) ShowEnginePreviewWindow(i);
1035 }
1036 }
1037 }
1038});
1039
1045{
1046 for (Engine *e : Engine::Iterate()) {
1047 e->company_hidden.Reset(cid);
1048 }
1049}
1050
1059{
1060 Engine *e = Engine::GetIfValid(engine_id);
1061 if (e == nullptr || _current_company >= MAX_COMPANIES) return CMD_ERROR;
1062 if (!IsEngineBuildable(e->index, e->type, _current_company)) return CMD_ERROR;
1063
1064 if (flags.Test(DoCommandFlag::Execute)) {
1067 }
1068
1069 return CommandCost();
1070}
1071
1080{
1081 Engine *e = Engine::GetIfValid(engine_id);
1082 if (e == nullptr || !e->flags.Test(EngineFlag::ExclusivePreview) || e->preview_company != _current_company) return CMD_ERROR;
1083
1085
1086 return CommandCost();
1087}
1088
1097CommandCost CmdEngineCtrl(DoCommandFlags flags, EngineID engine_id, CompanyID company_id, bool allow)
1098{
1099 if (_current_company != OWNER_DEITY) return CMD_ERROR;
1100
1101 if (!Engine::IsValidID(engine_id) || !Company::IsValidID(company_id)) return CMD_ERROR;
1102
1103 if (flags.Test(DoCommandFlag::Execute)) {
1104 if (allow) {
1105 EnableEngineForCompany(engine_id, company_id);
1106 } else {
1107 DisableEngineForCompany(engine_id, company_id);
1108 }
1109 }
1110
1111 return CommandCost();
1112}
1113
1120{
1121 EngineID index = e->index;
1122
1123 /* In case the company didn't build the vehicle during the intro period,
1124 * prevent that company from getting future intro periods for a while. */
1126 for (Company *c : Company::Iterate()) {
1127 if (!e->company_avail.Test(c->index)) continue;
1128
1129 /* Check the company's 'ALL_GROUP' group statistics. This only includes countable vehicles, which is fine
1130 * as those are the only engines that can be given exclusive previews. */
1131 if (GetGroupNumEngines(c->index, ALL_GROUP, e->index) == 0) {
1132 /* The company did not build this engine during preview. */
1133 c->block_preview = 20;
1134 }
1135 }
1136 }
1137
1140
1141 /* Now available for all companies */
1142 e->company_avail.Set();
1143
1144 /* Do not introduce new rail wagons */
1145 if (IsWagon(index)) return;
1146
1147 if (e->type == VehicleType::Train) {
1148 /* maybe make another rail type available */
1149 assert(e->VehInfo<RailVehicleInfo>().railtypes != RailTypes{});
1151 for (Company *c : Company::Iterate()) c->avail_railtypes = AddDateIntroducedRailTypes(c->avail_railtypes | introduced, TimerGameCalendar::date);
1152 } else if (e->type == VehicleType::Road) {
1153 /* maybe make another road type available */
1154 assert(e->VehInfo<RoadVehicleInfo>().roadtype < ROADTYPE_END);
1155 for (Company *c : Company::Iterate()) c->avail_roadtypes = AddDateIntroducedRoadTypes(c->avail_roadtypes | GetRoadTypeInfo(e->VehInfo<RoadVehicleInfo>().roadtype)->introduces_roadtypes, TimerGameCalendar::date);
1156 }
1157
1158 /* Only broadcast event if AIs are able to build this vehicle type. */
1159 if (!IsVehicleTypeDisabled(e->type, true)) AI::BroadcastNewEvent(new ScriptEventEngineAvailable(index));
1160
1161 /* Only provide the "New Vehicle available" news paper entry, if engine can be built. */
1162 if (!IsVehicleTypeDisabled(e->type, false) && !e->info.extra_flags.Test(ExtraEngineFlag::NoNews)) {
1163 AddNewsItem(GetEncodedString(STR_NEWS_NEW_VEHICLE_NOW_AVAILABLE_WITH_TYPE,
1164 GetEngineCategoryName(index),
1167 }
1168
1169 /* Update the toolbar. */
1170 if (e->type == VehicleType::Road) InvalidateWindowData(WindowClass::BuildToolbar, TransportType::Road);
1171 if (e->type == VehicleType::Ship) InvalidateWindowData(WindowClass::BuildToolbar, TransportType::Water);
1172 if (e->type == VehicleType::Aircraft) InvalidateWindowData(WindowClass::BuildToolbar, TransportType::Air);
1173
1174 /* Remove from preview windows */
1175 InvalidateWindowClassesData(WindowClass::EnginePreview);
1176}
1177
1180{
1182 bool refresh = false;
1183 for (Engine *e : Engine::Iterate()) {
1184 /* Age the vehicle */
1185 if (e->flags.Test(EngineFlag::Available) && e->age != INT32_MAX) {
1186 e->age++;
1187 CalcEngineReliability(e, true);
1188 refresh = true;
1189 }
1190
1191 /* Do not introduce invalid engines */
1192 if (!e->IsEnabled()) continue;
1193
1194 if (!e->flags.Test(EngineFlag::Available) && TimerGameCalendar::date >= (e->intro_date + CalendarTime::DAYS_IN_YEAR)) {
1195 /* Introduce it to all companies */
1197 } else if (!e->flags.Any({EngineFlag::Available, EngineFlag::ExclusivePreview}) && TimerGameCalendar::date >= e->intro_date) {
1198 /* Introduction date has passed...
1199 * Check if it is allowed to build this vehicle type at all
1200 * based on the current game settings. If not, it does not
1201 * make sense to show the preview dialog to any company. */
1202 if (IsVehicleTypeDisabled(e->type, false)) continue;
1203
1204 /* Do not introduce new rail wagons */
1205 if (IsWagon(e->index)) continue;
1206
1207 /* Engine has no preview */
1208 if (e->info.extra_flags.Test(ExtraEngineFlag::NoPreview)) continue;
1209
1210 /* Show preview dialog to one of the companies. */
1211 e->flags.Set(EngineFlag::ExclusivePreview);
1212 e->preview_company = CompanyID::Invalid();
1213 e->preview_asked = CompanyMask{};
1214 }
1215 }
1216
1217 InvalidateWindowClassesData(WindowClass::BuildVehicle); // rebuild the purchase list (esp. when sorted by reliability)
1218
1219 if (refresh) {
1220 SetWindowClassesDirty(WindowClass::BuildVehicle);
1221 SetWindowClassesDirty(WindowClass::ReplaceVehicle);
1222 }
1223 }
1224}
1225
1226static const IntervalTimer<TimerGameCalendar> _calendar_engines_monthly({TimerGameCalendar::Trigger::Month, TimerGameCalendar::Priority::Engine}, [](auto)
1227{
1229});
1230
1236static bool IsUniqueEngineName(const std::string &name)
1237{
1238 for (const Engine *e : Engine::Iterate()) {
1239 if (!e->name.empty() && e->name == name) return false;
1240 }
1241
1242 return true;
1243}
1244
1252CommandCost CmdRenameEngine(DoCommandFlags flags, EngineID engine_id, const std::string &text)
1253{
1254 Engine *e = Engine::GetIfValid(engine_id);
1255 if (e == nullptr) return CMD_ERROR;
1256
1257 bool reset = text.empty();
1258
1259 if (!reset) {
1261 if (!IsUniqueEngineName(text)) return CommandCost(STR_ERROR_NAME_MUST_BE_UNIQUE);
1262 }
1263
1264 if (flags.Test(DoCommandFlag::Execute)) {
1265 if (reset) {
1266 e->name.clear();
1267 } else {
1268 e->name = text;
1269 }
1270
1272 }
1273
1274 return CommandCost();
1275}
1276
1277
1286bool IsEngineBuildable(EngineID engine, VehicleType type, CompanyID company)
1287{
1288 const Engine *e = Engine::GetIfValid(engine);
1289
1290 /* check if it's an engine that is in the engine array */
1291 if (e == nullptr) return false;
1292
1293 /* check if it's an engine of specified type */
1294 if (e->type != type) return false;
1295
1296 /* check if it's available ... */
1297 if (company == OWNER_DEITY) {
1298 /* ... for any company (preview does not count) */
1299 if (!e->flags.Test(EngineFlag::Available) || e->company_avail.None()) return false;
1300 } else {
1301 /* ... for this company */
1302 if (!e->company_avail.Test(company)) return false;
1303 }
1304
1305 if (!e->IsEnabled()) return false;
1306
1307 if (type == VehicleType::Train && company != OWNER_DEITY) {
1308 /* Check if the rail type is available to this company */
1309 const Company *c = Company::Get(company);
1310 if (!GetAllCompatibleRailTypes(e->VehInfo<RailVehicleInfo>().railtypes).Any(c->avail_railtypes)) return false;
1311 }
1312 if (type == VehicleType::Road && company != OWNER_DEITY) {
1313 /* Check if the road type is available to this company */
1314 const Company *c = Company::Get(company);
1315 if (!GetRoadTypeInfo(e->VehInfo<RoadVehicleInfo>().roadtype)->powered_roadtypes.Any(c->avail_roadtypes)) return false;
1316 }
1317
1318 return true;
1319}
1320
1328{
1329 const Engine *e = Engine::GetIfValid(engine);
1330
1331 /* check if it's an engine that is in the engine array */
1332 if (e == nullptr) return false;
1333
1334 if (!e->CanCarryCargo()) return false;
1335
1336 const EngineInfo *ei = &e->info;
1337 if (ei->refit_mask.None()) return false;
1338
1339 /* Are there suffixes?
1340 * Note: This does not mean the suffixes are actually available for every consist at any time. */
1342
1343 /* Is there any cargo except the default cargo? */
1344 CargoType default_cargo = e->GetDefaultCargoType();
1345 return IsValidCargoType(default_cargo) && ei->refit_mask != default_cargo;
1346}
1347
1352{
1353 TimerGameCalendar::Date min_date{INT32_MAX};
1354
1355 for (const Engine *e : Engine::Iterate()) {
1356 if (!e->IsEnabled()) continue;
1357
1358 /* Don't consider train wagons, we need a powered engine available. */
1359 if (e->type == VehicleType::Train && e->VehInfo<RailVehicleInfo>().railveh_type == RailVehicleType::Wagon) continue;
1360
1361 /* We have an available engine... yay! */
1362 if (e->flags.Test(EngineFlag::Available) && e->company_avail.Any()) return;
1363
1364 /* Okay, try to find the earliest date. */
1365 min_date = std::min(min_date, e->info.base_intro);
1366 }
1367
1368 if (min_date < INT32_MAX) {
1369 ShowErrorMessage(GetEncodedString(STR_ERROR_NO_VEHICLES_AVAILABLE_YET),
1370 GetEncodedString(STR_ERROR_NO_VEHICLES_AVAILABLE_YET_EXPLANATION, min_date), WarningLevel::Warning);
1371 } else {
1372 ShowErrorMessage(GetEncodedString(STR_ERROR_NO_VEHICLES_AVAILABLE_AT_ALL),
1373 GetEncodedString(STR_ERROR_NO_VEHICLES_AVAILABLE_AT_ALL_EXPLANATION), WarningLevel::Warning);
1374 }
1375}
Base functions for all AIs.
CargoTypes GetUnionOfArticulatedRefitMasks(EngineID engine, bool include_initial_cargo_type)
Ors the refit_masks of all articulated parts.
Functions related to articulated vehicles.
void AddRemoveEngineFromAutoreplaceAndBuildWindows(VehicleType type)
When an engine is made buildable or is removed from being buildable, add/remove it from the build/aut...
Functions related to the autoreplace GUIs.
static constexpr uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
static constexpr CargoLabel CT_INVALID
Invalid cargo type.
Definition cargo_type.h:74
static constexpr CargoType INVALID_CARGO
Invalid marker for cargoes.
Definition cargo_type.h:83
bool IsValidCargoType(CargoType cargo)
Test whether cargo type is not INVALID_CARGO.
Definition cargo_type.h:112
EnumBitSet< CargoType, uint64_t > CargoTypes
Bitset of CargoType elements.
Definition cargo_type.h:115
static constexpr CargoLabel CT_MAIL
Cargo label for mail.
Definition cargo_type.h:34
static constexpr CargoLabel CT_PASSENGERS
Cargo label for passengers.
Definition cargo_type.h:32
CargoType
Cargo slots to indicate a cargo type within a game.
Definition cargo_type.h:22
CargoType GetCargoTypeByLabel(CargoLabel label)
Get cargo assigned to a label.
Definition cargotype.h:268
@ Passengers
Passengers.
Definition cargotype.h:50
bool IsCargoInClass(CargoType cargo, CargoClasses cc)
Does a given cargo have any cargo class from cc.
Definition cargotype.h:288
static void BroadcastNewEvent(ScriptEvent *event, CompanyID skip_company=CompanyID::Invalid())
Broadcast a new event to all active AIs.
Definition ai_core.cpp:250
static void NewEvent(CompanyID company, ScriptEvent *event)
Queue a new event for an AI.
Definition ai_core.cpp:231
constexpr bool Test(Tvalue_type value) const
Test if the value-th bit is set.
constexpr bool None() const
Test if none of the values are set.
constexpr Timpl & Reset()
Reset all bits.
constexpr Timpl & Set()
Set all bits.
constexpr bool Any(const Timpl &other) const
Test if any of the given values are set.
Common return value for all commands.
StringID GetAircraftTypeText() const
Get the name of the aircraft type for display purposes.
Definition engine.cpp:496
uint GetPower() const
Returns the power of the engine for display and sorting purposes.
Definition engine.cpp:418
const Engine * GetDisplayVariant() const
Get the last display variant for an engine.
uint16_t GetRange() const
Get the range of an aircraft type.
Definition engine.cpp:481
uint16_t reliability_spd_dec
Speed of reliability decay between services (per day).
Definition engine_base.h:52
Money GetCost() const
Return how much a new engine costs.
Definition engine.cpp:346
uint16_t reliability_start
Initial reliability of the engine.
Definition engine_base.h:53
TimerGameCalendar::Date intro_date
Date of introduction of the engine.
Definition engine_base.h:48
const GRFFile * GetGRF() const
Retrieve the NewGRF the engine is tied to.
static Pool::IterateWrapperFiltered< Engine, EngineTypeFilter > IterateType(VehicleType vt, size_t from=0)
Returns an iterable ensemble of all valid engines of the given type.
uint GetDisplayMaxSpeed() const
Returns max speed of the engine for display purposes.
Definition engine.cpp:386
GrfID GetGRFID() const
Retrieve the GRF ID of the NewGRF the engine is tied to.
Definition engine.cpp:185
uint DetermineCapacity(const Vehicle *v, uint16_t *mail_capacity=nullptr) const
Determines capacity of a given vehicle from scratch.
Definition engine.cpp:229
EngineFlags flags
Flags of the engine.
Definition engine_base.h:59
CompanyMask company_avail
Bit for each company whether the engine is available for that company.
Definition engine_base.h:42
uint16_t reliability_max
Maximal reliability of the engine.
Definition engine_base.h:54
uint GetDisplayWeight() const
Returns the weight of the engine for display purposes.
Definition engine.cpp:436
bool IsEnabled() const
Checks whether the engine is a valid (non-articulated part of an) engine.
Definition engine.cpp:175
VehicleType type
Vehicle type, ie VehicleType::Road, VehicleType::Train, etc.
Definition engine_base.h:64
bool IsVariantHidden(CompanyID c) const
Check whether the engine variant chain is hidden in the GUI for the given company.
Definition engine.cpp:516
uint16_t reliability_final
Final reliability of the engine.
Definition engine_base.h:55
CompanyID preview_company
Company which is currently being offered a preview CompanyID::Invalid() means no company.
Definition engine_base.h:61
TimerGameCalendar::Date GetLifeLengthInDays() const
Returns the vehicle's (not model's!) life length in days.
Definition engine.cpp:471
uint16_t duration_phase_3
Third reliability phase in months, decaying to reliability_final.
Definition engine_base.h:58
uint16_t duration_phase_2
Second reliability phase in months, keeping reliability_max.
Definition engine_base.h:57
CargoType GetDefaultCargoType() const
Determines the default cargo type of an engine.
Definition engine_base.h:96
CompanyMask company_hidden
Bit for each company whether the engine is normally hidden in the build gui for that company.
Definition engine_base.h:43
Money GetRunningCost() const
Return how much the running costs of this engine are.
Definition engine.cpp:309
uint16_t reliability
Current reliability of the engine.
Definition engine_base.h:51
CompanyMask preview_asked
Bit for each company which has already been offered a preview.
Definition engine_base.h:44
uint GetDisplayMaxTractiveEffort() const
Returns the tractive effort of the engine for display purposes.
Definition engine.cpp:454
int32_t age
Age of the engine in months.
Definition engine_base.h:49
bool IsHidden(CompanyID c) const
Check whether the engine is hidden in the GUI for the given company.
bool CanCarryCargo() const
Determines whether an engine can carry something.
Definition engine.cpp:196
std::string name
Custom name of engine.
Definition engine_base.h:46
uint16_t duration_phase_1
First reliability phase in months, increasing reliability from reliability_start to reliability_max.
Definition engine_base.h:56
Iterate a range of enum values.
An interval timer will fire every interval, and will continue to fire until it is deleted.
Definition timer.h:76
RoadTypes powered_roadtypes
bitmask to the OTHER roadtypes on which a vehicle of THIS roadtype generates power
Definition road.h:98
static constexpr TimerGameTick::Ticks CARGO_AGING_TICKS
Cycle duration for aging cargo.
static Date ConvertYMDToDate(Year year, Month month, Day day)
Converts a tuple of Year, Month and Day to a Date.
static YearMonthDay ConvertDateToYMD(Date date)
Converts a Date to a Year, Month & Day.
static Date date
Current date in days (day counter).
static Year year
Current year, starting at 0.
StrongType::Typedef< int32_t, struct YearTag< struct Calendar >, StrongType::Compare, StrongType::Integer > Year
StrongType::Typedef< int32_t, DateTag< struct Calendar >, StrongType::Compare, StrongType::Integer > Date
Functions related to commands.
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
@ Execute
execute the given command
EnumBitSet< DoCommandFlag, uint16_t > DoCommandFlags
Bitset of DoCommandFlag elements.
Definition of stuff that is very close to a company, like the company struct itself.
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
CompanyID _current_company
Company currently doing an action.
Functions related to companies.
bool IsInteractiveCompany(CompanyID company)
Is the user representing company?
static constexpr Owner OWNER_DEITY
The object is owned by a superuser / goal script.
Some simple functions to help with accessing containers.
auto Slide(TIter first, TIter last, TIter position) -> std::pair< TIter, TIter >
Move elements between first and last to a new position, rotating elements in between as necessary.
Money GetPrice(Price index, uint cost_factor, const GRFFile *grf_file, int shift)
Determine a certain price.
Definition economy.cpp:941
Price
Enumeration of all base prices for use with Prices.
@ BuildVehicleWagon
Price for purchasing new wagons.
@ BuildVehicleTrain
Price for purchasing new train engines.
@ BuildVehicleShip
Price for purchasing new ships.
@ Invalid
Invalid base price.
@ BuildVehicleAircraft
Price for purchasing new aircrafts.
@ RunningAircraft
Running cost of aircrafts.
@ BuildVehicleRoad
Price for purchasing new road vehicles.
@ RunningShip
Running cost of ships.
void ClearEnginesHiddenFlagOfCompany(CompanyID cid)
Clear the 'hidden' flag for all engines of a new company.
Definition engine.cpp:1044
void SetYearEngineAgingStops()
Compute the value for _year_engine_aging_stops.
Definition engine.cpp:732
static void NewVehicleAvailable(Engine *e)
An engine has become available for general use.
Definition engine.cpp:1119
void SetupEngines()
Initialise the engine pool with the data from the original vehicles.
Definition engine.cpp:638
static CompanyID GetPreviewCompany(Engine *e)
Get the best company for an engine preview.
Definition engine.cpp:954
static void ClearLastVariant(EngineID engine_id, VehicleType type)
Ensure engine is not set as the last used variant for any other engine.
Definition engine.cpp:673
uint8_t GetOriginalEngineOffset(VehicleType type)
Get the index offset for original engines of a VehicleType.
Definition engine.cpp:80
static bool IsVehicleTypeDisabled(VehicleType type, bool ai)
Checks if a vehicle type is disabled for all/ai companies.
Definition engine.cpp:988
static void AcceptEnginePreview(EngineID eid, CompanyID company, int recursion_depth=0)
Company company accepts engine eid for preview.
Definition engine.cpp:922
CommandCost CmdRenameEngine(DoCommandFlags flags, EngineID engine_id, const std::string &text)
Rename an engine.
Definition engine.cpp:1252
static const IntervalTimer< TimerGameCalendar > _calendar_engines_daily({TimerGameCalendar::Trigger::Day, TimerGameCalendar::Priority::Engine}, [](auto) { for(Company *c :Company::Iterate()) { c->avail_railtypes=AddDateIntroducedRailTypes(c->avail_railtypes, TimerGameCalendar::date);c->avail_roadtypes=AddDateIntroducedRoadTypes(c->avail_roadtypes, TimerGameCalendar::date);} if(TimerGameCalendar::year >=_year_engine_aging_stops) return;for(Engine *e :Engine::Iterate()) { EngineID i=e->index;if(e->flags.Test(EngineFlag::ExclusivePreview)) { if(e->preview_company !=CompanyID::Invalid()) { if(!--e->preview_wait) { InvalidateWindowClassesData(WindowClass::EnginePreview);e->preview_company=CompanyID::Invalid();} } else if(e->preview_asked.Count()< MAX_COMPANIES) { e->preview_company=GetPreviewCompany(e);if(e->preview_company==CompanyID::Invalid()) { e->preview_asked.Set();continue;} e->preview_asked.Set(e->preview_company);e->preview_wait=20;if(!IsVehicleTypeDisabled(e->type, true)) AI::NewEvent(e->preview_company, new ScriptEventEnginePreview(i));if(IsInteractiveCompany(e->preview_company)) ShowEnginePreviewWindow(i);} } } })
Daily check to offer an exclusive engine preview to the companies.
CommandCost CmdWantEnginePreview(DoCommandFlags flags, EngineID engine_id)
Accept an engine prototype.
Definition engine.cpp:1079
void CalendarEnginesMonthlyLoop()
Monthly update of the availability, reliability, and preview offers of the engines.
Definition engine.cpp:1179
static bool IsUniqueEngineName(const std::string &name)
Is name still free as name for an engine?
Definition engine.cpp:1236
bool IsEngineBuildable(EngineID engine, VehicleType type, CompanyID company)
Check if an engine is buildable.
Definition engine.cpp:1286
uint8_t GetOriginalEngineCount(VehicleType type)
Get the number of original engines for a VehicleType.
Definition engine.cpp:61
static TimerGameCalendar::Year _year_engine_aging_stops
Year that engine aging stops.
Definition engine.cpp:54
static void DisableEngineForCompany(EngineID eid, CompanyID company)
Forbids engine eid to be used by a company company.
Definition engine.cpp:898
void StartupEngines()
Start/initialise all our engines.
Definition engine.cpp:838
static bool IsWagon(EngineID index)
Determine whether an engine type is a wagon (and not a loco).
Definition engine.cpp:662
CommandCost CmdEngineCtrl(DoCommandFlags flags, EngineID engine_id, CompanyID company_id, bool allow)
Allow or forbid a specific company to use an engine.
Definition engine.cpp:1097
void StartupOneEngine(Engine *e, const TimerGameCalendar::YearMonthDay &aging_ymd, uint32_t seed)
Start/initialise one engine.
Definition engine.cpp:757
void CheckEngines()
Check for engines that have an appropriate availability.
Definition engine.cpp:1351
bool IsEngineRefittable(EngineID engine)
Check if an engine is refittable.
Definition engine.cpp:1327
CommandCost CmdSetVehicleVisibility(DoCommandFlags flags, EngineID engine_id, bool hide)
Set the visibility of an engine.
Definition engine.cpp:1058
void CalcEngineReliability(Engine *e, bool new_month)
Update Engine::reliability and (if needed) update the engine GUIs.
Definition engine.cpp:685
static void EnableEngineForCompany(EngineID eid, CompanyID company)
Allows engine eid to be used by a company company.
Definition engine.cpp:870
Base class for engines.
Functions related to engines.
StringID GetEngineCategoryName(EngineID engine)
Return the category of an engine.
Engine GUI functions, used by build_vehicle_gui and autoreplace_gui.
@ AIR_CTOL
Conventional Take Off and Landing, i.e. planes.
@ SyncReliability
Engine reliability will be synced with variant parent.
@ NoNews
No 'new vehicle' news will be generated.
@ JoinPreview
Engine will join exclusive preview with variant parent.
@ NoPreview
No exclusive preview will be offered.
@ NoDefaultCargoMultiplier
Use the new capacity algorithm. The default cargotype of the vehicle does not affect capacity multipl...
static const uint MAX_LENGTH_ENGINE_NAME_CHARS
The maximum length of an engine name in characters including '\0'.
PoolID< uint16_t, struct EngineIDTag, 64000, 0xFFFF > EngineID
Unique identification number of an engine.
Definition engine_type.h:25
uint64_t PackEngineNameDParam(EngineID engine_id, EngineNameContext context, uint32_t extra_data=0)
Combine an engine ID and a name context to an engine name StringParameter.
@ Available
This vehicle is available to everyone.
@ ExclusivePreview
This vehicle is in the exclusive preview stage, either being used or being offered to a company.
@ PreviewNews
Name is shown in exclusive preview or newspaper.
@ Multihead
indicates a combination of two locomotives
Definition engine_type.h:32
@ Wagon
simple wagon, not motorized
Definition engine_type.h:33
This file contains all the data for vehicles.
constexpr std::underlying_type_t< enum_type > to_underlying(enum_type e)
Implementation of std::to_underlying (from C++23).
Definition enum_type.hpp:21
Functions related to errors.
@ Warning
Other information.
Definition error.h:23
void ShowErrorMessage(EncodedString &&summary_msg, int x, int y, CommandCost &cc)
Display an error message in a window.
uint GetGroupNumEngines(CompanyID company, GroupID id_g, EngineID id_e)
Get the number of engines with EngineID id_e in the group with GroupID id_g and its sub-groups.
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
Definition gfx.cpp:1548
static constexpr GroupID ALL_GROUP
All vehicles are in this group.
Definition group_type.h:17
Base for the NewGRF implementation.
constexpr uint32_t FlattenNewGRFLabel(T label)
Flatten a NewGRF related label to a 32 bits integer.
Definition newgrf.h:262
void ReloadNewGRFData()
Reload all NewGRF files during a running game.
@ RefitCapacity
Cargo capacity after refit.
@ CargoSuffix
Show suffix after cargo name.
@ CBID_VEHICLE_REFIT_CAPACITY
Refit capacity, the passed vehicle needs to have its ->cargo_type set to the cargo we are refitting t...
static const uint CALLBACK_FAILED
Different values for Callback result evaluations.
uint16_t GetVehicleCallback(CallbackID callback, uint32_t param1, uint32_t param2, EngineID engine, const Vehicle *v, std::span< int32_t > regs100)
Evaluate a newgrf callback for vehicles.
Functions for NewGRF engines.
@ PROP_AIRCRAFT_PASSENGER_CAPACITY
Passenger Capacity.
@ PROP_ROADVEH_WEIGHT
Weight in 1/4 t.
@ PROP_TRAIN_COST_FACTOR
Purchase cost (if dualheaded: sum of both vehicles).
@ PROP_TRAIN_WEIGHT
Weight in t (if dualheaded: for each single vehicle).
@ PROP_AIRCRAFT_RANGE
Aircraft range.
@ PROP_TRAIN_CARGO_CAPACITY
Capacity (if dualheaded: for each single vehicle).
@ PROP_AIRCRAFT_RUNNING_COST_FACTOR
Yearly runningcost.
@ PROP_ROADVEH_RUNNING_COST_FACTOR
Yearly runningcost.
@ PROP_TRAIN_TRACTIVE_EFFORT
Tractive effort coefficient in 1/256.
@ PROP_SHIP_CARGO_CAPACITY
Capacity.
@ PROP_ROADVEH_TRACTIVE_EFFORT
Tractive effort coefficient in 1/256.
@ PROP_SHIP_COST_FACTOR
Purchase cost.
@ PROP_ROADVEH_CARGO_CAPACITY
Capacity.
@ PROP_AIRCRAFT_SPEED
Max. speed: 1 unit = 8 mph = 12.8 km-ish/h.
@ PROP_AIRCRAFT_MAIL_CAPACITY
Mail Capacity.
@ PROP_SHIP_SPEED
Max. speed: 1 unit = 1/3.2 mph = 0.5 km-ish/h.
@ PROP_SHIP_RUNNING_COST_FACTOR
Yearly runningcost.
@ PROP_ROADVEH_COST_FACTOR
Purchase cost.
@ PROP_ROADVEH_POWER
Power in 10 HP.
@ PROP_AIRCRAFT_COST_FACTOR
Purchase cost.
@ PROP_TRAIN_RUNNING_COST_FACTOR
Yearly runningcost (if dualheaded: sum of both vehicles).
@ PROP_TRAIN_POWER
Power in hp (if dualheaded: sum of both vehicles).
@ PROP_TRAIN_SPEED
Max. speed: 1 unit = 1/1.6 mph = 1 km-ish/h.
@ PROP_ROADVEH_SPEED
Max. speed: 1 unit = 1/0.8 mph = 2 km-ish/h.
static const GrfID INVALID_GRFID
An invalid NewGRF.
Definition newgrf_type.h:19
Label< struct GrfIDTag > GrfID
The unique identifier of a NewGRF.
Definition newgrf_type.h:17
Functions related to news.
void AddNewsItem(EncodedString &&headline, NewsType type, NewsStyle style, NewsFlags flags, NewsReference ref1={}, NewsReference ref2={}, std::unique_ptr< NewsAllocatedData > &&data=nullptr, AdviceType advice_type=AdviceType::Invalid)
Add a new newsitem to be shown.
Definition news_gui.cpp:919
@ NewVehicles
New vehicle has become available.
Definition news_type.h:45
@ Vehicle
Vehicle news item. (new engine available).
Definition news_type.h:84
Some methods of Pool are placed here in order to reduce compilation time and binary size.
#define INSTANTIATE_POOL_METHODS(name)
Force instantiation of pool methods so we don't get linker errors.
RailTypes GetCompanyRailTypes(CompanyID company, bool introduces)
Get the rail types the given company can build.
Definition rail.cpp:137
RailTypes AddDateIntroducedRailTypes(RailTypes current, TimerGameCalendar::Date date)
Add the rail types that are to be introduced at the given date.
Definition rail.cpp:104
Rail specific functions.
RailTypes GetAllIntroducesRailTypes(RailTypes railtypes)
Returns all introduced railtypes for a set of railtypes.
Definition rail.h:356
RailTypes GetAllCompatibleRailTypes(RailTypes railtypes)
Returns all compatible railtypes for a set of railtypes.
Definition rail.h:332
EnumBitSet< RailType, uint64_t > RailTypes
Bitset of RailType elements.
Definition rail_type.h:37
void SetRandomSeed(uint32_t seed)
(Re)set the state of the random number generators.
Pseudo random number generator.
void SaveRandomSeeds(SavedRandomSeeds *storage)
Saves the current seeds.
void RestoreRandomSeeds(const SavedRandomSeeds &storage)
Restores previously saved seeds.
RoadTypes GetCompanyRoadTypes(CompanyID company, bool introduces)
Get the road types the given company can build.
Definition road.cpp:209
RoadTypes AddDateIntroducedRoadTypes(RoadTypes current, TimerGameCalendar::Date date)
Add the road types that are to be introduced at the given date.
Definition road.cpp:176
const RoadTypeInfo * GetRoadTypeInfo(RoadType roadtype)
Returns a pointer to the Roadtype information for a given roadtype.
Definition road.h:217
Functions related to roads.
@ ROADTYPE_END
Used for iterations.
Definition road_type.h:28
A number of safeguards to prevent using unsafe methods.
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition settings.cpp:61
Definition of base types and functions in a cross-platform compatible way.
#define lengthof(array)
Return the length of an fixed size array.
Definition stdafx.h:261
size_t Utf8StringLength(std::string_view str)
Get the length of an UTF-8 encoded string in number of characters and thus not the number of bytes th...
Definition string.cpp:350
Functions related to low-level strings.
EncodedString GetEncodedString(StringID str)
Encode a string with no parameters into an encoded string.
Definition strings.cpp:89
Functions related to OTTD's strings.
StrongType::Typedef< uint32_t, struct StringIDTag, StrongType::Compare, StrongType::Integer > StringID
Numeric value that represents a string, independent of the selected language.
Information about a aircraft vehicle.
uint16_t multiplier
Capacity multiplier for vehicles. (8 fractional bits).
Definition cargotype.h:82
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo type.
Definition cargotype.h:140
RoadTypes avail_roadtypes
Road types available to this company.
RailTypes avail_railtypes
Rail types available to this company.
Projection to get a unique key of an EngineIDMapping, used for sorting in EngineOverrideManager.
static uint64_t Key(GrfID grfid, uint16_t internal_id)
Create a 64 bit key from the GRFID and internal ID for mappings.
uint64_t Key() const
Create a 64 bit key from this mapping.
Information about a vehicle.
TimerGameCalendar::Year base_life
Basic duration of engine availability (without random parts). 0xFF means infinite life.
LandscapeTypes climates
Climates supported by the engine.
EngineID variant_id
Engine variant ID. If set, will be treated specially in purchase lists.
VehicleCallbackMasks callback_mask
Bitmask of vehicle callbacks that have to be called.
TimerGameCalendar::Date base_intro
Basic date of engine introduction (without random parts).
int8_t retire_early
Number of years early to retire vehicle.
TimerGameCalendar::Year lifelength
Lifetime of a single vehicle.
Stores the mapping of EngineID to the internal id of newgrfs.
static bool ResetToCurrentNewGRFConfig()
Tries to reset the engine mapping to match the current NewGRF configuration.
Definition engine.cpp:622
void ResetToDefaultMapping()
Initializes the EngineOverrideManager with the default engines.
Definition engine.cpp:538
EngineID GetID(VehicleType type, uint16_t grf_local_id, GrfID grfid)
Looks up an EngineID in the EngineOverrideManager.
Definition engine.cpp:559
void SetID(VehicleType type, uint16_t grf_local_id, GrfID grfid, uint8_t substitute_id, EngineID engine)
Create an override to the given engine.
Definition engine.cpp:605
EngineID UseUnreservedID(VehicleType type, uint16_t grf_local_id, GrfID grfid, bool static_access)
Look for an unreserved EngineID matching the local id, and reserve it if found.
Definition engine.cpp:578
Dynamic data of a loaded NewGRF.
Definition newgrf.h:126
GrfID grfid
The GRF ID.
Definition newgrf.h:128
static Pool::IterateWrapper< Vehicle > Iterate(size_t from=0)
static T * CreateAtIndex(EngineID index, Targs &&... args)
static Engine * Get(auto index)
static bool IsValidID(auto index)
static Engine * GetIfValid(auto index)
Information about a rail vehicle.
Definition engine_type.h:73
RailTypes railtypes
Railtypes, mangled if elrail is disabled.
Definition engine_type.h:77
RailVehicleType railveh_type
Type of rail vehicle.
Definition engine_type.h:75
Information about a road vehicle.
RoadType roadtype
Road type.
Stores the state of all random number generators.
Information about a ship vehicle.
Definition engine_type.h:98
Vehicle data structure.
EngineID engine_type
The type of engine used for this vehicle.
CargoType cargo_type
type of cargo this vehicle is carrying
uint8_t cargo_subtype
Used for livery refits (NewGRF variations).
Definition of Interval and OneShot timers.
Definition of the game-calendar-timer.
Definition of the tick-based game-timer.
@ Water
Transport over water.
@ Air
Transport through air.
@ Road
Transport by road vehicle.
Base class for all vehicles.
Functions related to vehicles.
bool IsCompanyBuildableVehicleType(VehicleType type)
Is the given vehicle type buildable by a company?
VehicleType
Available vehicle types.
@ Ship
Ship vehicle type.
@ Invalid
Non-existing type of vehicle.
@ CompanyEnd
Last company-ownable type.
@ Aircraft
Aircraft vehicle type.
@ Road
Road vehicle type.
@ Train
Train vehicle type.
EnumIndexArray< T, VehicleType, Tend > VehicleTypeIndexArray
Array with VehicleType as index.
static const int GROUND_ACCELERATION
Acceleration due to gravity, 9.8 m/s^2.
void CloseWindowByClass(WindowClass cls, int data)
Close all windows of a given class.
Definition window.cpp:1255
void SetWindowClassesDirty(WindowClass cls)
Mark all windows of a particular class as dirty (in need of repainting).
Definition window.cpp:3285
void InvalidateWindowData(WindowClass cls, WindowNumber number, int data, bool gui_scope)
Mark window data of the window of a given class and specific window number as invalid (in need of re-...
Definition window.cpp:3377
void InvalidateWindowClassesData(WindowClass cls, int data, bool gui_scope)
Mark window data of all windows of a given class as invalid (in need of re-computing) Note that by de...
Definition window.cpp:3395
Window functions not directly related to making/drawing windows.