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 27700 2016-12-20 12:35:36Z 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
52 const uint8 _engine_counts[4] = {
53 lengthof(_orig_rail_vehicle_info),
54 lengthof(_orig_road_vehicle_info),
55 lengthof(_orig_ship_vehicle_info),
56 lengthof(_orig_aircraft_vehicle_info),
57 };
58
60 const uint8 _engine_offsets[4] = {
61 0,
62 lengthof(_orig_rail_vehicle_info),
63 lengthof(_orig_rail_vehicle_info) + lengthof(_orig_road_vehicle_info),
64 lengthof(_orig_rail_vehicle_info) + lengthof(_orig_road_vehicle_info) + lengthof(_orig_ship_vehicle_info),
65 };
66
67 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));
68
69 const uint EngineOverrideManager::NUM_DEFAULT_ENGINES = _engine_counts[VEH_TRAIN] + _engine_counts[VEH_ROAD] + _engine_counts[VEH_SHIP] + _engine_counts[VEH_AIRCRAFT];
70
71 Engine::Engine() :
72 name(NULL),
73 overrides_count(0),
74 overrides(NULL)
75 {
76 }
77
78 Engine::Engine(VehicleType type, EngineID base)
79 {
80 this->type = type;
81 this->grf_prop.local_id = base;
82 this->list_position = base;
83 this->preview_company = INVALID_COMPANY;
84
85 /* Check if this base engine is within the original engine data range */
86 if (base >= _engine_counts[type]) {
87 /* Set model life to maximum to make wagons available */
88 this->info.base_life = 0xFF;
89 /* Set road vehicle tractive effort to the default value */
90 if (type == VEH_ROAD) this->u.road.tractive_effort = 0x4C;
91 /* Aircraft must have CT_INVALID as default, as there is no property */
92 if (type == VEH_AIRCRAFT) this->info.cargo_type = CT_INVALID;
93 /* Set visual effect to the default value */
94 switch (type) {
95 case VEH_TRAIN: this->u.rail.visual_effect = VE_DEFAULT; break;
96 case VEH_ROAD: this->u.road.visual_effect = VE_DEFAULT; break;
97 case VEH_SHIP: this->u.ship.visual_effect = VE_DEFAULT; break;
98 default: break; // The aircraft, disasters and especially visual effects have no NewGRF configured visual effects
99 }
100 /* Set cargo aging period to the default value. */
101 this->info.cargo_age_period = CARGO_AGING_TICKS;
102 return;
103 }
104
105 /* Copy the original engine info for this slot */
106 this->info = _orig_engine_info[_engine_offsets[type] + base];
107
108 /* Copy the original engine data for this slot */
109 switch (type) {
110 default: NOT_REACHED();
111
112 case VEH_TRAIN:
113 this->u.rail = _orig_rail_vehicle_info[base];
114 this->original_image_index = this->u.rail.image_index;
115 this->info.string_id = STR_VEHICLE_NAME_TRAIN_ENGINE_RAIL_KIRBY_PAUL_TANK_STEAM + base;
116
117 /* Set the default model life of original wagons to "infinite" */
118 if (this->u.rail.railveh_type == RAILVEH_WAGON) this->info.base_life = 0xFF;
119
120 break;
121
122 case VEH_ROAD:
123 this->u.road = _orig_road_vehicle_info[base];
124 this->original_image_index = this->u.road.image_index;
125 this->info.string_id = STR_VEHICLE_NAME_ROAD_VEHICLE_MPS_REGAL_BUS + base;
126 break;
127
128 case VEH_SHIP:
129 this->u.ship = _orig_ship_vehicle_info[base];
130 this->original_image_index = this->u.ship.image_index;
131 this->info.string_id = STR_VEHICLE_NAME_SHIP_MPS_OIL_TANKER + base;
132 break;
133
134 case VEH_AIRCRAFT:
135 this->u.air = _orig_aircraft_vehicle_info[base];
136 this->original_image_index = this->u.air.image_index;
137 this->info.string_id = STR_VEHICLE_NAME_AIRCRAFT_SAMPSON_U52 + base;
138 break;
139 }
140 }
141
142 Engine::~Engine()
143 {
144 UnloadWagonOverrides(this);
145 free(this->name);
146 }
147
152 bool Engine::IsEnabled() const
153 {
154 return this->info.string_id != STR_NEWGRF_INVALID_ENGINE && HasBit(this->info.climates, _settings_game.game_creation.landscape);
155 }
156
162 uint32 Engine::GetGRFID() const
163 {
164 const GRFFile *file = this->GetGRF();
165 return file == NULL ? 0 : file->grfid;
166 }
167
173 bool Engine::CanCarryCargo() const
174 {
175 /* For engines that can appear in a consist (i.e. rail vehicles and (articulated) road vehicles), a capacity
176 * of zero is a special case, to define the vehicle to not carry anything. The default cargotype is still used
177 * for livery selection etc.
178 * Note: Only the property is tested. A capacity callback returning 0 does not have the same effect.
179 */
180 switch (this->type) {
181 case VEH_TRAIN:
182 if (this->u.rail.capacity == 0) return false;
183 break;
184
185 case VEH_ROAD:
186 if (this->u.road.capacity == 0) return false;
187 break;
188
189 case VEH_SHIP:
190 case VEH_AIRCRAFT:
191 break;
192
193 default: NOT_REACHED();
194 }
195 return this->GetDefaultCargoType() != CT_INVALID;
196 }
197
198
206 uint Engine::DetermineCapacity(const Vehicle *v, uint16 *mail_capacity) const
207 {
208 assert(v == NULL || this->index == v->engine_type);
209 if (mail_capacity != NULL) *mail_capacity = 0;
210
211 if (!this->CanCarryCargo()) return 0;
212
213 bool new_multipliers = HasBit(this->info.misc_flags, EF_NO_DEFAULT_CARGO_MULTIPLIER);
214 CargoID default_cargo = this->GetDefaultCargoType();
215 CargoID cargo_type = (v != NULL) ? v->cargo_type : default_cargo;
216
217 if (mail_capacity != NULL && this->type == VEH_AIRCRAFT && IsCargoInClass(cargo_type, CC_PASSENGERS)) {
218 *mail_capacity = GetEngineProperty(this->index, PROP_AIRCRAFT_MAIL_CAPACITY, this->u.air.mail_capacity, v);
219 }
220
221 /* Check the refit capacity callback if we are not in the default configuration, or if we are using the new multiplier algorithm. */
222 if (HasBit(this->info.callback_mask, CBM_VEHICLE_REFIT_CAPACITY) &&
223 (new_multipliers || default_cargo != cargo_type || (v != NULL && v->cargo_subtype != 0))) {
224 uint16 callback = GetVehicleCallback(CBID_VEHICLE_REFIT_CAPACITY, 0, 0, this->index, v);
225 if (callback != CALLBACK_FAILED) return callback;
226 }
227
228 /* Get capacity according to property resp. CB */
229 uint capacity;
230 uint extra_mail_cap = 0;
231 switch (this->type) {
232 case VEH_TRAIN:
233 capacity = GetEngineProperty(this->index, PROP_TRAIN_CARGO_CAPACITY, this->u.rail.capacity, v);
234
235 /* In purchase list add the capacity of the second head. Always use the plain property for this. */
236 if (v == NULL && this->u.rail.railveh_type == RAILVEH_MULTIHEAD) capacity += this->u.rail.capacity;
237 break;
238
239 case VEH_ROAD:
240 capacity = GetEngineProperty(this->index, PROP_ROADVEH_CARGO_CAPACITY, this->u.road.capacity, v);
241 break;
242
243 case VEH_SHIP:
244 capacity = GetEngineProperty(this->index, PROP_SHIP_CARGO_CAPACITY, this->u.ship.capacity, v);
245 break;
246
247 case VEH_AIRCRAFT:
248 capacity = GetEngineProperty(this->index, PROP_AIRCRAFT_PASSENGER_CAPACITY, this->u.air.passenger_capacity, v);
249 if (!IsCargoInClass(cargo_type, CC_PASSENGERS)) {
250 extra_mail_cap = GetEngineProperty(this->index, PROP_AIRCRAFT_MAIL_CAPACITY, this->u.air.mail_capacity, v);
251 }
252 if (!new_multipliers && cargo_type == CT_MAIL) return capacity + extra_mail_cap;
253 default_cargo = CT_PASSENGERS; // Always use 'passengers' wrt. cargo multipliers
254 break;
255
256 default: NOT_REACHED();
257 }
258
259 if (!new_multipliers) {
260 /* Use the passenger multiplier for mail as well */
261 capacity += extra_mail_cap;
262 extra_mail_cap = 0;
263 }
264
265 /* Apply multipliers depending on cargo- and vehicletype. */
266 if (new_multipliers || (this->type != VEH_SHIP && default_cargo != cargo_type)) {
267 uint16 default_multiplier = new_multipliers ? 0x100 : CargoSpec::Get(default_cargo)->multiplier;
268 uint16 cargo_multiplier = CargoSpec::Get(cargo_type)->multiplier;
269 capacity *= cargo_multiplier;
270 if (extra_mail_cap > 0) {
271 uint mail_multiplier = CargoSpec::Get(CT_MAIL)->multiplier;
272 capacity += (default_multiplier * extra_mail_cap * cargo_multiplier + mail_multiplier / 2) / mail_multiplier;
273 }
274 capacity = (capacity + default_multiplier / 2) / default_multiplier;
275 }
276
277 return capacity;
278 }
279
284 Money Engine::GetRunningCost() const
285 {
286 Price base_price;
287 uint cost_factor;
288 switch (this->type) {
289 case VEH_ROAD:
290 base_price = this->u.road.running_cost_class;
291 if (base_price == INVALID_PRICE) return 0;
292 cost_factor = GetEngineProperty(this->index, PROP_ROADVEH_RUNNING_COST_FACTOR, this->u.road.running_cost);
293 break;
294
295 case VEH_TRAIN:
296 base_price = this->u.rail.running_cost_class;
297 if (base_price == INVALID_PRICE) return 0;
298 cost_factor = GetEngineProperty(this->index, PROP_TRAIN_RUNNING_COST_FACTOR, this->u.rail.running_cost);
299 break;
300
301 case VEH_SHIP:
302 base_price = PR_RUNNING_SHIP;
303 cost_factor = GetEngineProperty(this->index, PROP_SHIP_RUNNING_COST_FACTOR, this->u.ship.running_cost);
304 break;
305
306 case VEH_AIRCRAFT:
307 base_price = PR_RUNNING_AIRCRAFT;
308 cost_factor = GetEngineProperty(this->index, PROP_AIRCRAFT_RUNNING_COST_FACTOR, this->u.air.running_cost);
309 break;
310
311 default: NOT_REACHED();
312 }
313
314 return GetPrice(base_price, cost_factor, this->GetGRF(), -8);
315 }
316
321 Money Engine::GetCost() const
322 {
323 Price base_price;
324 uint cost_factor;
325 switch (this->type) {
326 case VEH_ROAD:
327 base_price = PR_BUILD_VEHICLE_ROAD;
328 cost_factor = GetEngineProperty(this->index, PROP_ROADVEH_COST_FACTOR, this->u.road.cost_factor);
329 break;
330
331 case VEH_TRAIN:
332 if (this->u.rail.railveh_type == RAILVEH_WAGON) {
333 base_price = PR_BUILD_VEHICLE_WAGON;
334 cost_factor = GetEngineProperty(this->index, PROP_TRAIN_COST_FACTOR, this->u.rail.cost_factor);
335 } else {
336 base_price = PR_BUILD_VEHICLE_TRAIN;
337 cost_factor = GetEngineProperty(this->index, PROP_TRAIN_COST_FACTOR, this->u.rail.cost_factor);
338 }
339 break;
340
341 case VEH_SHIP:
342 base_price = PR_BUILD_VEHICLE_SHIP;
343 cost_factor = GetEngineProperty(this->index, PROP_SHIP_COST_FACTOR, this->u.ship.cost_factor);
344 break;
345
346 case VEH_AIRCRAFT:
347 base_price = PR_BUILD_VEHICLE_AIRCRAFT;
348 cost_factor = GetEngineProperty(this->index, PROP_AIRCRAFT_COST_FACTOR, this->u.air.cost_factor);
349 break;
350
351 default: NOT_REACHED();
352 }
353
354 return GetPrice(base_price, cost_factor, this->GetGRF(), -8);
355 }
356
361 uint Engine::GetDisplayMaxSpeed() const
362 {
363 switch (this->type) {
364 case VEH_TRAIN:
365 return GetEngineProperty(this->index, PROP_TRAIN_SPEED, this->u.rail.max_speed);
366
367 case VEH_ROAD: {
368 uint max_speed = GetEngineProperty(this->index, PROP_ROADVEH_SPEED, 0);
369 return (max_speed != 0) ? max_speed * 2 : this->u.road.max_speed / 2;
370 }
371
372 case VEH_SHIP:
373 return GetEngineProperty(this->index, PROP_SHIP_SPEED, this->u.ship.max_speed) / 2;
374
375 case VEH_AIRCRAFT: {
376 uint max_speed = GetEngineProperty(this->index, PROP_AIRCRAFT_SPEED, 0);
377 if (max_speed != 0) {
378 return (max_speed * 128) / 10;
379 }
380 return this->u.air.max_speed;
381 }
382
383 default: NOT_REACHED();
384 }
385 }
386
393 uint Engine::GetPower() const
394 {
395 /* Only trains and road vehicles have 'power'. */
396 switch (this->type) {
397 case VEH_TRAIN:
398 return GetEngineProperty(this->index, PROP_TRAIN_POWER, this->u.rail.power);
399 case VEH_ROAD:
400 return GetEngineProperty(this->index, PROP_ROADVEH_POWER, this->u.road.power) * 10;
401
402 default: NOT_REACHED();
403 }
404 }
405
411 uint Engine::GetDisplayWeight() const
412 {
413 /* Only trains and road vehicles have 'weight'. */
414 switch (this->type) {
415 case VEH_TRAIN:
416 return GetEngineProperty(this->index, PROP_TRAIN_WEIGHT, this->u.rail.weight) << (this->u.rail.railveh_type == RAILVEH_MULTIHEAD ? 1 : 0);
417 case VEH_ROAD:
418 return GetEngineProperty(this->index, PROP_ROADVEH_WEIGHT, this->u.road.weight) / 4;
419
420 default: NOT_REACHED();
421 }
422 }
423
429 uint Engine::GetDisplayMaxTractiveEffort() const
430 {
431 /* Only trains and road vehicles have 'tractive effort'. */
432 switch (this->type) {
433 case VEH_TRAIN:
434 return (10 * this->GetDisplayWeight() * GetEngineProperty(this->index, PROP_TRAIN_TRACTIVE_EFFORT, this->u.rail.tractive_effort)) / 256;
435 case VEH_ROAD:
436 return (10 * this->GetDisplayWeight() * GetEngineProperty(this->index, PROP_ROADVEH_TRACTIVE_EFFORT, this->u.road.tractive_effort)) / 256;
437
438 default: NOT_REACHED();
439 }
440 }
441
446 Date Engine::GetLifeLengthInDays() const
447 {
448 /* Assume leap years; this gives the player a bit more than the given amount of years, but never less. */
449 return (this->info.lifelength + _settings_game.vehicle.extend_vehicle_life) * DAYS_IN_LEAP_YEAR;
450 }
451
456 uint16 Engine::GetRange() const
457 {
458 switch (this->type) {
459 case VEH_AIRCRAFT:
460 return GetEngineProperty(this->index, PROP_AIRCRAFT_RANGE, this->u.air.max_range);
461
462 default: NOT_REACHED();
463 }
464 }
465
469 void EngineOverrideManager::ResetToDefaultMapping()
470 {
471 this->Clear();
472 for (VehicleType type = VEH_TRAIN; type <= VEH_AIRCRAFT; type++) {
473 for (uint internal_id = 0; internal_id < _engine_counts[type]; internal_id++) {
474 EngineIDMapping *eid = this->Append();
475 eid->type = type;
476 eid->grfid = INVALID_GRFID;
477 eid->internal_id = internal_id;
478 eid->substitute_id = internal_id;
479 }
480 }
481 }
482
492 EngineID EngineOverrideManager::GetID(VehicleType type, uint16 grf_local_id, uint32 grfid)
493 {
494 const EngineIDMapping *end = this->End();
495 EngineID index = 0;
496 for (const EngineIDMapping *eid = this->Begin(); eid != end; eid++, index++) {
497 if (eid->type == type && eid->grfid == grfid && eid->internal_id == grf_local_id) {
498 return index;
499 }
500 }
501 return INVALID_ENGINE;
502 }
503
509 bool EngineOverrideManager::ResetToCurrentNewGRFConfig()
510 {
511 const Vehicle *v;
512 FOR_ALL_VEHICLES(v) {
513 if (IsCompanyBuildableVehicleType(v)) return false;
514 }
515
516 /* Reset the engines, they will get new EngineIDs */
517 _engine_mngr.ResetToDefaultMapping();
518 ReloadNewGRFData();
519
520 return true;
521 }
522
526 void SetupEngines()
527 {
528 DeleteWindowByClass(WC_ENGINE_PREVIEW);
529 _engine_pool.CleanPool();
530
531 assert(_engine_mngr.Length() >= _engine_mngr.NUM_DEFAULT_ENGINES);
532 const EngineIDMapping *end = _engine_mngr.End();
533 uint index = 0;
534 for (const EngineIDMapping *eid = _engine_mngr.Begin(); eid != end; eid++, index++) {
535 /* Assert is safe; there won't be more than 256 original vehicles
536 * in any case, and we just cleaned the pool. */
537 assert(Engine::CanAllocateItem());
538 const Engine *e = new Engine(eid->type, eid->internal_id);
539 assert(e->index == index);
540 }
541 }
542
543 void ShowEnginePreviewWindow(EngineID engine);
544
550 static bool IsWagon(EngineID index)
551 {
552 const Engine *e = Engine::Get(index);
553 return e->type == VEH_TRAIN && e->u.rail.railveh_type == RAILVEH_WAGON;
554 }
555
560 static void CalcEngineReliability(Engine *e)
561 {
562 uint age = e->age;
563
564 /* Check for early retirement */
565 if (e->company_avail != 0 && !_settings_game.vehicle.never_expire_vehicles && e->info.base_life != 0xFF) {
566 int retire_early = e->info.retire_early;
567 uint retire_early_max_age = max(0, e->duration_phase_1 + e->duration_phase_2 - retire_early * 12);
568 if (retire_early != 0 && age >= retire_early_max_age) {
569 /* Early retirement is enabled and we're past the date... */
570 e->company_avail = 0;
571 AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
572 }
573 }
574
575 if (age < e->duration_phase_1) {
576 uint start = e->reliability_start;
577 e->reliability = age * (e->reliability_max - start) / e->duration_phase_1 + start;
578 } else if ((age -= e->duration_phase_1) < e->duration_phase_2 || _settings_game.vehicle.never_expire_vehicles || e->info.base_life == 0xFF) {
579 /* We are at the peak of this engines life. It will have max reliability.
580 * This is also true if the engines never expire. They will not go bad over time */
581 e->reliability = e->reliability_max;
582 } else if ((age -= e->duration_phase_2) < e->duration_phase_3) {
583 uint max = e->reliability_max;
584 e->reliability = (int)age * (int)(e->reliability_final - max) / e->duration_phase_3 + max;
585 } else {
586 /* time's up for this engine.
587 * We will now completely retire this design */
588 e->company_avail = 0;
589 e->reliability = e->reliability_final;
590 /* Kick this engine out of the lists */
591 AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
592 }
593 SetWindowClassesDirty(WC_BUILD_VEHICLE); // Update to show the new reliability
594 SetWindowClassesDirty(WC_REPLACE_VEHICLE);
595 }
596
598 void SetYearEngineAgingStops()
599 {
600 /* Determine last engine aging year, default to 2050 as previously. */
601 _year_engine_aging_stops = 2050;
602
603 const Engine *e;
604 FOR_ALL_ENGINES(e) {
605 const EngineInfo *ei = &e->info;
606
607 /* Exclude certain engines */
608 if (!HasBit(ei->climates, _settings_game.game_creation.landscape)) continue;
609 if (e->type == VEH_TRAIN && e->u.rail.railveh_type == RAILVEH_WAGON) continue;
610
611 /* Base year ending date on half the model life */
612 YearMonthDay ymd;
613 ConvertDateToYMD(ei->base_intro + (ei->lifelength * DAYS_IN_LEAP_YEAR) / 2, &ymd);
614
615 _year_engine_aging_stops = max(_year_engine_aging_stops, ymd.year);
616 }
617 }
618
624 void StartupOneEngine(Engine *e, Date aging_date)
625 {
626 const EngineInfo *ei = &e->info;
627
628 e->age = 0;
629 e->flags = 0;
630 e->company_avail = 0;
631 e->company_hidden = 0;
632
633 /* Don't randomise the start-date in the first two years after gamestart to ensure availability
634 * of engines in early starting games.
635 * Note: TTDP uses fixed 1922 */
636 uint32 r = Random();
637 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;
638 if (e->intro_date <= _date) {
639 e->age = (aging_date - e->intro_date) >> 5;
640 e->company_avail = (CompanyMask)-1;
641 e->flags |= ENGINE_AVAILABLE;
642 }
643
644 e->reliability_start = GB(r, 16, 14) + 0x7AE0;
645 r = Random();
646 e->reliability_max = GB(r, 0, 14) + 0xBFFF;
647 e->reliability_final = GB(r, 16, 14) + 0x3FFF;
648
649 r = Random();
650 e->duration_phase_1 = GB(r, 0, 5) + 7;
651 e->duration_phase_2 = GB(r, 5, 4) + ei->base_life * 12 - 96;
652 e->duration_phase_3 = GB(r, 9, 7) + 120;
653
654 e->reliability_spd_dec = ei->decay_speed << 2;
655
656 CalcEngineReliability(e);
657
658 /* prevent certain engines from ever appearing. */
659 if (!HasBit(ei->climates, _settings_game.game_creation.landscape)) {
660 e->flags |= ENGINE_AVAILABLE;
661 e->company_avail = 0;
662 }
663 }
664
669 void StartupEngines()
670 {
671 Engine *e;
672 /* Aging of vehicles stops, so account for that when starting late */
673 const Date aging_date = min(_date, ConvertYMDToDate(_year_engine_aging_stops, 0, 1));
674
675 FOR_ALL_ENGINES(e) {
676 StartupOneEngine(e, aging_date);
677 }
678
679 /* Update the bitmasks for the vehicle lists */
680 Company *c;
681 FOR_ALL_COMPANIES(c) {
682 c->avail_railtypes = GetCompanyRailtypes(c->index);
683 c->avail_roadtypes = GetCompanyRoadtypes(c->index);
684 }
685
686 /* Invalidate any open purchase lists */
687 InvalidateWindowClassesData(WC_BUILD_VEHICLE);
688 }
689
695 static void AcceptEnginePreview(EngineID eid, CompanyID company)
696 {
697 Engine *e = Engine::Get(eid);
698 Company *c = Company::Get(company);
699
700 SetBit(e->company_avail, company);
701 if (e->type == VEH_TRAIN) {
702 assert(e->u.rail.railtype < RAILTYPE_END);
703 c->avail_railtypes = AddDateIntroducedRailTypes(c->avail_railtypes | GetRailTypeInfo(e->u.rail.railtype)->introduces_railtypes, _date);
704 } else if (e->type == VEH_ROAD) {
705 SetBit(c->avail_roadtypes, HasBit(e->info.misc_flags, EF_ROAD_TRAM) ? ROADTYPE_TRAM : ROADTYPE_ROAD);
706 }
707
708 e->preview_company = INVALID_COMPANY;
709 e->preview_asked = (CompanyMask)-1;
710 if (company == _local_company) {
711 AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
712 }
713
714 /* Update the toolbar. */
715 if (e->type == VEH_ROAD) InvalidateWindowData(WC_BUILD_TOOLBAR, TRANSPORT_ROAD);
716 if (e->type == VEH_SHIP) InvalidateWindowData(WC_BUILD_TOOLBAR, TRANSPORT_WATER);
717
718 /* Notify preview window, that it might want to close.
719 * Note: We cannot directly close the window.
720 * In singleplayer this function is called from the preview window, so
721 * we have to use the GUI-scope scheduling of InvalidateWindowData.
722 */
723 InvalidateWindowData(WC_ENGINE_PREVIEW, eid);
724 }
725
731 static CompanyID GetPreviewCompany(Engine *e)
732 {
733 CompanyID best_company = INVALID_COMPANY;
734
735 /* For trains the cargomask has no useful meaning, since you can attach other wagons */
736 uint32 cargomask = e->type != VEH_TRAIN ? GetUnionOfArticulatedRefitMasks(e->index, true) : (uint32)-1;
737
738 int32 best_hist = -1;
739 const Company *c;
740 FOR_ALL_COMPANIES(c) {
741 if (c->block_preview == 0 && !HasBit(e->preview_asked, c->index) &&
742 c->old_economy[0].performance_history > best_hist) {
743
744 /* Check whether the company uses similar vehicles */
745 Vehicle *v;
746 FOR_ALL_VEHICLES(v) {
747 if (v->owner != c->index || v->type != e->type) continue;
748 if (!v->GetEngine()->CanCarryCargo() || !HasBit(cargomask, v->cargo_type)) continue;
749
750 best_hist = c->old_economy[0].performance_history;
751 best_company = c->index;
752 break;
753 }
754 }
755 }
756
757 return best_company;
758 }
759
767 static bool IsVehicleTypeDisabled(VehicleType type, bool ai)
768 {
769 switch (type) {
770 case VEH_TRAIN: return _settings_game.vehicle.max_trains == 0 || (ai && _settings_game.ai.ai_disable_veh_train);
771 case VEH_ROAD: return _settings_game.vehicle.max_roadveh == 0 || (ai && _settings_game.ai.ai_disable_veh_roadveh);
772 case VEH_SHIP: return _settings_game.vehicle.max_ships == 0 || (ai && _settings_game.ai.ai_disable_veh_ship);
773 case VEH_AIRCRAFT: return _settings_game.vehicle.max_aircraft == 0 || (ai && _settings_game.ai.ai_disable_veh_aircraft);
774
775 default: NOT_REACHED();
776 }
777 }
778
780 void EnginesDailyLoop()
781 {
782 Company *c;
783 FOR_ALL_COMPANIES(c) {
784 c->avail_railtypes = AddDateIntroducedRailTypes(c->avail_railtypes, _date);
785 }
786
787 if (_cur_year >= _year_engine_aging_stops) return;
788
789 Engine *e;
790 FOR_ALL_ENGINES(e) {
791 EngineID i = e->index;
792 if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) {
793 if (e->preview_company != INVALID_COMPANY) {
794 if (!--e->preview_wait) {
795 DeleteWindowById(WC_ENGINE_PREVIEW, i);
796 e->preview_company = INVALID_COMPANY;
797 }
798 } else if (CountBits(e->preview_asked) < MAX_COMPANIES) {
799 e->preview_company = GetPreviewCompany(e);
800
801 if (e->preview_company == INVALID_COMPANY) {
802 e->preview_asked = (CompanyMask)-1;
803 continue;
804 }
805
806 SetBit(e->preview_asked, e->preview_company);
807 e->preview_wait = 20;
808 /* AIs are intentionally not skipped for preview even if they cannot build a certain
809 * vehicle type. This is done to not give poor performing human companies an "unfair"
810 * boost that they wouldn't have gotten against other human companies. The check on
811 * the line below is just to make AIs not notice that they have a preview if they
812 * cannot build the vehicle. */
813 if (!IsVehicleTypeDisabled(e->type, true)) AI::NewEvent(e->preview_company, new ScriptEventEnginePreview(i));
814 if (IsInteractiveCompany(e->preview_company)) ShowEnginePreviewWindow(i);
815 }
816 }
817 }
818 }
819
824 void ClearEnginesHiddenFlagOfCompany(CompanyID cid)
825 {
826 Engine *e;
827 FOR_ALL_ENGINES(e) {
828 SB(e->company_hidden, cid, 1, 0);
829 }
830 }
831
841 CommandCost CmdSetVehicleVisibility(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
842 {
843 Engine *e = Engine::GetIfValid(GB(p2, 0, 31));
844 if (e == NULL || _current_company >= MAX_COMPANIES) return CMD_ERROR;
845 if (!IsEngineBuildable(e->index, e->type, _current_company)) return CMD_ERROR;
846
847 if ((flags & DC_EXEC) != 0) {
848 SB(e->company_hidden, _current_company, 1, GB(p2, 31, 1));
849 AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
850 }
851
852 return CommandCost();
853 }
854
865 CommandCost CmdWantEnginePreview(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
866 {
867 Engine *e = Engine::GetIfValid(p1);
868 if (e == NULL || !(e->flags & ENGINE_EXCLUSIVE_PREVIEW) || e->preview_company != _current_company) return CMD_ERROR;
869
870 if (flags & DC_EXEC) AcceptEnginePreview(p1, _current_company);
871
872 return CommandCost();
873 }
874
880 static void NewVehicleAvailable(Engine *e)
881 {
882 Vehicle *v;
883 Company *c;
884 EngineID index = e->index;
885
886 /* In case the company didn't build the vehicle during the intro period,
887 * prevent that company from getting future intro periods for a while. */
888 if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) {
889 FOR_ALL_COMPANIES(c) {
890 uint block_preview = c->block_preview;
891
892 if (!HasBit(e->company_avail, c->index)) continue;
893
894 /* We assume the user did NOT build it.. prove me wrong ;) */
895 c->block_preview = 20;
896
897 FOR_ALL_VEHICLES(v) {
898 if (v->type == VEH_TRAIN || v->type == VEH_ROAD || v->type == VEH_SHIP ||
899 (v->type == VEH_AIRCRAFT && Aircraft::From(v)->IsNormalAircraft())) {
900 if (v->owner == c->index && v->engine_type == index) {
901 /* The user did prove me wrong, so restore old value */
902 c->block_preview = block_preview;
903 break;
904 }
905 }
906 }
907 }
908 }
909
910 e->flags = (e->flags & ~ENGINE_EXCLUSIVE_PREVIEW) | ENGINE_AVAILABLE;
911 AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
912
913 /* Now available for all companies */
914 e->company_avail = (CompanyMask)-1;
915
916 /* Do not introduce new rail wagons */
917 if (IsWagon(index)) return;
918
919 if (e->type == VEH_TRAIN) {
920 /* maybe make another rail type available */
921 RailType railtype = e->u.rail.railtype;
922 assert(railtype < RAILTYPE_END);
923 FOR_ALL_COMPANIES(c) c->avail_railtypes = AddDateIntroducedRailTypes(c->avail_railtypes | GetRailTypeInfo(e->u.rail.railtype)->introduces_railtypes, _date);
924 } else if (e->type == VEH_ROAD) {
925 /* maybe make another road type available */
926 FOR_ALL_COMPANIES(c) SetBit(c->avail_roadtypes, HasBit(e->info.misc_flags, EF_ROAD_TRAM) ? ROADTYPE_TRAM : ROADTYPE_ROAD);
927 }
928
929 /* Only broadcast event if AIs are able to build this vehicle type. */
930 if (!IsVehicleTypeDisabled(e->type, true)) AI::BroadcastNewEvent(new ScriptEventEngineAvailable(index));
931
932 /* Only provide the "New Vehicle available" news paper entry, if engine can be built. */
933 if (!IsVehicleTypeDisabled(e->type, false)) {
934 SetDParam(0, GetEngineCategoryName(index));
935 SetDParam(1, index);
936 AddNewsItem(STR_NEWS_NEW_VEHICLE_NOW_AVAILABLE_WITH_TYPE, NT_NEW_VEHICLES, NF_VEHICLE, NR_ENGINE, index);
937 }
938
939 /* Update the toolbar. */
940 if (e->type == VEH_ROAD) InvalidateWindowData(WC_BUILD_TOOLBAR, TRANSPORT_ROAD);
941 if (e->type == VEH_SHIP) InvalidateWindowData(WC_BUILD_TOOLBAR, TRANSPORT_WATER);
942
943 /* Close pending preview windows */
944 DeleteWindowById(WC_ENGINE_PREVIEW, index);
945 }
946
948 void EnginesMonthlyLoop()
949 {
950 if (_cur_year < _year_engine_aging_stops) {
951 Engine *e;
952 FOR_ALL_ENGINES(e) {
953 /* Age the vehicle */
954 if ((e->flags & ENGINE_AVAILABLE) && e->age != MAX_DAY) {
955 e->age++;
956 CalcEngineReliability(e);
957 }
958
959 /* Do not introduce invalid engines */
960 if (!e->IsEnabled()) continue;
961
962 if (!(e->flags & ENGINE_AVAILABLE) && _date >= (e->intro_date + DAYS_IN_YEAR)) {
963 /* Introduce it to all companies */
964 NewVehicleAvailable(e);
965 } else if (!(e->flags & (ENGINE_AVAILABLE | ENGINE_EXCLUSIVE_PREVIEW)) && _date >= e->intro_date) {
966 /* Introduction date has passed...
967 * Check if it is allowed to build this vehicle type at all
968 * based on the current game settings. If not, it does not
969 * make sense to show the preview dialog to any company. */
970 if (IsVehicleTypeDisabled(e->type, false)) continue;
971
972 /* Do not introduce new rail wagons */
973 if (IsWagon(e->index)) continue;
974
975 /* Show preview dialog to one of the companies. */
976 e->flags |= ENGINE_EXCLUSIVE_PREVIEW;
977 e->preview_company = INVALID_COMPANY;
978 e->preview_asked = 0;
979 }
980 }
981
982 InvalidateWindowClassesData(WC_BUILD_VEHICLE); // rebuild the purchase list (esp. when sorted by reliability)
983 }
984 }
985
991 static bool IsUniqueEngineName(const char *name)
992 {
993 const Engine *e;
994
995 FOR_ALL_ENGINES(e) {
996 if (e->name != NULL && strcmp(e->name, name) == 0) return false;
997 }
998
999 return true;
1000 }
1001
1011 CommandCost CmdRenameEngine(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1012 {
1013 Engine *e = Engine::GetIfValid(p1);
1014 if (e == NULL) return CMD_ERROR;
1015
1016 bool reset = StrEmpty(text);
1017
1018 if (!reset) {
1019 if (Utf8StringLength(text) >= MAX_LENGTH_ENGINE_NAME_CHARS) return CMD_ERROR;
1020 if (!IsUniqueEngineName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
1021 }
1022
1023 if (flags & DC_EXEC) {
1024 free(e->name);
1025
1026 if (reset) {
1027 e->name = NULL;
1028 } else {
1029 e->name = stredup(text);
1030 }
1031
1032 MarkWholeScreenDirty();
1033 }
1034
1035 return CommandCost();
1036 }
1037
1038
1047 bool IsEngineBuildable(EngineID engine, VehicleType type, CompanyID company)
1048 {
1049 const Engine *e = Engine::GetIfValid(engine);
1050
1051 /* check if it's an engine that is in the engine array */
1052 if (e == NULL) return false;
1053
1054 /* check if it's an engine of specified type */
1055 if (e->type != type) return false;
1056
1057 /* check if it's available ... */
1058 if (company == OWNER_DEITY) {
1059 /* ... for any company (preview does not count) */
1060 if (!(e->flags & ENGINE_AVAILABLE) || e->company_avail == 0) return false;
1061 } else {
1062 /* ... for this company */
1063 if (!HasBit(e->company_avail, company)) return false;
1064 }
1065
1066 if (!e->IsEnabled()) return false;
1067
1068 if (type == VEH_TRAIN && company != OWNER_DEITY) {
1069 /* Check if the rail type is available to this company */
1070 const Company *c = Company::Get(company);
1071 if (((GetRailTypeInfo(e->u.rail.railtype))->compatible_railtypes & c->avail_railtypes) == 0) return false;
1072 }
1073
1074 return true;
1075 }
1076
1083 bool IsEngineRefittable(EngineID engine)
1084 {
1085 const Engine *e = Engine::GetIfValid(engine);
1086
1087 /* check if it's an engine that is in the engine array */
1088 if (e == NULL) return false;
1089
1090 if (!e->CanCarryCargo()) return false;
1091
1092 const EngineInfo *ei = &e->info;
1093 if (ei->refit_mask == 0) return false;
1094
1095 /* Are there suffixes?
1096 * Note: This does not mean the suffixes are actually available for every consist at any time. */
1097 if (HasBit(ei->callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) return true;
1098
1099 /* Is there any cargo except the default cargo? */
1100 CargoID default_cargo = e->GetDefaultCargoType();
1101 return default_cargo != CT_INVALID && ei->refit_mask != 1U << default_cargo;
1102 }
1103
1107 void CheckEngines()
1108 {
1109 const Engine *e;
1110 Date min_date = INT32_MAX;
1111
1112 FOR_ALL_ENGINES(e) {
1113 if (!e->IsEnabled()) continue;
1114
1115 /* We have an available engine... yay! */
1116 if ((e->flags & ENGINE_AVAILABLE) != 0 && e->company_avail != 0) return;
1117
1118 /* Okay, try to find the earliest date. */
1119 min_date = min(min_date, e->info.base_intro);
1120 }
1121
1122 if (min_date < INT32_MAX) {
1123 SetDParam(0, min_date);
1124 ShowErrorMessage(STR_ERROR_NO_VEHICLES_AVAILABLE_YET, STR_ERROR_NO_VEHICLES_AVAILABLE_YET_EXPLANATION, WL_WARNING);
1125 } else {
1126 ShowErrorMessage(STR_ERROR_NO_VEHICLES_AVAILABLE_AT_ALL, STR_ERROR_NO_VEHICLES_AVAILABLE_AT_ALL_EXPLANATION, WL_WARNING);
1127 }
1128 }