OpenTTD: src/engine.cpp Source File

OpenTTD

- Main Page
- Related Pages
- Modules
- Namespaces
- Data Structures
- Files

- File List
- Globals

engine.cpp
Go to the documentation of this file.
1 /* $Id: engine.cpp 27598 2016-06-09 19:04:53Z frosch $ */
2
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 */
9
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_func.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"
34
35 #include "table/strings.h"
36 #include "table/engines.h"
37
38 #include "safeguards.h"
39
40 EnginePool _engine_pool("Engine");
41 INSTANTIATE_POOL_METHODS(Engine)
42
43 EngineOverrideManager _engine_mngr;
44
49 static Year _year_engine_aging_stops;
50
54 static uint16 _introduced_railtypes;
55
57 const uint8 _engine_counts[4] = {
58 lengthof(_orig_rail_vehicle_info),
59 lengthof(_orig_road_vehicle_info),
60 lengthof(_orig_ship_vehicle_info),
61 lengthof(_orig_aircraft_vehicle_info),
62 };
63
65 const uint8 _engine_offsets[4] = {
66 0,
67 lengthof(_orig_rail_vehicle_info),
68 lengthof(_orig_rail_vehicle_info) + lengthof(_orig_road_vehicle_info),
69 lengthof(_orig_rail_vehicle_info) + lengthof(_orig_road_vehicle_info) + lengthof(_orig_ship_vehicle_info),
70 };
71
72 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));
73
74 const uint EngineOverrideManager::NUM_DEFAULT_ENGINES = _engine_counts[VEH_TRAIN] + _engine_counts[VEH_ROAD] + _engine_counts[VEH_SHIP] + _engine_counts[VEH_AIRCRAFT];
75
76 Engine::Engine() :
77 name(NULL),
78 overrides_count(0),
79 overrides(NULL)
80 {
81 }
82
83 Engine::Engine(VehicleType type, EngineID base)
84 {
85 this->type = type;
86 this->grf_prop.local_id = base;
87 this->list_position = base;
88 this->preview_company = INVALID_COMPANY;
89
90 /* Check if this base engine is within the original engine data range */
91 if (base >= _engine_counts[type]) {
92 /* Set model life to maximum to make wagons available */
93 this->info.base_life = 0xFF;
94 /* Set road vehicle tractive effort to the default value */
95 if (type == VEH_ROAD) this->u.road.tractive_effort = 0x4C;
96 /* Aircraft must have CT_INVALID as default, as there is no property */
97 if (type == VEH_AIRCRAFT) this->info.cargo_type = CT_INVALID;
98 /* Set visual effect to the default value */
99 switch (type) {
100 case VEH_TRAIN: this->u.rail.visual_effect = VE_DEFAULT; break;
101 case VEH_ROAD: this->u.road.visual_effect = VE_DEFAULT; break;
102 case VEH_SHIP: this->u.ship.visual_effect = VE_DEFAULT; break;
103 default: break; // The aircraft, disasters and especially visual effects have no NewGRF configured visual effects
104 }
105 /* Set cargo aging period to the default value. */
106 this->info.cargo_age_period = CARGO_AGING_TICKS;
107 return;
108 }
109
110 /* Copy the original engine info for this slot */
111 this->info = _orig_engine_info[_engine_offsets[type] + base];
112
113 /* Copy the original engine data for this slot */
114 switch (type) {
115 default: NOT_REACHED();
116
117 case VEH_TRAIN:
118 this->u.rail = _orig_rail_vehicle_info[base];
119 this->original_image_index = this->u.rail.image_index;
120 this->info.string_id = STR_VEHICLE_NAME_TRAIN_ENGINE_RAIL_KIRBY_PAUL_TANK_STEAM + base;
121
122 /* Set the default model life of original wagons to "infinite" */
123 if (this->u.rail.railveh_type == RAILVEH_WAGON) this->info.base_life = 0xFF;
124
125 break;
126
127 case VEH_ROAD:
128 this->u.road = _orig_road_vehicle_info[base];
129 this->original_image_index = this->u.road.image_index;
130 this->info.string_id = STR_VEHICLE_NAME_ROAD_VEHICLE_MPS_REGAL_BUS + base;
131 break;
132
133 case VEH_SHIP:
134 this->u.ship = _orig_ship_vehicle_info[base];
135 this->original_image_index = this->u.ship.image_index;
136 this->info.string_id = STR_VEHICLE_NAME_SHIP_MPS_OIL_TANKER + base;
137 break;
138
139 case VEH_AIRCRAFT:
140 this->u.air = _orig_aircraft_vehicle_info[base];
141 this->original_image_index = this->u.air.image_index;
142 this->info.string_id = STR_VEHICLE_NAME_AIRCRAFT_SAMPSON_U52 + base;
143 break;
144 }
145 }
146
147 Engine::~Engine()
148 {
149 UnloadWagonOverrides(this);
150 free(this->name);
151 }
152
157 bool Engine::IsEnabled() const
158 {
159 return this->info.string_id != STR_NEWGRF_INVALID_ENGINE && HasBit(this->info.climates, _settings_game.game_creation.landscape);
160 }
161
167 uint32 Engine::GetGRFID() const
168 {
169 const GRFFile *file = this->GetGRF();
170 return file == NULL ? 0 : file->grfid;
171 }
172
178 bool Engine::CanCarryCargo() const
179 {
180 /* For engines that can appear in a consist (i.e. rail vehicles and (articulated) road vehicles), a capacity
181 * of zero is a special case, to define the vehicle to not carry anything. The default cargotype is still used
182 * for livery selection etc.
183 * Note: Only the property is tested. A capacity callback returning 0 does not have the same effect.
184 */
185 switch (this->type) {
186 case VEH_TRAIN:
187 if (this->u.rail.capacity == 0) return false;
188 break;
189
190 case VEH_ROAD:
191 if (this->u.road.capacity == 0) return false;
192 break;
193
194 case VEH_SHIP:
195 case VEH_AIRCRAFT:
196 break;
197
198 default: NOT_REACHED();
199 }
200 return this->GetDefaultCargoType() != CT_INVALID;
201 }
202
203
211 uint Engine::DetermineCapacity(const Vehicle *v, uint16 *mail_capacity) const
212 {
213 assert(v == NULL || this->index == v->engine_type);
214 if (mail_capacity != NULL) *mail_capacity = 0;
215
216 if (!this->CanCarryCargo()) return 0;
217
218 bool new_multipliers = HasBit(this->info.misc_flags, EF_NO_DEFAULT_CARGO_MULTIPLIER);
219 CargoID default_cargo = this->GetDefaultCargoType();
220 CargoID cargo_type = (v != NULL) ? v->cargo_type : default_cargo;
221
222 if (mail_capacity != NULL && this->type == VEH_AIRCRAFT && IsCargoInClass(cargo_type, CC_PASSENGERS)) {
223 *mail_capacity = GetEngineProperty(this->index, PROP_AIRCRAFT_MAIL_CAPACITY, this->u.air.mail_capacity, v);
224 }
225
226 /* Check the refit capacity callback if we are not in the default configuration, or if we are using the new multiplier algorithm. */
227 if (HasBit(this->info.callback_mask, CBM_VEHICLE_REFIT_CAPACITY) &&
228 (new_multipliers || default_cargo != cargo_type || (v != NULL && v->cargo_subtype != 0))) {
229 uint16 callback = GetVehicleCallback(CBID_VEHICLE_REFIT_CAPACITY, 0, 0, this->index, v);
230 if (callback != CALLBACK_FAILED) return callback;
231 }
232
233 /* Get capacity according to property resp. CB */
234 uint capacity;
235 uint extra_mail_cap = 0;
236 switch (this->type) {
237 case VEH_TRAIN:
238 capacity = GetEngineProperty(this->index, PROP_TRAIN_CARGO_CAPACITY, this->u.rail.capacity, v);
239
240 /* In purchase list add the capacity of the second head. Always use the plain property for this. */
241 if (v == NULL && this->u.rail.railveh_type == RAILVEH_MULTIHEAD) capacity += this->u.rail.capacity;
242 break;
243
244 case VEH_ROAD:
245 capacity = GetEngineProperty(this->index, PROP_ROADVEH_CARGO_CAPACITY, this->u.road.capacity, v);
246 break;
247
248 case VEH_SHIP:
249 capacity = GetEngineProperty(this->index, PROP_SHIP_CARGO_CAPACITY, this->u.ship.capacity, v);
250 break;
251
252 case VEH_AIRCRAFT:
253 capacity = GetEngineProperty(this->index, PROP_AIRCRAFT_PASSENGER_CAPACITY, this->u.air.passenger_capacity, v);
254 if (!IsCargoInClass(cargo_type, CC_PASSENGERS)) {
255 extra_mail_cap = GetEngineProperty(this->index, PROP_AIRCRAFT_MAIL_CAPACITY, this->u.air.mail_capacity, v);
256 }
257 if (!new_multipliers && cargo_type == CT_MAIL) return capacity + extra_mail_cap;
258 default_cargo = CT_PASSENGERS; // Always use 'passengers' wrt. cargo multipliers
259 break;
260
261 default: NOT_REACHED();
262 }
263
264 if (!new_multipliers) {
265 /* Use the passenger multiplier for mail as well */
266 capacity += extra_mail_cap;
267 extra_mail_cap = 0;
268 }
269
270 /* Apply multipliers depending on cargo- and vehicletype. */
271 if (new_multipliers || (this->type != VEH_SHIP && default_cargo != cargo_type)) {
272 uint16 default_multiplier = new_multipliers ? 0x100 : CargoSpec::Get(default_cargo)->multiplier;
273 uint16 cargo_multiplier = CargoSpec::Get(cargo_type)->multiplier;
274 capacity *= cargo_multiplier;
275 if (extra_mail_cap > 0) {
276 uint mail_multiplier = CargoSpec::Get(CT_MAIL)->multiplier;
277 capacity += (default_multiplier * extra_mail_cap * cargo_multiplier + mail_multiplier / 2) / mail_multiplier;
278 }
279 capacity = (capacity + default_multiplier / 2) / default_multiplier;
280 }
281
282 return capacity;
283 }
284
289 Money Engine::GetRunningCost() const
290 {
291 Price base_price;
292 uint cost_factor;
293 switch (this->type) {
294 case VEH_ROAD:
295 base_price = this->u.road.running_cost_class;
296 if (base_price == INVALID_PRICE) return 0;
297 cost_factor = GetEngineProperty(this->index, PROP_ROADVEH_RUNNING_COST_FACTOR, this->u.road.running_cost);
298 break;
299
300 case VEH_TRAIN:
301 base_price = this->u.rail.running_cost_class;
302 if (base_price == INVALID_PRICE) return 0;
303 cost_factor = GetEngineProperty(this->index, PROP_TRAIN_RUNNING_COST_FACTOR, this->u.rail.running_cost);
304 break;
305
306 case VEH_SHIP:
307 base_price = PR_RUNNING_SHIP;
308 cost_factor = GetEngineProperty(this->index, PROP_SHIP_RUNNING_COST_FACTOR, this->u.ship.running_cost);
309 break;
310
311 case VEH_AIRCRAFT:
312 base_price = PR_RUNNING_AIRCRAFT;
313 cost_factor = GetEngineProperty(this->index, PROP_AIRCRAFT_RUNNING_COST_FACTOR, this->u.air.running_cost);
314 break;
315
316 default: NOT_REACHED();
317 }
318
319 return GetPrice(base_price, cost_factor, this->GetGRF(), -8);
320 }
321
326 Money Engine::GetCost() const
327 {
328 Price base_price;
329 uint cost_factor;
330 switch (this->type) {
331 case VEH_ROAD:
332 base_price = PR_BUILD_VEHICLE_ROAD;
333 cost_factor = GetEngineProperty(this->index, PROP_ROADVEH_COST_FACTOR, this->u.road.cost_factor);
334 break;
335
336 case VEH_TRAIN:
337 if (this->u.rail.railveh_type == RAILVEH_WAGON) {
338 base_price = PR_BUILD_VEHICLE_WAGON;
339 cost_factor = GetEngineProperty(this->index, PROP_TRAIN_COST_FACTOR, this->u.rail.cost_factor);
340 } else {
341 base_price = PR_BUILD_VEHICLE_TRAIN;
342 cost_factor = GetEngineProperty(this->index, PROP_TRAIN_COST_FACTOR, this->u.rail.cost_factor);
343 }
344 break;
345
346 case VEH_SHIP:
347 base_price = PR_BUILD_VEHICLE_SHIP;
348 cost_factor = GetEngineProperty(this->index, PROP_SHIP_COST_FACTOR, this->u.ship.cost_factor);
349 break;
350
351 case VEH_AIRCRAFT:
352 base_price = PR_BUILD_VEHICLE_AIRCRAFT;
353 cost_factor = GetEngineProperty(this->index, PROP_AIRCRAFT_COST_FACTOR, this->u.air.cost_factor);
354 break;
355
356 default: NOT_REACHED();
357 }
358
359 return GetPrice(base_price, cost_factor, this->GetGRF(), -8);
360 }
361
366 uint Engine::GetDisplayMaxSpeed() const
367 {
368 switch (this->type) {
369 case VEH_TRAIN:
370 return GetEngineProperty(this->index, PROP_TRAIN_SPEED, this->u.rail.max_speed);
371
372 case VEH_ROAD: {
373 uint max_speed = GetEngineProperty(this->index, PROP_ROADVEH_SPEED, 0);
374 return (max_speed != 0) ? max_speed * 2 : this->u.road.max_speed / 2;
375 }
376
377 case VEH_SHIP:
378 return GetEngineProperty(this->index, PROP_SHIP_SPEED, this->u.ship.max_speed) / 2;
379
380 case VEH_AIRCRAFT: {
381 uint max_speed = GetEngineProperty(this->index, PROP_AIRCRAFT_SPEED, 0);
382 if (max_speed != 0) {
383 return (max_speed * 128) / 10;
384 }
385 return this->u.air.max_speed;
386 }
387
388 default: NOT_REACHED();
389 }
390 }
391
398 uint Engine::GetPower() const
399 {
400 /* Only trains and road vehicles have 'power'. */
401 switch (this->type) {
402 case VEH_TRAIN:
403 return GetEngineProperty(this->index, PROP_TRAIN_POWER, this->u.rail.power);
404 case VEH_ROAD:
405 return GetEngineProperty(this->index, PROP_ROADVEH_POWER, this->u.road.power) * 10;
406
407 default: NOT_REACHED();
408 }
409 }
410
416 uint Engine::GetDisplayWeight() const
417 {
418 /* Only trains and road vehicles have 'weight'. */
419 switch (this->type) {
420 case VEH_TRAIN:
421 return GetEngineProperty(this->index, PROP_TRAIN_WEIGHT, this->u.rail.weight) << (this->u.rail.railveh_type == RAILVEH_MULTIHEAD ? 1 : 0);
422 case VEH_ROAD:
423 return GetEngineProperty(this->index, PROP_ROADVEH_WEIGHT, this->u.road.weight) / 4;
424
425 default: NOT_REACHED();
426 }
427 }
428
434 uint Engine::GetDisplayMaxTractiveEffort() const
435 {
436 /* Only trains and road vehicles have 'tractive effort'. */
437 switch (this->type) {
438 case VEH_TRAIN:
439 return (10 * this->GetDisplayWeight() * GetEngineProperty(this->index, PROP_TRAIN_TRACTIVE_EFFORT, this->u.rail.tractive_effort)) / 256;
440 case VEH_ROAD:
441 return (10 * this->GetDisplayWeight() * GetEngineProperty(this->index, PROP_ROADVEH_TRACTIVE_EFFORT, this->u.road.tractive_effort)) / 256;
442
443 default: NOT_REACHED();
444 }
445 }
446
451 Date Engine::GetLifeLengthInDays() const
452 {
453 /* Assume leap years; this gives the player a bit more than the given amount of years, but never less. */
454 return (this->info.lifelength + _settings_game.vehicle.extend_vehicle_life) * DAYS_IN_LEAP_YEAR;
455 }
456
461 uint16 Engine::GetRange() const
462 {
463 switch (this->type) {
464 case VEH_AIRCRAFT:
465 return GetEngineProperty(this->index, PROP_AIRCRAFT_RANGE, this->u.air.max_range);
466
467 default: NOT_REACHED();
468 }
469 }
470
474 void EngineOverrideManager::ResetToDefaultMapping()
475 {
476 this->Clear();
477 for (VehicleType type = VEH_TRAIN; type <= VEH_AIRCRAFT; type++) {
478 for (uint internal_id = 0; internal_id < _engine_counts[type]; internal_id++) {
479 EngineIDMapping *eid = this->Append();
480 eid->type = type;
481 eid->grfid = INVALID_GRFID;
482 eid->internal_id = internal_id;
483 eid->substitute_id = internal_id;
484 }
485 }
486 }
487
497 EngineID EngineOverrideManager::GetID(VehicleType type, uint16 grf_local_id, uint32 grfid)
498 {
499 const EngineIDMapping *end = this->End();
500 EngineID index = 0;
501 for (const EngineIDMapping *eid = this->Begin(); eid != end; eid++, index++) {
502 if (eid->type == type && eid->grfid == grfid && eid->internal_id == grf_local_id) {
503 return index;
504 }
505 }
506 return INVALID_ENGINE;
507 }
508
514 bool EngineOverrideManager::ResetToCurrentNewGRFConfig()
515 {
516 const Vehicle *v;
517 FOR_ALL_VEHICLES(v) {
518 if (IsCompanyBuildableVehicleType(v)) return false;
519 }
520
521 /* Reset the engines, they will get new EngineIDs */
522 _engine_mngr.ResetToDefaultMapping();
523 ReloadNewGRFData();
524
525 return true;
526 }
527
531 void SetupEngines()
532 {
533 DeleteWindowByClass(WC_ENGINE_PREVIEW);
534 _engine_pool.CleanPool();
535
536 assert(_engine_mngr.Length() >= _engine_mngr.NUM_DEFAULT_ENGINES);
537 const EngineIDMapping *end = _engine_mngr.End();
538 uint index = 0;
539 for (const EngineIDMapping *eid = _engine_mngr.Begin(); eid != end; eid++, index++) {
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 const Engine *e = new Engine(eid->type, eid->internal_id);
544 assert(e->index == index);
545 }
546
547 _introduced_railtypes = 0;
548 }
549
553 static void CheckRailIntroduction()
554 {
555 /* All railtypes have been introduced. */
556 if (_introduced_railtypes == UINT16_MAX || Company::GetPoolSize() == 0) return;
557
558 /* We need to find the railtypes that are known to all companies. */
559 RailTypes rts = (RailTypes)UINT16_MAX;
560
561 /* We are at, or past the introduction date of the rail. */
562 Company *c;
563 FOR_ALL_COMPANIES(c) {
564 c->avail_railtypes = AddDateIntroducedRailTypes(c->avail_railtypes, _date);
565 rts &= c->avail_railtypes;
566 }
567
568 _introduced_railtypes |= rts;
569 }
570
571 void ShowEnginePreviewWindow(EngineID engine);
572
578 static bool IsWagon(EngineID index)
579 {
580 const Engine *e = Engine::Get(index);
581 return e->type == VEH_TRAIN && e->u.rail.railveh_type == RAILVEH_WAGON;
582 }
583
588 static void CalcEngineReliability(Engine *e)
589 {
590 uint age = e->age;
591
592 /* Check for early retirement */
593 if (e->company_avail != 0 && !_settings_game.vehicle.never_expire_vehicles && e->info.base_life != 0xFF) {
594 int retire_early = e->info.retire_early;
595 uint retire_early_max_age = max(0, e->duration_phase_1 + e->duration_phase_2 - retire_early * 12);
596 if (retire_early != 0 && age >= retire_early_max_age) {
597 /* Early retirement is enabled and we're past the date... */
598 e->company_avail = 0;
599 AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
600 }
601 }
602
603 if (age < e->duration_phase_1) {
604 uint start = e->reliability_start;
605 e->reliability = age * (e->reliability_max - start) / e->duration_phase_1 + start;
606 } else if ((age -= e->duration_phase_1) < e->duration_phase_2 || _settings_game.vehicle.never_expire_vehicles || e->info.base_life == 0xFF) {
607 /* We are at the peak of this engines life. It will have max reliability.
608 * This is also true if the engines never expire. They will not go bad over time */
609 e->reliability = e->reliability_max;
610 } else if ((age -= e->duration_phase_2) < e->duration_phase_3) {
611 uint max = e->reliability_max;
612 e->reliability = (int)age * (int)(e->reliability_final - max) / e->duration_phase_3 + max;
613 } else {
614 /* time's up for this engine.
615 * We will now completely retire this design */
616 e->company_avail = 0;
617 e->reliability = e->reliability_final;
618 /* Kick this engine out of the lists */
619 AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
620 }
621 SetWindowClassesDirty(WC_BUILD_VEHICLE); // Update to show the new reliability
622 SetWindowClassesDirty(WC_REPLACE_VEHICLE);
623 }
624
626 void SetYearEngineAgingStops()
627 {
628 /* Determine last engine aging year, default to 2050 as previously. */
629 _year_engine_aging_stops = 2050;
630
631 const Engine *e;
632 FOR_ALL_ENGINES(e) {
633 const EngineInfo *ei = &e->info;
634
635 /* Exclude certain engines */
636 if (!HasBit(ei->climates, _settings_game.game_creation.landscape)) continue;
637 if (e->type == VEH_TRAIN && e->u.rail.railveh_type == RAILVEH_WAGON) continue;
638
639 /* Base year ending date on half the model life */
640 YearMonthDay ymd;
641 ConvertDateToYMD(ei->base_intro + (ei->lifelength * DAYS_IN_LEAP_YEAR) / 2, &ymd);
642
643 _year_engine_aging_stops = max(_year_engine_aging_stops, ymd.year);
644 }
645 }
646
652 void StartupOneEngine(Engine *e, Date aging_date)
653 {
654 const EngineInfo *ei = &e->info;
655
656 e->age = 0;
657 e->flags = 0;
658 e->company_avail = 0;
659 e->company_hidden = 0;
660
661 /* Don't randomise the start-date in the first two years after gamestart to ensure availability
662 * of engines in early starting games.
663 * Note: TTDP uses fixed 1922 */
664 uint32 r = Random();
665 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;
666 if (e->intro_date <= _date) {
667 e->age = (aging_date - e->intro_date) >> 5;
668 e->company_avail = (CompanyMask)-1;
669 e->flags |= ENGINE_AVAILABLE;
670 }
671
672 e->reliability_start = GB(r, 16, 14) + 0x7AE0;
673 r = Random();
674 e->reliability_max = GB(r, 0, 14) + 0xBFFF;
675 e->reliability_final = GB(r, 16, 14) + 0x3FFF;
676
677 r = Random();
678 e->duration_phase_1 = GB(r, 0, 5) + 7;
679 e->duration_phase_2 = GB(r, 5, 4) + ei->base_life * 12 - 96;
680 e->duration_phase_3 = GB(r, 9, 7) + 120;
681
682 e->reliability_spd_dec = ei->decay_speed << 2;
683
684 CalcEngineReliability(e);
685
686 /* prevent certain engines from ever appearing. */
687 if (!HasBit(ei->climates, _settings_game.game_creation.landscape)) {
688 e->flags |= ENGINE_AVAILABLE;
689 e->company_avail = 0;
690 }
691 }
692
697 void StartupEngines()
698 {
699 Engine *e;
700 /* Aging of vehicles stops, so account for that when starting late */
701 const Date aging_date = min(_date, ConvertYMDToDate(_year_engine_aging_stops, 0, 1));
702
703 FOR_ALL_ENGINES(e) {
704 StartupOneEngine(e, aging_date);
705 }
706
707 /* Update the bitmasks for the vehicle lists */
708 Company *c;
709 FOR_ALL_COMPANIES(c) {
710 c->avail_railtypes = GetCompanyRailtypes(c->index);
711 c->avail_roadtypes = GetCompanyRoadtypes(c->index);
712 }
713
714 /* Rail types that are invalid or never introduced are marked as
715 * being introduced upon start. That way we can easily check whether
716 * there is any date related introduction that is still going to
717 * happen somewhere in the future. */
718 for (RailType rt = RAILTYPE_BEGIN; rt != RAILTYPE_END; rt++) {
719 const RailtypeInfo *rti = GetRailTypeInfo(rt);
720 if (rti->label != 0 && IsInsideMM(rti->introduction_date, 0, MAX_DAY)) continue;
721
722 SetBit(_introduced_railtypes, rt);
723 }
724
725 CheckRailIntroduction();
726
727 /* Invalidate any open purchase lists */
728 InvalidateWindowClassesData(WC_BUILD_VEHICLE);
729 }
730
736 static void AcceptEnginePreview(EngineID eid, CompanyID company)
737 {
738 Engine *e = Engine::Get(eid);
739 Company *c = Company::Get(company);
740
741 SetBit(e->company_avail, company);
742 if (e->type == VEH_TRAIN) {
743 assert(e->u.rail.railtype < RAILTYPE_END);
744 c->avail_railtypes = AddDateIntroducedRailTypes(c->avail_railtypes | GetRailTypeInfo(e->u.rail.railtype)->introduces_railtypes, _date);
745 } else if (e->type == VEH_ROAD) {
746 SetBit(c->avail_roadtypes, HasBit(e->info.misc_flags, EF_ROAD_TRAM) ? ROADTYPE_TRAM : ROADTYPE_ROAD);
747 }
748
749 e->preview_company = INVALID_COMPANY;
750 e->preview_asked = (CompanyMask)-1;
751 if (company == _local_company) {
752 AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
753 }
754
755 /* Update the toolbar. */
756 if (e->type == VEH_ROAD) InvalidateWindowData(WC_BUILD_TOOLBAR, TRANSPORT_ROAD);
757 if (e->type == VEH_SHIP) InvalidateWindowData(WC_BUILD_TOOLBAR, TRANSPORT_WATER);
758
759 /* Notify preview window, that it might want to close.
760 * Note: We cannot directly close the window.
761 * In singleplayer this function is called from the preview window, so
762 * we have to use the GUI-scope scheduling of InvalidateWindowData.
763 */
764 InvalidateWindowData(WC_ENGINE_PREVIEW, eid);
765 }
766
772 static CompanyID GetPreviewCompany(Engine *e)
773 {
774 CompanyID best_company = INVALID_COMPANY;
775
776 /* For trains the cargomask has no useful meaning, since you can attach other wagons */
777 uint32 cargomask = e->type != VEH_TRAIN ? GetUnionOfArticulatedRefitMasks(e->index, true) : (uint32)-1;
778
779 int32 best_hist = -1;
780 const Company *c;
781 FOR_ALL_COMPANIES(c) {
782 if (c->block_preview == 0 && !HasBit(e->preview_asked, c->index) &&
783 c->old_economy[0].performance_history > best_hist) {
784
785 /* Check whether the company uses similar vehicles */
786 Vehicle *v;
787 FOR_ALL_VEHICLES(v) {
788 if (v->owner != c->index || v->type != e->type) continue;
789 if (!v->GetEngine()->CanCarryCargo() || !HasBit(cargomask, v->cargo_type)) continue;
790
791 best_hist = c->old_economy[0].performance_history;
792 best_company = c->index;
793 break;
794 }
795 }
796 }
797
798 return best_company;
799 }
800
808 static bool IsVehicleTypeDisabled(VehicleType type, bool ai)
809 {
810 switch (type) {
811 case VEH_TRAIN: return _settings_game.vehicle.max_trains == 0 || (ai && _settings_game.ai.ai_disable_veh_train);
812 case VEH_ROAD: return _settings_game.vehicle.max_roadveh == 0 || (ai && _settings_game.ai.ai_disable_veh_roadveh);
813 case VEH_SHIP: return _settings_game.vehicle.max_ships == 0 || (ai && _settings_game.ai.ai_disable_veh_ship);
814 case VEH_AIRCRAFT: return _settings_game.vehicle.max_aircraft == 0 || (ai && _settings_game.ai.ai_disable_veh_aircraft);
815
816 default: NOT_REACHED();
817 }
818 }
819
821 void EnginesDailyLoop()
822 {
823 CheckRailIntroduction();
824
825 if (_cur_year >= _year_engine_aging_stops) return;
826
827 Engine *e;
828 FOR_ALL_ENGINES(e) {
829 EngineID i = e->index;
830 if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) {
831 if (e->preview_company != INVALID_COMPANY) {
832 if (!--e->preview_wait) {
833 DeleteWindowById(WC_ENGINE_PREVIEW, i);
834 e->preview_company = INVALID_COMPANY;
835 }
836 } else if (CountBits(e->preview_asked) < MAX_COMPANIES) {
837 e->preview_company = GetPreviewCompany(e);
838
839 if (e->preview_company == INVALID_COMPANY) {
840 e->preview_asked = (CompanyMask)-1;
841 continue;
842 }
843
844 SetBit(e->preview_asked, e->preview_company);
845 e->preview_wait = 20;
846 /* AIs are intentionally not skipped for preview even if they cannot build a certain
847 * vehicle type. This is done to not give poor performing human companies an "unfair"
848 * boost that they wouldn't have gotten against other human companies. The check on
849 * the line below is just to make AIs not notice that they have a preview if they
850 * cannot build the vehicle. */
851 if (!IsVehicleTypeDisabled(e->type, true)) AI::NewEvent(e->preview_company, new ScriptEventEnginePreview(i));
852 if (IsInteractiveCompany(e->preview_company)) ShowEnginePreviewWindow(i);
853 }
854 }
855 }
856 }
857
862 void ClearEnginesHiddenFlagOfCompany(CompanyID cid)
863 {
864 Engine *e;
865 FOR_ALL_ENGINES(e) {
866 SB(e->company_hidden, cid, 1, 0);
867 }
868 }
869
879 CommandCost CmdSetVehicleVisibility(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
880 {
881 Engine *e = Engine::GetIfValid(GB(p2, 0, 31));
882 if (e == NULL || _current_company >= MAX_COMPANIES) return CMD_ERROR;
883 if (!IsEngineBuildable(e->index, e->type, _current_company)) return CMD_ERROR;
884
885 if ((flags & DC_EXEC) != 0) {
886 SB(e->company_hidden, _current_company, 1, GB(p2, 31, 1));
887 AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
888 }
889
890 return CommandCost();
891 }
892
903 CommandCost CmdWantEnginePreview(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
904 {
905 Engine *e = Engine::GetIfValid(p1);
906 if (e == NULL || !(e->flags & ENGINE_EXCLUSIVE_PREVIEW) || e->preview_company != _current_company) return CMD_ERROR;
907
908 if (flags & DC_EXEC) AcceptEnginePreview(p1, _current_company);
909
910 return CommandCost();
911 }
912
918 static void NewVehicleAvailable(Engine *e)
919 {
920 Vehicle *v;
921 Company *c;
922 EngineID index = e->index;
923
924 /* In case the company didn't build the vehicle during the intro period,
925 * prevent that company from getting future intro periods for a while. */
926 if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) {
927 FOR_ALL_COMPANIES(c) {
928 uint block_preview = c->block_preview;
929
930 if (!HasBit(e->company_avail, c->index)) continue;
931
932 /* We assume the user did NOT build it.. prove me wrong ;) */
933 c->block_preview = 20;
934
935 FOR_ALL_VEHICLES(v) {
936 if (v->type == VEH_TRAIN || v->type == VEH_ROAD || v->type == VEH_SHIP ||
937 (v->type == VEH_AIRCRAFT && Aircraft::From(v)->IsNormalAircraft())) {
938 if (v->owner == c->index && v->engine_type == index) {
939 /* The user did prove me wrong, so restore old value */
940 c->block_preview = block_preview;
941 break;
942 }
943 }
944 }
945 }
946 }
947
948 e->flags = (e->flags & ~ENGINE_EXCLUSIVE_PREVIEW) | ENGINE_AVAILABLE;
949 AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
950
951 /* Now available for all companies */
952 e->company_avail = (CompanyMask)-1;
953
954 /* Do not introduce new rail wagons */
955 if (IsWagon(index)) return;
956
957 if (e->type == VEH_TRAIN) {
958 /* maybe make another rail type available */
959 RailType railtype = e->u.rail.railtype;
960 assert(railtype < RAILTYPE_END);
961 FOR_ALL_COMPANIES(c) c->avail_railtypes = AddDateIntroducedRailTypes(c->avail_railtypes | GetRailTypeInfo(e->u.rail.railtype)->introduces_railtypes, _date);
962 } else if (e->type == VEH_ROAD) {
963 /* maybe make another road type available */
964 FOR_ALL_COMPANIES(c) SetBit(c->avail_roadtypes, HasBit(e->info.misc_flags, EF_ROAD_TRAM) ? ROADTYPE_TRAM : ROADTYPE_ROAD);
965 }
966
967 /* Only broadcast event if AIs are able to build this vehicle type. */
968 if (!IsVehicleTypeDisabled(e->type, true)) AI::BroadcastNewEvent(new ScriptEventEngineAvailable(index));
969
970 /* Only provide the "New Vehicle available" news paper entry, if engine can be built. */
971 if (!IsVehicleTypeDisabled(e->type, false)) {
972 SetDParam(0, GetEngineCategoryName(index));
973 SetDParam(1, index);
974 AddNewsItem(STR_NEWS_NEW_VEHICLE_NOW_AVAILABLE_WITH_TYPE, NT_NEW_VEHICLES, NF_VEHICLE, NR_ENGINE, index);
975 }
976
977 /* Update the toolbar. */
978 if (e->type == VEH_ROAD) InvalidateWindowData(WC_BUILD_TOOLBAR, TRANSPORT_ROAD);
979 if (e->type == VEH_SHIP) InvalidateWindowData(WC_BUILD_TOOLBAR, TRANSPORT_WATER);
980
981 /* Close pending preview windows */
982 DeleteWindowById(WC_ENGINE_PREVIEW, index);
983 }
984
986 void EnginesMonthlyLoop()
987 {
988 if (_cur_year < _year_engine_aging_stops) {
989 Engine *e;
990 FOR_ALL_ENGINES(e) {
991 /* Age the vehicle */
992 if ((e->flags & ENGINE_AVAILABLE) && e->age != MAX_DAY) {
993 e->age++;
994 CalcEngineReliability(e);
995 }
996
997 /* Do not introduce invalid engines */
998 if (!e->IsEnabled()) continue;
999
1000 if (!(e->flags & ENGINE_AVAILABLE) && _date >= (e->intro_date + DAYS_IN_YEAR)) {
1001 /* Introduce it to all companies */
1002 NewVehicleAvailable(e);
1003 } else if (!(e->flags & (ENGINE_AVAILABLE | ENGINE_EXCLUSIVE_PREVIEW)) && _date >= e->intro_date) {
1004 /* Introduction date has passed...
1005 * Check if it is allowed to build this vehicle type at all
1006 * based on the current game settings. If not, it does not
1007 * make sense to show the preview dialog to any company. */
1008 if (IsVehicleTypeDisabled(e->type, false)) continue;
1009
1010 /* Do not introduce new rail wagons */
1011 if (IsWagon(e->index)) continue;
1012
1013 /* Show preview dialog to one of the companies. */
1014 e->flags |= ENGINE_EXCLUSIVE_PREVIEW;
1015 e->preview_company = INVALID_COMPANY;
1016 e->preview_asked = 0;
1017 }
1018 }
1019
1020 InvalidateWindowClassesData(WC_BUILD_VEHICLE); // rebuild the purchase list (esp. when sorted by reliability)
1021 }
1022 }
1023
1029 static bool IsUniqueEngineName(const char *name)
1030 {
1031 const Engine *e;
1032
1033 FOR_ALL_ENGINES(e) {
1034 if (e->name != NULL && strcmp(e->name, name) == 0) return false;
1035 }
1036
1037 return true;
1038 }
1039
1049 CommandCost CmdRenameEngine(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1050 {
1051 Engine *e = Engine::GetIfValid(p1);
1052 if (e == NULL) return CMD_ERROR;
1053
1054 bool reset = StrEmpty(text);
1055
1056 if (!reset) {
1057 if (Utf8StringLength(text) >= MAX_LENGTH_ENGINE_NAME_CHARS) return CMD_ERROR;
1058 if (!IsUniqueEngineName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
1059 }
1060
1061 if (flags & DC_EXEC) {
1062 free(e->name);
1063
1064 if (reset) {
1065 e->name = NULL;
1066 } else {
1067 e->name = stredup(text);
1068 }
1069
1070 MarkWholeScreenDirty();
1071 }
1072
1073 return CommandCost();
1074 }
1075
1076
1085 bool IsEngineBuildable(EngineID engine, VehicleType type, CompanyID company)
1086 {
1087 const Engine *e = Engine::GetIfValid(engine);
1088
1089 /* check if it's an engine that is in the engine array */
1090 if (e == NULL) return false;
1091
1092 /* check if it's an engine of specified type */
1093 if (e->type != type) return false;
1094
1095 /* check if it's available ... */
1096 if (company == OWNER_DEITY) {
1097 /* ... for any company (preview does not count) */
1098 if (!(e->flags & ENGINE_AVAILABLE) || e->company_avail == 0) return false;
1099 } else {
1100 /* ... for this company */
1101 if (!HasBit(e->company_avail, company)) return false;
1102 }
1103
1104 if (!e->IsEnabled()) return false;
1105
1106 if (type == VEH_TRAIN && company != OWNER_DEITY) {
1107 /* Check if the rail type is available to this company */
1108 const Company *c = Company::Get(company);
1109 if (((GetRailTypeInfo(e->u.rail.railtype))->compatible_railtypes & c->avail_railtypes) == 0) return false;
1110 }
1111
1112 return true;
1113 }
1114
1121 bool IsEngineRefittable(EngineID engine)
1122 {
1123 const Engine *e = Engine::GetIfValid(engine);
1124
1125 /* check if it's an engine that is in the engine array */
1126 if (e == NULL) return false;
1127
1128 if (!e->CanCarryCargo()) return false;
1129
1130 const EngineInfo *ei = &e->info;
1131 if (ei->refit_mask == 0) return false;
1132
1133 /* Are there suffixes?
1134 * Note: This does not mean the suffixes are actually available for every consist at any time. */
1135 if (HasBit(ei->callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) return true;
1136
1137 /* Is there any cargo except the default cargo? */
1138 CargoID default_cargo = e->GetDefaultCargoType();
1139 return default_cargo != CT_INVALID && ei->refit_mask != 1U << default_cargo;
1140 }
1141
1145 void CheckEngines()
1146 {
1147 const Engine *e;
1148 Date min_date = INT32_MAX;
1149
1150 FOR_ALL_ENGINES(e) {
1151 if (!e->IsEnabled()) continue;
1152
1153 /* We have an available engine... yay! */
1154 if ((e->flags & ENGINE_AVAILABLE) != 0 && e->company_avail != 0) return;
1155
1156 /* Okay, try to find the earliest date. */
1157 min_date = min(min_date, e->info.base_intro);
1158 }
1159
1160 if (min_date < INT32_MAX) {
1161 SetDParam(0, min_date);
1162 ShowErrorMessage(STR_ERROR_NO_VEHICLES_AVAILABLE_YET, STR_ERROR_NO_VEHICLES_AVAILABLE_YET_EXPLANATION, WL_WARNING);
1163 } else {
1164 ShowErrorMessage(STR_ERROR_NO_VEHICLES_AVAILABLE_AT_ALL, STR_ERROR_NO_VEHICLES_AVAILABLE_AT_ALL_EXPLANATION, WL_WARNING);
1165 }
1166 }