Rework ChoosePylonPosition to simplify the loop
[openttd/fttd.git] / src / engine.cpp
blob85a8251616b3327aab5dd579503f84ea86d3d772
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * 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.
6 * 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.
7 * 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/>.
8 */
10 /** @file engine.cpp Base for all engine handling. */
12 #include "stdafx.h"
13 #include "company_func.h"
14 #include "command_func.h"
15 #include "news_func.h"
16 #include "aircraft.h"
17 #include "newgrf.h"
18 #include "newgrf_engine.h"
19 #include "strings_func.h"
20 #include "core/random_func.hpp"
21 #include "window_func.h"
22 #include "date_func.h"
23 #include "autoreplace_gui.h"
24 #include "string.h"
25 #include "ai/ai.hpp"
26 #include "core/pool_func.hpp"
27 #include "engine_gui.h"
28 #include "engine_func.h"
29 #include "engine_base.h"
30 #include "company_base.h"
31 #include "vehicle_func.h"
32 #include "articulated_vehicles.h"
33 #include "error.h"
35 #include "table/strings.h"
36 #include "table/engines.h"
38 template<> Engine::Pool Engine::PoolItem::pool ("Engine");
39 INSTANTIATE_POOL_METHODS(Engine)
41 EngineOverrideManager _engine_mngr;
43 /**
44 * Year that engine aging stops. Engines will not reduce in reliability
45 * and no more engines will be introduced
47 static Year _year_engine_aging_stops;
49 /** Number of engines of each vehicle type in original engine data */
50 const uint8 _engine_counts[4] = {
51 lengthof(_orig_rail_vehicle_info),
52 lengthof(_orig_road_vehicle_info),
53 lengthof(_orig_ship_vehicle_info),
54 lengthof(_orig_aircraft_vehicle_info),
57 /** Offset of the first engine of each vehicle type in original engine data */
58 const uint8 _engine_offsets[4] = {
60 lengthof(_orig_rail_vehicle_info),
61 lengthof(_orig_rail_vehicle_info) + lengthof(_orig_road_vehicle_info),
62 lengthof(_orig_rail_vehicle_info) + lengthof(_orig_road_vehicle_info) + lengthof(_orig_ship_vehicle_info),
65 assert_compile(lengthof(_orig_rail_vehicle_info) + lengthof(_orig_road_vehicle_info) + lengthof(_orig_ship_vehicle_info) + lengthof(_orig_aircraft_vehicle_info) == lengthof(_orig_engine_info));
67 const uint EngineOverrideManager::NUM_DEFAULT_ENGINES = _engine_counts[VEH_TRAIN] + _engine_counts[VEH_ROAD] + _engine_counts[VEH_SHIP] + _engine_counts[VEH_AIRCRAFT];
69 Engine::Engine() :
70 overrides_count(0),
71 overrides(NULL)
73 memset (this->spritegroup, 0, sizeof(this->spritegroup));
76 Engine::Engine(VehicleType type, EngineID base)
78 this->type = type;
79 this->grf_prop.local_id = base;
80 memset (this->spritegroup, 0, sizeof(this->spritegroup));
81 this->list_position = base;
82 this->preview_company = INVALID_COMPANY;
84 /* Check if this base engine is within the original engine data range */
85 if (base >= _engine_counts[type]) {
86 /* Set model life to maximum to make wagons available */
87 this->info.base_life = 0xFF;
88 /* Set road vehicle tractive effort to the default value */
89 if (type == VEH_ROAD) this->u.road.tractive_effort = 0x4C;
90 /* Aircraft must have CT_INVALID as default, as there is no property */
91 if (type == VEH_AIRCRAFT) this->info.cargo_type = CT_INVALID;
92 /* Set visual effect to the default value */
93 switch (type) {
94 case VEH_TRAIN: this->u.rail.visual_effect = VE_DEFAULT; break;
95 case VEH_ROAD: this->u.road.visual_effect = VE_DEFAULT; break;
96 case VEH_SHIP: this->u.ship.visual_effect = VE_DEFAULT; break;
97 default: break; // The aircraft, disasters and especially visual effects have no NewGRF configured visual effects
99 /* Set cargo aging period to the default value. */
100 this->info.cargo_age_period = CARGO_AGING_TICKS;
101 return;
104 /* Copy the original engine info for this slot */
105 this->info = _orig_engine_info[_engine_offsets[type] + base];
107 /* Copy the original engine data for this slot */
108 switch (type) {
109 default: NOT_REACHED();
111 case VEH_TRAIN:
112 this->u.rail = _orig_rail_vehicle_info[base];
113 this->original_image_index = this->u.rail.image_index;
114 this->info.string_id = STR_VEHICLE_NAME_TRAIN_ENGINE_RAIL_KIRBY_PAUL_TANK_STEAM + base;
116 /* Set the default model life of original wagons to "infinite" */
117 if (this->u.rail.railveh_type == RAILVEH_WAGON) this->info.base_life = 0xFF;
119 break;
121 case VEH_ROAD:
122 this->u.road = _orig_road_vehicle_info[base];
123 this->original_image_index = this->u.road.image_index;
124 this->info.string_id = STR_VEHICLE_NAME_ROAD_VEHICLE_MPS_REGAL_BUS + base;
125 break;
127 case VEH_SHIP:
128 this->u.ship = _orig_ship_vehicle_info[base];
129 this->original_image_index = this->u.ship.image_index;
130 this->info.string_id = STR_VEHICLE_NAME_SHIP_MPS_OIL_TANKER + base;
131 break;
133 case VEH_AIRCRAFT:
134 this->u.air = _orig_aircraft_vehicle_info[base];
135 this->original_image_index = this->u.air.image_index;
136 this->info.string_id = STR_VEHICLE_NAME_AIRCRAFT_SAMPSON_U52 + base;
137 break;
141 Engine::~Engine()
143 UnloadWagonOverrides(this);
147 * Checks whether the engine is a valid (non-articulated part of an) engine.
148 * @return true if enabled
150 bool Engine::IsEnabled() const
152 return this->info.string_id != STR_NEWGRF_INVALID_ENGINE && HasBit(this->info.climates, _settings_game.game_creation.landscape);
156 * Retrieve the GRF ID of the NewGRF the engine is tied to.
157 * This is the GRF providing the Action 3.
158 * @return GRF ID of the associated NewGRF.
160 uint32 Engine::GetGRFID() const
162 const GRFFile *file = this->GetGRF();
163 return file == NULL ? 0 : file->grfid;
167 * Determines whether an engine can carry something.
168 * A vehicle cannot carry anything if its capacity is zero, or none of the possible cargoes is available in the climate.
169 * @return true if the vehicle can carry something.
171 bool Engine::CanCarryCargo() const
173 /* For engines that can appear in a consist (i.e. rail vehicles and (articulated) road vehicles), a capacity
174 * of zero is a special case, to define the vehicle to not carry anything. The default cargotype is still used
175 * for livery selection etc.
176 * Note: Only the property is tested. A capacity callback returning 0 does not have the same effect.
178 switch (this->type) {
179 case VEH_TRAIN:
180 if (this->u.rail.capacity == 0) return false;
181 break;
183 case VEH_ROAD:
184 if (this->u.road.capacity == 0) return false;
185 break;
187 case VEH_SHIP:
188 case VEH_AIRCRAFT:
189 break;
191 default: NOT_REACHED();
193 return this->GetDefaultCargoType() != CT_INVALID;
198 * Determines capacity of a given vehicle from scratch.
199 * For aircraft the main capacity is determined. Mail might be present as well.
200 * @param v Vehicle of interest; NULL in purchase list
201 * @param mail_capacity returns secondary cargo (mail) capacity of aircraft
202 * @return Capacity
204 uint Engine::DetermineCapacity(const Vehicle *v, uint16 *mail_capacity) const
206 assert(v == NULL || this->index == v->engine_type);
207 if (mail_capacity != NULL) *mail_capacity = 0;
209 if (!this->CanCarryCargo()) return 0;
211 bool new_multipliers = HasBit(this->info.misc_flags, EF_NO_DEFAULT_CARGO_MULTIPLIER);
212 CargoID default_cargo = this->GetDefaultCargoType();
213 CargoID cargo_type = (v != NULL) ? v->cargo_type : default_cargo;
215 if (mail_capacity != NULL && this->type == VEH_AIRCRAFT && IsCargoInClass(cargo_type, CC_PASSENGERS)) {
216 *mail_capacity = GetEngineProperty(this->index, PROP_AIRCRAFT_MAIL_CAPACITY, this->u.air.mail_capacity, v);
219 /* Check the refit capacity callback if we are not in the default configuration, or if we are using the new multiplier algorithm. */
220 if (HasBit(this->info.callback_mask, CBM_VEHICLE_REFIT_CAPACITY) &&
221 (new_multipliers || default_cargo != cargo_type || (v != NULL && v->cargo_subtype != 0))) {
222 uint16 callback = GetVehicleCallback(CBID_VEHICLE_REFIT_CAPACITY, 0, 0, this->index, v);
223 if (callback != CALLBACK_FAILED) return callback;
226 /* Get capacity according to property resp. CB */
227 uint capacity;
228 uint extra_mail_cap = 0;
229 switch (this->type) {
230 case VEH_TRAIN:
231 capacity = GetEngineProperty(this->index, PROP_TRAIN_CARGO_CAPACITY, this->u.rail.capacity, v);
233 /* In purchase list add the capacity of the second head. Always use the plain property for this. */
234 if (v == NULL && this->u.rail.railveh_type == RAILVEH_MULTIHEAD) capacity += this->u.rail.capacity;
235 break;
237 case VEH_ROAD:
238 capacity = GetEngineProperty(this->index, PROP_ROADVEH_CARGO_CAPACITY, this->u.road.capacity, v);
239 break;
241 case VEH_SHIP:
242 capacity = GetEngineProperty(this->index, PROP_SHIP_CARGO_CAPACITY, this->u.ship.capacity, v);
243 break;
245 case VEH_AIRCRAFT:
246 capacity = GetEngineProperty(this->index, PROP_AIRCRAFT_PASSENGER_CAPACITY, this->u.air.passenger_capacity, v);
247 if (!IsCargoInClass(cargo_type, CC_PASSENGERS)) {
248 extra_mail_cap = GetEngineProperty(this->index, PROP_AIRCRAFT_MAIL_CAPACITY, this->u.air.mail_capacity, v);
250 if (!new_multipliers && cargo_type == CT_MAIL) return capacity + extra_mail_cap;
251 default_cargo = CT_PASSENGERS; // Always use 'passengers' wrt. cargo multipliers
252 break;
254 default: NOT_REACHED();
257 if (!new_multipliers) {
258 /* Use the passenger multiplier for mail as well */
259 capacity += extra_mail_cap;
260 extra_mail_cap = 0;
263 /* Apply multipliers depending on cargo- and vehicletype. */
264 if (new_multipliers || (this->type != VEH_SHIP && default_cargo != cargo_type)) {
265 uint16 default_multiplier = new_multipliers ? 0x100 : CargoSpec::Get(default_cargo)->multiplier;
266 uint16 cargo_multiplier = CargoSpec::Get(cargo_type)->multiplier;
267 capacity *= cargo_multiplier;
268 if (extra_mail_cap > 0) {
269 uint mail_multiplier = CargoSpec::Get(CT_MAIL)->multiplier;
270 capacity += (default_multiplier * extra_mail_cap * cargo_multiplier + mail_multiplier / 2) / mail_multiplier;
272 capacity = (capacity + default_multiplier / 2) / default_multiplier;
275 return capacity;
279 * Return how much the running costs of this engine are.
280 * @return Yearly running cost of the engine.
282 Money Engine::GetRunningCost() const
284 Price base_price;
285 uint cost_factor;
286 switch (this->type) {
287 case VEH_ROAD:
288 base_price = this->u.road.running_cost_class;
289 if (base_price == INVALID_PRICE) return 0;
290 cost_factor = GetEngineProperty(this->index, PROP_ROADVEH_RUNNING_COST_FACTOR, this->u.road.running_cost);
291 break;
293 case VEH_TRAIN:
294 base_price = this->u.rail.running_cost_class;
295 if (base_price == INVALID_PRICE) return 0;
296 cost_factor = GetEngineProperty(this->index, PROP_TRAIN_RUNNING_COST_FACTOR, this->u.rail.running_cost);
297 break;
299 case VEH_SHIP:
300 base_price = PR_RUNNING_SHIP;
301 cost_factor = GetEngineProperty(this->index, PROP_SHIP_RUNNING_COST_FACTOR, this->u.ship.running_cost);
302 break;
304 case VEH_AIRCRAFT:
305 base_price = PR_RUNNING_AIRCRAFT;
306 cost_factor = GetEngineProperty(this->index, PROP_AIRCRAFT_RUNNING_COST_FACTOR, this->u.air.running_cost);
307 break;
309 default: NOT_REACHED();
312 return GetPrice(base_price, cost_factor, this->GetGRF(), -8);
316 * Return how much a new engine costs.
317 * @return Cost of the engine.
319 Money Engine::GetCost() const
321 Price base_price;
322 uint cost_factor;
323 switch (this->type) {
324 case VEH_ROAD:
325 base_price = PR_BUILD_VEHICLE_ROAD;
326 cost_factor = GetEngineProperty(this->index, PROP_ROADVEH_COST_FACTOR, this->u.road.cost_factor);
327 break;
329 case VEH_TRAIN:
330 if (this->u.rail.railveh_type == RAILVEH_WAGON) {
331 base_price = PR_BUILD_VEHICLE_WAGON;
332 cost_factor = GetEngineProperty(this->index, PROP_TRAIN_COST_FACTOR, this->u.rail.cost_factor);
333 } else {
334 base_price = PR_BUILD_VEHICLE_TRAIN;
335 cost_factor = GetEngineProperty(this->index, PROP_TRAIN_COST_FACTOR, this->u.rail.cost_factor);
337 break;
339 case VEH_SHIP:
340 base_price = PR_BUILD_VEHICLE_SHIP;
341 cost_factor = GetEngineProperty(this->index, PROP_SHIP_COST_FACTOR, this->u.ship.cost_factor);
342 break;
344 case VEH_AIRCRAFT:
345 base_price = PR_BUILD_VEHICLE_AIRCRAFT;
346 cost_factor = GetEngineProperty(this->index, PROP_AIRCRAFT_COST_FACTOR, this->u.air.cost_factor);
347 break;
349 default: NOT_REACHED();
352 return GetPrice(base_price, cost_factor, this->GetGRF(), -8);
356 * Returns max speed of the engine for display purposes
357 * @return max speed in km-ish/h
359 uint Engine::GetDisplayMaxSpeed() const
361 switch (this->type) {
362 case VEH_TRAIN:
363 return GetEngineProperty(this->index, PROP_TRAIN_SPEED, this->u.rail.max_speed);
365 case VEH_ROAD: {
366 uint max_speed = GetEngineProperty(this->index, PROP_ROADVEH_SPEED, 0);
367 return (max_speed != 0) ? max_speed * 2 : this->u.road.max_speed / 2;
370 case VEH_SHIP:
371 return GetEngineProperty(this->index, PROP_SHIP_SPEED, this->u.ship.max_speed) / 2;
373 case VEH_AIRCRAFT: {
374 uint max_speed = GetEngineProperty(this->index, PROP_AIRCRAFT_SPEED, 0);
375 if (max_speed != 0) {
376 return (max_speed * 128) / 10;
378 return this->u.air.max_speed;
381 default: NOT_REACHED();
386 * Returns the power of the engine for display
387 * and sorting purposes.
388 * Only trains and road vehicles have power
389 * @return power in display units hp
391 uint Engine::GetPower() const
393 /* Only trains and road vehicles have 'power'. */
394 switch (this->type) {
395 case VEH_TRAIN:
396 return GetEngineProperty(this->index, PROP_TRAIN_POWER, this->u.rail.power);
397 case VEH_ROAD:
398 return GetEngineProperty(this->index, PROP_ROADVEH_POWER, this->u.road.power) * 10;
400 default: NOT_REACHED();
405 * Returns the weight of the engine for display purposes.
406 * For dual-headed train-engines this is the weight of both heads
407 * @return weight in display units metric tons
409 uint Engine::GetDisplayWeight() const
411 /* Only trains and road vehicles have 'weight'. */
412 switch (this->type) {
413 case VEH_TRAIN:
414 return GetEngineProperty(this->index, PROP_TRAIN_WEIGHT, this->u.rail.weight) << (this->u.rail.railveh_type == RAILVEH_MULTIHEAD ? 1 : 0);
415 case VEH_ROAD:
416 return GetEngineProperty(this->index, PROP_ROADVEH_WEIGHT, this->u.road.weight) / 4;
418 default: NOT_REACHED();
423 * Returns the tractive effort of the engine for display purposes.
424 * For dual-headed train-engines this is the tractive effort of both heads
425 * @return tractive effort in display units kN
427 uint Engine::GetDisplayMaxTractiveEffort() const
429 /* Only trains and road vehicles have 'tractive effort'. */
430 switch (this->type) {
431 case VEH_TRAIN:
432 return (10 * this->GetDisplayWeight() * GetEngineProperty(this->index, PROP_TRAIN_TRACTIVE_EFFORT, this->u.rail.tractive_effort)) / 256;
433 case VEH_ROAD:
434 return (10 * this->GetDisplayWeight() * GetEngineProperty(this->index, PROP_ROADVEH_TRACTIVE_EFFORT, this->u.road.tractive_effort)) / 256;
436 default: NOT_REACHED();
441 * Returns the vehicle's (not model's!) life length in days.
442 * @return the life length
444 Date Engine::GetLifeLengthInDays() const
446 /* Assume leap years; this gives the player a bit more than the given amount of years, but never less. */
447 return (this->info.lifelength + _settings_game.vehicle.extend_vehicle_life) * DAYS_IN_LEAP_YEAR;
451 * Get the range of an aircraft type.
452 * @return Range of the aircraft type in tiles or 0 if unlimited range.
454 uint16 Engine::GetRange() const
456 switch (this->type) {
457 case VEH_AIRCRAFT:
458 return GetEngineProperty(this->index, PROP_AIRCRAFT_RANGE, this->u.air.max_range);
460 default: NOT_REACHED();
465 * Get the name of the aircraft type for display purposes.
466 * @return Aircraft type string.
468 StringID Engine::GetAircraftTypeText() const
470 switch (this->type) {
471 case VEH_AIRCRAFT:
472 switch (this->u.air.subtype) {
473 case AIR_HELI: return STR_LIVERY_HELICOPTER;
474 case AIR_CTOL: return STR_LIVERY_SMALL_PLANE;
475 case AIR_CTOL | AIR_FAST: return STR_LIVERY_LARGE_PLANE;
476 default: NOT_REACHED();
479 default: NOT_REACHED();
484 * Initializes the #EngineOverrideManager with the default engines.
486 void EngineOverrideManager::ResetToDefaultMapping()
488 this->Clear();
489 for (VehicleType type = VEH_TRAIN; type <= VEH_AIRCRAFT; type++) {
490 for (uint internal_id = 0; internal_id < _engine_counts[type]; internal_id++) {
491 EngineIDMapping *eid = this->Append();
492 eid->type = type;
493 eid->grfid = INVALID_GRFID;
494 eid->internal_id = internal_id;
495 eid->substitute_id = internal_id;
501 * Looks up an EngineID in the EngineOverrideManager
502 * @param type Vehicle type
503 * @param grf_local_id The local id in the newgrf
504 * @param grfid The GrfID that defines the scope of grf_local_id.
505 * If a newgrf overrides the engines of another newgrf, the "scope grfid" is the ID of the overridden newgrf.
506 * If dynnamic_engines is disabled, all newgrf share the same ID scope identified by INVALID_GRFID.
507 * @return The engine ID if present, or INVALID_ENGINE if not.
509 EngineID EngineOverrideManager::GetID(VehicleType type, uint16 grf_local_id, uint32 grfid)
511 const EngineIDMapping *end = this->End();
512 EngineID index = 0;
513 for (const EngineIDMapping *eid = this->Begin(); eid != end; eid++, index++) {
514 if (eid->type == type && eid->grfid == grfid && eid->internal_id == grf_local_id) {
515 return index;
518 return INVALID_ENGINE;
522 * Tries to reset the engine mapping to match the current NewGRF configuration.
523 * This is only possible when there are currently no vehicles in the game.
524 * @return false if resetting failed due to present vehicles.
526 bool EngineOverrideManager::ResetToCurrentNewGRFConfig()
528 const Vehicle *v;
529 FOR_ALL_VEHICLES(v) {
530 if (IsCompanyBuildableVehicleType(v)) return false;
533 /* Reset the engines, they will get new EngineIDs */
534 _engine_mngr.ResetToDefaultMapping();
535 ReloadNewGRFData();
537 return true;
541 * Initialise the engine pool with the data from the original vehicles.
543 void SetupEngines()
545 DeleteWindowByClass(WC_ENGINE_PREVIEW);
546 Engine::pool.CleanPool();
548 assert(_engine_mngr.Length() >= _engine_mngr.NUM_DEFAULT_ENGINES);
549 const EngineIDMapping *end = _engine_mngr.End();
550 uint index = 0;
551 for (const EngineIDMapping *eid = _engine_mngr.Begin(); eid != end; eid++, index++) {
552 /* Assert is safe; there won't be more than 256 original vehicles
553 * in any case, and we just cleaned the pool. */
554 assert(Engine::CanAllocateItem());
555 const Engine *e = new Engine(eid->type, eid->internal_id);
556 assert(e->index == index);
560 void ShowEnginePreviewWindow(EngineID engine);
563 * Determine whether an engine type is a wagon (and not a loco).
564 * @param index %Engine getting queried.
565 * @return Whether the queried engine is a wagon.
567 static bool IsWagon(EngineID index)
569 const Engine *e = Engine::Get(index);
570 return e->type == VEH_TRAIN && e->u.rail.railveh_type == RAILVEH_WAGON;
574 * Update #reliability of engine \a e.
575 * @param e %EngineState to update.
576 * @param ei %EngineInfo for the engine.
578 static void CalcEngineReliability (EngineState *e, const EngineInfo *ei)
580 uint age = e->age;
582 /* Check for early retirement */
583 if (e->company_avail != 0 && !_settings_game.vehicle.never_expire_vehicles && ei->base_life != 0xFF) {
584 int retire_early = ei->retire_early;
585 uint retire_early_max_age = max(0, e->duration_phase_1 + e->duration_phase_2 - retire_early * 12);
586 if (retire_early != 0 && age >= retire_early_max_age) {
587 /* Early retirement is enabled and we're past the date... */
588 e->company_avail = 0;
592 if (age < e->duration_phase_1) {
593 uint start = e->reliability_start;
594 e->reliability = age * (e->reliability_max - start) / e->duration_phase_1 + start;
595 } else if ((age -= e->duration_phase_1) < e->duration_phase_2 || _settings_game.vehicle.never_expire_vehicles || ei->base_life == 0xFF) {
596 /* We are at the peak of this engines life. It will have max reliability.
597 * This is also true if the engines never expire. They will not go bad over time */
598 e->reliability = e->reliability_max;
599 } else if ((age -= e->duration_phase_2) < e->duration_phase_3) {
600 uint max = e->reliability_max;
601 e->reliability = (int)age * (int)(e->reliability_final - max) / e->duration_phase_3 + max;
602 } else {
603 /* time's up for this engine.
604 * We will now completely retire this design */
605 e->company_avail = 0;
606 e->reliability = e->reliability_final;
610 /** Compute the value for #_year_engine_aging_stops. */
611 void SetYearEngineAgingStops()
613 /* Determine last engine aging year, default to 2050 as previously. */
614 _year_engine_aging_stops = 2050;
616 const Engine *e;
617 FOR_ALL_ENGINES(e) {
618 const EngineInfo *ei = &e->info;
620 /* Exclude certain engines */
621 if (!HasBit(ei->climates, _settings_game.game_creation.landscape)) continue;
622 if (e->type == VEH_TRAIN && e->u.rail.railveh_type == RAILVEH_WAGON) continue;
624 /* Base year ending date on half the model life */
625 YearMonthDay ymd;
626 ConvertDateToYMD(ei->base_intro + (ei->lifelength * DAYS_IN_LEAP_YEAR) / 2, &ymd);
628 _year_engine_aging_stops = max(_year_engine_aging_stops, ymd.year);
633 * Reset or initialise the variable data of an engine.
634 * @param ei Engine info.
635 * @param aging_date The date used for age calculations.
637 void EngineState::reset (const EngineInfo *ei, Date aging_date)
639 this->age = 0;
640 this->flags = 0;
641 this->company_avail = 0;
642 this->company_hidden = 0;
644 /* Don't randomise the start-date in the first two years after gamestart to ensure availability
645 * of engines in early starting games.
646 * Note: TTDP uses fixed 1922 */
647 uint32 r = Random();
648 this->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;
649 if (this->intro_date <= _date) {
650 this->age = (aging_date - this->intro_date) >> 5;
651 this->company_avail = (CompanyMask)-1;
652 this->flags |= ENGINE_AVAILABLE;
655 this->reliability_start = GB(r, 16, 14) + 0x7AE0;
656 r = Random();
657 this->reliability_max = GB(r, 0, 14) + 0xBFFF;
658 this->reliability_final = GB(r, 16, 14) + 0x3FFF;
660 r = Random();
661 this->duration_phase_1 = GB(r, 0, 5) + 7;
662 this->duration_phase_2 = GB(r, 5, 4) + ei->base_life * 12 - 96;
663 this->duration_phase_3 = GB(r, 9, 7) + 120;
665 this->reliability_spd_dec = ei->decay_speed << 2;
667 CalcEngineReliability (this, ei);
669 /* prevent certain engines from ever appearing. */
670 if (!HasBit(ei->climates, _settings_game.game_creation.landscape)) {
671 this->flags |= ENGINE_AVAILABLE;
672 this->company_avail = 0;
677 * Start/initialise all our engines. Must be called whenever there are changes
678 * to the NewGRF config.
680 void StartupEngines()
682 Engine *e;
683 /* Aging of vehicles stops, so account for that when starting late */
684 const Date aging_date = min(_date, ConvertYMDToDate(_year_engine_aging_stops, 0, 1));
686 FOR_ALL_ENGINES(e) {
687 e->reset (&e->info, aging_date);
690 /* Update the bitmasks for the vehicle lists */
691 Company *c;
692 FOR_ALL_COMPANIES(c) {
693 c->avail_railtypes = GetCompanyRailtypes(c->index);
694 c->avail_roadtypes = GetCompanyRoadtypes(c->index);
697 SetWindowClassesDirty(WC_BUILD_VEHICLE); // Update to show the new reliability
698 SetWindowClassesDirty(WC_REPLACE_VEHICLE);
700 /* Invalidate any open purchase lists */
701 InvalidateWindowClassesData(WC_BUILD_VEHICLE);
702 InvalidateWindowClassesData(WC_REPLACE_VEHICLE);
706 * Company \a company accepts engine \a eid for preview.
707 * @param eid Engine being accepted (is under preview).
708 * @param company Current company previewing the engine.
710 static void AcceptEnginePreview(EngineID eid, CompanyID company)
712 Engine *e = Engine::Get(eid);
713 Company *c = Company::Get(company);
715 SetBit(e->company_avail, company);
716 if (e->type == VEH_TRAIN) {
717 assert(e->u.rail.railtype < RAILTYPE_END);
718 c->avail_railtypes = AddDateIntroducedRailTypes(c->avail_railtypes | GetRailTypeInfo(e->u.rail.railtype)->introduces_railtypes, _date);
719 } else if (e->type == VEH_ROAD) {
720 SetBit(c->avail_roadtypes, HasBit(e->info.misc_flags, EF_ROAD_TRAM) ? ROADTYPE_TRAM : ROADTYPE_ROAD);
723 e->preview_company = INVALID_COMPANY;
724 e->preview_asked = (CompanyMask)-1;
725 if (company == _local_company) {
726 AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
729 /* Update the toolbar. */
730 if (e->type == VEH_ROAD) InvalidateWindowData(WC_BUILD_TOOLBAR, TRANSPORT_ROAD);
731 if (e->type == VEH_SHIP) InvalidateWindowData(WC_BUILD_TOOLBAR, TRANSPORT_WATER);
733 /* Notify preview window, that it might want to close.
734 * Note: We cannot directly close the window.
735 * In singleplayer this function is called from the preview window, so
736 * we have to use the GUI-scope scheduling of InvalidateWindowData.
738 InvalidateWindowData(WC_ENGINE_PREVIEW, eid);
742 * Get the best company for an engine preview.
743 * @param e Engine to preview.
744 * @return Best company if it exists, #INVALID_COMPANY otherwise.
746 static CompanyID GetPreviewCompany(Engine *e)
748 CompanyID best_company = INVALID_COMPANY;
750 /* For trains the cargomask has no useful meaning, since you can attach other wagons */
751 uint32 cargomask = e->type != VEH_TRAIN ? GetUnionOfArticulatedRefitMasks(e->index, true) : (uint32)-1;
753 int32 best_hist = -1;
754 const Company *c;
755 FOR_ALL_COMPANIES(c) {
756 if (c->block_preview == 0 && !HasBit(e->preview_asked, c->index) &&
757 c->old_economy[0].performance_history > best_hist) {
759 /* Check whether the company uses similar vehicles */
760 Vehicle *v;
761 FOR_ALL_VEHICLES(v) {
762 if (v->owner != c->index || v->type != e->type) continue;
763 if (!v->GetEngine()->CanCarryCargo() || !HasBit(cargomask, v->cargo_type)) continue;
765 best_hist = c->old_economy[0].performance_history;
766 best_company = c->index;
767 break;
772 return best_company;
776 * Checks if a vehicle type is disabled for all/ai companies.
777 * @param type The vehicle type which shall be checked.
778 * @param ai If true, check if the type is disabled for AI companies, otherwise check if
779 * the vehicle type is disabled for human companies.
780 * @return Whether or not a vehicle type is disabled.
782 static bool IsVehicleTypeDisabled(VehicleType type, bool ai)
784 switch (type) {
785 case VEH_TRAIN: return _settings_game.vehicle.max_trains == 0 || (ai && _settings_game.ai.ai_disable_veh_train);
786 case VEH_ROAD: return _settings_game.vehicle.max_roadveh == 0 || (ai && _settings_game.ai.ai_disable_veh_roadveh);
787 case VEH_SHIP: return _settings_game.vehicle.max_ships == 0 || (ai && _settings_game.ai.ai_disable_veh_ship);
788 case VEH_AIRCRAFT: return _settings_game.vehicle.max_aircraft == 0 || (ai && _settings_game.ai.ai_disable_veh_aircraft);
790 default: NOT_REACHED();
794 /** Daily check to offer an exclusive engine preview to the companies. */
795 void EnginesDailyLoop()
797 Company *c;
798 FOR_ALL_COMPANIES(c) {
799 c->avail_railtypes = AddDateIntroducedRailTypes(c->avail_railtypes, _date);
802 if (_cur_year >= _year_engine_aging_stops) return;
804 Engine *e;
805 FOR_ALL_ENGINES(e) {
806 EngineID i = e->index;
807 if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) {
808 if (e->preview_company != INVALID_COMPANY) {
809 if (!--e->preview_wait) {
810 DeleteWindowById(WC_ENGINE_PREVIEW, i);
811 e->preview_company = INVALID_COMPANY;
813 } else if (CountBits(e->preview_asked) < MAX_COMPANIES) {
814 e->preview_company = GetPreviewCompany(e);
816 if (e->preview_company == INVALID_COMPANY) {
817 e->preview_asked = (CompanyMask)-1;
818 continue;
821 SetBit(e->preview_asked, e->preview_company);
822 e->preview_wait = 20;
823 /* AIs are intentionally not skipped for preview even if they cannot build a certain
824 * vehicle type. This is done to not give poor performing human companies an "unfair"
825 * boost that they wouldn't have gotten against other human companies. The check on
826 * the line below is just to make AIs not notice that they have a preview if they
827 * cannot build the vehicle. */
828 if (!IsVehicleTypeDisabled(e->type, true)) AI::NewEvent(e->preview_company, new ScriptEventEnginePreview(i));
829 if (IsInteractiveCompany(e->preview_company)) ShowEnginePreviewWindow(i);
836 * Clear the 'hidden' flag for all engines of a new company.
837 * @param cid Company being created.
839 void ClearEnginesHiddenFlagOfCompany(CompanyID cid)
841 Engine *e;
842 FOR_ALL_ENGINES(e) {
843 SB(e->company_hidden, cid, 1, 0);
848 * Set the visibility of an engine.
849 * @param tile Unused.
850 * @param flags Operation to perform.
851 * @param p1 Unused.
852 * @param p2 Bit 31: 0=visible, 1=hidden, other bits for the #EngineID.
853 * @param text Unused.
854 * @return The cost of this operation or an error.
856 CommandCost CmdSetVehicleVisibility(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
858 Engine *e = Engine::GetIfValid(GB(p2, 0, 31));
859 if (e == NULL || _current_company >= MAX_COMPANIES) return CMD_ERROR;
860 if (!IsEngineBuildable(e->index, e->type, _current_company)) return CMD_ERROR;
862 if ((flags & DC_EXEC) != 0) {
863 SB(e->company_hidden, _current_company, 1, GB(p2, 31, 1));
864 AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
867 return CommandCost();
871 * Accept an engine prototype. XXX - it is possible that the top-company
872 * changes while you are waiting to accept the offer? Then it becomes invalid
873 * @param tile unused
874 * @param flags operation to perform
875 * @param p1 engine-prototype offered
876 * @param p2 unused
877 * @param text unused
878 * @return the cost of this operation or an error
880 CommandCost CmdWantEnginePreview(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
882 Engine *e = Engine::GetIfValid(p1);
883 if (e == NULL || !(e->flags & ENGINE_EXCLUSIVE_PREVIEW) || e->preview_company != _current_company) return CMD_ERROR;
885 if (flags & DC_EXEC) AcceptEnginePreview(p1, _current_company);
887 return CommandCost();
891 * An engine has become available for general use.
892 * Also handle the exclusive engine preview contract.
893 * @param e Engine generally available as of now.
895 static void NewVehicleAvailable(Engine *e)
897 Vehicle *v;
898 Company *c;
899 EngineID index = e->index;
901 /* In case the company didn't build the vehicle during the intro period,
902 * prevent that company from getting future intro periods for a while. */
903 if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) {
904 FOR_ALL_COMPANIES(c) {
905 uint block_preview = c->block_preview;
907 if (!HasBit(e->company_avail, c->index)) continue;
909 /* We assume the user did NOT build it.. prove me wrong ;) */
910 c->block_preview = 20;
912 FOR_ALL_VEHICLES(v) {
913 if (v->type == VEH_TRAIN || v->type == VEH_ROAD || v->type == VEH_SHIP ||
914 (v->type == VEH_AIRCRAFT && Aircraft::From(v)->IsNormalAircraft())) {
915 if (v->owner == c->index && v->engine_type == index) {
916 /* The user did prove me wrong, so restore old value */
917 c->block_preview = block_preview;
918 break;
925 e->flags = (e->flags & ~ENGINE_EXCLUSIVE_PREVIEW) | ENGINE_AVAILABLE;
926 AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
928 /* Now available for all companies */
929 e->company_avail = (CompanyMask)-1;
931 /* Do not introduce new rail wagons */
932 if (IsWagon(index)) return;
934 if (e->type == VEH_TRAIN) {
935 /* maybe make another rail type available */
936 RailType railtype = e->u.rail.railtype;
937 assert(railtype < RAILTYPE_END);
938 FOR_ALL_COMPANIES(c) c->avail_railtypes = AddDateIntroducedRailTypes(c->avail_railtypes | GetRailTypeInfo(e->u.rail.railtype)->introduces_railtypes, _date);
939 } else if (e->type == VEH_ROAD) {
940 /* maybe make another road type available */
941 FOR_ALL_COMPANIES(c) SetBit(c->avail_roadtypes, HasBit(e->info.misc_flags, EF_ROAD_TRAM) ? ROADTYPE_TRAM : ROADTYPE_ROAD);
944 /* Only broadcast event if AIs are able to build this vehicle type. */
945 if (!IsVehicleTypeDisabled(e->type, true)) AI::BroadcastNewEvent(new ScriptEventEngineAvailable(index));
947 /* Only provide the "New Vehicle available" news paper entry, if engine can be built. */
948 if (!IsVehicleTypeDisabled(e->type, false)) {
949 AddNewsItem<EngineNewsItem> (index);
952 /* Update the toolbar. */
953 if (e->type == VEH_ROAD) InvalidateWindowData(WC_BUILD_TOOLBAR, TRANSPORT_ROAD);
954 if (e->type == VEH_SHIP) InvalidateWindowData(WC_BUILD_TOOLBAR, TRANSPORT_WATER);
956 /* Close pending preview windows */
957 DeleteWindowById(WC_ENGINE_PREVIEW, index);
960 /** Monthly update of the availability, reliability, and preview offers of the engines. */
961 void EnginesMonthlyLoop()
963 if (_cur_year < _year_engine_aging_stops) {
964 Engine *e;
965 FOR_ALL_ENGINES(e) {
966 /* Age the vehicle */
967 if ((e->flags & ENGINE_AVAILABLE) && e->age != MAX_DAY) {
968 e->age++;
969 CalcEngineReliability (e, &e->info);
972 /* Do not introduce invalid engines */
973 if (!e->IsEnabled()) continue;
975 if (!(e->flags & ENGINE_AVAILABLE) && _date >= (e->intro_date + DAYS_IN_YEAR)) {
976 /* Introduce it to all companies */
977 NewVehicleAvailable(e);
978 } else if (!(e->flags & (ENGINE_AVAILABLE | ENGINE_EXCLUSIVE_PREVIEW)) && _date >= e->intro_date) {
979 /* Introduction date has passed...
980 * Check if it is allowed to build this vehicle type at all
981 * based on the current game settings. If not, it does not
982 * make sense to show the preview dialog to any company. */
983 if (IsVehicleTypeDisabled(e->type, false)) continue;
985 /* Do not introduce new rail wagons */
986 if (IsWagon(e->index)) continue;
988 /* Show preview dialog to one of the companies. */
989 e->flags |= ENGINE_EXCLUSIVE_PREVIEW;
990 e->preview_company = INVALID_COMPANY;
991 e->preview_asked = 0;
995 SetWindowClassesDirty(WC_BUILD_VEHICLE); // Update to show the new reliability
996 SetWindowClassesDirty(WC_REPLACE_VEHICLE);
998 InvalidateWindowClassesData(WC_BUILD_VEHICLE); // rebuild the purchase list (esp. when sorted by reliability)
999 InvalidateWindowClassesData(WC_REPLACE_VEHICLE);
1004 * Is \a name still free as name for an engine?
1005 * @param name New name of an engine.
1006 * @return \c false if the name is being used already, else \c true.
1008 static bool IsUniqueEngineName(const char *name)
1010 const Engine *e;
1012 FOR_ALL_ENGINES(e) {
1013 if (e->name != NULL && strcmp(e->name, name) == 0) return false;
1016 return true;
1020 * Rename an engine.
1021 * @param tile unused
1022 * @param flags operation to perform
1023 * @param p1 engine ID to rename
1024 * @param p2 unused
1025 * @param text the new name or an empty string when resetting to the default
1026 * @return the cost of this operation or an error
1028 CommandCost CmdRenameEngine(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1030 Engine *e = Engine::GetIfValid(p1);
1031 if (e == NULL) return CMD_ERROR;
1033 bool reset = StrEmpty(text);
1035 if (!reset) {
1036 if (Utf8StringLength(text) >= MAX_LENGTH_ENGINE_NAME_CHARS) return CMD_ERROR;
1037 if (!IsUniqueEngineName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
1040 if (flags & DC_EXEC) {
1041 free(e->name);
1043 if (reset) {
1044 e->name = NULL;
1045 } else {
1046 e->name = xstrdup(text);
1049 MarkWholeScreenDirty();
1052 return CommandCost();
1057 * Check if an engine is buildable.
1058 * @param engine index of the engine to check.
1059 * @param type the type the engine should be.
1060 * @param company index of the company.
1061 * @return True if an engine is valid, of the specified type, and buildable by
1062 * the given company.
1064 bool IsEngineBuildable(EngineID engine, VehicleType type, CompanyID company)
1066 const Engine *e = Engine::GetIfValid(engine);
1068 /* check if it's an engine that is in the engine array */
1069 if (e == NULL) return false;
1071 /* check if it's an engine of specified type */
1072 if (e->type != type) return false;
1074 /* check if it's available ... */
1075 if (company == OWNER_DEITY) {
1076 /* ... for any company (preview does not count) */
1077 if (!(e->flags & ENGINE_AVAILABLE) || e->company_avail == 0) return false;
1078 } else {
1079 /* ... for this company */
1080 if (!HasBit(e->company_avail, company)) return false;
1083 if (!e->IsEnabled()) return false;
1085 if (type == VEH_TRAIN && company != OWNER_DEITY) {
1086 /* Check if the rail type is available to this company */
1087 const Company *c = Company::Get(company);
1088 if (((GetRailTypeInfo(e->u.rail.railtype))->compatible_railtypes & c->avail_railtypes) == 0) return false;
1091 return true;
1095 * Check if an engine is refittable.
1096 * Note: Likely you want to use IsArticulatedVehicleRefittable().
1097 * @param engine index of the engine to check.
1098 * @return true if the engine is refittable.
1100 bool IsEngineRefittable(EngineID engine)
1102 const Engine *e = Engine::GetIfValid(engine);
1104 /* check if it's an engine that is in the engine array */
1105 if (e == NULL) return false;
1107 if (!e->CanCarryCargo()) return false;
1109 const EngineInfo *ei = &e->info;
1110 if (ei->refit_mask == 0) return false;
1112 /* Are there suffixes?
1113 * Note: This does not mean the suffixes are actually available for every consist at any time. */
1114 if (HasBit(ei->callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) return true;
1116 /* Is there any cargo except the default cargo? */
1117 CargoID default_cargo = e->GetDefaultCargoType();
1118 return default_cargo != CT_INVALID && ei->refit_mask != 1U << default_cargo;
1122 * Check for engines that have an appropriate availability.
1124 void CheckEngines()
1126 const Engine *e;
1127 Date min_date = INT32_MAX;
1129 FOR_ALL_ENGINES(e) {
1130 if (!e->IsEnabled()) continue;
1132 /* We have an available engine... yay! */
1133 if ((e->flags & ENGINE_AVAILABLE) != 0 && e->company_avail != 0) return;
1135 /* Okay, try to find the earliest date. */
1136 min_date = min(min_date, e->info.base_intro);
1139 if (min_date < INT32_MAX) {
1140 SetDParam(0, min_date);
1141 ShowErrorMessage(STR_ERROR_NO_VEHICLES_AVAILABLE_YET, STR_ERROR_NO_VEHICLES_AVAILABLE_YET_EXPLANATION, WL_WARNING);
1142 } else {
1143 ShowErrorMessage(STR_ERROR_NO_VEHICLES_AVAILABLE_AT_ALL, STR_ERROR_NO_VEHICLES_AVAILABLE_AT_ALL_EXPLANATION, WL_WARNING);