Change: Reword Finance window's Net Profit to Profit
[openttd-github.git] / src / engine.cpp
blobd1e9cc472fee15bddd965a9de298e9ca8638116f
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 <http://www.gnu.org/licenses/>.
6 */
8 /** @file engine.cpp Base for all engine handling. */
10 #include "stdafx.h"
11 #include "company_func.h"
12 #include "command_func.h"
13 #include "news_func.h"
14 #include "aircraft.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 "date_func.h"
21 #include "autoreplace_gui.h"
22 #include "string_func.h"
23 #include "ai/ai.hpp"
24 #include "core/pool_func.hpp"
25 #include "engine_gui.h"
26 #include "engine_func.h"
27 #include "engine_base.h"
28 #include "company_base.h"
29 #include "vehicle_func.h"
30 #include "articulated_vehicles.h"
31 #include "error.h"
32 #include "engine_base.h"
34 #include "table/strings.h"
35 #include "table/engines.h"
37 #include "safeguards.h"
39 EnginePool _engine_pool("Engine");
40 INSTANTIATE_POOL_METHODS(Engine)
42 EngineOverrideManager _engine_mngr;
44 /**
45 * Year that engine aging stops. Engines will not reduce in reliability
46 * and no more engines will be introduced
48 static Year _year_engine_aging_stops;
50 /** Number of engines of each vehicle type in original engine data */
51 const uint8 _engine_counts[4] = {
52 lengthof(_orig_rail_vehicle_info),
53 lengthof(_orig_road_vehicle_info),
54 lengthof(_orig_ship_vehicle_info),
55 lengthof(_orig_aircraft_vehicle_info),
58 /** Offset of the first engine of each vehicle type in original engine data */
59 const uint8 _engine_offsets[4] = {
61 lengthof(_orig_rail_vehicle_info),
62 lengthof(_orig_rail_vehicle_info) + lengthof(_orig_road_vehicle_info),
63 lengthof(_orig_rail_vehicle_info) + lengthof(_orig_road_vehicle_info) + lengthof(_orig_ship_vehicle_info),
66 static_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));
68 const uint EngineOverrideManager::NUM_DEFAULT_ENGINES = _engine_counts[VEH_TRAIN] + _engine_counts[VEH_ROAD] + _engine_counts[VEH_SHIP] + _engine_counts[VEH_AIRCRAFT];
70 Engine::Engine(VehicleType type, EngineID base)
72 this->type = type;
73 this->grf_prop.local_id = base;
74 this->list_position = base;
75 this->preview_company = INVALID_COMPANY;
77 /* Check if this base engine is within the original engine data range */
78 if (base >= _engine_counts[type]) {
79 /* 'power' defaults to zero, so we also have to default to 'wagon' */
80 if (type == VEH_TRAIN) this->u.rail.railveh_type = RAILVEH_WAGON;
81 /* Set model life to maximum to make wagons available */
82 this->info.base_life = 0xFF;
83 /* Set road vehicle tractive effort to the default value */
84 if (type == VEH_ROAD) this->u.road.tractive_effort = 0x4C;
85 /* Aircraft must have CT_INVALID as default, as there is no property */
86 if (type == VEH_AIRCRAFT) this->info.cargo_type = CT_INVALID;
87 /* Set visual effect to the default value */
88 switch (type) {
89 case VEH_TRAIN: this->u.rail.visual_effect = VE_DEFAULT; break;
90 case VEH_ROAD: this->u.road.visual_effect = VE_DEFAULT; break;
91 case VEH_SHIP: this->u.ship.visual_effect = VE_DEFAULT; break;
92 default: break; // The aircraft, disasters and especially visual effects have no NewGRF configured visual effects
94 /* Set cargo aging period to the default value. */
95 this->info.cargo_age_period = CARGO_AGING_TICKS;
96 return;
99 /* Copy the original engine info for this slot */
100 this->info = _orig_engine_info[_engine_offsets[type] + base];
102 /* Copy the original engine data for this slot */
103 switch (type) {
104 default: NOT_REACHED();
106 case VEH_TRAIN:
107 this->u.rail = _orig_rail_vehicle_info[base];
108 this->original_image_index = this->u.rail.image_index;
109 this->info.string_id = STR_VEHICLE_NAME_TRAIN_ENGINE_RAIL_KIRBY_PAUL_TANK_STEAM + base;
111 /* Set the default model life of original wagons to "infinite" */
112 if (this->u.rail.railveh_type == RAILVEH_WAGON) this->info.base_life = 0xFF;
114 break;
116 case VEH_ROAD:
117 this->u.road = _orig_road_vehicle_info[base];
118 this->original_image_index = this->u.road.image_index;
119 this->info.string_id = STR_VEHICLE_NAME_ROAD_VEHICLE_MPS_REGAL_BUS + base;
120 break;
122 case VEH_SHIP:
123 this->u.ship = _orig_ship_vehicle_info[base];
124 this->original_image_index = this->u.ship.image_index;
125 this->info.string_id = STR_VEHICLE_NAME_SHIP_MPS_OIL_TANKER + base;
126 break;
128 case VEH_AIRCRAFT:
129 this->u.air = _orig_aircraft_vehicle_info[base];
130 this->original_image_index = this->u.air.image_index;
131 this->info.string_id = STR_VEHICLE_NAME_AIRCRAFT_SAMPSON_U52 + base;
132 break;
137 * Checks whether the engine is a valid (non-articulated part of an) engine.
138 * @return true if enabled
140 bool Engine::IsEnabled() const
142 return this->info.string_id != STR_NEWGRF_INVALID_ENGINE && HasBit(this->info.climates, _settings_game.game_creation.landscape);
146 * Retrieve the GRF ID of the NewGRF the engine is tied to.
147 * This is the GRF providing the Action 3.
148 * @return GRF ID of the associated NewGRF.
150 uint32 Engine::GetGRFID() const
152 const GRFFile *file = this->GetGRF();
153 return file == nullptr ? 0 : file->grfid;
157 * Determines whether an engine can carry something.
158 * A vehicle cannot carry anything if its capacity is zero, or none of the possible cargoes is available in the climate.
159 * @return true if the vehicle can carry something.
161 bool Engine::CanCarryCargo() const
163 /* For engines that can appear in a consist (i.e. rail vehicles and (articulated) road vehicles), a capacity
164 * of zero is a special case, to define the vehicle to not carry anything. The default cargotype is still used
165 * for livery selection etc.
166 * Note: Only the property is tested. A capacity callback returning 0 does not have the same effect.
168 switch (this->type) {
169 case VEH_TRAIN:
170 if (this->u.rail.capacity == 0) return false;
171 break;
173 case VEH_ROAD:
174 if (this->u.road.capacity == 0) return false;
175 break;
177 case VEH_SHIP:
178 case VEH_AIRCRAFT:
179 break;
181 default: NOT_REACHED();
183 return this->GetDefaultCargoType() != CT_INVALID;
188 * Determines capacity of a given vehicle from scratch.
189 * For aircraft the main capacity is determined. Mail might be present as well.
190 * @param v Vehicle of interest; nullptr in purchase list
191 * @param mail_capacity returns secondary cargo (mail) capacity of aircraft
192 * @return Capacity
194 uint Engine::DetermineCapacity(const Vehicle *v, uint16 *mail_capacity) const
196 assert(v == nullptr || this->index == v->engine_type);
197 if (mail_capacity != nullptr) *mail_capacity = 0;
199 if (!this->CanCarryCargo()) return 0;
201 bool new_multipliers = HasBit(this->info.misc_flags, EF_NO_DEFAULT_CARGO_MULTIPLIER);
202 CargoID default_cargo = this->GetDefaultCargoType();
203 CargoID cargo_type = (v != nullptr) ? v->cargo_type : default_cargo;
205 if (mail_capacity != nullptr && this->type == VEH_AIRCRAFT && IsCargoInClass(cargo_type, CC_PASSENGERS)) {
206 *mail_capacity = GetEngineProperty(this->index, PROP_AIRCRAFT_MAIL_CAPACITY, this->u.air.mail_capacity, v);
209 /* Check the refit capacity callback if we are not in the default configuration, or if we are using the new multiplier algorithm. */
210 if (HasBit(this->info.callback_mask, CBM_VEHICLE_REFIT_CAPACITY) &&
211 (new_multipliers || default_cargo != cargo_type || (v != nullptr && v->cargo_subtype != 0))) {
212 uint16 callback = GetVehicleCallback(CBID_VEHICLE_REFIT_CAPACITY, 0, 0, this->index, v);
213 if (callback != CALLBACK_FAILED) return callback;
216 /* Get capacity according to property resp. CB */
217 uint capacity;
218 uint extra_mail_cap = 0;
219 switch (this->type) {
220 case VEH_TRAIN:
221 capacity = GetEngineProperty(this->index, PROP_TRAIN_CARGO_CAPACITY, this->u.rail.capacity, v);
223 /* In purchase list add the capacity of the second head. Always use the plain property for this. */
224 if (v == nullptr && this->u.rail.railveh_type == RAILVEH_MULTIHEAD) capacity += this->u.rail.capacity;
225 break;
227 case VEH_ROAD:
228 capacity = GetEngineProperty(this->index, PROP_ROADVEH_CARGO_CAPACITY, this->u.road.capacity, v);
229 break;
231 case VEH_SHIP:
232 capacity = GetEngineProperty(this->index, PROP_SHIP_CARGO_CAPACITY, this->u.ship.capacity, v);
233 break;
235 case VEH_AIRCRAFT:
236 capacity = GetEngineProperty(this->index, PROP_AIRCRAFT_PASSENGER_CAPACITY, this->u.air.passenger_capacity, v);
237 if (!IsCargoInClass(cargo_type, CC_PASSENGERS)) {
238 extra_mail_cap = GetEngineProperty(this->index, PROP_AIRCRAFT_MAIL_CAPACITY, this->u.air.mail_capacity, v);
240 if (!new_multipliers && cargo_type == CT_MAIL) return capacity + extra_mail_cap;
241 default_cargo = CT_PASSENGERS; // Always use 'passengers' wrt. cargo multipliers
242 break;
244 default: NOT_REACHED();
247 if (!new_multipliers) {
248 /* Use the passenger multiplier for mail as well */
249 capacity += extra_mail_cap;
250 extra_mail_cap = 0;
253 /* Apply multipliers depending on cargo- and vehicletype. */
254 if (new_multipliers || (this->type != VEH_SHIP && default_cargo != cargo_type)) {
255 uint16 default_multiplier = new_multipliers ? 0x100 : CargoSpec::Get(default_cargo)->multiplier;
256 uint16 cargo_multiplier = CargoSpec::Get(cargo_type)->multiplier;
257 capacity *= cargo_multiplier;
258 if (extra_mail_cap > 0) {
259 uint mail_multiplier = CargoSpec::Get(CT_MAIL)->multiplier;
260 capacity += (default_multiplier * extra_mail_cap * cargo_multiplier + mail_multiplier / 2) / mail_multiplier;
262 capacity = (capacity + default_multiplier / 2) / default_multiplier;
265 return capacity;
269 * Return how much the running costs of this engine are.
270 * @return Yearly running cost of the engine.
272 Money Engine::GetRunningCost() const
274 Price base_price;
275 uint cost_factor;
276 switch (this->type) {
277 case VEH_ROAD:
278 base_price = this->u.road.running_cost_class;
279 if (base_price == INVALID_PRICE) return 0;
280 cost_factor = GetEngineProperty(this->index, PROP_ROADVEH_RUNNING_COST_FACTOR, this->u.road.running_cost);
281 break;
283 case VEH_TRAIN:
284 base_price = this->u.rail.running_cost_class;
285 if (base_price == INVALID_PRICE) return 0;
286 cost_factor = GetEngineProperty(this->index, PROP_TRAIN_RUNNING_COST_FACTOR, this->u.rail.running_cost);
287 break;
289 case VEH_SHIP:
290 base_price = PR_RUNNING_SHIP;
291 cost_factor = GetEngineProperty(this->index, PROP_SHIP_RUNNING_COST_FACTOR, this->u.ship.running_cost);
292 break;
294 case VEH_AIRCRAFT:
295 base_price = PR_RUNNING_AIRCRAFT;
296 cost_factor = GetEngineProperty(this->index, PROP_AIRCRAFT_RUNNING_COST_FACTOR, this->u.air.running_cost);
297 break;
299 default: NOT_REACHED();
302 return GetPrice(base_price, cost_factor, this->GetGRF(), -8);
306 * Return how much a new engine costs.
307 * @return Cost of the engine.
309 Money Engine::GetCost() const
311 Price base_price;
312 uint cost_factor;
313 switch (this->type) {
314 case VEH_ROAD:
315 base_price = PR_BUILD_VEHICLE_ROAD;
316 cost_factor = GetEngineProperty(this->index, PROP_ROADVEH_COST_FACTOR, this->u.road.cost_factor);
317 break;
319 case VEH_TRAIN:
320 if (this->u.rail.railveh_type == RAILVEH_WAGON) {
321 base_price = PR_BUILD_VEHICLE_WAGON;
322 cost_factor = GetEngineProperty(this->index, PROP_TRAIN_COST_FACTOR, this->u.rail.cost_factor);
323 } else {
324 base_price = PR_BUILD_VEHICLE_TRAIN;
325 cost_factor = GetEngineProperty(this->index, PROP_TRAIN_COST_FACTOR, this->u.rail.cost_factor);
327 break;
329 case VEH_SHIP:
330 base_price = PR_BUILD_VEHICLE_SHIP;
331 cost_factor = GetEngineProperty(this->index, PROP_SHIP_COST_FACTOR, this->u.ship.cost_factor);
332 break;
334 case VEH_AIRCRAFT:
335 base_price = PR_BUILD_VEHICLE_AIRCRAFT;
336 cost_factor = GetEngineProperty(this->index, PROP_AIRCRAFT_COST_FACTOR, this->u.air.cost_factor);
337 break;
339 default: NOT_REACHED();
342 return GetPrice(base_price, cost_factor, this->GetGRF(), -8);
346 * Returns max speed of the engine for display purposes
347 * @return max speed in km-ish/h
349 uint Engine::GetDisplayMaxSpeed() const
351 switch (this->type) {
352 case VEH_TRAIN:
353 return GetEngineProperty(this->index, PROP_TRAIN_SPEED, this->u.rail.max_speed);
355 case VEH_ROAD: {
356 uint max_speed = GetEngineProperty(this->index, PROP_ROADVEH_SPEED, 0);
357 return (max_speed != 0) ? max_speed * 2 : this->u.road.max_speed / 2;
360 case VEH_SHIP:
361 return GetEngineProperty(this->index, PROP_SHIP_SPEED, this->u.ship.max_speed) / 2;
363 case VEH_AIRCRAFT: {
364 uint max_speed = GetEngineProperty(this->index, PROP_AIRCRAFT_SPEED, 0);
365 if (max_speed != 0) {
366 return (max_speed * 128) / 10;
368 return this->u.air.max_speed;
371 default: NOT_REACHED();
376 * Returns the power of the engine for display
377 * and sorting purposes.
378 * Only trains and road vehicles have power
379 * @return power in display units hp
381 uint Engine::GetPower() const
383 /* Only trains and road vehicles have 'power'. */
384 switch (this->type) {
385 case VEH_TRAIN:
386 return GetEngineProperty(this->index, PROP_TRAIN_POWER, this->u.rail.power);
387 case VEH_ROAD:
388 return GetEngineProperty(this->index, PROP_ROADVEH_POWER, this->u.road.power) * 10;
390 default: NOT_REACHED();
395 * Returns the weight of the engine for display purposes.
396 * For dual-headed train-engines this is the weight of both heads
397 * @return weight in display units metric tons
399 uint Engine::GetDisplayWeight() const
401 /* Only trains and road vehicles have 'weight'. */
402 switch (this->type) {
403 case VEH_TRAIN:
404 return GetEngineProperty(this->index, PROP_TRAIN_WEIGHT, this->u.rail.weight) << (this->u.rail.railveh_type == RAILVEH_MULTIHEAD ? 1 : 0);
405 case VEH_ROAD:
406 return GetEngineProperty(this->index, PROP_ROADVEH_WEIGHT, this->u.road.weight) / 4;
408 default: NOT_REACHED();
413 * Returns the tractive effort of the engine for display purposes.
414 * For dual-headed train-engines this is the tractive effort of both heads
415 * @return tractive effort in display units kN
417 uint Engine::GetDisplayMaxTractiveEffort() const
419 /* Only trains and road vehicles have 'tractive effort'. */
420 switch (this->type) {
421 case VEH_TRAIN:
422 return (GROUND_ACCELERATION * this->GetDisplayWeight() * GetEngineProperty(this->index, PROP_TRAIN_TRACTIVE_EFFORT, this->u.rail.tractive_effort)) / 256 / 1000;
423 case VEH_ROAD:
424 return (GROUND_ACCELERATION * this->GetDisplayWeight() * GetEngineProperty(this->index, PROP_ROADVEH_TRACTIVE_EFFORT, this->u.road.tractive_effort)) / 256 / 1000;
426 default: NOT_REACHED();
431 * Returns the vehicle's (not model's!) life length in days.
432 * @return the life length
434 Date Engine::GetLifeLengthInDays() const
436 /* Assume leap years; this gives the player a bit more than the given amount of years, but never less. */
437 return (this->info.lifelength + _settings_game.vehicle.extend_vehicle_life) * DAYS_IN_LEAP_YEAR;
441 * Get the range of an aircraft type.
442 * @return Range of the aircraft type in tiles or 0 if unlimited range.
444 uint16 Engine::GetRange() const
446 switch (this->type) {
447 case VEH_AIRCRAFT:
448 return GetEngineProperty(this->index, PROP_AIRCRAFT_RANGE, this->u.air.max_range);
450 default: NOT_REACHED();
455 * Get the name of the aircraft type for display purposes.
456 * @return Aircraft type string.
458 StringID Engine::GetAircraftTypeText() const
460 switch (this->type) {
461 case VEH_AIRCRAFT:
462 switch (this->u.air.subtype) {
463 case AIR_HELI: return STR_LIVERY_HELICOPTER;
464 case AIR_CTOL: return STR_LIVERY_SMALL_PLANE;
465 case AIR_CTOL | AIR_FAST: return STR_LIVERY_LARGE_PLANE;
466 default: NOT_REACHED();
469 default: NOT_REACHED();
474 * Initializes the #EngineOverrideManager with the default engines.
476 void EngineOverrideManager::ResetToDefaultMapping()
478 this->clear();
479 for (VehicleType type = VEH_TRAIN; type <= VEH_AIRCRAFT; type++) {
480 for (uint internal_id = 0; internal_id < _engine_counts[type]; internal_id++) {
481 EngineIDMapping &eid = this->emplace_back();
482 eid.type = type;
483 eid.grfid = INVALID_GRFID;
484 eid.internal_id = internal_id;
485 eid.substitute_id = internal_id;
491 * Looks up an EngineID in the EngineOverrideManager
492 * @param type Vehicle type
493 * @param grf_local_id The local id in the newgrf
494 * @param grfid The GrfID that defines the scope of grf_local_id.
495 * If a newgrf overrides the engines of another newgrf, the "scope grfid" is the ID of the overridden newgrf.
496 * If dynnamic_engines is disabled, all newgrf share the same ID scope identified by INVALID_GRFID.
497 * @return The engine ID if present, or INVALID_ENGINE if not.
499 EngineID EngineOverrideManager::GetID(VehicleType type, uint16 grf_local_id, uint32 grfid)
501 EngineID index = 0;
502 for (const EngineIDMapping &eid : *this) {
503 if (eid.type == type && eid.grfid == grfid && eid.internal_id == grf_local_id) {
504 return index;
506 index++;
508 return INVALID_ENGINE;
512 * Tries to reset the engine mapping to match the current NewGRF configuration.
513 * This is only possible when there are currently no vehicles in the game.
514 * @return false if resetting failed due to present vehicles.
516 bool EngineOverrideManager::ResetToCurrentNewGRFConfig()
518 for (const Vehicle *v : Vehicle::Iterate()) {
519 if (IsCompanyBuildableVehicleType(v)) return false;
522 /* Reset the engines, they will get new EngineIDs */
523 _engine_mngr.ResetToDefaultMapping();
524 ReloadNewGRFData();
526 return true;
530 * Initialise the engine pool with the data from the original vehicles.
532 void SetupEngines()
534 CloseWindowByClass(WC_ENGINE_PREVIEW);
535 _engine_pool.CleanPool();
537 assert(_engine_mngr.size() >= _engine_mngr.NUM_DEFAULT_ENGINES);
538 uint index = 0;
539 for (const EngineIDMapping &eid : _engine_mngr) {
540 /* Assert is safe; there won't be more than 256 original vehicles
541 * in any case, and we just cleaned the pool. */
542 assert(Engine::CanAllocateItem());
543 [[maybe_unused]] const Engine *e = new Engine(eid.type, eid.internal_id);
544 assert(e->index == index);
545 index++;
549 void ShowEnginePreviewWindow(EngineID engine);
552 * Determine whether an engine type is a wagon (and not a loco).
553 * @param index %Engine getting queried.
554 * @return Whether the queried engine is a wagon.
556 static bool IsWagon(EngineID index)
558 const Engine *e = Engine::Get(index);
559 return e->type == VEH_TRAIN && e->u.rail.railveh_type == RAILVEH_WAGON;
563 * Update #Engine::reliability and (if needed) update the engine GUIs.
564 * @param e %Engine to update.
566 static void CalcEngineReliability(Engine *e)
568 uint age = e->age;
570 /* Check for early retirement */
571 if (e->company_avail != 0 && !_settings_game.vehicle.never_expire_vehicles && e->info.base_life != 0xFF) {
572 int retire_early = e->info.retire_early;
573 uint retire_early_max_age = std::max(0, e->duration_phase_1 + e->duration_phase_2 - retire_early * 12);
574 if (retire_early != 0 && age >= retire_early_max_age) {
575 /* Early retirement is enabled and we're past the date... */
576 e->company_avail = 0;
577 AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
581 if (age < e->duration_phase_1) {
582 uint start = e->reliability_start;
583 e->reliability = age * (e->reliability_max - start) / e->duration_phase_1 + start;
584 } else if ((age -= e->duration_phase_1) < e->duration_phase_2 || _settings_game.vehicle.never_expire_vehicles || e->info.base_life == 0xFF) {
585 /* We are at the peak of this engines life. It will have max reliability.
586 * This is also true if the engines never expire. They will not go bad over time */
587 e->reliability = e->reliability_max;
588 } else if ((age -= e->duration_phase_2) < e->duration_phase_3) {
589 uint max = e->reliability_max;
590 e->reliability = (int)age * (int)(e->reliability_final - max) / e->duration_phase_3 + max;
591 } else {
592 /* time's up for this engine.
593 * We will now completely retire this design */
594 e->company_avail = 0;
595 e->reliability = e->reliability_final;
596 /* Kick this engine out of the lists */
597 AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
599 SetWindowClassesDirty(WC_BUILD_VEHICLE); // Update to show the new reliability
600 SetWindowClassesDirty(WC_REPLACE_VEHICLE);
603 /** Compute the value for #_year_engine_aging_stops. */
604 void SetYearEngineAgingStops()
606 /* Determine last engine aging year, default to 2050 as previously. */
607 _year_engine_aging_stops = 2050;
609 for (const Engine *e : Engine::Iterate()) {
610 const EngineInfo *ei = &e->info;
612 /* Exclude certain engines */
613 if (!HasBit(ei->climates, _settings_game.game_creation.landscape)) continue;
614 if (e->type == VEH_TRAIN && e->u.rail.railveh_type == RAILVEH_WAGON) continue;
616 /* Base year ending date on half the model life */
617 YearMonthDay ymd;
618 ConvertDateToYMD(ei->base_intro + (ei->lifelength * DAYS_IN_LEAP_YEAR) / 2, &ymd);
620 _year_engine_aging_stops = std::max(_year_engine_aging_stops, ymd.year);
625 * Start/initialise one engine.
626 * @param e The engine to initialise.
627 * @param aging_date The date used for age calculations.
629 void StartupOneEngine(Engine *e, Date aging_date)
631 const EngineInfo *ei = &e->info;
633 e->age = 0;
634 e->flags = 0;
635 e->company_avail = 0;
636 e->company_hidden = 0;
638 /* Vehicles with the same base_intro date shall be introduced at the same time.
639 * Make sure they use the same randomisation of the date. */
640 SavedRandomSeeds saved_seeds;
641 SaveRandomSeeds(&saved_seeds);
642 SetRandomSeed(_settings_game.game_creation.generation_seed ^
643 ei->base_intro ^
644 e->type ^
645 e->GetGRFID());
646 uint32 r = Random();
648 /* Don't randomise the start-date in the first two years after gamestart to ensure availability
649 * of engines in early starting games.
650 * Note: TTDP uses fixed 1922 */
651 e->intro_date = ei->base_intro <= ConvertYMDToDate(_settings_game.game_creation.starting_year + 2, 0, 1) ? ei->base_intro : (Date)GB(r, 0, 9) + ei->base_intro;
652 if (e->intro_date <= _date) {
653 e->age = (aging_date - e->intro_date) >> 5;
654 e->company_avail = (CompanyMask)-1;
655 e->flags |= ENGINE_AVAILABLE;
658 RestoreRandomSeeds(saved_seeds);
660 r = Random();
661 e->reliability_start = GB(r, 16, 14) + 0x7AE0;
662 e->reliability_max = GB(r, 0, 14) + 0xBFFF;
664 r = Random();
665 e->reliability_final = GB(r, 16, 14) + 0x3FFF;
666 e->duration_phase_1 = GB(r, 0, 5) + 7;
667 e->duration_phase_2 = GB(r, 5, 4) + ei->base_life * 12 - 96;
668 e->duration_phase_3 = GB(r, 9, 7) + 120;
670 e->reliability_spd_dec = ei->decay_speed << 2;
672 CalcEngineReliability(e);
674 /* prevent certain engines from ever appearing. */
675 if (!HasBit(ei->climates, _settings_game.game_creation.landscape)) {
676 e->flags |= ENGINE_AVAILABLE;
677 e->company_avail = 0;
682 * Start/initialise all our engines. Must be called whenever there are changes
683 * to the NewGRF config.
685 void StartupEngines()
687 /* Aging of vehicles stops, so account for that when starting late */
688 const Date aging_date = std::min(_date, ConvertYMDToDate(_year_engine_aging_stops, 0, 1));
690 for (Engine *e : Engine::Iterate()) {
691 StartupOneEngine(e, aging_date);
694 /* Update the bitmasks for the vehicle lists */
695 for (Company *c : Company::Iterate()) {
696 c->avail_railtypes = GetCompanyRailtypes(c->index);
697 c->avail_roadtypes = GetCompanyRoadTypes(c->index);
700 /* Invalidate any open purchase lists */
701 InvalidateWindowClassesData(WC_BUILD_VEHICLE);
705 * Allows engine \a eid to be used by a company \a company.
706 * @param eid The engine to enable.
707 * @param company The company to allow using the engine.
709 static void EnableEngineForCompany(EngineID eid, CompanyID company)
711 Engine *e = Engine::Get(eid);
712 Company *c = Company::Get(company);
714 SetBit(e->company_avail, company);
715 if (e->type == VEH_TRAIN) {
716 c->avail_railtypes = GetCompanyRailtypes(c->index);
717 } else if (e->type == VEH_ROAD) {
718 c->avail_roadtypes = GetCompanyRoadTypes(c->index);
721 if (company == _local_company) {
722 AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
724 /* Update the toolbar. */
725 InvalidateWindowData(WC_MAIN_TOOLBAR, 0);
726 if (e->type == VEH_ROAD) InvalidateWindowData(WC_BUILD_TOOLBAR, TRANSPORT_ROAD);
727 if (e->type == VEH_SHIP) InvalidateWindowData(WC_BUILD_TOOLBAR, TRANSPORT_WATER);
728 if (e->type == VEH_AIRCRAFT) InvalidateWindowData(WC_BUILD_TOOLBAR, TRANSPORT_AIR);
733 * Forbids engine \a eid to be used by a company \a company.
734 * @param eid The engine to disable.
735 * @param company The company to forbid using the engine.
737 static void DisableEngineForCompany(EngineID eid, CompanyID company)
739 Engine *e = Engine::Get(eid);
740 Company *c = Company::Get(company);
742 ClrBit(e->company_avail, company);
743 if (e->type == VEH_TRAIN) {
744 c->avail_railtypes = GetCompanyRailtypes(c->index);
745 } else if (e->type == VEH_ROAD) {
746 c->avail_roadtypes = GetCompanyRoadTypes(c->index);
749 if (company == _local_company) {
750 AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
755 * Company \a company accepts engine \a eid for preview.
756 * @param eid Engine being accepted (is under preview).
757 * @param company Current company previewing the engine.
759 static void AcceptEnginePreview(EngineID eid, CompanyID company)
761 Engine *e = Engine::Get(eid);
763 e->preview_company = INVALID_COMPANY;
764 e->preview_asked = (CompanyMask)-1;
766 EnableEngineForCompany(eid, company);
768 /* Notify preview window, that it might want to close.
769 * Note: We cannot directly close the window.
770 * In singleplayer this function is called from the preview window, so
771 * we have to use the GUI-scope scheduling of InvalidateWindowData.
773 InvalidateWindowData(WC_ENGINE_PREVIEW, eid);
777 * Get the best company for an engine preview.
778 * @param e Engine to preview.
779 * @return Best company if it exists, #INVALID_COMPANY otherwise.
781 static CompanyID GetPreviewCompany(Engine *e)
783 CompanyID best_company = INVALID_COMPANY;
785 /* For trains the cargomask has no useful meaning, since you can attach other wagons */
786 CargoTypes cargomask = e->type != VEH_TRAIN ? GetUnionOfArticulatedRefitMasks(e->index, true) : ALL_CARGOTYPES;
788 int32 best_hist = -1;
789 for (const Company *c : Company::Iterate()) {
790 if (c->block_preview == 0 && !HasBit(e->preview_asked, c->index) &&
791 c->old_economy[0].performance_history > best_hist) {
793 /* Check whether the company uses similar vehicles */
794 for (const Vehicle *v : Vehicle::Iterate()) {
795 if (v->owner != c->index || v->type != e->type) continue;
796 if (!v->GetEngine()->CanCarryCargo() || !HasBit(cargomask, v->cargo_type)) continue;
798 best_hist = c->old_economy[0].performance_history;
799 best_company = c->index;
800 break;
805 return best_company;
809 * Checks if a vehicle type is disabled for all/ai companies.
810 * @param type The vehicle type which shall be checked.
811 * @param ai If true, check if the type is disabled for AI companies, otherwise check if
812 * the vehicle type is disabled for human companies.
813 * @return Whether or not a vehicle type is disabled.
815 static bool IsVehicleTypeDisabled(VehicleType type, bool ai)
817 switch (type) {
818 case VEH_TRAIN: return _settings_game.vehicle.max_trains == 0 || (ai && _settings_game.ai.ai_disable_veh_train);
819 case VEH_ROAD: return _settings_game.vehicle.max_roadveh == 0 || (ai && _settings_game.ai.ai_disable_veh_roadveh);
820 case VEH_SHIP: return _settings_game.vehicle.max_ships == 0 || (ai && _settings_game.ai.ai_disable_veh_ship);
821 case VEH_AIRCRAFT: return _settings_game.vehicle.max_aircraft == 0 || (ai && _settings_game.ai.ai_disable_veh_aircraft);
823 default: NOT_REACHED();
827 /** Daily check to offer an exclusive engine preview to the companies. */
828 void EnginesDailyLoop()
830 for (Company *c : Company::Iterate()) {
831 c->avail_railtypes = AddDateIntroducedRailTypes(c->avail_railtypes, _date);
832 c->avail_roadtypes = AddDateIntroducedRoadTypes(c->avail_roadtypes, _date);
835 if (_cur_year >= _year_engine_aging_stops) return;
837 for (Engine *e : Engine::Iterate()) {
838 EngineID i = e->index;
839 if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) {
840 if (e->preview_company != INVALID_COMPANY) {
841 if (!--e->preview_wait) {
842 CloseWindowById(WC_ENGINE_PREVIEW, i);
843 e->preview_company = INVALID_COMPANY;
845 } else if (CountBits(e->preview_asked) < MAX_COMPANIES) {
846 e->preview_company = GetPreviewCompany(e);
848 if (e->preview_company == INVALID_COMPANY) {
849 e->preview_asked = (CompanyMask)-1;
850 continue;
853 SetBit(e->preview_asked, e->preview_company);
854 e->preview_wait = 20;
855 /* AIs are intentionally not skipped for preview even if they cannot build a certain
856 * vehicle type. This is done to not give poor performing human companies an "unfair"
857 * boost that they wouldn't have gotten against other human companies. The check on
858 * the line below is just to make AIs not notice that they have a preview if they
859 * cannot build the vehicle. */
860 if (!IsVehicleTypeDisabled(e->type, true)) AI::NewEvent(e->preview_company, new ScriptEventEnginePreview(i));
861 if (IsInteractiveCompany(e->preview_company)) ShowEnginePreviewWindow(i);
868 * Clear the 'hidden' flag for all engines of a new company.
869 * @param cid Company being created.
871 void ClearEnginesHiddenFlagOfCompany(CompanyID cid)
873 for (Engine *e : Engine::Iterate()) {
874 SB(e->company_hidden, cid, 1, 0);
879 * Set the visibility of an engine.
880 * @param flags Operation to perform.
881 * @param engine_id Engine id..
882 * @param hide Set for hidden, unset for visible.
883 * @return The cost of this operation or an error.
885 CommandCost CmdSetVehicleVisibility(DoCommandFlag flags, EngineID engine_id, bool hide)
887 Engine *e = Engine::GetIfValid(engine_id);
888 if (e == nullptr || _current_company >= MAX_COMPANIES) return CMD_ERROR;
889 if (!IsEngineBuildable(e->index, e->type, _current_company)) return CMD_ERROR;
891 if ((flags & DC_EXEC) != 0) {
892 SB(e->company_hidden, _current_company, 1, hide ? 1 : 0);
893 AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
896 return CommandCost();
900 * Accept an engine prototype. XXX - it is possible that the top-company
901 * changes while you are waiting to accept the offer? Then it becomes invalid
902 * @param flags operation to perform
903 * @param engine_id engine-prototype offered
904 * @return the cost of this operation or an error
906 CommandCost CmdWantEnginePreview(DoCommandFlag flags, EngineID engine_id)
908 Engine *e = Engine::GetIfValid(engine_id);
909 if (e == nullptr || !(e->flags & ENGINE_EXCLUSIVE_PREVIEW) || e->preview_company != _current_company) return CMD_ERROR;
911 if (flags & DC_EXEC) AcceptEnginePreview(engine_id, _current_company);
913 return CommandCost();
917 * Allow or forbid a specific company to use an engine
918 * @param flags operation to perform
919 * @param engine_id engine id
920 * @param company_id Company to allow/forbid the use of an engine.
921 * @param allow false to forbid, true to allow.
922 * @return the cost of this operation or an error
924 CommandCost CmdEngineCtrl(DoCommandFlag flags, EngineID engine_id, CompanyID company_id, bool allow)
926 if (_current_company != OWNER_DEITY) return CMD_ERROR;
928 if (!Engine::IsValidID(engine_id) || !Company::IsValidID(company_id)) return CMD_ERROR;
930 if (flags & DC_EXEC) {
931 if (allow) {
932 EnableEngineForCompany(engine_id, company_id);
933 } else {
934 DisableEngineForCompany(engine_id, company_id);
938 return CommandCost();
942 * An engine has become available for general use.
943 * Also handle the exclusive engine preview contract.
944 * @param e Engine generally available as of now.
946 static void NewVehicleAvailable(Engine *e)
948 EngineID index = e->index;
950 /* In case the company didn't build the vehicle during the intro period,
951 * prevent that company from getting future intro periods for a while. */
952 if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) {
953 for (Company *c : Company::Iterate()) {
954 uint block_preview = c->block_preview;
956 if (!HasBit(e->company_avail, c->index)) continue;
958 /* We assume the user did NOT build it.. prove me wrong ;) */
959 c->block_preview = 20;
961 for (const Vehicle *v : Vehicle::Iterate()) {
962 if (v->type == VEH_TRAIN || v->type == VEH_ROAD || v->type == VEH_SHIP ||
963 (v->type == VEH_AIRCRAFT && Aircraft::From(v)->IsNormalAircraft())) {
964 if (v->owner == c->index && v->engine_type == index) {
965 /* The user did prove me wrong, so restore old value */
966 c->block_preview = block_preview;
967 break;
974 e->flags = (e->flags & ~ENGINE_EXCLUSIVE_PREVIEW) | ENGINE_AVAILABLE;
975 AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
977 /* Now available for all companies */
978 e->company_avail = (CompanyMask)-1;
980 /* Do not introduce new rail wagons */
981 if (IsWagon(index)) return;
983 if (e->type == VEH_TRAIN) {
984 /* maybe make another rail type available */
985 assert(e->u.rail.railtype < RAILTYPE_END);
986 for (Company *c : Company::Iterate()) c->avail_railtypes = AddDateIntroducedRailTypes(c->avail_railtypes | GetRailTypeInfo(e->u.rail.railtype)->introduces_railtypes, _date);
987 } else if (e->type == VEH_ROAD) {
988 /* maybe make another road type available */
989 assert(e->u.road.roadtype < ROADTYPE_END);
990 for (Company* c : Company::Iterate()) c->avail_roadtypes = AddDateIntroducedRoadTypes(c->avail_roadtypes | GetRoadTypeInfo(e->u.road.roadtype)->introduces_roadtypes, _date);
993 /* Only broadcast event if AIs are able to build this vehicle type. */
994 if (!IsVehicleTypeDisabled(e->type, true)) AI::BroadcastNewEvent(new ScriptEventEngineAvailable(index));
996 /* Only provide the "New Vehicle available" news paper entry, if engine can be built. */
997 if (!IsVehicleTypeDisabled(e->type, false)) {
998 SetDParam(0, GetEngineCategoryName(index));
999 SetDParam(1, index);
1000 AddNewsItem(STR_NEWS_NEW_VEHICLE_NOW_AVAILABLE_WITH_TYPE, NT_NEW_VEHICLES, NF_VEHICLE, NR_ENGINE, index);
1003 /* Update the toolbar. */
1004 if (e->type == VEH_ROAD) InvalidateWindowData(WC_BUILD_TOOLBAR, TRANSPORT_ROAD);
1005 if (e->type == VEH_SHIP) InvalidateWindowData(WC_BUILD_TOOLBAR, TRANSPORT_WATER);
1006 if (e->type == VEH_AIRCRAFT) InvalidateWindowData(WC_BUILD_TOOLBAR, TRANSPORT_AIR);
1008 /* Close pending preview windows */
1009 CloseWindowById(WC_ENGINE_PREVIEW, index);
1012 /** Monthly update of the availability, reliability, and preview offers of the engines. */
1013 void EnginesMonthlyLoop()
1015 if (_cur_year < _year_engine_aging_stops) {
1016 for (Engine *e : Engine::Iterate()) {
1017 /* Age the vehicle */
1018 if ((e->flags & ENGINE_AVAILABLE) && e->age != MAX_DAY) {
1019 e->age++;
1020 CalcEngineReliability(e);
1023 /* Do not introduce invalid engines */
1024 if (!e->IsEnabled()) continue;
1026 if (!(e->flags & ENGINE_AVAILABLE) && _date >= (e->intro_date + DAYS_IN_YEAR)) {
1027 /* Introduce it to all companies */
1028 NewVehicleAvailable(e);
1029 } else if (!(e->flags & (ENGINE_AVAILABLE | ENGINE_EXCLUSIVE_PREVIEW)) && _date >= e->intro_date) {
1030 /* Introduction date has passed...
1031 * Check if it is allowed to build this vehicle type at all
1032 * based on the current game settings. If not, it does not
1033 * make sense to show the preview dialog to any company. */
1034 if (IsVehicleTypeDisabled(e->type, false)) continue;
1036 /* Do not introduce new rail wagons */
1037 if (IsWagon(e->index)) continue;
1039 /* Show preview dialog to one of the companies. */
1040 e->flags |= ENGINE_EXCLUSIVE_PREVIEW;
1041 e->preview_company = INVALID_COMPANY;
1042 e->preview_asked = 0;
1046 InvalidateWindowClassesData(WC_BUILD_VEHICLE); // rebuild the purchase list (esp. when sorted by reliability)
1051 * Is \a name still free as name for an engine?
1052 * @param name New name of an engine.
1053 * @return \c false if the name is being used already, else \c true.
1055 static bool IsUniqueEngineName(const std::string &name)
1057 for (const Engine *e : Engine::Iterate()) {
1058 if (!e->name.empty() && e->name == name) return false;
1061 return true;
1065 * Rename an engine.
1066 * @param flags operation to perform
1067 * @param engine_id engine ID to rename
1068 * @param text the new name or an empty string when resetting to the default
1069 * @return the cost of this operation or an error
1071 CommandCost CmdRenameEngine(DoCommandFlag flags, EngineID engine_id, const std::string &text)
1073 Engine *e = Engine::GetIfValid(engine_id);
1074 if (e == nullptr) return CMD_ERROR;
1076 bool reset = text.empty();
1078 if (!reset) {
1079 if (Utf8StringLength(text) >= MAX_LENGTH_ENGINE_NAME_CHARS) return CMD_ERROR;
1080 if (!IsUniqueEngineName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
1083 if (flags & DC_EXEC) {
1084 if (reset) {
1085 e->name.clear();
1086 } else {
1087 e->name = text;
1090 MarkWholeScreenDirty();
1093 return CommandCost();
1098 * Check if an engine is buildable.
1099 * @param engine index of the engine to check.
1100 * @param type the type the engine should be.
1101 * @param company index of the company.
1102 * @return True if an engine is valid, of the specified type, and buildable by
1103 * the given company.
1105 bool IsEngineBuildable(EngineID engine, VehicleType type, CompanyID company)
1107 const Engine *e = Engine::GetIfValid(engine);
1109 /* check if it's an engine that is in the engine array */
1110 if (e == nullptr) return false;
1112 /* check if it's an engine of specified type */
1113 if (e->type != type) return false;
1115 /* check if it's available ... */
1116 if (company == OWNER_DEITY) {
1117 /* ... for any company (preview does not count) */
1118 if (!(e->flags & ENGINE_AVAILABLE) || e->company_avail == 0) return false;
1119 } else {
1120 /* ... for this company */
1121 if (!HasBit(e->company_avail, company)) return false;
1124 if (!e->IsEnabled()) return false;
1126 if (type == VEH_TRAIN && company != OWNER_DEITY) {
1127 /* Check if the rail type is available to this company */
1128 const Company *c = Company::Get(company);
1129 if (((GetRailTypeInfo(e->u.rail.railtype))->compatible_railtypes & c->avail_railtypes) == 0) return false;
1131 if (type == VEH_ROAD && company != OWNER_DEITY) {
1132 /* Check if the road type is available to this company */
1133 const Company *c = Company::Get(company);
1134 if ((GetRoadTypeInfo(e->u.road.roadtype)->powered_roadtypes & c->avail_roadtypes) == ROADTYPES_NONE) return false;
1137 return true;
1141 * Check if an engine is refittable.
1142 * Note: Likely you want to use IsArticulatedVehicleRefittable().
1143 * @param engine index of the engine to check.
1144 * @return true if the engine is refittable.
1146 bool IsEngineRefittable(EngineID engine)
1148 const Engine *e = Engine::GetIfValid(engine);
1150 /* check if it's an engine that is in the engine array */
1151 if (e == nullptr) return false;
1153 if (!e->CanCarryCargo()) return false;
1155 const EngineInfo *ei = &e->info;
1156 if (ei->refit_mask == 0) return false;
1158 /* Are there suffixes?
1159 * Note: This does not mean the suffixes are actually available for every consist at any time. */
1160 if (HasBit(ei->callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) return true;
1162 /* Is there any cargo except the default cargo? */
1163 CargoID default_cargo = e->GetDefaultCargoType();
1164 CargoTypes default_cargo_mask = 0;
1165 SetBit(default_cargo_mask, default_cargo);
1166 return default_cargo != CT_INVALID && ei->refit_mask != default_cargo_mask;
1170 * Check for engines that have an appropriate availability.
1172 void CheckEngines()
1174 Date min_date = INT32_MAX;
1176 for (const Engine *e : Engine::Iterate()) {
1177 if (!e->IsEnabled()) continue;
1179 /* We have an available engine... yay! */
1180 if ((e->flags & ENGINE_AVAILABLE) != 0 && e->company_avail != 0) return;
1182 /* Okay, try to find the earliest date. */
1183 min_date = std::min(min_date, e->info.base_intro);
1186 if (min_date < INT32_MAX) {
1187 SetDParam(0, min_date);
1188 ShowErrorMessage(STR_ERROR_NO_VEHICLES_AVAILABLE_YET, STR_ERROR_NO_VEHICLES_AVAILABLE_YET_EXPLANATION, WL_WARNING);
1189 } else {
1190 ShowErrorMessage(STR_ERROR_NO_VEHICLES_AVAILABLE_AT_ALL, STR_ERROR_NO_VEHICLES_AVAILABLE_AT_ALL_EXPLANATION, WL_WARNING);