OpenTTD Source 20261129-master-g72a8bdc861
vehicle.cpp
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
9
10#include "stdafx.h"
11#include "error.h"
12#include "roadveh.h"
13#include "ship.h"
14#include "spritecache.h"
15#include "timetable.h"
16#include "viewport_func.h"
17#include "news_func.h"
18#include "command_func.h"
19#include "company_base.h"
20#include "company_func.h"
21#include "train.h"
22#include "aircraft.h"
23#include "newgrf_debug.h"
24#include "newgrf_sound.h"
25#include "newgrf_station.h"
26#include "group_gui.h"
27#include "strings_func.h"
28#include "zoom_func.h"
29#include "vehicle_func.h"
30#include "vehicle_gui.h"
31#include "autoreplace_func.h"
32#include "autoreplace_gui.h"
33#include "station_base.h"
34#include "station_func.h"
35#include "ai/ai.hpp"
36#include "depot_func.h"
37#include "network/network.h"
38#include "core/pool_func.hpp"
39#include "economy_base.h"
41#include "roadstop_base.h"
42#include "core/random_func.hpp"
43#include "core/backup_type.hpp"
45#include "order_backup.h"
46#include "sound_func.h"
47#include "effectvehicle_func.h"
48#include "effectvehicle_base.h"
49#include "vehiclelist.h"
50#include "bridge_map.h"
51#include "tunnel_map.h"
52#include "depot_map.h"
53#include "gamelog.h"
54#include "linkgraph/refresh.h"
55#include "framerate_type.h"
56#include "autoreplace_cmd.h"
57#include "misc_cmd.h"
58#include "train_cmd.h"
59#include "vehicle_cmd.h"
60#include "newgrf_roadstop.h"
61#include "script/api/script_event_types.hpp"
62#include "timer/timer.h"
66
67#include "table/strings.h"
68
69#include "safeguards.h"
70
73static const uint GEN_HASHX_BITS = 6;
74static const uint GEN_HASHY_BITS = 6;
76
79static const uint GEN_HASHX_BUCKET_BITS = 7;
80static const uint GEN_HASHY_BUCKET_BITS = 6;
82
83/* Compute hash for vehicle coord */
84static inline uint GetViewportHashX(int x)
85{
86 return GB(x, GEN_HASHX_BUCKET_BITS + ZOOM_BASE_SHIFT, GEN_HASHX_BITS);
87}
88
89static inline uint GetViewportHashY(int y)
90{
91 return GB(y, GEN_HASHY_BUCKET_BITS + ZOOM_BASE_SHIFT, GEN_HASHY_BITS) << GEN_HASHX_BITS;
92}
93
94static inline uint GetViewportHash(int x, int y)
95{
96 return GetViewportHashX(x) + GetViewportHashY(y);
97}
98
101static const uint GEN_HASHX_SIZE = 1 << (GEN_HASHX_BUCKET_BITS + GEN_HASHX_BITS + ZOOM_BASE_SHIFT);
102static const uint GEN_HASHY_SIZE = 1 << (GEN_HASHY_BUCKET_BITS + GEN_HASHY_BITS + ZOOM_BASE_SHIFT);
104
107static const uint GEN_HASHX_INC = 1;
108static const uint GEN_HASHY_INC = 1 << GEN_HASHX_BITS;
110
113static const uint GEN_HASHX_MASK = (1 << GEN_HASHX_BITS) - 1;
114static const uint GEN_HASHY_MASK = ((1 << GEN_HASHY_BITS) - 1) << GEN_HASHX_BITS;
116
120
121
122
126void VehicleSpriteSeq::GetBounds(Rect *bounds) const
127{
128 bounds->left = bounds->top = bounds->right = bounds->bottom = 0;
129 for (uint i = 0; i < this->count; ++i) {
130 const Sprite *spr = GetSprite(this->seq[i].sprite, SpriteType::Normal);
131 if (i == 0) {
132 bounds->left = spr->x_offs;
133 bounds->top = spr->y_offs;
134 bounds->right = spr->width + spr->x_offs - 1;
135 bounds->bottom = spr->height + spr->y_offs - 1;
136 } else {
137 if (spr->x_offs < bounds->left) bounds->left = spr->x_offs;
138 if (spr->y_offs < bounds->top) bounds->top = spr->y_offs;
139 int right = spr->width + spr->x_offs - 1;
140 int bottom = spr->height + spr->y_offs - 1;
141 if (right > bounds->right) bounds->right = right;
142 if (bottom > bounds->bottom) bounds->bottom = bottom;
143 }
144 }
145}
146
154void VehicleSpriteSeq::Draw(int x, int y, PaletteID default_pal, bool force_pal) const
155{
156 for (uint i = 0; i < this->count; ++i) {
157 PaletteID pal = force_pal || !this->seq[i].pal ? default_pal : this->seq[i].pal;
158 DrawSprite(this->seq[i].sprite, pal, x, y);
159 }
160}
161
168bool Vehicle::NeedsAutorenewing(const Company *c, bool use_renew_setting) const
169{
170 /* We can always generate the Company pointer when we have the vehicle.
171 * However this takes time and since the Company pointer is often present
172 * when this function is called then it's faster to pass the pointer as an
173 * argument rather than finding it again. */
174 assert(c == Company::Get(this->owner));
175
176 if (use_renew_setting && !c->settings.engine_renew) return false;
177 if (this->age - this->max_age < (c->settings.engine_renew_months * 30)) return false;
178
179 /* Only engines need renewing */
180 if (this->type == VehicleType::Train && !Train::From(this)->IsEngine()) return false;
181
182 return true;
183}
184
191{
192 assert(v != nullptr);
193 SetWindowDirty(WindowClass::VehicleDetails, v->index); // ensure that last service date and reliability are updated
194
195 do {
200 /* Prevent vehicles from breaking down directly after exiting the depot. */
201 v->breakdown_chance /= 4;
202 if (_settings_game.difficulty.vehicle_breakdowns == VehicleBreakdowns::Reduced) v->breakdown_chance = 0; // on reduced breakdown
203 v = v->Next();
204 } while (v != nullptr && v->HasEngineType());
205}
206
214{
215 /* Stopped or crashed vehicles will not move, as such making unmovable
216 * vehicles to go for service is lame. */
217 if (this->vehstatus.Any({VehState::Stopped, VehState::Crashed})) return false;
218
219 /* Are we ready for the next service cycle? */
220 const Company *c = Company::Get(this->owner);
221
222 /* Service intervals can be measured in different units, which we handle individually. */
223 if (this->ServiceIntervalIsPercent()) {
224 /* Service interval is in percents. */
225 if (this->reliability >= this->GetEngine()->reliability * (100 - this->GetServiceInterval()) / 100) return false;
227 /* Service interval is in minutes. */
228 if (this->date_of_last_service + (this->GetServiceInterval() * EconomyTime::DAYS_IN_ECONOMY_MONTH) >= TimerGameEconomy::date) return false;
229 } else {
230 /* Service interval is in days. */
231 if (this->date_of_last_service + this->GetServiceInterval() >= TimerGameEconomy::date) return false;
232 }
233
234 /* If we're servicing anyway, because we have not disabled servicing when
235 * there are no breakdowns or we are playing with breakdowns, bail out. */
236 if (!_settings_game.order.no_servicing_if_no_breakdowns ||
237 _settings_game.difficulty.vehicle_breakdowns != VehicleBreakdowns::None) {
238 return true;
239 }
240
241 /* Test whether there is some pending autoreplace.
242 * Note: We do this after the service-interval test.
243 * There are a lot more reasons for autoreplace to fail than we can test here reasonably. */
244 bool pending_replace = false;
245 Money needed_money = c->settings.engine_renew_money;
246 if (needed_money > GetAvailableMoney(c->index)) return false;
247
248 for (const Vehicle *v = this; v != nullptr; v = (v->type == VehicleType::Train) ? Train::From(v)->GetNextUnit() : nullptr) {
249 const EngineRenew *er = GetEngineRenew(v->owner, v->group_id, v->engine_type, true);
250 EngineID new_engine = er == nullptr ? EngineID::Invalid() : er->to;
251 bool replace_when_old = er != nullptr && er->replace_when_old;
252
253 /* Check engine availability */
254 if (new_engine == EngineID::Invalid() || !Engine::Get(new_engine)->company_avail.Test(v->owner)) continue;
255 /* Is the vehicle old if we are not always replacing? */
256 if (replace_when_old && !v->NeedsAutorenewing(c, false)) continue;
257
258 /* Check refittability */
259 CargoTypes available_cargo_types, union_mask;
260 GetArticulatedRefitMasks(new_engine, true, &union_mask, &available_cargo_types);
261 /* Is there anything to refit? */
262 if (union_mask.Any()) {
265 if (!HasAtMostOneBit(cargo_mask.base())) {
266 CargoTypes new_engine_default_cargoes = GetCargoTypesOfArticulatedParts(new_engine);
267 if ((cargo_mask & new_engine_default_cargoes) != cargo_mask) {
268 /* We cannot refit to mixed cargoes in an automated way */
269 continue;
270 }
271 /* engine_type is already a mixed cargo type which matches the incoming vehicle by default, no refit required */
272 } else {
273 /* Did the old vehicle carry anything? */
275 /* We can't refit the vehicle to carry the cargo we want */
276 if (!available_cargo_types.Test(cargo_type)) continue;
277 }
278 }
279 }
280
281 /* Check money.
282 * We want 2*(the price of the new vehicle) without looking at the value of the vehicle we are going to sell. */
283 pending_replace = true;
284 needed_money += 2 * Engine::Get(new_engine)->GetCost();
285 if (needed_money > GetAvailableMoney(c->index)) return false;
286 }
287
288 return pending_replace;
289}
290
297{
298 if (this->HasDepotOrder()) return false;
299 if (this->current_order.IsType(OT_LOADING)) return false;
300 if (this->current_order.IsType(OT_GOTO_DEPOT) && !this->current_order.GetDepotOrderType().Test(OrderDepotTypeFlag::Service)) return false;
301 return NeedsServicing();
302}
303
305{
306 assert(!this->vehstatus.Test(VehState::Crashed));
307 assert(this->Previous() == nullptr); // IsPrimaryVehicle fails for free-wagon-chains
308
309 uint pass = 0;
310 /* Stop the vehicle. */
311 if (this->IsPrimaryVehicle()) this->vehstatus.Set(VehState::Stopped);
312 /* crash all wagons, and count passengers */
313 for (Vehicle *v = this; v != nullptr; v = v->Next()) {
314 /* We do not transfer reserver cargo back, so TotalCount() instead of StoredCount() */
315 if (IsCargoInClass(v->cargo_type, CargoClass::Passengers)) pass += v->cargo.TotalCount();
316 v->vehstatus.Set(VehState::Crashed);
317 v->MarkAllViewportsDirty();
318 }
319
320 /* Dirty some windows */
322 SetWindowWidgetDirty(WindowClass::VehicleView, this->index, WID_VV_START_STOP);
323 SetWindowDirty(WindowClass::VehicleDetails, this->index);
324 SetWindowDirty(WindowClass::VehicleDepot, this->GetMovingFront()->tile);
325
326 delete this->cargo_payment;
327 assert(this->cargo_payment == nullptr); // cleared by ~CargoPayment
328
329 return RandomRange(pass + 1); // Randomise deceased passengers.
330}
331
332
341void ShowNewGrfVehicleError(EngineID engine, StringID part1, StringID part2, GRFBug bug_type, bool critical)
342{
343 const Engine *e = Engine::Get(engine);
344 GRFConfig *grfconfig = GetGRFConfig(e->GetGRFID());
345
346 /* Missing GRF. Nothing useful can be done in this situation. */
347 if (grfconfig == nullptr) return;
348
349 if (!grfconfig->grf_bugs.Test(bug_type)) {
350 grfconfig->grf_bugs.Set(bug_type);
351 ShowErrorMessage(GetEncodedString(part1, grfconfig->GetName()),
352 GetEncodedString(part2, std::monostate{}, engine), WarningLevel::Critical);
353 if (!_networking) Command<Commands::Pause>::Do(DoCommandFlag::Execute, critical ? PauseMode::Error : PauseMode::Normal, true);
354 }
355
356 /* debug output */
358
359 Debug(Facility::Grf, Severity::Critical, "{}", StrMakeValid(GetString(part2, std::monostate{}, engine)));
360}
361
368{
369 /* show a warning once for each engine in whole game and once for each GRF after each game load */
370 const Engine *engine = u->GetEngine();
371 GrfID grfid = engine->grf_prop.grfid;
372 GRFConfig *grfconfig = GetGRFConfig(grfid);
373 if (_gamelog.GRFBugReverse(grfid, engine->grf_prop.local_id) || !grfconfig->grf_bugs.Test(GRFBug::VehLength)) {
374 ShowNewGrfVehicleError(u->engine_type, STR_NEWGRF_BROKEN, STR_NEWGRF_BROKEN_VEHICLE_LENGTH, GRFBug::VehLength, true);
375 }
376}
377
384{
385 this->type = type;
386 this->coord.left = INVALID_COORD;
387 this->sprite_cache.old_coord.left = INVALID_COORD;
388 this->group_id = DEFAULT_GROUP;
389 this->fill_percent_te_id = INVALID_TE_ID;
390 this->first = this;
391 this->last = this;
392 this->colourmap = PAL_NONE;
393 this->cargo_age_counter = 1;
394 this->last_station_visited = StationID::Invalid();
395 this->last_loading_station = StationID::Invalid();
396}
397
402constexpr uint TILE_HASH_BITS = 7;
403constexpr uint TILE_HASH_SIZE = 1 << TILE_HASH_BITS;
404constexpr uint TILE_HASH_MASK = TILE_HASH_SIZE - 1;
405constexpr uint TOTAL_TILE_HASH_SIZE = 1 << (TILE_HASH_BITS * 2);
407
412constexpr uint TILE_HASH_RES = 0;
413
419static inline uint GetTileHash1D(uint p)
420{
421 return GB(p, TILE_HASH_RES, TILE_HASH_BITS);
422}
423
429static inline uint IncTileHash1D(uint h)
430{
431 return (h + 1) & TILE_HASH_MASK;
432}
433
440static inline uint ComposeTileHash(uint hx, uint hy)
441{
442 return hx | hy << TILE_HASH_BITS;
443}
444
451static inline uint GetTileHash(uint x, uint y)
452{
454}
455
456static std::array<Vehicle *, TOTAL_TILE_HASH_SIZE> _vehicle_tile_hash{};
457
465VehiclesNearTileXY::Iterator::Iterator(int32_t x, int32_t y, uint max_dist)
466{
467 /* There are no negative tile coordinates */
468 this->pos_rect.left = std::max<int>(0, x - max_dist);
469 this->pos_rect.right = std::max<int>(0, x + max_dist);
470 this->pos_rect.top = std::max<int>(0, y - max_dist);
471 this->pos_rect.bottom = std::max<int>(0, y + max_dist);
472
473 if (2 * max_dist < TILE_HASH_MASK * TILE_SIZE) {
474 /* Hash area to scan */
475 this->hxmin = this->hx = GetTileHash1D(this->pos_rect.left / TILE_SIZE);
476 this->hxmax = GetTileHash1D(this->pos_rect.right / TILE_SIZE);
477 this->hymin = this->hy = GetTileHash1D(this->pos_rect.top / TILE_SIZE);
478 this->hymax = GetTileHash1D(this->pos_rect.bottom / TILE_SIZE);
479 } else {
480 /* Scan all */
481 this->hxmin = this->hx = 0;
482 this->hxmax = TILE_HASH_MASK;
483 this->hymin = this->hy = 0;
484 this->hymax = TILE_HASH_MASK;
485 }
486
487 this->current_veh = _vehicle_tile_hash[ComposeTileHash(this->hx, this->hy)];
488 this->SkipEmptyBuckets();
489 this->SkipFalseMatches();
490}
491
496{
497 assert(this->current_veh != nullptr);
498 this->current_veh = this->current_veh->hash_tile_next;
499 this->SkipEmptyBuckets();
500}
501
506{
507 while (this->current_veh == nullptr) {
508 if (this->hx != this->hxmax) {
509 this->hx = IncTileHash1D(this->hx);
510 } else if (this->hy != this->hymax) {
511 this->hx = this->hxmin;
512 this->hy = IncTileHash1D(this->hy);
513 } else {
514 return;
515 }
516 this->current_veh = _vehicle_tile_hash[ComposeTileHash(this->hx, this->hy)];
517 }
518}
519
524{
525 while (this->current_veh != nullptr && !this->pos_rect.Contains({this->current_veh->x_pos, this->current_veh->y_pos})) this->Increment();
526}
527
534{
535 this->current = _vehicle_tile_hash[GetTileHash(TileX(tile), TileY(tile))];
536 this->SkipFalseMatches();
537}
538
544{
545 this->current = this->current->hash_tile_next;
546}
547
552{
553 while (this->current != nullptr && this->current->tile != this->tile) this->Increment();
554}
555
562{
563 int z = GetTileMaxPixelZ(tile);
564
565 /* Value v is not safe in MP games, however, it is used to generate a local
566 * error message only (which may be different for different machines).
567 * Such a message does not affect MP synchronisation.
568 */
569 for (const Vehicle *v : VehiclesOnTile(tile)) {
570 if (v->type == VehicleType::Disaster || (v->type == VehicleType::Aircraft && v->subtype == AIR_SHADOW)) continue;
571 if (v->z_pos > z) continue;
572
573 return CommandCost(STR_ERROR_TRAIN_IN_THE_WAY + to_underlying(v->type));
574 }
575 return CommandCost();
576}
577
586{
587 for (TileIndex t : {tile, endtile}) {
588 /* Value v is not safe in MP games, however, it is used to generate a local
589 * error message only (which may be different for different machines).
590 * Such a message does not affect MP synchronisation.
591 */
592 for (const Vehicle *v : VehiclesOnTile(t)) {
593 if (v->type != VehicleType::Train && v->type != VehicleType::Road && v->type != VehicleType::Ship) continue;
594 if (v == ignore) continue;
595 return CommandCost(STR_ERROR_TRAIN_IN_THE_WAY + to_underlying(v->type));
596 }
597 }
598 return CommandCost();
599}
600
610{
611 /* Value v is not safe in MP games, however, it is used to generate a local
612 * error message only (which may be different for different machines).
613 * Such a message does not affect MP synchronisation.
614 */
615 for (const Vehicle *v : VehiclesOnTile(tile)) {
616 if (v->type != VehicleType::Train) continue;
617
618 const Train *t = Train::From(v);
619 if ((t->track != track_bits) && !TracksOverlap(t->track | track_bits)) continue;
620
621 return CommandCost(STR_ERROR_TRAIN_IN_THE_WAY + to_underlying(v->type));
622 }
623 return CommandCost();
624}
625
626static void UpdateVehicleTileHash(Vehicle *v, bool remove)
627{
628 Vehicle **old_hash = v->hash_tile_current;
629 Vehicle **new_hash;
630
631 if (remove) {
632 new_hash = nullptr;
633 } else {
634 new_hash = &_vehicle_tile_hash[GetTileHash(TileX(v->tile), TileY(v->tile))];
635 }
636
637 if (old_hash == new_hash) return;
638
639 /* Remove from the old position in the hash table */
640 if (old_hash != nullptr) {
643 }
644
645 /* Insert vehicle at beginning of the new position in the hash table */
646 if (new_hash != nullptr) {
647 v->hash_tile_next = *new_hash;
648 if (v->hash_tile_next != nullptr) v->hash_tile_next->hash_tile_prev = &v->hash_tile_next;
649 v->hash_tile_prev = new_hash;
650 *new_hash = v;
651 }
652
653 /* Remember current hash position */
654 v->hash_tile_current = new_hash;
655}
656
657static std::array<Vehicle *, 1 << (GEN_HASHX_BITS + GEN_HASHY_BITS)> _vehicle_viewport_hash{};
658
659static void UpdateVehicleViewportHash(Vehicle *v, int x, int y, int old_x, int old_y)
660{
661 Vehicle **old_hash, **new_hash;
662
663 new_hash = (x == INVALID_COORD) ? nullptr : &_vehicle_viewport_hash[GetViewportHash(x, y)];
664 old_hash = (old_x == INVALID_COORD) ? nullptr : &_vehicle_viewport_hash[GetViewportHash(old_x, old_y)];
665
666 if (old_hash == new_hash) return;
667
668 /* remove from hash table? */
669 if (old_hash != nullptr) {
672 }
673
674 /* insert into hash table? */
675 if (new_hash != nullptr) {
676 v->hash_viewport_next = *new_hash;
678 v->hash_viewport_prev = new_hash;
679 *new_hash = v;
680 }
681}
682
683void ResetVehicleHash()
684{
685 for (Vehicle *v : Vehicle::Iterate()) { v->hash_tile_current = nullptr; }
686 _vehicle_viewport_hash.fill(nullptr);
687 _vehicle_tile_hash.fill(nullptr);
688}
689
690void ResetVehicleColourMap()
691{
692 for (Vehicle *v : Vehicle::Iterate()) { v->colourmap = PAL_NONE; }
693}
694
699using AutoreplaceMap = std::map<VehicleID, bool>;
700static AutoreplaceMap _vehicles_to_autoreplace;
701
702void InitializeVehicles()
703{
704 _vehicles_to_autoreplace.clear();
705 ResetVehicleHash();
706}
707
708uint CountVehiclesInChain(const Vehicle *v)
709{
710 uint count = 0;
711 do count++; while ((v = v->Next()) != nullptr);
712 return count;
713}
714
720{
721 switch (this->type) {
722 case VehicleType::Aircraft: return Aircraft::From(this)->IsNormalAircraft(); // don't count plane shadows and helicopter rotors
724 return !this->IsArticulatedPart() && // tenders and other articulated parts
725 !Train::From(this)->IsRearDualheaded(); // rear parts of multiheaded engines
727 case VehicleType::Ship: return true;
728 default: return false; // Only count company buildable vehicles
729 }
730}
731
737{
738 switch (this->type) {
742 case VehicleType::Ship: return true;
743 default: return false;
744 }
745}
746
753{
754 return Engine::Get(this->engine_type);
755}
756
763{
764 return this->GetEngine()->GetGRF();
765}
766
773{
774 return this->GetEngine()->GetGRFID();
775}
776
783{
784 this->date_of_last_service = std::max(this->date_of_last_service + interval, TimerGameEconomy::Date(0));
785 /* date_of_last_service_newgrf is not updated here as it must stay stable
786 * for vehicles outside of a depot. */
787}
788
797{
798 if (path_found) {
799 /* Route found, is the vehicle marked with "lost" flag? */
800 if (!this->vehicle_flags.Test(VehicleFlag::PathfinderLost)) return;
801
802 /* Clear the flag as the PF's problem was solved. */
804 SetWindowWidgetDirty(WindowClass::VehicleView, this->index, WID_VV_START_STOP);
806 /* Delete the news item. */
808 return;
809 }
810
811 /* Were we already lost? */
812 if (this->vehicle_flags.Test(VehicleFlag::PathfinderLost)) return;
813
814 /* It is first time the problem occurred, set the "lost" flag. */
816 SetWindowWidgetDirty(WindowClass::VehicleView, this->index, WID_VV_START_STOP);
818
819 /* Unbunching data is no longer valid. */
820 this->ResetDepotUnbunching();
821
822 /* Notify user about the event. */
823 AI::NewEvent(this->owner, new ScriptEventVehicleLost(this->index));
824 if (_settings_client.gui.lost_vehicle_warn && this->owner == _local_company) {
825 AddVehicleAdviceNewsItem(AdviceType::VehicleLost, GetEncodedString(STR_NEWS_VEHICLE_IS_LOST, this->index), this->index);
826 }
827}
828
831{
832 if (CleaningPool()) return;
833
836 st->loading_vehicles.remove(this);
837
839 this->CancelReservation(StationID::Invalid(), st);
840 delete this->cargo_payment;
841 assert(this->cargo_payment == nullptr); // cleared by ~CargoPayment
842 }
843
844 if (this->IsEngineCountable()) {
846 if (this->IsPrimaryVehicle()) GroupStatistics::CountVehicle(this, -1);
848
851 }
852
853 Company::Get(this->owner)->freeunits[this->type].ReleaseID(this->unitnumber);
854
855 if (this->type == VehicleType::Aircraft && this->IsPrimaryVehicle()) {
856 Aircraft *a = Aircraft::From(this);
858 if (st != nullptr) {
859 const auto &layout = st->airport.GetFTA()->layout;
860 st->airport.blocks.Reset(layout[a->previous_pos].blocks | layout[a->pos].blocks);
861 }
862 }
863
864
865 if (this->type == VehicleType::Road && this->IsPrimaryVehicle()) {
867 if (!v->vehstatus.Test(VehState::Crashed) && IsInsideMM(v->state, RVSB_IN_DT_ROAD_STOP, RVSB_IN_DT_ROAD_STOP_END)) {
868 /* Leave the drive through roadstop, when you have not already left it. */
870 }
871
872 if (v->disaster_vehicle != VehicleID::Invalid()) ReleaseDisasterVehicle(v->disaster_vehicle);
873 }
874
875 if (this->Previous() == nullptr) {
876 InvalidateWindowData(WindowClass::VehicleDepot, this->tile);
877 }
878
879 if (this->IsPrimaryVehicle()) {
880 CloseWindowById(WindowClass::VehicleView, this->index);
881 CloseWindowById(WindowClass::VehicleOrders, this->index);
882 CloseWindowById(WindowClass::VehicleRefit, this->index);
883 CloseWindowById(WindowClass::VehicleDetails, this->index);
884 CloseWindowById(WindowClass::VehicleTimetable, this->index);
885 SetWindowDirty(WindowClass::Company, this->owner);
887 }
889
890 this->cargo.Truncate();
893
894 StopGlobalFollowVehicle(this);
895}
896
898{
899 if (CleaningPool()) {
900 this->cargo.OnCleanPool();
901 return;
902 }
903
904 /* sometimes, eg. for disaster vehicles, when company bankrupts, when removing crashed/flooded vehicles,
905 * it may happen that vehicle chain is deleted when visible */
906 if (!this->vehstatus.Test(VehState::Hidden)) this->MarkAllViewportsDirty();
907
908 Vehicle *v = this->Next();
909 this->SetNext(nullptr);
910
911 delete v;
912
913 UpdateVehicleTileHash(this, true);
914 UpdateVehicleViewportHash(this, INVALID_COORD, 0, this->sprite_cache.old_coord.left, this->sprite_cache.old_coord.top);
915 if (this->type != VehicleType::Effect) {
918 }
919}
920
926{
927 /* Vehicle should stop in the depot if it was in 'stopping' state */
928 _vehicles_to_autoreplace[v->index] = !v->vehstatus.Test(VehState::Stopped);
929
930 /* We ALWAYS set the stopped state. Even when the vehicle does not plan on
931 * stopping in the depot, so we stop it to ensure that it will not reserve
932 * the path out of the depot before we might autoreplace it to a different
933 * engine. The new engine would not own the reserved path we store that we
934 * stopped the vehicle, so autoreplace can start it again */
936}
937
942{
943 if (_game_mode != GameMode::Normal) return;
944
945 /* Run the calendar day proc for every DAY_TICKS vehicle starting at TimerGameCalendar::date_fract. */
947 Vehicle *v = Vehicle::Get(i);
948 if (v == nullptr) continue;
949 v->OnNewCalendarDay();
950 }
951}
952
959{
960 if (_game_mode != GameMode::Normal) return;
961
962 /* Run the economy day proc for every DAY_TICKS vehicle starting at TimerGameEconomy::date_fract. */
964 Vehicle *v = Vehicle::Get(i);
965 if (v == nullptr) continue;
966
967 /* Call the 32-day callback if needed */
968 if ((v->day_counter & 0x1F) == 0 && v->HasEngineType()) {
969 uint16_t callback = GetVehicleCallback(CBID_VEHICLE_32DAY_CALLBACK, 0, 0, v->engine_type, v);
970 if (callback != CALLBACK_FAILED) {
971 if (HasBit(callback, 0)) {
972 TriggerVehicleRandomisation(v, VehicleRandomTrigger::Callback32); // Trigger vehicle trigger 10
973 }
974
975 /* After a vehicle trigger, the graphics and properties of the vehicle could change.
976 * Note: MarkDirty also invalidates the palette, which is the meaning of bit 1. So, nothing special there. */
977 if (callback != 0) v->First()->MarkDirty();
978
979 if (callback & ~3) ErrorUnknownCallbackResult(v->GetGRFID(), CBID_VEHICLE_32DAY_CALLBACK, callback);
980 }
981 }
982
983 /* This is called once per day for each vehicle, but not in the first tick of the day */
984 v->OnNewEconomyDay();
985 }
986}
987
988void CallVehicleTicks()
989{
990 _vehicles_to_autoreplace.clear();
991
993
994 {
995 PerformanceMeasurer framerate(PerformanceElement::GameLoopEconomy);
997 }
1002
1003 for (Vehicle *v : Vehicle::Iterate()) {
1004 [[maybe_unused]] VehicleID vehicle_index = v->index;
1005
1006 /* Vehicle could be deleted in this tick */
1007 if (!v->Tick()) {
1008 assert(Vehicle::Get(vehicle_index) == nullptr);
1009 continue;
1010 }
1011
1012 assert(Vehicle::Get(vehicle_index) == v);
1013
1014 switch (v->type) {
1015 default: break;
1016
1017 case VehicleType::Train:
1018 case VehicleType::Road:
1020 case VehicleType::Ship: {
1021 Vehicle *front = v->First();
1022
1023 if (v->vcache.cached_cargo_age_period != 0) {
1025 if (--v->cargo_age_counter == 0) {
1026 v->cargo.AgeCargo();
1028 }
1029 }
1030
1031 /* Do not play any sound when crashed */
1032 if (front->vehstatus.Test(VehState::Crashed)) continue;
1033
1034 /* Do not play any sound when in depot or tunnel */
1035 if (v->vehstatus.Test(VehState::Hidden)) continue;
1036
1037 /* Do not play any sound when stopped */
1038 if (front->vehstatus.Test(VehState::Stopped) && (front->type != VehicleType::Train || front->cur_speed == 0)) continue;
1039
1040 /* Update motion counter for animation purposes. Relative motion is negative (animations go backwards) if the vehicle is reversing */
1041 v->motion_counter += v->IsDrivingBackwards() ? -front->cur_speed : front->cur_speed;
1042
1043 /* Check vehicle type specifics */
1044 switch (v->type) {
1045 case VehicleType::Train:
1046 if (!Train::From(v)->IsEngine()) continue;
1047 break;
1048
1049 case VehicleType::Road:
1050 if (!RoadVehicle::From(v)->IsFrontEngine()) continue;
1051 break;
1052
1054 if (!Aircraft::From(v)->IsNormalAircraft()) continue;
1055 break;
1056
1057 default:
1058 break;
1059 }
1060
1061 /* Play a running sound if the motion counter passes 256 (Do we not skip sounds?) */
1063
1064 /* Play an alternating running sound every 16 ticks */
1065 if (GB(v->tick_counter, 0, 4) == 0) {
1066 /* Play running sound when speed > 0 and not braking */
1067 bool running = (front->cur_speed > 0) && !front->vehstatus.Any({VehState::Stopped, VehState::TrainSlowing});
1069 }
1070
1071 break;
1072 }
1073 }
1074 }
1075
1076 for (auto &it : _vehicles_to_autoreplace) {
1077 Vehicle *v = Vehicle::Get(it.first);
1078 /* Autoreplace needs the current company set as the vehicle owner */
1079 AutoRestoreBackup cur_company(_current_company, v->owner);
1080
1081 /* Start vehicle if we stopped them in VehicleEnteredDepotThisTick()
1082 * We need to stop them between VehicleEnteredDepotThisTick() and here or we risk that
1083 * they are already leaving the depot again before being replaced. */
1084 if (it.second) v->vehstatus.Reset(VehState::Stopped);
1085
1086 /* Store the position of the effect as the vehicle pointer will become invalid later */
1087 int x = v->x_pos;
1088 int y = v->y_pos;
1089 int z = v->z_pos;
1090
1093 CommandCost res = Command<Commands::AutoreplaceVehicle>::Do(DoCommandFlag::Execute, v->index);
1095
1096 if (!IsLocalCompany()) continue;
1097
1098 if (res.Succeeded()) {
1099 ShowCostOrIncomeAnimation(x, y, z, res.GetCost());
1100 continue;
1101 }
1102
1103 StringID error_message = res.GetErrorMessage();
1104 if (error_message == STR_ERROR_AUTOREPLACE_NOTHING_TO_DO || error_message == INVALID_STRING_ID) continue;
1105
1106 if (error_message == STR_ERROR_NOT_ENOUGH_CASH_REQUIRES_CURRENCY) error_message = STR_ERROR_AUTOREPLACE_MONEY_LIMIT;
1107
1108 EncodedString headline;
1109 if (error_message == STR_ERROR_TRAIN_TOO_LONG_AFTER_REPLACEMENT) {
1110 headline = GetEncodedString(error_message, v->index);
1111 } else {
1112 headline = GetEncodedString(STR_NEWS_VEHICLE_AUTORENEW_FAILED, v->index, error_message, std::monostate{});
1113 }
1114
1115 AddVehicleAdviceNewsItem(AdviceType::AutorenewFailed, std::move(headline), v->index);
1116 }
1117}
1118
1123static void DoDrawVehicle(const Vehicle *v)
1124{
1125 PaletteID pal = PAL_NONE;
1126
1128
1129 /* Check whether the vehicle shall be transparent due to the game state */
1130 bool shadowed = v->vehstatus.Test(VehState::Shadow);
1131
1132 if (v->type == VehicleType::Effect) {
1133 /* Check whether the vehicle shall be transparent/invisible due to GUI settings.
1134 * However, transparent smoke and bubbles look weird, so always hide them. */
1136 if (to != TransparencyOption::Invalid && (IsTransparencySet(to) || IsInvisibilitySet(to))) return;
1137 }
1138
1140 for (uint i = 0; i < v->sprite_cache.sprite_seq.count; ++i) {
1141 PaletteID pal2 = v->sprite_cache.sprite_seq.seq[i].pal;
1142 if (!pal2 || v->vehstatus.Test(VehState::Crashed)) pal2 = pal;
1143 AddSortableSpriteToDraw(v->sprite_cache.sprite_seq.seq[i].sprite, pal2, v->x_pos, v->y_pos, v->z_pos, v->bounds, shadowed);
1144 }
1146}
1147
1153{
1154 /* The bounding rectangle */
1155 const int l = dpi->left;
1156 const int r = dpi->left + dpi->width;
1157 const int t = dpi->top;
1158 const int b = dpi->top + dpi->height;
1159
1160 /* Border size of MAX_VEHICLE_PIXEL_xy */
1161 const int xb = MAX_VEHICLE_PIXEL_X * ZOOM_BASE;
1162 const int yb = MAX_VEHICLE_PIXEL_Y * ZOOM_BASE;
1163
1164 /* The hash area to scan */
1165 uint xl, xu, yl, yu;
1166
1167 if (static_cast<uint>(dpi->width + xb) < GEN_HASHX_SIZE) {
1168 xl = GetViewportHashX(l - xb);
1169 xu = GetViewportHashX(r);
1170 } else {
1171 /* scan whole hash row */
1172 xl = 0;
1173 xu = GEN_HASHX_MASK;
1174 }
1175
1176 if (static_cast<uint>(dpi->height + yb) < GEN_HASHY_SIZE) {
1177 yl = GetViewportHashY(t - yb);
1178 yu = GetViewportHashY(b);
1179 } else {
1180 /* scan whole column */
1181 yl = 0;
1182 yu = GEN_HASHY_MASK;
1183 }
1184
1185 for (uint y = yl;; y = (y + GEN_HASHY_INC) & GEN_HASHY_MASK) {
1186 for (uint x = xl;; x = (x + GEN_HASHX_INC) & GEN_HASHX_MASK) {
1187 const Vehicle *v = _vehicle_viewport_hash[x + y]; // already masked & 0xFFF
1188
1189 while (v != nullptr) {
1190
1191 if (!v->vehstatus.Test(VehState::Hidden) &&
1192 l <= v->coord.right + xb &&
1193 t <= v->coord.bottom + yb &&
1194 r >= v->coord.left - xb &&
1195 b >= v->coord.top - yb)
1196 {
1197 /*
1198 * This vehicle can potentially be drawn as part of this viewport and
1199 * needs to be revalidated, as the sprite may not be correct.
1200 */
1202 VehicleSpriteSeq seq;
1204
1205 if (seq.IsValid() && v->sprite_cache.sprite_seq != seq) {
1206 v->sprite_cache.sprite_seq = seq;
1207 /*
1208 * A sprite change may also result in a bounding box change,
1209 * so we need to update the bounding box again before we
1210 * check to see if the vehicle should be drawn. Note that
1211 * we can't interfere with the viewport hash at this point,
1212 * so we keep the original hash on the assumption there will
1213 * not be a significant change in the top and left coordinates
1214 * of the vehicle.
1215 */
1217
1218 }
1219
1221 }
1222
1223 if (l <= v->coord.right &&
1224 t <= v->coord.bottom &&
1225 r >= v->coord.left &&
1226 b >= v->coord.top) DoDrawVehicle(v);
1227 }
1228
1229 v = v->hash_viewport_next;
1230 }
1231
1232 if (x == xu) break;
1233 }
1234
1235 if (y == yu) break;
1236 }
1237}
1238
1246Vehicle *CheckClickOnVehicle(const Viewport &vp, int x, int y)
1247{
1248 Vehicle *found = nullptr;
1249 uint dist, best_dist = UINT_MAX;
1250
1251 x -= vp.left;
1252 y -= vp.top;
1253 if (!IsInsideMM(x, 0, vp.width) || !IsInsideMM(y, 0, vp.height)) return nullptr;
1254
1255 x = ScaleByZoom(x, vp.zoom) + vp.virtual_left;
1256 y = ScaleByZoom(y, vp.zoom) + vp.virtual_top;
1257
1258 /* Border size of MAX_VEHICLE_PIXEL_xy */
1259 const int xb = MAX_VEHICLE_PIXEL_X * ZOOM_BASE;
1260 const int yb = MAX_VEHICLE_PIXEL_Y * ZOOM_BASE;
1261
1262 /* The hash area to scan */
1263 uint xl = GetViewportHashX(x - xb);
1264 uint xu = GetViewportHashX(x);
1265 uint yl = GetViewportHashY(y - yb);
1266 uint yu = GetViewportHashY(y);
1267
1268 for (uint hy = yl;; hy = (hy + GEN_HASHY_INC) & GEN_HASHY_MASK) {
1269 for (uint hx = xl;; hx = (hx + GEN_HASHX_INC) & GEN_HASHX_MASK) {
1270 Vehicle *v = _vehicle_viewport_hash[hx + hy]; // already masked & 0xFFF
1271
1272 while (v != nullptr) {
1273 if (!v->vehstatus.Any({VehState::Hidden, VehState::Unclickable}) &&
1274 x >= v->coord.left && x <= v->coord.right &&
1275 y >= v->coord.top && y <= v->coord.bottom) {
1276
1277 dist = std::max(
1278 abs(((v->coord.left + v->coord.right) >> 1) - x),
1279 abs(((v->coord.top + v->coord.bottom) >> 1) - y)
1280 );
1281
1282 if (dist < best_dist) {
1283 found = v;
1284 best_dist = dist;
1285 }
1286 }
1287 v = v->hash_viewport_next;
1288 }
1289 if (hx == xu) break;
1290 }
1291 if (hy == yu) break;
1292 }
1293
1294 return found;
1295}
1296
1302{
1303 v->value -= v->value >> 8;
1304 SetWindowDirty(WindowClass::VehicleDetails, v->index);
1305}
1306
1307static const uint8_t _breakdown_chance[64] = {
1308 3, 3, 3, 3, 3, 3, 3, 3,
1309 4, 4, 5, 5, 6, 6, 7, 7,
1310 8, 8, 9, 9, 10, 10, 11, 11,
1311 12, 13, 13, 13, 13, 14, 15, 16,
1312 17, 19, 21, 25, 28, 31, 34, 37,
1313 40, 44, 48, 52, 56, 60, 64, 68,
1314 72, 80, 90, 100, 110, 120, 130, 140,
1315 150, 170, 190, 210, 230, 250, 250, 250,
1316};
1317
1323{
1324 /* Vehicles in the menu don't break down. */
1325 if (_game_mode == GameMode::Menu) return;
1326
1327 /* If both breakdowns and automatic servicing are disabled, we don't decrease reliability or break down. */
1328 if (_settings_game.difficulty.vehicle_breakdowns == VehicleBreakdowns::None && _settings_game.order.no_servicing_if_no_breakdowns) return;
1329
1330 /* With Reduced breakdowns, vehicles (un)loading at stations don't lose reliability. */
1331 if (_settings_game.difficulty.vehicle_breakdowns == VehicleBreakdowns::Reduced && v->current_order.IsType(OT_LOADING)) return;
1332
1333 /* Decrease reliability. */
1334 int rel_old = v->reliability;
1335 v->reliability = Clamp(rel_old - v->reliability_spd_dec, 0, Engine::Get(v->engine_type)->reliability);
1336 if ((rel_old >> 8) != (v->reliability >> 8)) SetWindowDirty(WindowClass::VehicleDetails, v->index);
1337
1338 /* Some vehicles lose reliability but won't break down. */
1339 /* Breakdowns are disabled. */
1340 if (_settings_game.difficulty.vehicle_breakdowns == VehicleBreakdowns::None) return;
1341 /* The vehicle is already broken down. */
1342 if (v->breakdown_ctr != 0) return;
1343 /* The vehicle is stopped or going very slow. */
1344 if (v->cur_speed < 5) return;
1345 /* The vehicle has been manually stopped. */
1346 if (v->vehstatus.Test(VehState::Stopped)) return;
1347
1348 /* Time to consider breaking down. */
1349
1350 uint32_t r = Random();
1351
1352 /* Increase chance of failure. */
1353 int chance = v->breakdown_chance + 1;
1354 if (Chance16I(1, 25, r)) chance += 25;
1356
1357 /* Calculate reliability value to use in comparison. */
1358 int rel = v->reliability;
1359 if (v->type == VehicleType::Ship) rel += 0x6666;
1360
1361 /* Reduce the chance if the player has chosen the Reduced setting. */
1362 if (_settings_game.difficulty.vehicle_breakdowns == VehicleBreakdowns::Reduced) rel += 0x6666;
1363
1364 /* Check the random chance and inform the vehicle of the result. */
1365 if (_breakdown_chance[ClampTo<uint16_t>(rel) >> 10] <= v->breakdown_chance) {
1366 v->breakdown_ctr = GB(r, 16, 6) + 0x3F;
1367 v->breakdown_delay = GB(r, 24, 7) + 0x80;
1368 v->breakdown_chance = 0;
1369 }
1370}
1371
1379{
1380 /* Possible states for Vehicle::breakdown_ctr
1381 * 0 - vehicle is running normally
1382 * 1 - vehicle is currently broken down
1383 * 2 - vehicle is going to break down now
1384 * >2 - vehicle is counting down to the actual breakdown event */
1385 switch (this->breakdown_ctr) {
1386 case 0:
1387 return false;
1388
1389 case 2:
1390 this->breakdown_ctr = 1;
1391
1392 if (this->breakdowns_since_last_service != 255) {
1394 }
1395
1396 if (this->type == VehicleType::Aircraft) {
1397 /* Aircraft just need this flag, the rest is handled elsewhere */
1399 } else {
1400 this->cur_speed = 0;
1401
1403 bool train_or_ship = this->type == VehicleType::Train || this->type == VehicleType::Ship;
1404 SndPlayVehicleFx((_settings_game.game_creation.landscape != LandscapeType::Toyland) ?
1407 }
1408
1409 if (!this->vehstatus.Test(VehState::Hidden) && !EngInfo(this->engine_type)->misc_flags.Test(EngineMiscFlag::NoBreakdownSmoke)) {
1411 if (u != nullptr) u->animation_state = this->breakdown_delay * 2;
1412 }
1413 }
1414
1415 this->MarkDirty(); // Update graphics after speed is zeroed
1416 SetWindowDirty(WindowClass::VehicleView, this->index);
1417 SetWindowDirty(WindowClass::VehicleDetails, this->index);
1418
1419 [[fallthrough]];
1420 case 1:
1421 /* Aircraft breakdowns end only when arriving at the airport */
1422 if (this->type == VehicleType::Aircraft) return false;
1423
1424 /* For trains this function is called twice per tick, so decrease v->breakdown_delay at half the rate */
1425 if ((this->tick_counter & (this->type == VehicleType::Train ? 3 : 1)) == 0) {
1426 if (--this->breakdown_delay == 0) {
1427 this->breakdown_ctr = 0;
1428 this->MarkDirty();
1429 SetWindowDirty(WindowClass::VehicleView, this->index);
1430 }
1431 }
1432 return true;
1433
1434 default:
1435 if (!this->current_order.IsType(OT_LOADING)) this->breakdown_ctr--;
1436 return false;
1437 }
1438}
1439
1451
1457{
1458 if (v->age < CalendarTime::MAX_DATE) v->age++;
1459
1460 if (!v->IsPrimaryVehicle() && (v->type != VehicleType::Train || !Train::From(v)->IsEngine())) return;
1461
1462 auto age = v->age - v->max_age;
1463 for (int32_t i = 0; i <= 4; i++) {
1465 v->reliability_spd_dec <<= 1;
1466 break;
1467 }
1468 }
1469
1470 SetWindowDirty(WindowClass::VehicleDetails, v->index);
1471
1472 /* Don't warn if warnings are disabled */
1473 if (!_settings_client.gui.old_vehicle_warn) return;
1474
1475 /* Don't warn about vehicles which are non-primary (e.g., part of an articulated vehicle), don't belong to us, are crashed, or are stopped */
1476 if (v->Previous() != nullptr || v->owner != _local_company || v->vehstatus.Any({VehState::Crashed, VehState::Stopped})) return;
1477
1478 const Company *c = Company::Get(v->owner);
1479 /* Don't warn if a renew is active */
1480 if (c->settings.engine_renew && v->GetEngine()->company_avail.Any()) return;
1481 /* Don't warn if a replacement is active */
1482 if (EngineHasReplacement(v->owner, v->group_id, v->engine_type, true)) return;
1483
1484 StringID str;
1486 str = STR_NEWS_VEHICLE_IS_GETTING_OLD;
1488 str = STR_NEWS_VEHICLE_IS_GETTING_VERY_OLD;
1490 str = STR_NEWS_VEHICLE_IS_GETTING_VERY_OLD_AND;
1491 } else {
1492 return;
1493 }
1494
1496}
1497
1507uint8_t CalcPercentVehicleFilled(const Vehicle *front, StringID *colour)
1508{
1509 int count = 0;
1510 int max = 0;
1511 int cars = 0;
1512 int unloading = 0;
1513 bool loading = false;
1514
1515 bool is_loading = front->current_order.IsType(OT_LOADING);
1516
1517 /* The station may be nullptr when the (colour) string does not need to be set. */
1519 assert(colour == nullptr || (st != nullptr && is_loading));
1520
1521 bool order_no_load = is_loading && front->current_order.GetLoadType() == OrderLoadType::NoLoad;
1522 bool order_full_load = is_loading && front->current_order.IsFullLoadOrder();
1523
1524 /* Count up max and used */
1525 for (const Vehicle *v = front; v != nullptr; v = v->Next()) {
1526 count += v->cargo.StoredCount();
1527 max += v->cargo_cap;
1528 if (v->cargo_cap != 0 && colour != nullptr) {
1529 unloading += v->vehicle_flags.Test(VehicleFlag::CargoUnloading) ? 1 : 0;
1530 loading |= !order_no_load &&
1531 (order_full_load || st->goods[v->cargo_type].HasRating()) &&
1533 cars++;
1534 }
1535 }
1536
1537 if (colour != nullptr) {
1538 if (unloading == 0 && loading) {
1539 *colour = STR_PERCENT_UP;
1540 } else if (unloading == 0 && !loading) {
1541 *colour = STR_PERCENT_NONE;
1542 } else if (cars == unloading || !loading) {
1543 *colour = STR_PERCENT_DOWN;
1544 } else {
1545 *colour = STR_PERCENT_UP_DOWN;
1546 }
1547 }
1548
1549 /* Train without capacity */
1550 if (max == 0) return 100;
1551
1552 /* Return the percentage */
1553 if (count * 2 < max) {
1554 /* Less than 50%; round up, so that 0% means really empty. */
1555 return CeilDiv(count * 100, max);
1556 } else {
1557 /* More than 50%; round down, so that 100% means really full. */
1558 return (count * 100) / max;
1559 }
1560}
1561
1567{
1568 /* Always work with the front of the vehicle */
1569 assert(v == v->First());
1570
1571 switch (v->type) {
1572 case VehicleType::Train: {
1573 Train *t = Train::From(v);
1574 SetWindowClassesDirty(WindowClass::TrainList);
1575 /* Clear path reservation */
1576 SetDepotReservation(t->tile, false);
1577 if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(t->tile);
1578
1580 t->wait_counter = 0;
1584 break;
1585 }
1586
1587 case VehicleType::Road:
1588 SetWindowClassesDirty(WindowClass::RoadVehicleList);
1589 break;
1590
1591 case VehicleType::Ship: {
1592 SetWindowClassesDirty(WindowClass::ShipList);
1593 Ship *ship = Ship::From(v);
1594 ship->state = Track::Depot;
1595 ship->UpdateCache();
1596 ship->UpdateViewport(true, true);
1597 SetWindowDirty(WindowClass::VehicleDepot, v->tile);
1598 break;
1599 }
1600
1602 SetWindowClassesDirty(WindowClass::AircraftList);
1604 break;
1605 default: NOT_REACHED();
1606 }
1607 if (v->type != VehicleType::Train) {
1608 /* Trains update the vehicle list when the first unit enters the depot and calls VehicleEnterDepot() when the last unit enters.
1609 * We only increase the number of vehicles when the first one enters, so we will not need to search for more vehicles in the depot */
1610 InvalidateWindowData(WindowClass::VehicleDepot, v->tile);
1611 }
1612 SetWindowDirty(WindowClass::VehicleDepot, v->tile);
1613
1615 v->cur_speed = 0;
1616
1618
1619 /* Store that the vehicle entered a depot this tick */
1621
1622 /* After a vehicle trigger, the graphics and properties of the vehicle could change. */
1623 TriggerVehicleRandomisation(v, VehicleRandomTrigger::Depot);
1624 v->MarkDirty();
1625
1626 InvalidateWindowData(WindowClass::VehicleView, v->index);
1627
1628 if (v->current_order.IsType(OT_GOTO_DEPOT)) {
1629 const Order *real_order = v->GetOrder(v->cur_real_order_index);
1630
1631 /* Test whether we are heading for this depot. If not, do nothing.
1632 * Note: The target depot for nearest-/manual-depot-orders is only updated on junctions, but we want to accept every depot. */
1634 real_order != nullptr && !real_order->GetDepotActionType().Test(OrderDepotActionFlag::NearestDepot) &&
1636 /* We are heading for another depot, keep driving. */
1637 return;
1638 }
1639
1640 if (v->current_order.IsRefit()) {
1641 AutoRestoreBackup cur_company(_current_company, v->owner);
1642 CommandCost cost = ExtractCommandCost(Command<Commands::RefitVehicle>::Do(DoCommandFlag::Execute, v->index, v->current_order.GetRefitCargo(), 0xFF, false, false, 0));
1643
1644 if (cost.Failed()) {
1645 _vehicles_to_autoreplace[v->index] = false;
1646 if (v->owner == _local_company) {
1647 /* Notify the user that we stopped the vehicle */
1648 AddVehicleAdviceNewsItem(AdviceType::RefitFailed, GetEncodedString(STR_NEWS_ORDER_REFIT_FAILED, v->index), v->index);
1649 }
1650 } else if (cost.GetCost() != 0) {
1651 v->profit_this_year -= cost.GetCost() << 8;
1652 if (v->owner == _local_company) {
1654 }
1655 }
1656 }
1657
1659 /* Part of orders */
1661 UpdateVehicleTimetable(v, true);
1663 }
1665 /* Vehicles are always stopped on entering depots. Do not restart this one. */
1666 _vehicles_to_autoreplace[v->index] = false;
1667 /* Invalidate last_loading_station. As the link from the station
1668 * before the stop to the station after the stop can't be predicted
1669 * we shouldn't construct it when the vehicle visits the next stop. */
1670 v->last_loading_station = StationID::Invalid();
1671
1672 /* Clear unbunching data. */
1674
1675 /* Announce that the vehicle is waiting to players and AIs. */
1676 if (v->owner == _local_company) {
1677 AddVehicleAdviceNewsItem(AdviceType::VehicleWaiting, GetEncodedString(STR_NEWS_TRAIN_IS_WAITING + to_underlying(v->type), v->index), v->index);
1678 }
1679 AI::NewEvent(v->owner, new ScriptEventVehicleWaitingInDepot(v->index));
1680 }
1681
1682 /* If we've entered our unbunching depot, record the round trip duration. */
1685 if (v->round_trip_time == 0) {
1686 /* This might be our first round trip. */
1687 v->round_trip_time = measured_round_trip;
1688 } else {
1689 /* If we have a previous trip, smooth the effects of outlier trip calculations caused by jams or other interference. */
1690 v->round_trip_time = Clamp(measured_round_trip, (v->round_trip_time / 2), ClampTo<TimerGameTick::Ticks>(v->round_trip_time * 2));
1691 }
1692 }
1693
1695 }
1696}
1697
1698
1704{
1705 UpdateVehicleTileHash(this, false);
1706}
1707
1712void Vehicle::UpdateBoundingBoxCoordinates(bool update_cache) const
1713{
1714 Rect new_coord;
1715 this->sprite_cache.sprite_seq.GetBounds(&new_coord);
1716
1717 /* z-bounds are not used. */
1718 Point pt = RemapCoords(this->x_pos + this->bounds.origin.x + this->bounds.offset.x, this->y_pos + this->bounds.origin.y + this->bounds.offset.y, this->z_pos);
1719 new_coord.left += pt.x;
1720 new_coord.top += pt.y;
1721 new_coord.right += pt.x + 2 * ZOOM_BASE;
1722 new_coord.bottom += pt.y + 2 * ZOOM_BASE;
1723
1724 extern bool _draw_bounding_boxes;
1725 if (_draw_bounding_boxes) {
1726 int x = this->x_pos + this->bounds.origin.x;
1727 int y = this->y_pos + this->bounds.origin.y;
1728 int z = this->z_pos + this->bounds.origin.z;
1729 new_coord.left = std::min(new_coord.left, RemapCoords(x + bounds.extent.x, y, z).x);
1730 new_coord.right = std::max(new_coord.right, RemapCoords(x, y + bounds.extent.y, z).x + 1);
1731 new_coord.top = std::min(new_coord.top, RemapCoords(x, y, z + bounds.extent.z).y);
1732 new_coord.bottom = std::max(new_coord.bottom, RemapCoords(x + bounds.extent.x, y + bounds.extent.y, z).y + 1);
1733 }
1734
1735 if (update_cache) {
1736 /*
1737 * If the old coordinates are invalid, set the cache to the new coordinates for correct
1738 * behaviour the next time the coordinate cache is checked.
1739 */
1740 this->sprite_cache.old_coord = this->coord.left == INVALID_COORD ? new_coord : this->coord;
1741 }
1742 else {
1743 /* Extend the bounds of the existing cached bounding box so the next dirty window is correct */
1744 this->sprite_cache.old_coord.left = std::min(this->sprite_cache.old_coord.left, this->coord.left);
1745 this->sprite_cache.old_coord.top = std::min(this->sprite_cache.old_coord.top, this->coord.top);
1746 this->sprite_cache.old_coord.right = std::max(this->sprite_cache.old_coord.right, this->coord.right);
1747 this->sprite_cache.old_coord.bottom = std::max(this->sprite_cache.old_coord.bottom, this->coord.bottom);
1748 }
1749
1750 this->coord = new_coord;
1751}
1752
1758{
1759 /* If the existing cache is invalid we should ignore it, as it will be set to the current coords by UpdateBoundingBoxCoordinates */
1760 bool ignore_cached_coords = this->sprite_cache.old_coord.left == INVALID_COORD;
1761
1762 this->UpdateBoundingBoxCoordinates(true);
1763
1764 if (ignore_cached_coords) {
1765 UpdateVehicleViewportHash(this, this->coord.left, this->coord.top, INVALID_COORD, INVALID_COORD);
1766 } else {
1767 UpdateVehicleViewportHash(this, this->coord.left, this->coord.top, this->sprite_cache.old_coord.left, this->sprite_cache.old_coord.top);
1768 }
1769
1770 if (dirty) {
1771 if (ignore_cached_coords) {
1772 this->sprite_cache.is_viewport_candidate = this->MarkAllViewportsDirty();
1773 } else {
1774 this->sprite_cache.is_viewport_candidate = ::MarkAllViewportsDirty(
1775 std::min(this->sprite_cache.old_coord.left, this->coord.left),
1776 std::min(this->sprite_cache.old_coord.top, this->coord.top),
1777 std::max(this->sprite_cache.old_coord.right, this->coord.right),
1778 std::max(this->sprite_cache.old_coord.bottom, this->coord.bottom));
1779 }
1780 }
1781}
1782
1787{
1788 if (this->type != VehicleType::Effect) this->UpdatePosition();
1789 this->UpdateViewport(true);
1790}
1791
1797{
1798 return ::MarkAllViewportsDirty(this->coord.left, this->coord.top, this->coord.right, this->coord.bottom);
1799}
1800
1807{
1808 static constexpr DirectionIndexArray<Coord2D<int8_t>> delta_coord{{{
1809 {-1, -1}, // N
1810 {-1, 0}, // NE
1811 {-1, 1}, // E
1812 {0, 1}, // SE
1813 {1, 1}, // S
1814 {1, 0}, // SW
1815 {1, -1}, // W
1816 {0, -1}, // NW
1817 }}};
1818
1819 const Coord2D<int8_t> &coord = delta_coord[v->GetMovingDirection()];
1820 int x = v->x_pos + coord.x;
1821 int y = v->y_pos + coord.y;
1822
1824 gp.x = x;
1825 gp.y = y;
1826 gp.old_tile = v->tile;
1827 gp.new_tile = TileVirtXY(x, y);
1828 return gp;
1829}
1830
1831static const Direction _new_direction_table[] = {
1835};
1836
1837Direction GetDirectionTowards(const Vehicle *v, int x, int y)
1838{
1839 int i = 0;
1840
1841 if (y >= v->y_pos) {
1842 if (y != v->y_pos) i += 3;
1843 i += 3;
1844 }
1845
1846 if (x >= v->x_pos) {
1847 if (x != v->x_pos) i++;
1848 i++;
1849 }
1850
1851 Direction dir = v->GetMovingDirection();
1852
1853 DirDiff dirdiff = DirDifference(_new_direction_table[i], dir);
1854 if (dirdiff == DirDiff::Same) return dir;
1855 return ChangeDir(dir, LimitDirDiff(dirdiff));
1856}
1857
1868{
1869 return _tile_type_procs[GetTileType(tile)]->vehicle_enter_tile_proc(v, tile, x, y);
1870}
1871
1878{
1879 for (auto it = std::begin(this->used_bitmap); it != std::end(this->used_bitmap); ++it) {
1880 BitmapStorage available = ~(*it);
1881 if (available == 0) continue;
1882 return static_cast<UnitID>(std::distance(std::begin(this->used_bitmap), it) * BITMAP_SIZE + FindFirstBit(available) + 1);
1883 }
1884 return static_cast<UnitID>(this->used_bitmap.size() * BITMAP_SIZE + 1);
1885}
1886
1893{
1894 if (index == 0 || index == UINT16_MAX) return index;
1895
1896 index--;
1897
1898 size_t slot = index / BITMAP_SIZE;
1899 if (slot >= this->used_bitmap.size()) this->used_bitmap.resize(slot + 1);
1900 SetBit(this->used_bitmap[index / BITMAP_SIZE], index % BITMAP_SIZE);
1901
1902 return index + 1;
1903}
1904
1910{
1911 if (index == 0 || index == UINT16_MAX) return;
1912
1913 index--;
1914
1915 assert(index / BITMAP_SIZE < this->used_bitmap.size());
1916 ClrBit(this->used_bitmap[index / BITMAP_SIZE], index % BITMAP_SIZE);
1917}
1918
1925{
1926 /* Check whether it is allowed to build another vehicle. */
1927 uint max_veh;
1928 switch (type) {
1929 case VehicleType::Train: max_veh = _settings_game.vehicle.max_trains; break;
1930 case VehicleType::Road: max_veh = _settings_game.vehicle.max_roadveh; break;
1931 case VehicleType::Ship: max_veh = _settings_game.vehicle.max_ships; break;
1932 case VehicleType::Aircraft: max_veh = _settings_game.vehicle.max_aircraft; break;
1933 default: NOT_REACHED();
1934 }
1935
1937 if (c->group_all[type].num_vehicle >= max_veh) return UINT16_MAX; // Currently already at the limit, no room to make a new one.
1938
1939 return c->freeunits[type].NextID();
1940}
1941
1942
1953{
1954 assert(IsCompanyBuildableVehicleType(type));
1955
1956 if (!Company::IsValidID(_local_company)) return false;
1957
1958 UnitID max;
1959 switch (type) {
1960 case VehicleType::Train:
1961 if (!HasAnyRailTypesAvail(_local_company)) return false;
1962 max = _settings_game.vehicle.max_trains;
1963 break;
1964 case VehicleType::Road:
1965 if (!HasAnyRoadTypesAvail(_local_company, subtype)) return false;
1966 max = _settings_game.vehicle.max_roadveh;
1967 break;
1968 case VehicleType::Ship: max = _settings_game.vehicle.max_ships; break;
1969 case VehicleType::Aircraft: max = _settings_game.vehicle.max_aircraft; break;
1970 default: NOT_REACHED();
1971 }
1972
1973 /* We can build vehicle infrastructure when we may build the vehicle type */
1974 if (max > 0) {
1975 /* Can we actually build the vehicle type? */
1976 for (const Engine *e : Engine::IterateType(type)) {
1977 if (type == VehicleType::Road && GetRoadTramType(e->VehInfo<RoadVehicleInfo>().roadtype) != subtype) continue;
1978 if (e->company_avail.Test(_local_company)) return true;
1979 }
1980 return false;
1981 }
1982
1983 /* We should be able to build infrastructure when we have the actual vehicle type */
1984 for (const Vehicle *v : Vehicle::Iterate()) {
1985 if (v->type == VehicleType::Road && GetRoadTramType(RoadVehicle::From(v)->roadtype) != subtype) continue;
1986 if (v->owner == _local_company && v->type == type) return true;
1987 }
1988
1989 return false;
1990}
1991
1992
2000LiveryScheme GetEngineLiveryScheme(EngineID engine_type, EngineID parent_engine_type, const Vehicle *v)
2001{
2002 CargoType cargo_type = v == nullptr ? INVALID_CARGO : v->cargo_type;
2003 const Engine *e = Engine::Get(engine_type);
2004 switch (e->type) {
2005 default: NOT_REACHED();
2006 case VehicleType::Train:
2007 if (v != nullptr && parent_engine_type != EngineID::Invalid() && (UsesWagonOverride(v) || (v->IsArticulatedPart() && e->VehInfo<RailVehicleInfo>().railveh_type != RailVehicleType::Wagon))) {
2008 /* Wagonoverrides use the colour scheme of the front engine.
2009 * Articulated parts use the colour scheme of the first part. (Not supported for articulated wagons) */
2010 engine_type = parent_engine_type;
2011 e = Engine::Get(engine_type);
2012 /* Note: Luckily cargo_type is not needed for engines */
2013 }
2014
2015 if (!IsValidCargoType(cargo_type)) cargo_type = e->GetDefaultCargoType();
2016 if (!IsValidCargoType(cargo_type)) cargo_type = GetCargoTypeByLabel(CT_GOODS); // The vehicle does not carry anything, let's pick some freight cargo
2017 assert(IsValidCargoType(cargo_type));
2019 if (!CargoSpec::Get(cargo_type)->is_freight) {
2020 if (parent_engine_type == EngineID::Invalid()) {
2022 } else {
2023 bool is_mu = EngInfo(parent_engine_type)->misc_flags.Test(EngineMiscFlag::RailIsMU);
2024 switch (RailVehInfo(parent_engine_type)->engclass) {
2025 default: NOT_REACHED();
2031 }
2032 }
2033 } else {
2035 }
2036 } else {
2037 bool is_mu = e->info.misc_flags.Test(EngineMiscFlag::RailIsMU);
2038
2039 switch (e->VehInfo<RailVehicleInfo>().engclass) {
2040 default: NOT_REACHED();
2046 }
2047 }
2048
2049 case VehicleType::Road:
2050 /* Always use the livery of the front */
2051 if (v != nullptr && parent_engine_type != EngineID::Invalid()) {
2052 engine_type = parent_engine_type;
2053 e = Engine::Get(engine_type);
2054 cargo_type = v->First()->cargo_type;
2055 }
2056 if (!IsValidCargoType(cargo_type)) cargo_type = e->GetDefaultCargoType();
2057 if (!IsValidCargoType(cargo_type)) cargo_type = GetCargoTypeByLabel(CT_GOODS); // The vehicle does not carry anything, let's pick some freight cargo
2058 assert(IsValidCargoType(cargo_type));
2059
2060 /* Important: Use Tram Flag of front part. Luckily engine_type refers to the front part here. */
2062 /* Tram */
2064 } else {
2065 /* Bus or truck */
2067 }
2068
2069 case VehicleType::Ship:
2070 if (!IsValidCargoType(cargo_type)) cargo_type = e->GetDefaultCargoType();
2071 if (!IsValidCargoType(cargo_type)) cargo_type = GetCargoTypeByLabel(CT_GOODS); // The vehicle does not carry anything, let's pick some freight cargo
2072 assert(IsValidCargoType(cargo_type));
2074
2076 switch (e->VehInfo<AircraftVehicleInfo>().subtype) {
2077 case AIR_HELI: return LiveryScheme::Helicopter;
2079 case AIR_CTOL | AIR_FAST: return LiveryScheme::LargePlane;
2080 default: NOT_REACHED();
2081 }
2082 }
2083}
2084
2094const Livery *GetEngineLivery(EngineID engine_type, CompanyID company, EngineID parent_engine_type, const Vehicle *v, uint8_t livery_setting)
2095{
2096 const Company *c = Company::Get(company);
2098
2099 if (livery_setting == LIT_ALL || (livery_setting == LIT_COMPANY && company == _local_company)) {
2100 if (v != nullptr) {
2101 const Group *g = Group::GetIfValid(v->First()->group_id);
2102 if (g != nullptr) {
2103 /* Traverse parents until we find a livery or reach the top */
2104 while (!g->livery.in_use.Any({Livery::Flag::Primary, Livery::Flag::Secondary}) && g->parent != GroupID::Invalid()) {
2105 g = Group::Get(g->parent);
2106 }
2107 if (g->livery.in_use.Any({Livery::Flag::Primary, Livery::Flag::Secondary})) return &g->livery;
2108 }
2109 }
2110
2111 /* The default livery is always available for use, but its in_use flag determines
2112 * whether any _other_ liveries are in use. */
2113 if (c->livery[LiveryScheme::Default].in_use.Any({Livery::Flag::Primary, Livery::Flag::Secondary})) {
2114 /* Determine the livery scheme to use */
2115 scheme = GetEngineLiveryScheme(engine_type, parent_engine_type, v);
2116 }
2117 }
2118
2119 return &c->livery[scheme];
2120}
2121
2122
2123static PaletteID GetEngineColourMap(EngineID engine_type, CompanyID company, EngineID parent_engine_type, const Vehicle *v)
2124{
2125 PaletteID map = (v != nullptr) ? v->colourmap : PAL_NONE;
2126
2127 /* Return cached value if any */
2128 if (map != PAL_NONE) return map;
2129
2130 const Engine *e = Engine::Get(engine_type);
2131
2132 /* Check if we should use the colour map callback */
2134 uint16_t callback = GetVehicleCallback(CBID_VEHICLE_COLOUR_MAPPING, 0, 0, engine_type, v);
2135 /* Failure means "use the default two-colour" */
2136 if (callback != CALLBACK_FAILED) {
2137 static_assert(PAL_NONE == 0); // Returning 0x4000 (resp. 0xC000) coincidences with default value (PAL_NONE)
2138 map = GB(callback, 0, 14);
2139 /* If bit 14 is set, then the company colours are applied to the
2140 * map else it's returned as-is. */
2141 if (!HasBit(callback, 14)) {
2142 /* Update cache */
2143 if (v != nullptr) const_cast<Vehicle *>(v)->colourmap = map;
2144 return map;
2145 }
2146 }
2147 }
2148
2149 bool twocc = e->info.misc_flags.Test(EngineMiscFlag::Uses2CC);
2150
2151 if (map == PAL_NONE) map = twocc ? (PaletteID)SPR_2CCMAP_BASE : (PaletteID)PALETTE_RECOLOUR_START;
2152
2153 /* Spectator has news shown too, but has invalid company ID - as well as dedicated server */
2154 if (!Company::IsValidID(company)) return map;
2155
2156 const Livery *livery = GetEngineLivery(engine_type, company, parent_engine_type, v, _settings_client.gui.liveries);
2157
2158 map += livery->GetRecolourOffset(twocc);
2159
2160 /* Update cache */
2161 if (v != nullptr) const_cast<Vehicle *>(v)->colourmap = map;
2162 return map;
2163}
2164
2171PaletteID GetEnginePalette(EngineID engine_type, CompanyID company)
2172{
2173 return GetEngineColourMap(engine_type, company, EngineID::Invalid(), nullptr);
2174}
2175
2182{
2183 if (v->IsGroundVehicle()) {
2184 return GetEngineColourMap(v->engine_type, v->owner, v->GetGroundVehicleCache()->first_engine, v);
2185 }
2186
2187 return GetEngineColourMap(v->engine_type, v->owner, EngineID::Invalid(), v);
2188}
2189
2194{
2195 if (this->IsGroundVehicle()) {
2196 GroundVehicleFlags &gv_flags = this->GetGroundVehicleFlags();
2198 /* Do not delete orders, only skip them */
2201 InvalidateVehicleOrder(this, 0);
2202 return;
2203 }
2204 }
2205
2206 auto orders = this->Orders();
2208 while (cur != INVALID_VEH_ORDER_ID) {
2209 if (this->cur_implicit_order_index == this->cur_real_order_index) break;
2210
2211 if (orders[cur].IsType(OT_IMPLICIT)) {
2213 /* DeleteOrder does various magic with order_indices, so resync 'order' with 'cur_implicit_order_index' */
2214 } else {
2215 /* Skip non-implicit orders, e.g. service-orders */
2216 if (cur < this->orders->GetNext(cur)) {
2218 } else {
2219 /* Wrapped around. */
2220 this->cur_implicit_order_index = 0;
2221 }
2222 cur = this->orders->GetNext(cur);
2223 }
2224 }
2225}
2226
2232{
2234
2236 if (this->current_order.IsType(OT_GOTO_STATION) &&
2237 this->current_order.GetDestination() == this->last_station_visited) {
2239
2240 /* Now both order indices point to the destination station, and we can start loading */
2241 this->current_order.MakeLoading(true);
2242 UpdateVehicleTimetable(this, true);
2243
2244 /* Furthermore add the Non Stop flag to mark that this station
2245 * is the actual destination of the vehicle, which is (for example)
2246 * necessary to be known for HandleTrainLoading to determine
2247 * whether the train is lost or not; not marking a train lost
2248 * that arrives at random stations is bad. */
2250
2251 } else {
2252 /* We weren't scheduled to stop here. Insert an implicit order
2253 * to show that we are stopping here.
2254 * While only groundvehicles have implicit orders, e.g. aircraft might still enter
2255 * the 'wrong' terminal when skipping orders etc. */
2256 Order *in_list = this->GetOrder(this->cur_implicit_order_index);
2257 if (this->IsGroundVehicle() &&
2258 (in_list == nullptr || !in_list->IsType(OT_IMPLICIT) ||
2259 in_list->GetDestination() != this->last_station_visited)) {
2260 bool suppress_implicit_orders = this->GetGroundVehicleFlags().Test(GroundVehicleFlag::SuppressImplicitOrders);
2261 /* Do not create consecutive duplicates of implicit orders */
2262 const Order *prev_order = this->cur_implicit_order_index > 0 ? this->GetOrder(this->cur_implicit_order_index - 1) : (this->GetNumOrders() > 1 ? this->GetLastOrder() : nullptr);
2263 if (prev_order == nullptr ||
2264 (!prev_order->IsType(OT_IMPLICIT) && !prev_order->IsType(OT_GOTO_STATION)) ||
2265 prev_order->GetDestination() != this->last_station_visited) {
2266
2267 /* Prefer deleting implicit orders instead of inserting new ones,
2268 * so test whether the right order follows later. In case of only
2269 * implicit orders treat the last order in the list like an
2270 * explicit one, except if the overall number of orders surpasses
2271 * IMPLICIT_ORDER_ONLY_CAP. */
2272 int target_index = this->cur_implicit_order_index;
2273 bool found = false;
2274 while (target_index != this->cur_real_order_index || this->GetNumManualOrders() == 0) {
2275 const Order *order = this->GetOrder(target_index);
2276 if (order == nullptr) break; // No orders.
2277 if (order->IsType(OT_IMPLICIT) && order->GetDestination() == this->last_station_visited) {
2278 found = true;
2279 break;
2280 }
2281 target_index++;
2282 if (target_index >= this->orders->GetNumOrders()) {
2283 if (this->GetNumManualOrders() == 0 &&
2285 break;
2286 }
2287 target_index = 0;
2288 }
2289 if (target_index == this->cur_implicit_order_index) break; // Avoid infinite loop.
2290 }
2291
2292 if (found) {
2293 if (suppress_implicit_orders) {
2294 /* Skip to the found order */
2295 this->cur_implicit_order_index = target_index;
2296 InvalidateVehicleOrder(this, 0);
2297 } else {
2298 /* Delete all implicit orders up to the station we just reached */
2299 const Order *order = this->GetOrder(this->cur_implicit_order_index);
2300 while (!order->IsType(OT_IMPLICIT) || order->GetDestination() != this->last_station_visited) {
2301 if (order->IsType(OT_IMPLICIT)) {
2303 } else {
2304 /* Skip non-implicit orders, e.g. service-orders */
2306 }
2307 order = this->GetOrder(this->cur_implicit_order_index);
2308
2309 /* Wrapped around. */
2310 if (order == nullptr) {
2311 this->cur_implicit_order_index = 0;
2312 order = this->GetOrder(this->cur_implicit_order_index);
2313 }
2314 assert(order != nullptr);
2315 }
2316 }
2317 } else if (!suppress_implicit_orders &&
2318 (this->orders == nullptr ? OrderList::CanAllocateItem() : this->orders->GetNumOrders() < MAX_VEH_ORDER_ID)) {
2319 /* Insert new implicit order */
2320 Order implicit_order{};
2321 implicit_order.MakeImplicit(this->last_station_visited);
2322 InsertOrder(this, std::move(implicit_order), this->cur_implicit_order_index);
2324
2325 /* InsertOrder disabled creation of implicit orders for all vehicles with the same implicit order.
2326 * Reenable it for this vehicle */
2328 }
2329 }
2330 }
2331 this->current_order.MakeLoading(false);
2332 }
2333
2334 if (this->last_loading_station != StationID::Invalid() &&
2336 (this->current_order.GetLoadType() != OrderLoadType::NoLoad ||
2337 this->current_order.GetUnloadType() != OrderUnloadType::NoUnload)) {
2338 IncreaseStats(Station::Get(this->last_loading_station), this, this->last_station_visited, travel_time);
2339 }
2340
2341 PrepareUnload(this);
2342
2344 SetWindowWidgetDirty(WindowClass::VehicleView, this->index, WID_VV_START_STOP);
2345 SetWindowDirty(WindowClass::VehicleDetails, this->index);
2346 SetWindowDirty(WindowClass::StationView, this->last_station_visited);
2347
2349 this->cur_speed = 0;
2350 this->MarkDirty();
2351}
2352
2360{
2361 for (Vehicle *v = this; v != nullptr; v = v->next) {
2363 if (cargo.ActionCount(VehicleCargoList::MoveToAction::Load) > 0) {
2364 Debug(Facility::Misc, Severity::Error, "cancelling cargo reservation");
2365 cargo.Return(UINT_MAX, &st->goods[v->cargo_type].GetOrCreateData().cargo, next, v->tile);
2366 }
2367 cargo.KeepAll();
2368 }
2369}
2370
2376{
2377 assert(this->current_order.IsType(OT_LOADING));
2378
2379 delete this->cargo_payment;
2380 assert(this->cargo_payment == nullptr); // cleared by ~CargoPayment
2381
2382 /* Only update the timetable if the vehicle was supposed to stop here. */
2383 if (this->current_order.GetNonStopType().Any()) UpdateVehicleTimetable(this, false);
2384
2385 if (this->current_order.GetLoadType() != OrderLoadType::NoLoad ||
2386 this->current_order.GetUnloadType() != OrderUnloadType::NoUnload) {
2387 if (this->current_order.CanLeaveWithCargo(this->last_loading_station != StationID::Invalid())) {
2388 /* Refresh next hop stats to make sure we've done that at least once
2389 * during the stop and that refit_cap == cargo_cap for each vehicle in
2390 * the consist. */
2391 this->ResetRefitCaps();
2392 LinkRefresher::Run(this);
2393
2394 /* if the vehicle could load here or could stop with cargo loaded set the last loading station */
2397 } else {
2398 /* if the vehicle couldn't load and had to unload or transfer everything
2399 * set the last loading station to invalid as it will leave empty. */
2400 this->last_loading_station = StationID::Invalid();
2401 }
2402 }
2403
2404 this->current_order.MakeLeaveStation();
2406 this->CancelReservation(StationID::Invalid(), st);
2407 st->loading_vehicles.remove(this);
2408
2411
2412 if (this->type == VehicleType::Train && !this->vehstatus.Test(VehState::Crashed)) {
2413 /* Trigger station animation (trains only) */
2414 TileIndex tile = this->GetMovingFront()->tile;
2417 TriggerStationAnimation(st, tile, StationAnimationTrigger::VehicleDeparts);
2418 }
2419
2421 }
2422 if (this->type == VehicleType::Road && !this->vehstatus.Test(VehState::Crashed)) {
2423 /* Trigger road stop animation */
2424 if (IsStationRoadStopTile(this->tile)) {
2426 TriggerRoadStopAnimation(st, this->tile, StationAnimationTrigger::VehicleDeparts);
2427 }
2428 }
2429
2430
2431 this->MarkDirty();
2432}
2433
2438{
2439 for (Vehicle *v = this; v != nullptr; v = v->Next()) v->refit_cap = v->cargo_cap;
2440}
2441
2446{
2447 Company::Get(this->owner)->freeunits[this->type].ReleaseID(this->unitnumber);
2448 this->unitnumber = 0;
2449}
2450
2457{
2458 switch (this->current_order.GetType()) {
2459 case OT_LOADING: {
2460 TimerGameTick::Ticks wait_time = std::max(this->current_order.GetTimetabledWait() - this->lateness_counter, 0);
2461
2462 /* Not the first call for this tick, or still loading */
2463 if (mode || !this->vehicle_flags.Test(VehicleFlag::LoadingFinished) || this->current_order_time < wait_time) return;
2464
2465 this->PlayLeaveStationSound();
2466
2467 this->LeaveStation();
2468
2469 /* Only advance to next order if we just loaded at the current one */
2470 const Order *order = this->GetOrder(this->cur_implicit_order_index);
2471 if (order == nullptr ||
2472 (!order->IsType(OT_IMPLICIT) && !order->IsType(OT_GOTO_STATION)) ||
2473 order->GetDestination() != this->last_station_visited) {
2474 return;
2475 }
2476 break;
2477 }
2478
2479 case OT_DUMMY: break;
2480
2481 default: return;
2482 }
2483
2485}
2486
2492{
2493 return std::ranges::any_of(this->Orders(), [](const Order &o) {
2494 return o.IsType(OT_GOTO_STATION) && o.IsFullLoadOrder();
2495 });
2496}
2497
2503{
2504 return std::ranges::any_of(this->Orders(), [](const Order &o) { return o.IsType(OT_CONDITIONAL); });
2505}
2506
2512{
2513 return std::ranges::any_of(this->Orders(), [](const Order &o) {
2514 return o.IsType(OT_GOTO_DEPOT) && o.GetDepotActionType().Test(OrderDepotActionFlag::Unbunch);
2515 });
2516}
2517
2524{
2525 /* If we are headed for the first order, we must wrap around back to the last order. */
2526 bool is_first_order = (v->GetOrder(v->cur_implicit_order_index) == v->GetFirstOrder());
2527 const Order *previous_order = (is_first_order) ? v->GetLastOrder() : v->GetOrder(v->cur_implicit_order_index - 1);
2528
2529 if (previous_order == nullptr || !previous_order->IsType(OT_GOTO_DEPOT)) return false;
2530 return previous_order->GetDepotActionType().Test(OrderDepotActionFlag::Unbunch);
2531}
2532
2537{
2538 /* Don't do anything if this is not our unbunching order. */
2539 if (!PreviousOrderIsUnbunching(this)) return;
2540
2541 /* Set the start point for this round trip time. */
2543
2544 /* Tell the timetable we are now "on time." */
2545 this->lateness_counter = 0;
2546 SetWindowDirty(WindowClass::VehicleTimetable, this->index);
2547
2548 /* Find the average travel time of vehicles that we share orders with. */
2549 int num_vehicles = 0;
2550 TimerGameTick::Ticks total_travel_time = 0;
2551
2552 Vehicle *u = this->FirstShared();
2553 for (; u != nullptr; u = u->NextShared()) {
2554 /* Ignore vehicles that are manually stopped or crashed. */
2555 if (u->vehstatus.Any({VehState::Stopped, VehState::Crashed})) continue;
2556
2557 num_vehicles++;
2558 total_travel_time += u->round_trip_time;
2559 }
2560
2561 /* Make sure we cannot divide by 0. */
2562 num_vehicles = std::max(num_vehicles, 1);
2563
2564 /* Calculate the separation by finding the average travel time, then calculating equal separation (minimum 1 tick) between vehicles. */
2565 TimerGameTick::Ticks separation = std::max((total_travel_time / num_vehicles / num_vehicles), 1);
2566 TimerGameTick::TickCounter next_departure = TimerGameTick::counter + separation;
2567
2568 /* Set the departure time of all vehicles that we share orders with. */
2569 u = this->FirstShared();
2570 for (; u != nullptr; u = u->NextShared()) {
2571 /* Ignore vehicles that are manually stopped or crashed. */
2572 if (u->vehstatus.Any({VehState::Stopped, VehState::Crashed})) continue;
2573
2574 u->depot_unbunching_next_departure = next_departure;
2575 InvalidateWindowData(WindowClass::VehicleView, u->index);
2576 }
2577}
2578
2584{
2585 assert(this->IsInDepot());
2586
2587 /* Don't bother if there are no vehicles sharing orders. */
2588 if (!this->IsOrderListShared()) return false;
2589
2590 /* Don't do anything if there aren't enough orders. */
2591 if (this->GetNumOrders() <= 1) return false;
2592
2593 /* Don't do anything if this is not our unbunching order. */
2594 if (!PreviousOrderIsUnbunching(this)) return false;
2595
2597};
2598
2606{
2607 CommandCost ret = CheckOwnership(this->owner);
2608 if (ret.Failed()) return ret;
2609
2610 if (this->vehstatus.Test(VehState::Crashed)) return CMD_ERROR;
2611 if (this->IsStoppedInDepot()) return CMD_ERROR;
2612
2613 /* No matter why we're headed to the depot, unbunching data is no longer valid. */
2615
2616 if (this->current_order.IsType(OT_GOTO_DEPOT)) {
2617 bool halt_in_depot = this->current_order.GetDepotActionType().Test(OrderDepotActionFlag::Halt);
2618 if (command.Test(DepotCommandFlag::Service) == halt_in_depot) {
2619 /* We called with a different DEPOT_SERVICE setting.
2620 * Now we change the setting to apply the new one and let the vehicle head for the same depot.
2621 * Note: the if is (true for requesting service == true for ordered to stop in depot) */
2622 if (flags.Test(DoCommandFlag::Execute)) {
2623 this->current_order.SetDepotOrderType({});
2624 this->current_order.SetDepotActionType(halt_in_depot ? OrderDepotActionFlags{} : OrderDepotActionFlag::Halt);
2625 InvalidateWindowData(WindowClass::VehicleView, this->index);
2626 }
2627 return CommandCost();
2628 }
2629
2630 if (command.Test(DepotCommandFlag::DontCancel)) return CMD_ERROR; // Requested no cancellation of depot orders
2631 if (flags.Test(DoCommandFlag::Execute)) {
2632 /* If the orders to 'goto depot' are in the orders list (forced servicing),
2633 * then skip to the next order; effectively cancelling this forced service */
2634 if (this->current_order.GetDepotOrderType().Test(OrderDepotTypeFlag::PartOfOrders)) this->IncrementRealOrderIndex();
2635
2636 if (this->IsGroundVehicle()) {
2638 }
2639
2640 this->current_order.MakeDummy();
2641 InvalidateWindowData(WindowClass::VehicleView, this->index);
2642 }
2643 return CommandCost();
2644 }
2645
2646 ClosestDepot closest_depot = this->FindClosestDepot();
2647 static constexpr VehicleTypeIndexArray<const StringID> no_depot = {STR_ERROR_UNABLE_TO_FIND_ROUTE_TO, STR_ERROR_UNABLE_TO_FIND_LOCAL_DEPOT, STR_ERROR_UNABLE_TO_FIND_LOCAL_DEPOT, STR_ERROR_UNABLE_TO_FIND_LOCAL_HANGAR};
2648 if (!closest_depot.found) return CommandCost(no_depot[this->type]);
2649
2650 if (flags.Test(DoCommandFlag::Execute)) {
2651 if (this->current_order.IsType(OT_LOADING)) this->LeaveStation();
2652
2653 if (this->IsGroundVehicle() && this->GetNumManualOrders() > 0) {
2655 }
2656
2657 this->SetDestTile(closest_depot.location);
2658 this->current_order.MakeGoToDepot(closest_depot.destination.ToDepotID(), {});
2659 if (!command.Test(DepotCommandFlag::Service)) this->current_order.SetDepotActionType(OrderDepotActionFlag::Halt);
2660 InvalidateWindowData(WindowClass::VehicleView, this->index);
2661
2662 /* If there is no depot in front and the train is not already reversing, reverse automatically (trains only) */
2663 if (this->type == VehicleType::Train && (closest_depot.reverse ^ Train::From(this)->flags.Test(VehicleRailFlag::Reversing))) {
2664 Command<Commands::ReverseTrainDirection>::Do(DoCommandFlag::Execute, this->index, false);
2665 }
2666
2667 if (this->type == VehicleType::Aircraft) {
2668 Aircraft *a = Aircraft::From(this);
2669 if (a->state == FLYING && a->targetairport != closest_depot.destination) {
2670 /* The aircraft is now heading for a different hangar than the next in the orders */
2672 }
2673 }
2674 }
2675
2676 return CommandCost();
2677
2678}
2679
2684void Vehicle::UpdateVisualEffect(bool allow_power_change)
2685{
2686 bool powered_before = HasBit(this->vcache.cached_vis_effect, VE_DISABLE_WAGON_POWER);
2687 const Engine *e = this->GetEngine();
2688
2689 /* Evaluate properties */
2690 uint8_t visual_effect;
2691 switch (e->type) {
2692 case VehicleType::Train: visual_effect = e->VehInfo<RailVehicleInfo>().visual_effect; break;
2693 case VehicleType::Road: visual_effect = e->VehInfo<RoadVehicleInfo>().visual_effect; break;
2694 case VehicleType::Ship: visual_effect = e->VehInfo<ShipVehicleInfo>().visual_effect; break;
2695 default: visual_effect = 1 << VE_DISABLE_EFFECT; break;
2696 }
2697
2698 /* Check powered wagon / visual effect callback */
2700 uint16_t callback = GetVehicleCallback(CBID_VEHICLE_VISUAL_EFFECT, 0, 0, this->engine_type, this);
2701
2702 if (callback != CALLBACK_FAILED) {
2703 if (callback >= 0x100 && e->GetGRF()->grf_version >= 8) ErrorUnknownCallbackResult(e->GetGRFID(), CBID_VEHICLE_VISUAL_EFFECT, callback);
2704
2705 callback = GB(callback, 0, 8);
2706 /* Avoid accidentally setting 'visual_effect' to the default value
2707 * Since bit 6 (disable effects) is set anyways, we can safely erase some bits. */
2708 if (callback == VE_DEFAULT) {
2709 assert(HasBit(callback, VE_DISABLE_EFFECT));
2710 SB(callback, VE_TYPE_START, VE_TYPE_COUNT, 0);
2711 }
2712 visual_effect = callback;
2713 }
2714 }
2715
2716 /* Apply default values */
2717 if (visual_effect == VE_DEFAULT ||
2718 (!HasBit(visual_effect, VE_DISABLE_EFFECT) && GB(visual_effect, VE_TYPE_START, VE_TYPE_COUNT) == VE_TYPE_DEFAULT)) {
2719 /* Only train engines have default effects.
2720 * Note: This is independent of whether the engine is a front engine or articulated part or whatever. */
2722 if (visual_effect == VE_DEFAULT) {
2723 visual_effect = 1 << VE_DISABLE_EFFECT;
2724 } else {
2725 SetBit(visual_effect, VE_DISABLE_EFFECT);
2726 }
2727 } else {
2728 if (visual_effect == VE_DEFAULT) {
2729 /* Also set the offset */
2730 visual_effect = (VE_OFFSET_CENTRE - (e->VehInfo<RailVehicleInfo>().engclass == EngineClass::Steam ? 4 : 0)) << VE_OFFSET_START;
2731 }
2733 }
2734 }
2735
2736 this->vcache.cached_vis_effect = visual_effect;
2737
2738 if (!allow_power_change && powered_before != HasBit(this->vcache.cached_vis_effect, VE_DISABLE_WAGON_POWER)) {
2739 ToggleBit(this->vcache.cached_vis_effect, VE_DISABLE_WAGON_POWER);
2740 ShowNewGrfVehicleError(this->engine_type, STR_NEWGRF_BROKEN, STR_NEWGRF_BROKEN_POWERED_WAGON, GRFBug::VehPoweredWagon, false);
2741 }
2742}
2743
2746 1, 1, 1, 0, -1, -1, -1, 0
2747};
2748
2754{
2755 std::array<int32_t, 4> regs100;
2756 uint16_t callback = GetVehicleCallback(CBID_VEHICLE_SPAWN_VISUAL_EFFECT, 0, Random(), v->engine_type, v, regs100);
2757 if (callback == CALLBACK_FAILED) return;
2758
2759 uint count = GB(callback, 0, 2);
2760 assert(count <= std::size(regs100));
2761 bool auto_center = HasBit(callback, 13);
2762 bool auto_rotate = !HasBit(callback, 14);
2763
2764 int8_t l_center = 0;
2765 if (auto_center) {
2766 /* For road vehicles: Compute offset from vehicle position to vehicle center */
2767 if (v->type == VehicleType::Road) l_center = -(int)(VEHICLE_LENGTH - RoadVehicle::From(v)->gcache.cached_veh_length) / 2;
2768 } else {
2769 /* For trains: Compute offset from vehicle position to sprite position */
2771 }
2772
2773 Direction l_dir = v->direction;
2774 if ((v->type == VehicleType::Train && Train::From(v)->flags.Test(VehicleRailFlag::Flipped))
2775 || (v->type == VehicleType::Ship && Ship::From(v)->flags.Test(VehicleShipFlag::SecondEndFacingForward))) l_dir = ReverseDir(l_dir);
2776 Direction t_dir = ChangeDir(l_dir, DirDiff::Right90);
2777
2778 int8_t x_center = _vehicle_smoke_pos[l_dir] * l_center;
2779 int8_t y_center = _vehicle_smoke_pos[t_dir] * l_center;
2780
2781 for (uint i = 0; i < count; i++) {
2782 int32_t reg = regs100[i];
2783 uint type = GB(reg, 0, 8);
2784 int8_t x = GB(reg, 8, 8);
2785 int8_t y = GB(reg, 16, 8);
2786 int8_t z = GB(reg, 24, 8);
2787
2788 if (auto_rotate) {
2789 int8_t l = x;
2790 int8_t t = y;
2791 x = _vehicle_smoke_pos[l_dir] * l + _vehicle_smoke_pos[t_dir] * t;
2792 y = _vehicle_smoke_pos[t_dir] * l - _vehicle_smoke_pos[l_dir] * t;
2793 }
2794
2795 if (type >= 0xF0) {
2796 switch (type) {
2797 case 0xF1: CreateEffectVehicleRel(v, x_center + x, y_center + y, z, EV_STEAM_SMOKE); break;
2798 case 0xF2: CreateEffectVehicleRel(v, x_center + x, y_center + y, z, EV_DIESEL_SMOKE); break;
2799 case 0xF3: CreateEffectVehicleRel(v, x_center + x, y_center + y, z, EV_ELECTRIC_SPARK); break;
2800 case 0xFA: CreateEffectVehicleRel(v, x_center + x, y_center + y, z, EV_BREAKDOWN_SMOKE_AIRCRAFT); break;
2801 default: break;
2802 }
2803 }
2804 }
2805}
2806
2812static bool IsBridgeAboveVehicle(const Vehicle *v)
2813{
2814 if (IsBridgeTile(v->tile)) {
2815 /* If the vehicle is 'on' a bridge tile, check the real position of the vehicle. If it's different then the
2816 * vehicle is on the middle of the bridge, which cannot have a bridge above. */
2817 TileIndex tile = TileVirtXY(v->x_pos, v->y_pos);
2818 if (tile != v->tile) return false;
2819 }
2820 return IsBridgeAbove(v->tile);
2821}
2822
2823
2833
2839{
2840 assert(this->IsPrimaryVehicle());
2841 bool sound = false;
2842
2843 /* Do not show any smoke when:
2844 * - vehicle smoke is disabled by the player
2845 * - the vehicle is slowing down or stopped (by the player)
2846 * - the vehicle is moving very slowly
2847 */
2848 if (_settings_game.vehicle.smoke_amount == 0 ||
2849 this->vehstatus.Any({VehState::TrainSlowing, VehState::Stopped}) ||
2850 this->cur_speed < 2) {
2851 return;
2852 }
2853
2854 /* Use the speed as limited by underground and orders. */
2855 uint max_speed = this->GetCurrentMaxSpeed();
2856
2857 if (this->type == VehicleType::Train) {
2858 const Train *t = Train::From(this);
2859 const Train *moving_front = t->GetMovingFront();
2860 /* For trains, do not show any smoke when:
2861 * - the train is reversing
2862 * - is entering a station with an order to stop there and its speed is equal to maximum station entering speed
2863 */
2865 (IsRailStationTile(moving_front->tile) && t->IsFrontEngine() && t->current_order.ShouldStopAtStation(t, GetStationIndex(moving_front->tile)) &&
2866 t->cur_speed >= max_speed)) {
2867 return;
2868 }
2869 }
2870
2871 const Vehicle *v = this;
2872
2873 do {
2877 if (advanced) {
2878 effect_offset = VE_OFFSET_CENTRE;
2879 effect_model = static_cast<VisualEffectSpawnModel>(GB(v->vcache.cached_vis_effect, 0, VE_ADVANCED_EFFECT));
2880 if (effect_model >= VisualEffectSpawnModel::End) effect_model = VisualEffectSpawnModel::None; // unknown spawning model
2881 } else {
2883 assert(to_underlying(effect_model) != to_underlying(VE_TYPE_DEFAULT)); // should have been resolved by UpdateVisualEffect
2887 }
2888
2889 /* Show no smoke when:
2890 * - Smoke has been disabled for this vehicle
2891 * - The vehicle is not visible
2892 * - The vehicle is under a bridge
2893 * - The vehicle is on a depot tile
2894 * - The vehicle is on a tunnel tile
2895 * - The vehicle is a train engine that is currently unpowered */
2896 if (effect_model == VisualEffectSpawnModel::None ||
2899 IsDepotTile(v->tile) ||
2900 IsTunnelTile(v->tile) ||
2901 (v->type == VehicleType::Train &&
2902 !HasPowerOnRail(Train::From(v)->railtypes, GetTileRailType(v->tile)))) {
2903 continue;
2904 }
2905
2906 EffectVehicleType evt = EV_END;
2907 switch (effect_model) {
2909 /* Steam smoke - amount is gradually falling until vehicle reaches its maximum speed, after that it's normal.
2910 * Details: while vehicle's current speed is gradually increasing, steam plumes' density decreases by one third each
2911 * third of its maximum speed spectrum. Steam emission finally normalises at very close to vehicle's maximum speed.
2912 * REGULATION:
2913 * - instead of 1, 4 / 2^smoke_amount (max. 2) is used to provide sufficient regulation to steam puffs' amount. */
2914 if (GB(v->tick_counter, 0, ((4 >> _settings_game.vehicle.smoke_amount) + ((this->cur_speed * 3) / max_speed))) == 0) {
2915 evt = EV_STEAM_SMOKE;
2916 }
2917 break;
2918
2920 /* Diesel smoke - thicker when vehicle is starting, gradually subsiding till it reaches its maximum speed
2921 * when smoke emission stops.
2922 * Details: Vehicle's (max.) speed spectrum is divided into 32 parts. When max. speed is reached, chance for smoke
2923 * emission erodes by 32 (1/4). For trains, power and weight come in handy too to either increase smoke emission in
2924 * 6 steps (1000HP each) if the power is low or decrease smoke emission in 6 steps (512 tonnes each) if the train
2925 * isn't overweight. Power and weight contributions are expressed in a way that neither extreme power, nor
2926 * extreme weight can ruin the balance (e.g. FreightWagonMultiplier) in the formula. When the vehicle reaches
2927 * maximum speed no diesel_smoke is emitted.
2928 * REGULATION:
2929 * - up to which speed a diesel vehicle is emitting smoke (with reduced/small setting only until 1/2 of max_speed),
2930 * - in Chance16 - the last value is 512 / 2^smoke_amount (max. smoke when 128 = smoke_amount of 2). */
2931 int power_weight_effect = 0;
2932 if (v->type == VehicleType::Train) {
2933 power_weight_effect = (32 >> (Train::From(this)->gcache.cached_power >> 10)) - (32 >> (Train::From(this)->gcache.cached_weight >> 9));
2934 }
2935 if (this->cur_speed < (max_speed >> (2 >> _settings_game.vehicle.smoke_amount)) &&
2936 Chance16((64 - ((this->cur_speed << 5) / max_speed) + power_weight_effect), (512 >> _settings_game.vehicle.smoke_amount))) {
2937 evt = EV_DIESEL_SMOKE;
2938 }
2939 break;
2940 }
2941
2943 /* Electric train's spark - more often occurs when train is departing (more load)
2944 * Details: Electric locomotives are usually at least twice as powerful as their diesel counterparts, so spark
2945 * emissions are kept simple. Only when starting, creating huge force are sparks more likely to happen, but when
2946 * reaching its max. speed, quarter by quarter of it, chance decreases until the usual 2,22% at train's top speed.
2947 * REGULATION:
2948 * - in Chance16 the last value is 360 / 2^smoke_amount (max. sparks when 90 = smoke_amount of 2). */
2949 if (GB(v->tick_counter, 0, 2) == 0 &&
2950 Chance16((6 - ((this->cur_speed << 2) / max_speed)), (360 >> _settings_game.vehicle.smoke_amount))) {
2951 evt = EV_ELECTRIC_SPARK;
2952 }
2953 break;
2954
2955 default:
2956 NOT_REACHED();
2957 }
2958
2959 if (evt != EV_END && advanced) {
2960 sound = true;
2962 } else if (evt != EV_END) {
2963 sound = true;
2964
2965 /* The effect offset is relative to a point 4 units behind the vehicle's
2966 * front (which is the center of an 8/8 vehicle). Shorter vehicles need a
2967 * correction factor. */
2968 if (v->type == VehicleType::Train) effect_offset += (VEHICLE_LENGTH - Train::From(v)->gcache.cached_veh_length) / 2;
2969
2970 int x = _vehicle_smoke_pos[v->direction] * effect_offset;
2971 int y = _vehicle_smoke_pos[ChangeDir(v->direction, DirDiff::Right90)] * effect_offset;
2972
2973 if ((v->type == VehicleType::Train && Train::From(v)->flags.Test(VehicleRailFlag::Flipped))
2975 x = -x;
2976 y = -y;
2977 }
2978
2979 CreateEffectVehicleRel(v, x, y, 10, evt);
2980 }
2981 } while ((v = v->Next()) != nullptr);
2982
2984}
2985
2991{
2992 assert(this != next);
2993
2994 if (this->next != nullptr) {
2995 /* We had an old next vehicle. Update the first and previous pointers */
2996 for (Vehicle *v = this->next; v != nullptr; v = v->Next()) {
2997 v->first = this->next;
2998 }
2999 this->next->previous = nullptr;
3000 }
3001
3002 this->next = next;
3003
3004 if (this->next != nullptr) {
3005 /* A new next vehicle. Update the first and previous pointers */
3006 if (this->next->previous != nullptr) this->next->previous->next = nullptr;
3007 this->next->previous = this;
3008 for (Vehicle *v = this->next; v != nullptr; v = v->Next()) {
3009 v->first = this->first;
3010 }
3011 }
3012
3013 /* Update last vehicle of the entire chain. */
3014 Vehicle *new_last = this;
3015 while (new_last->Next() != nullptr) new_last = new_last->Next();
3016 for (Vehicle *v = this->first; v!= nullptr; v = v->Next()) {
3017 v->last = new_last;
3018 }
3019}
3020
3027{
3028 assert(this->previous_shared == nullptr && this->next_shared == nullptr);
3029
3030 if (shared_chain->orders == nullptr) {
3031 assert(shared_chain->previous_shared == nullptr);
3032 assert(shared_chain->next_shared == nullptr);
3033 this->orders = shared_chain->orders = OrderList::Create(shared_chain);
3034 }
3035
3036 this->next_shared = shared_chain->next_shared;
3037 this->previous_shared = shared_chain;
3038
3039 shared_chain->next_shared = this;
3040
3041 if (this->next_shared != nullptr) this->next_shared->previous_shared = this;
3042
3043 shared_chain->orders->AddVehicle(this);
3044}
3045
3050{
3051 /* Remember if we were first and the old window number before RemoveVehicle()
3052 * as this changes first if needed. */
3053 bool were_first = (this->FirstShared() == this);
3055
3056 this->orders->RemoveVehicle(this);
3057
3058 if (!were_first) {
3059 /* We are not the first shared one, so only relink our previous one. */
3060 this->previous_shared->next_shared = this->NextShared();
3061 }
3062
3063 if (this->next_shared != nullptr) this->next_shared->previous_shared = this->previous_shared;
3064
3065
3066 if (this->orders->GetNumVehicles() == 1) {
3067 /* When there is only one vehicle, remove the shared order list window. */
3070 } else if (were_first) {
3071 /* If we were the first one, update to the new first one.
3072 * Note: FirstShared() is already the new first */
3073 InvalidateWindowData(GetWindowClassForVehicleType(this->type), vli.ToWindowNumber(), this->FirstShared()->index.base() | (1U << 31));
3074 }
3075
3076 this->next_shared = nullptr;
3077 this->previous_shared = nullptr;
3078}
3079
3081static const IntervalTimer<TimerGameEconomy> _economy_vehicles_yearly({TimerGameEconomy::Trigger::Year, TimerGameEconomy::Priority::Vehicle}, [](auto)
3082{
3083 for (Vehicle *v : Vehicle::Iterate()) {
3084 if (v->IsPrimaryVehicle()) {
3085 /* show warning if vehicle is not generating enough income last 2 years (corresponds to a red icon in the vehicle list) */
3086 Money profit = v->GetDisplayProfitThisYear();
3087 if (v->economy_age >= VEHICLE_PROFIT_MIN_AGE && profit < 0) {
3090 GetEncodedString(TimerGameEconomy::UsingWallclockUnits() ? STR_NEWS_VEHICLE_UNPROFITABLE_PERIOD : STR_NEWS_VEHICLE_UNPROFITABLE_YEAR, v->index, profit),
3091 v->index);
3092 }
3093 AI::NewEvent(v->owner, new ScriptEventVehicleUnprofitable(v->index));
3094 }
3095
3097 v->profit_this_year = 0;
3098 SetWindowDirty(WindowClass::VehicleDetails, v->index);
3099 }
3100 }
3102 SetWindowClassesDirty(WindowClass::TrainList);
3103 SetWindowClassesDirty(WindowClass::ShipList);
3104 SetWindowClassesDirty(WindowClass::RoadVehicleList);
3105 SetWindowClassesDirty(WindowClass::AircraftList);
3106});
3107
3117bool CanVehicleUseStation(EngineID engine_type, const Station *st)
3118{
3119 const Engine *e = Engine::GetIfValid(engine_type);
3120 assert(e != nullptr);
3121
3122 switch (e->type) {
3123 case VehicleType::Train:
3125
3126 case VehicleType::Road:
3127 /* For road vehicles we need the vehicle to know whether it can actually
3128 * use the station, but if it doesn't have facilities for RVs it is
3129 * certainly not possible that the station can be used. */
3131
3132 case VehicleType::Ship:
3134
3138
3139 default:
3140 return false;
3141 }
3142}
3143
3150bool CanVehicleUseStation(const Vehicle *v, const Station *st)
3151{
3152 if (v->type == VehicleType::Road) return st->GetPrimaryRoadStop(RoadVehicle::From(v)) != nullptr;
3153
3154 return CanVehicleUseStation(v->engine_type, st);
3155}
3156
3164{
3165 switch (v->type) {
3166 case VehicleType::Train:
3167 return STR_ERROR_NO_RAIL_STATION;
3168
3169 case VehicleType::Road: {
3170 const RoadVehicle *rv = RoadVehicle::From(v);
3171 RoadStop *rs = st->GetPrimaryRoadStop(rv->IsBus() ? RoadStopType::Bus : RoadStopType::Truck);
3172
3173 StringID err = rv->IsBus() ? STR_ERROR_NO_BUS_STATION : STR_ERROR_NO_TRUCK_STATION;
3174
3175 for (; rs != nullptr; rs = rs->next) {
3176 /* Articulated vehicles cannot use bay road stops, only drive-through. Make sure the vehicle can actually use this bay stop */
3178 err = STR_ERROR_NO_STOP_ARTICULATED_VEHICLE;
3179 continue;
3180 }
3181
3182 /* Bay stop errors take precedence, but otherwise the vehicle may not be compatible with the roadtype/tramtype of this station tile.
3183 * We give bay stop errors precedence because they are usually a bus sent to a tram station or vice versa. */
3184 if (!HasTileAnyRoadType(rs->xy, rv->compatible_roadtypes) && err != STR_ERROR_NO_STOP_ARTICULATED_VEHICLE) {
3185 err = RoadTypeIsRoad(rv->roadtype) ? STR_ERROR_NO_STOP_COMPATIBLE_ROAD_TYPE : STR_ERROR_NO_STOP_COMPATIBLE_TRAM_TYPE;
3186 continue;
3187 }
3188 }
3189
3190 return err;
3191 }
3192
3193 case VehicleType::Ship:
3194 return STR_ERROR_NO_DOCK;
3195
3197 if (!st->facilities.Test(StationFacility::Airport)) return STR_ERROR_NO_AIRPORT;
3198 if (v->GetEngine()->VehInfo<AircraftVehicleInfo>().subtype & AIR_CTOL) {
3199 return STR_ERROR_AIRPORT_NO_PLANES;
3200 } else {
3201 return STR_ERROR_AIRPORT_NO_HELICOPTERS;
3202 }
3203
3204 default:
3205 return INVALID_STRING_ID;
3206 }
3207}
3208
3215{
3216 assert(this->IsGroundVehicle());
3217 if (this->type == VehicleType::Train) {
3218 return &Train::From(this)->gcache;
3219 } else {
3220 return &RoadVehicle::From(this)->gcache;
3221 }
3222}
3223
3230{
3231 assert(this->IsGroundVehicle());
3232 if (this->type == VehicleType::Train) {
3233 return &Train::From(this)->gcache;
3234 } else {
3235 return &RoadVehicle::From(this)->gcache;
3236 }
3237}
3238
3245{
3246 assert(this->IsGroundVehicle());
3247 if (this->type == VehicleType::Train) {
3248 return Train::From(this)->gv_flags;
3249 } else {
3250 return RoadVehicle::From(this)->gv_flags;
3251 }
3252}
3253
3260{
3261 assert(this->IsGroundVehicle());
3262 if (this->type == VehicleType::Train) {
3263 return Train::From(this)->gv_flags;
3264 } else {
3265 return RoadVehicle::From(this)->gv_flags;
3266 }
3267}
3268
3277void GetVehicleSet(VehicleSet &set, Vehicle *v, uint8_t num_vehicles)
3278{
3279 if (v->type == VehicleType::Train) {
3280 Train *u = Train::From(v);
3281 /* Only include whole vehicles, so start with the first articulated part */
3282 u = u->GetFirstEnginePart();
3283
3284 /* Include num_vehicles vehicles, not counting articulated parts */
3285 for (; u != nullptr && num_vehicles > 0; num_vehicles--) {
3286 do {
3287 /* Include current vehicle in the selection. */
3288 include(set, u->index);
3289
3290 /* If the vehicle is multiheaded, add the other part too. */
3291 if (u->IsMultiheaded()) include(set, u->other_multiheaded_part->index);
3292
3293 u = u->Next();
3294 } while (u != nullptr && u->IsArticulatedPart());
3295 }
3296 }
3297}
3298
3304{
3305 uint32_t max_weight = 0;
3306
3307 for (const Vehicle *u = this; u != nullptr; u = u->Next()) {
3308 max_weight += u->GetMaxWeight();
3309 }
3310
3311 return max_weight;
3312}
3313
3319{
3320 uint32_t max_weight = GetDisplayMaxWeight();
3321 if (max_weight == 0) return 0;
3322 return GetGroundVehicleCache()->cached_power * 10u / max_weight;
3323}
3324
3332{
3333 while (true) {
3334 if (v1 == nullptr && v2 == nullptr) return true;
3335 if (v1 == nullptr || v2 == nullptr) return false;
3336 if (v1->GetEngine() != v2->GetEngine()) return false;
3337 v1 = v1->GetNextVehicle();
3338 v2 = v2->GetNextVehicle();
3339 }
3340}
3341
3349{
3350 return std::ranges::equal(v1->Orders(), v2->Orders(), [](const Order &o1, const Order &o2) { return o1.Equals(o2); });
3351}
3352
3360{
3361 return v1->FirstShared() == v2->FirstShared();
3362}
3363
3365struct VehicleSubcoordData : Coord2D<uint8_t> {
3367};
3368
3374 {{{ // NE
3375 {{15, 8}, Direction::NE}, // TRACK_X
3376 {}, // TRACK_Y
3377 {}, // TRACK_UPPER
3378 {{15, 8}, Direction::E}, // TRACK_LOWER
3379 {{15, 7}, Direction::N}, // TRACK_LEFT
3380 {}, // TRACK_RIGHT
3381 }}},
3382 {{{ // SE
3383 {}, // TRACK_X
3384 {{8, 0}, Direction::SE}, // TRACK_Y
3385 {{7, 0}, Direction::E}, // TRACK_UPPER
3386 {}, // TRACK_LOWER
3387 {{8, 0}, Direction::S}, // TRACK_LEFT
3388 {}, // TRACK_RIGHT
3389 }}},
3390 {{{ // SW
3391 {{0, 8}, Direction::SW}, // TRACK_X
3392 {}, // TRACK_Y
3393 {{0, 7}, Direction::W}, // TRACK_UPPER
3394 {}, // TRACK_LOWER
3395 {}, // TRACK_LEFT
3396 {{0, 8}, Direction::S}, // TRACK_RIGHT
3397 }}},
3398 {{{ // NW
3399 {}, // TRACK_X
3400 {{8, 15}, Direction::NW}, // TRACK_Y
3401 {}, // TRACK_UPPER
3402 {{8, 15}, Direction::W}, // TRACK_LOWER
3403 {}, // TRACK_LEFT
3404 {{7, 15}, Direction::N}, // TRACK_RIGHT
3405 }}},
3406}}};
3407
3416{
3417 const VehicleSubcoordData &b = _vehicle_subcoord[enterdir][track];
3418 gp.x = (gp.x & ~TILE_UNIT_MASK) | b.x;
3419 gp.y = (gp.y & ~TILE_UNIT_MASK) | b.y;
3420 return b.dir;
3421}
Base functions for all AIs.
Base for aircraft.
void AircraftNextAirportPos_and_Order(Aircraft *v)
Set the right pos when heading to other airports after takeoff.
Station * GetTargetAirportIfValid(const Aircraft *v)
Returns aircraft's target station if v->target_airport is a valid station with airport.
@ AIR_SHADOW
shadow of the aircraft
Definition aircraft.h:31
void HandleAircraftEnterHangar(Aircraft *v)
Handle Aircraft specific tasks when an Aircraft enters a hangar.
@ FLYING
Vehicle is flying in the air.
Definition airport.h:78
@ None
Tile is not animated.
CargoTypes GetCargoTypesOfArticulatedVehicle(const Vehicle *v, CargoType *cargo_type)
Get cargo mask of all cargoes carried by an articulated vehicle.
void GetArticulatedRefitMasks(EngineID engine, bool include_initial_cargo_type, CargoTypes *union_mask, CargoTypes *intersection_mask)
Merges the refit_masks of all articulated parts.
CargoTypes GetCargoTypesOfArticulatedParts(EngineID engine)
Get the cargo mask of the parts of a given engine.
Functions related to articulated vehicles.
const EngineRenew * GetEngineRenew(const EngineRenewList &erl, EngineID engine)
Search within a single engine renew list for an engine to renew.
Command definitions related to autoreplace.
Functions related to autoreplacing.
bool EngineHasReplacement(CompanyID company, GroupID group, EngineID engine, bool search)
Check if a company has a replacement set up for the given engine.
void InvalidateAutoreplaceWindow(EngineID e, GroupID id_g)
Rebuild the left autoreplace list if an engine is removed or added.
Functions related to the autoreplace GUIs.
Class for backupping variables and making sure they are restored later.
@ PathfinderLost
Vehicle's pathfinder is lost.
@ StopLoading
Don't load anymore during the next load cycle.
@ LoadingFinished
Vehicle has finished loading.
@ CargoUnloading
Vehicle is unloading cargo.
@ End
We are looking for this amount of GRFs.
constexpr T SB(T &x, const uint8_t s, const uint8_t n, const U d)
Set n bits in x starting at bit s to d.
static constexpr uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
constexpr T SetBit(T &x, const uint8_t y)
Set a bit in a variable.
constexpr uint8_t FindFirstBit(T x)
Search the first set bit in a value.
constexpr bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
constexpr bool HasAtMostOneBit(T value)
Test whether value has at most 1 bit set.
constexpr T ToggleBit(T &x, const uint8_t y)
Toggles a bit in a variable.
constexpr T ClrBit(T &x, const uint8_t y)
Clears a bit in a variable.
Map accessor functions for bridges.
bool IsBridgeTile(Tile t)
checks if there is a bridge on this tile
Definition bridge_map.h:35
bool IsBridgeAbove(Tile t)
checks if a bridge is set above the ground of this tile
Definition bridge_map.h:45
static constexpr CargoType INVALID_CARGO
Invalid marker for cargoes.
Definition cargo_type.h:83
bool IsValidCargoType(CargoType cargo)
Test whether cargo type is not INVALID_CARGO.
Definition cargo_type.h:112
EnumBitSet< CargoType, uint64_t > CargoTypes
Bitset of CargoType elements.
Definition cargo_type.h:115
static constexpr CargoLabel CT_GOODS
Cargo label for goods.
Definition cargo_type.h:37
CargoType
Cargo slots to indicate a cargo type within a game.
Definition cargo_type.h:22
CargoType GetCargoTypeByLabel(CargoLabel label)
Get cargo assigned to a label.
Definition cargotype.h:268
@ Passengers
Passengers.
Definition cargotype.h:50
bool IsCargoInClass(CargoType cargo, CargoClasses cc)
Does a given cargo have any cargo class from cc.
Definition cargotype.h:288
static void NewEvent(CompanyID company, ScriptEvent *event)
Queue a new event for an AI.
Definition ai_core.cpp:231
constexpr bool Test(Tvalue_type value) const
Test if the value-th bit is set.
constexpr Tstorage base() const noexcept
Retrieve the raw value behind this bit set.
constexpr Timpl & Reset()
Reset all bits.
constexpr Timpl & Set()
Set all bits.
constexpr bool Any(const Timpl &other) const
Test if any of the given values are set.
Common return value for all commands.
bool Succeeded() const
Did this command succeed?
Money GetCost() const
The costs as made up to this moment.
bool Failed() const
Did this command fail?
StringID GetErrorMessage() const
Returns the error message of a command.
static constexpr int DAYS_IN_ECONOMY_MONTH
Days in an economy month, when in wallclock timekeeping mode.
const GRFFile * GetGRF() const
Retrieve the NewGRF the engine is tied to.
static Pool::IterateWrapperFiltered< Engine, EngineTypeFilter > IterateType(VehicleType vt, size_t from=0)
Returns an iterable ensemble of all valid engines of the given type.
CargoGRFFileProps grf_prop
Link to NewGRF.
Definition engine_base.h:73
GrfID GetGRFID() const
Retrieve the GRF ID of the NewGRF the engine is tied to.
Definition engine.cpp:185
CompanyMask company_avail
Bit for each company whether the engine is available for that company.
Definition engine_base.h:42
VehicleType type
Vehicle type, ie VehicleType::Road, VehicleType::Train, etc.
Definition engine_base.h:64
CargoType GetDefaultCargoType() const
Determines the default cargo type of an engine.
Definition engine_base.h:96
uint16_t reliability
Current reliability of the engine.
Definition engine_base.h:51
UnitID UseID(UnitID index)
Use a unit number.
Definition vehicle.cpp:1892
void ReleaseID(UnitID index)
Release a unit number.
Definition vehicle.cpp:1909
UnitID NextID() const
Find first unused unit number.
Definition vehicle.cpp:1877
An interval timer will fire every interval, and will continue to fire until it is deleted.
Definition timer.h:76
static void Run(Vehicle *v, bool allow_merge=true, bool is_full_loading=false)
Refresh all links the given vehicle will visit.
Definition refresh.cpp:26
static void Reset(PerformanceElement elem)
Store the previous accumulator value and reset for a new cycle of accumulating measurements.
static constexpr TimerGameTick::Ticks DAY_TICKS
1 day is 74 ticks; TimerGameCalendar::date_fract used to be uint16_t and incremented by 885.
static Date date
Current date in days (day counter).
static DateFract date_fract
Fractional part of the day.
static constexpr TimerGame< struct Economy >::Date MAX_DATE
static Date date
Current date in days (day counter).
static bool UsingWallclockUnits(bool newgame=false)
Check if we are using wallclock units.
static DateFract date_fract
Fractional part of the day.
uint64_t TickCounter
The type that the tick counter is stored in.
static TickCounter counter
Monotonic counter, in ticks, since start of game.
int32_t Ticks
The type to store ticks in.
StrongType::Typedef< int32_t, struct YearTag< struct Calendar >, StrongType::Compare, StrongType::Integer > Year
static constexpr Date DateAtStartOfYear(Year year)
StrongType::Typedef< int32_t, DateTag< struct Economy >, StrongType::Compare, StrongType::Integer > Date
CargoList that is used for vehicles.
void AgeCargo()
Ages the all cargo in this list.
uint StoredCount() const
Returns sum of cargo on board the vehicle (ie not only reserved).
void SkipEmptyBuckets()
Advance the internal state until we reach a non-empty bucket, or the end.
Definition vehicle.cpp:505
Iterator(int32_t x, int32_t y, uint max_dist)
Iterator constructor.
Definition vehicle.cpp:465
void Increment()
Advance the internal state to the next potential vehicle.
Definition vehicle.cpp:495
void SkipFalseMatches()
Advance the internal state until it reaches a vehicle within the search area.
Definition vehicle.cpp:523
Iterator(TileIndex tile)
Iterator constructor.
Definition vehicle.cpp:533
void Increment()
Advance the internal state to the next potential vehicle.
Definition vehicle.cpp:543
void SkipFalseMatches()
Advance the internal state until it reaches a vehicle on the correct tile or the end.
Definition vehicle.cpp:551
Iterate over all vehicles on a tile.
Functions related to commands.
CommandCost & ExtractCommandCost(Tret &ret)
Extract the CommandCost from a command proc result.
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
@ Execute
execute the given command
EnumBitSet< DoCommandFlag, uint16_t > DoCommandFlags
Bitset of DoCommandFlag elements.
Definition of stuff that is very close to a company, like the company struct itself.
static void SubtractMoneyFromCompany(Company *c, const CommandCost &cost)
Deduct costs of a command from the money of a company.
CommandCost CheckOwnership(Owner owner, TileIndex tile)
Check whether the current owner owns something.
Money GetAvailableMoney(CompanyID company)
Get the amount of money that a company has available, or INT64_MAX if there is no such valid company.
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
CompanyID _current_company
Company currently doing an action.
Functions related to companies.
bool IsLocalCompany()
Is the current company the local company?
Some simple functions to help with accessing containers.
bool include(Container &container, typename Container::const_reference &item)
Helper function to append an item to a container if it is not already contained.
#define Debug(facility, severity, format_string,...)
Output a line of debugging information.
Definition debug.h:36
@ Misc
Misc message facility.
Definition debug_type.h:32
@ Grf
Grf message facility.
Definition debug_type.h:30
@ Critical
Critical, user should know about this.
Definition debug_type.h:15
@ Error
Error, but we are recovering.
Definition debug_type.h:16
Functions related to depots.
void DeleteDepotHighlightOfVehicle(const Vehicle *v)
Removes the highlight of a vehicle in a depot window.
Map related accessors for depots.
bool IsDepotTile(Tile tile)
Is the given tile a tile with a depot on it?
Definition depot_map.h:45
DirDiff DirDifference(Direction d0, Direction d1)
Calculate the difference between two directions.
Direction ReverseDir(Direction d)
Return the reverse of a direction.
Direction ChangeDir(Direction d, DirDiff delta)
Change a direction by a given difference.
DirDiff LimitDirDiff(DirDiff d)
Limit a direction difference to up to 45 degrees.
DirDiff
Enumeration for the difference between two directions.
@ Same
Both directions faces to the same direction.
@ Right90
Angle of 90 degrees right.
EnumIndexArray< T, DiagDirection, DiagDirection::End > DiagDirectionIndexArray
Array with DiagDirection as index.
Direction
Defines the 8 directions on the map.
@ Invalid
Flag for an invalid direction.
@ SW
Southwest.
@ NW
Northwest.
@ NE
Northeast.
@ SE
Southeast.
EnumIndexArray< T, Direction, Direction::End > DirectionIndexArray
Array with Direction as index.
DiagDirection
Enumeration for diagonal directions.
@ Invalid
Flag for an invalid DiagDirection.
void LoadUnloadStation(Station *st)
Load/unload the vehicles in this station according to the order they entered.
Definition economy.cpp:1916
void PrepareUnload(Vehicle *front_v)
Prepare the vehicle to be unloaded.
Definition economy.cpp:1243
Base classes related to the economy.
@ NewVehicles
New vehicles.
EffectVehicle * CreateEffectVehicleRel(const Vehicle *v, int x, int y, int z, EffectVehicleType type)
Create an effect vehicle above a particular vehicle.
Base class for all effect vehicles.
Functions related to effect vehicles.
EffectVehicleType
Effect vehicle types.
@ EV_BREAKDOWN_SMOKE
Smoke of broken vehicles except aircraft.
@ EV_STEAM_SMOKE
Smoke of steam engines.
@ EV_DIESEL_SMOKE
Smoke of diesel engines.
@ EV_BREAKDOWN_SMOKE_AIRCRAFT
Smoke of broken aircraft.
@ EV_ELECTRIC_SPARK
Sparks of electric engines.
@ AIR_CTOL
Conventional Take Off and Landing, i.e. planes.
@ RoadIsTram
Road vehicle is a tram/light rail vehicle.
@ NoBreakdownSmoke
Do not show black smoke during a breakdown.
@ Uses2CC
Vehicle uses two company colours.
@ RailIsMU
Rail vehicle is a multiple-unit (DMU/EMU).
@ VE_TYPE_DEFAULT
Use default from engine class.
Definition engine_type.h:60
@ VE_TYPE_COUNT
Number of bits used for the effect type.
Definition engine_type.h:59
@ VE_OFFSET_CENTRE
Value of offset corresponding to a position above the centre of the vehicle.
Definition engine_type.h:56
@ VE_TYPE_ELECTRIC
Electric sparks.
Definition engine_type.h:63
@ VE_TYPE_START
First bit used for the type of effect.
Definition engine_type.h:58
@ VE_OFFSET_COUNT
Number of bits used for the offset.
Definition engine_type.h:55
@ VE_ADVANCED_EFFECT
Flag for advanced effects.
Definition engine_type.h:66
@ VE_DISABLE_EFFECT
Flag to disable visual effect.
Definition engine_type.h:65
@ VE_TYPE_STEAM
Steam plumes.
Definition engine_type.h:61
@ VE_TYPE_DIESEL
Diesel fumes.
Definition engine_type.h:62
@ VE_DEFAULT
Default value to indicate that visual effect should be based on engine class.
Definition engine_type.h:69
@ VE_OFFSET_START
First bit that contains the offset (0 = front, 8 = centre, 15 = rear).
Definition engine_type.h:54
@ VE_DISABLE_WAGON_POWER
Flag to disable wagon power.
Definition engine_type.h:67
PoolID< uint16_t, struct EngineIDTag, 64000, 0xFFFF > EngineID
Unique identification number of an engine.
Definition engine_type.h:25
@ Maglev
Maglev engine.
Definition engine_type.h:42
@ Steam
Steam rail engine.
Definition engine_type.h:38
@ Diesel
Diesel rail engine.
Definition engine_type.h:39
@ Electric
Electric rail engine.
Definition engine_type.h:40
@ Monorail
Mono rail engine.
Definition engine_type.h:41
@ Wagon
simple wagon, not motorized
Definition engine_type.h:33
constexpr std::underlying_type_t< enum_type > to_underlying(enum_type e)
Implementation of std::to_underlying (from C++23).
Definition enum_type.hpp:21
Functions related to errors.
@ Critical
Critical errors, the MessageBox is shown in all cases.
Definition error.h:25
void ShowErrorMessage(EncodedString &&summary_msg, int x, int y, CommandCost &cc)
Display an error message in a window.
Types for recording game performance data.
@ GameLoopRoadVehicles
Time spend processing road vehicles.
@ GameLoopShips
Time spent processing ships.
@ GameLoopAircraft
Time spent processing aircraft.
@ GameLoopTrains
Time spent processing trains.
@ GameLoopEconomy
Time spent processing cargo movement.
Gamelog _gamelog
Gamelog instance.
Definition gamelog.cpp:30
Functions to be called to log fundamental changes to the game.
void DrawSprite(SpriteID img, PaletteID pal, int x, int y, const SubSprite *sub, ZoomLevel zoom)
Draw a sprite, not in a viewport.
Definition gfx.cpp:1032
@ Normal
The most basic (normal) sprite.
Definition gfx_type.h:405
uint32_t PaletteID
The number of the palette.
Definition gfx_type.h:18
@ Company
Destination is a company.
Definition goal_type.h:56
@ Next
Next button.
Definition goal_type.h:35
@ Previous
Previous button.
Definition goal_type.h:34
bool MarkAllViewportsDirty(int left, int top, int right, int bottom)
Mark all viewports that display an area as dirty (in need of repaint).
void MarkTilesDirty(bool cargo_change) const
Marks the tiles of the station as dirty.
Definition station.cpp:250
void MarkTileDirtyByTile(TileIndex tile, int bridge_level_offset, int tile_height_override)
Mark a tile given by its index dirty for repaint.
virtual void MarkDirty()
Marks the vehicles to be redrawn and updates cached variables.
void DeleteGroupHighlightOfVehicle(const Vehicle *v)
Removes the highlight of a vehicle in a group window.
Functions/definitions that have something to do with groups.
static constexpr GroupID DEFAULT_GROUP
Ungrouped vehicles are in this group.
Definition group_type.h:18
const EnumIndexArray< const TileTypeProcs *, TileType, TileType::MaxSize > _tile_type_procs
Tile callback functions for each type of tile.
Definition landscape.cpp:71
Point RemapCoords(int x, int y, int z)
Map 3D world or tile coordinate to equivalent 2D coordinate as used in the viewports and smallmap.
Definition landscape.h:81
@ Toyland
Landscape with funky industries and vehicles.
static const uint8_t LIT_ALL
Show the liveries of all companies.
Definition livery.h:19
LiveryScheme
List of different livery schemes.
Definition livery.h:22
@ PassengerTram
Passenger trams.
Definition livery.h:55
@ SmallPlane
Small aeroplanes.
Definition livery.h:51
@ PassengerWagonMaglev
Passenger wagons attached to maglev engines.
Definition livery.h:38
@ Helicopter
Helicopters.
Definition livery.h:50
@ PassengerWagonElectric
Passenger wagons attached to electric engines.
Definition livery.h:36
@ Maglev
Maglev engines.
Definition livery.h:31
@ Steam
Steam engines.
Definition livery.h:27
@ PassengerShip
Passenger ships.
Definition livery.h:46
@ EMU
EMUs and their passenger wagons.
Definition livery.h:33
@ Bus
Buses.
Definition livery.h:42
@ Truck
Trucks.
Definition livery.h:43
@ Diesel
Diesel engines.
Definition livery.h:28
@ Default
Default scheme.
Definition livery.h:24
@ PassengerWagonDiesel
Passenger wagons attached to diesel engines.
Definition livery.h:35
@ FreightShip
Freight ships.
Definition livery.h:47
@ Electric
Electric engines.
Definition livery.h:29
@ PassengerWagonMonorail
Passenger wagons attached to monorail engines.
Definition livery.h:37
@ Monorail
Monorail engines.
Definition livery.h:30
@ FreightTram
Freight trams.
Definition livery.h:56
@ PassengerWagonSteam
Passenger wagons attached to steam engines.
Definition livery.h:34
@ LargePlane
Large aeroplanes.
Definition livery.h:52
@ FreightWagon
Freight wagons.
Definition livery.h:39
@ DMU
DMUs and their passenger wagons.
Definition livery.h:32
static const uint8_t LIT_COMPANY
Show the liveries of your own company.
Definition livery.h:18
#define Point
Macro that prevents name conflicts between included headers.
static TileIndex TileVirtXY(uint x, uint y)
Get a tile from the virtual XY-coordinate.
Definition map_func.h:407
static uint TileY(TileIndex tile)
Get the Y component of a tile.
Definition map_func.h:429
static uint TileX(TileIndex tile)
Get the X component of a tile.
Definition map_func.h:419
constexpr bool IsInsideMM(const size_t x, const size_t min, const size_t max) noexcept
Checks if a value is in an interval.
constexpr T abs(const T a)
Returns the absolute value of (scalar) variable.
Definition math_func.hpp:23
constexpr uint CeilDiv(uint a, uint b)
Computes ceil(a / b) for non-negative a and b.
constexpr T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Definition math_func.hpp:79
constexpr To ClampTo(From value)
Clamp the given value down to lie within the requested type.
Miscellaneous command definitions.
void HideFillingPercent(TextEffectID *te_id)
Hide vehicle loading indicators.
Definition misc_gui.cpp:582
void ShowCostOrIncomeAnimation(int x, int y, int z, Money cost)
Display animated income or costs on the map.
Definition misc_gui.cpp:508
bool _networking
are we in networking mode?
Definition network.cpp:63
Basic functions/variables used all over the place.
GrfSpecFeature GetGrfSpecFeature(VehicleType type)
Get the GrfSpecFeature associated with a VehicleType.
Definition newgrf.cpp:1889
@ VisualEffect
Visual effects and wagon power (trains, road vehicles and ships).
@ ColourRemap
Change colour mapping of vehicle.
@ CBID_VEHICLE_SPAWN_VISUAL_EFFECT
Called to spawn visual effects for vehicles.
@ CBID_VEHICLE_COLOUR_MAPPING
Called to determine if a specific colour map should be used for a vehicle instead of the default live...
@ CBID_VEHICLE_32DAY_CALLBACK
Called for every vehicle every 32 days (not all on same date though).
@ CBID_VEHICLE_VISUAL_EFFECT
Visual effects and wagon power.
static const uint CALLBACK_FAILED
Different values for Callback result evaluations.
void ErrorUnknownCallbackResult(GrfID grfid, uint16_t cbid, uint16_t cb_res)
Record that a NewGRF returned an unknown/invalid callback result.
GRFConfig * GetGRFConfig(GrfID grfid, uint32_t mask)
Retrieve a NewGRF from the current config by its grfid.
GRFBug
Encountered GRF bugs.
@ VehPoweredWagon
Powered wagon changed poweredness state when not inside a depot.
@ VehLength
Length of rail vehicle changes when not inside a depot.
Functions/types related to NewGRF debugging.
void DeleteNewGRFInspectWindow(GrfSpecFeature feature, uint index)
Delete inspect window for a given feature and index.
bool UsesWagonOverride(const Vehicle *v)
Check if a wagon is currently using a wagon override.
uint16_t GetVehicleCallback(CallbackID callback, uint32_t param1, uint32_t param2, EngineID engine, const Vehicle *v, std::span< int32_t > regs100)
Evaluate a newgrf callback for vehicles.
void TriggerRoadStopRandomisation(BaseStation *st, TileIndex tile, StationRandomTrigger trigger, CargoType cargo_type)
Trigger road stop randomisation.
NewGRF definitions and structures for road stops.
bool PlayVehicleSound(const Vehicle *v, VehicleSoundEvent event, bool force)
Checks whether a NewGRF wants to play a different vehicle sound effect.
Functions related to NewGRF provided sounds.
@ VisualEffect
Vehicle visual effect (steam, diesel smoke or electric spark) is shown.
@ Breakdown
Vehicle breaking down.
@ Stopped16
Every 16 ticks while the vehicle is stopped (speed == 0).
@ Running16
Every 16 ticks while the vehicle is running (speed > 0).
@ Running
Vehicle running normally.
void TriggerStationRandomisation(BaseStation *st, TileIndex trigger_tile, StationRandomTrigger trigger, CargoType cargo_type)
Trigger station randomisation.
Header file for NewGRF stations.
Label< struct GrfIDTag > GrfID
The unique identifier of a NewGRF.
Definition newgrf_type.h:17
Functions related to news.
void AddVehicleAdviceNewsItem(AdviceType advice_type, EncodedString &&headline, VehicleID vehicle)
Adds a vehicle-advice news item.
Definition news_func.h:43
void DeleteVehicleNews(VehicleID vid, AdviceType advice_type=AdviceType::Invalid)
Delete news with a given advice type about a vehicle.
@ Vehicle
Vehicle news item. (new engine available).
Definition news_type.h:84
@ VehicleLost
The vehicle has become lost.
Definition news_type.h:60
@ VehicleWaiting
The vehicle is waiting in the depot.
Definition news_type.h:63
@ AutorenewFailed
Autorenew or autoreplace failed.
Definition news_type.h:56
@ VehicleOld
The vehicle is starting to get old.
Definition news_type.h:61
@ VehicleUnprofitable
The vehicle is costing you money.
Definition news_type.h:62
@ RefitFailed
The refit order failed to execute.
Definition news_type.h:58
@ Error
A game paused because a (critical) error.
Definition openttd.h:75
@ Normal
A game normally paused.
Definition openttd.h:72
@ Normal
Playing a game.
Definition openttd.h:20
@ Menu
In the main menu.
Definition openttd.h:19
Functions related to order backups.
void InsertOrder(Vehicle *v, Order &&new_o, VehicleOrderID sel_ord)
Insert a new order but skip the validation.
void DeleteOrder(Vehicle *v, VehicleOrderID sel_ord)
Delete an order but skip the parameter validation.
void InvalidateVehicleOrder(const Vehicle *v, int data)
Updates the widgets of a vehicle which contains the order-data.
void DeleteVehicleOrders(Vehicle *v, bool keep_orderlist, bool reset_order_indices)
Delete all orders from a vehicle.
@ NoUnload
Totally no unloading will be done.
Definition order_type.h:71
@ NonStop
The vehicle will not stop at any stations it passes except the destination, aka non-stop.
Definition order_type.h:88
@ GoVia
The vehicle will stop at any station it passes except the destination, aka via.
Definition order_type.h:89
EnumBitSet< OrderDepotActionFlag, uint8_t > OrderDepotActionFlags
Bitset of OrderDepotActionFlag elements.
Definition order_type.h:126
uint8_t VehicleOrderID
The index of an order within its current vehicle (not pool related).
Definition order_type.h:18
@ NoLoad
Do not load anything.
Definition order_type.h:81
static const VehicleOrderID MAX_VEH_ORDER_ID
Last valid VehicleOrderID.
Definition order_type.h:41
@ Halt
Service the vehicle and then halt it.
Definition order_type.h:120
@ NearestDepot
Send the vehicle to the nearest depot.
Definition order_type.h:121
@ Unbunch
Service the vehicle and then unbunch it.
Definition order_type.h:122
@ PartOfOrders
This depot order is because of a regular order.
Definition order_type.h:110
@ Service
This depot order is because of the servicing limit.
Definition order_type.h:109
static const VehicleOrderID INVALID_VEH_ORDER_ID
Invalid vehicle order index (sentinel).
Definition order_type.h:39
static const uint IMPLICIT_ORDER_ONLY_CAP
Maximum number of orders in implicit-only lists before we start searching harder for duplicates.
Definition order_type.h:47
Some methods of Pool are placed here in order to reduce compilation time and binary size.
#define INSTANTIATE_POOL_METHODS(name)
Force instantiation of pool methods so we don't get linker errors.
bool HasAnyRailTypesAvail(const CompanyID company)
Test if any buildable railtype is available for a company.
Definition rail.cpp:80
RailType GetTileRailType(Tile tile)
Return the rail type of tile, or INVALID_RAILTYPE if this is no rail tile.
Definition rail.cpp:39
bool HasPowerOnRail(RailType enginetype, RailType tiletype)
Checks if an engine of the given RailType got power on a tile with a given RailType.
Definition rail.h:396
void SetDepotReservation(Tile t, bool b)
Set the reservation state of the depot.
Definition rail_map.h:268
Pseudo random number generator.
uint32_t RandomRange(uint32_t limit, const std::source_location location=std::source_location::current())
Pick a random number between 0 and limit - 1, inclusive.
bool Chance16I(const uint32_t a, const uint32_t b, const uint32_t r)
Checks if a given randomize-number is below a given probability.
bool Chance16(const uint32_t a, const uint32_t b, const std::source_location location=std::source_location::current())
Flips a coin with given probability.
Declaration of link refreshing utility.
bool HasAnyRoadTypesAvail(CompanyID company, RoadTramType rtt)
Test if any buildable RoadType is available for a company.
Definition road.cpp:152
bool HasTileAnyRoadType(Tile t, RoadTypes rts)
Check if a tile has one of the specified road types.
Definition road_map.h:232
RoadTramType
The different types of road type.
Definition road_type.h:38
Base class for roadstops.
Road vehicle states.
@ RVSB_IN_DT_ROAD_STOP
The vehicle is in a drive-through road stop.
Definition roadveh.h:51
A number of safeguards to prevent using unsafe methods.
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition settings.cpp:61
ClientSettings _settings_client
The current settings for this game.
Definition settings.cpp:60
Base for ships.
@ SecondEndFacingForward
Whether the other end is facing forward. Only applies to dual-ended ships.
Definition ship.h:31
SigSegState UpdateSignalsOnSegment(TileIndex tile, DiagDirection side, Owner owner)
Update signals, starting at one side of a tile Will check tile next to this at opposite side too.
Definition signal.cpp:655
Functions related to sound.
@ SND_3A_BREAKDOWN_TRAIN_SHIP_TOYLAND
58 == 0x3A Breakdown: train or ship (toyland)
Definition sound_type.h:105
@ SND_10_BREAKDOWN_TRAIN_SHIP
14 == 0x0E Breakdown: train or ship (non-toyland)
Definition sound_type.h:61
@ SND_0F_BREAKDOWN_ROADVEHICLE
13 == 0x0D Breakdown: road vehicle (non-toyland)
Definition sound_type.h:60
@ SND_35_BREAKDOWN_ROADVEHICLE_TOYLAND
53 == 0x35 Breakdown: road vehicle (toyland)
Definition sound_type.h:100
Functions to cache sprites in memory.
static const PaletteID PALETTE_RECOLOUR_START
First recolour sprite for company colours.
Definition sprites.h:1763
static const PaletteID PALETTE_CRASH
Recolour sprite greying of crashed vehicles.
Definition sprites.h:1794
Base classes/functions for stations.
void IncreaseStats(Station *st, CargoType cargo, StationID next_station_id, uint capacity, uint usage, uint32_t time, EdgeUpdateModes modes)
Increase capacity for a link stat given by station cargo and next hop.
Functions related to stations.
bool IsStationRoadStopTile(Tile t)
Is tile t a road stop station?
bool IsBayRoadStopTile(Tile t)
Is tile t a bay (non-drive through) road stop station?
bool IsRailStationTile(Tile t)
Is this tile a station tile and a rail station?
StationID GetStationIndex(Tile t)
Get StationID from a tile.
Definition station_map.h:26
RoadStopType GetRoadStopType(Tile t)
Get the road stop type of this tile.
Definition station_map.h:54
@ Bus
A standard stop for buses.
@ Truck
A standard stop for trucks.
@ Dock
Station with a dock.
@ TruckStop
Station with truck stops.
@ Train
Station with train station.
@ Airport
Station with an airport.
@ BusStop
Station with bus stops.
@ VehicleDeparts
Trigger platform when train leaves.
@ VehicleDeparts
Trigger platform when train leaves.
Definition of base types and functions in a cross-platform compatible way.
static void StrMakeValid(Builder &builder, StringConsumer &consumer, StringValidationSettings settings)
Copies the valid (UTF-8) characters from consumer to the builder.
Definition string.cpp:118
EncodedString GetEncodedString(StringID str)
Encode a string with no parameters into an encoded string.
Definition strings.cpp:89
std::string GetString(StringID string)
Resolve the given StringID into a std::string with formatting but no parameters.
Definition strings.cpp:423
Functions related to OTTD's strings.
StrongType::Typedef< uint32_t, struct StringIDTag, StrongType::Compare, StrongType::Integer > StringID
Numeric value that represents a string, independent of the selected language.
static constexpr StringID INVALID_STRING_ID
Constant representing an invalid string (16bit in case it is used in savegames).
Information about a aircraft vehicle.
uint8_t subtype
Type of aircraft.
Aircraft, helicopters, rotors and their shadows belong to this class.
Definition aircraft.h:75
uint8_t pos
Next desired position of the aircraft.
Definition aircraft.h:77
uint8_t state
State of the airport.
Definition aircraft.h:80
bool IsNormalAircraft() const
Check if the aircraft type is a normal flying device; eg not a rotor or a shadow.
Definition aircraft.h:123
uint8_t previous_pos
Previous desired position of the aircraft.
Definition aircraft.h:78
StationID targetairport
Airport to go to next.
Definition aircraft.h:79
@ Airplanes
Can planes land on this airport type?
Definition airport.h:165
@ Helicopters
Can helicopters land on this airport type?
Definition airport.h:166
std::vector< AirportFTA > layout
state machine for airport
Definition airport.h:195
Flags flags
Flags for this airport type.
Definition airport.h:198
AirportBlocks blocks
stores which blocks on the airport are taken. was 16 bit earlier on, then 32
const AirportFTAClass * GetFTA() const
Get the finite-state machine for this airport or the finite-state machine for the dummy airport in ca...
Class to backup a specific variable and restore it upon destruction of this object to prevent stack v...
TimerGameTick::TickCounter depot_unbunching_next_departure
When the vehicle will next try to leave its unbunching depot.
VehicleOrderID cur_real_order_index
The index to the current real (non-implicit) order.
TimerGameTick::Ticks round_trip_time
How many ticks for a single circumnavigation of the orders.
VehicleFlags vehicle_flags
Used for gradual loading and other miscellaneous things (.
TimerGameTick::TickCounter depot_unbunching_last_departure
When the vehicle last left its unbunching depot.
VehicleOrderID cur_implicit_order_index
The index to the current implicit order.
TimerGameTick::Ticks lateness_counter
How many ticks late (or early if negative) this vehicle is.
void ResetDepotUnbunching()
Resets all the data used for depot unbunching.
StationFacilities facilities
The facilities that this station has.
VehicleType type
Type of vehicle.
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo type.
Definition cargotype.h:140
GUISettings gui
settings related to the GUI
Structure to return information about the closest depot location, and whether it could be found.
DestinationID destination
The DestinationID as used for orders.
CompanySettings settings
settings specific for each company
uint32_t engine_renew_money
minimum amount of money before autorenew is used
int16_t engine_renew_months
months before/after the maximum vehicle age a vehicle should be renewed
bool engine_renew
is autorenew enabled
VehicleTypeIndexArray< GroupStatistics > group_all
NOSAVE: Statistics for the ALL_GROUP group.
A coordinate with two dimensions.
T y
Y coordinate.
T x
X coordinate.
Data about how and where to blit pixels.
Definition gfx_type.h:157
A special vehicle is one of the following:
TransparencyOption GetTransparencyOption() const
Determines the transparency option affecting the effect.
uint16_t animation_state
State primarily used to change the graphics/behaviour.
EngineMiscFlags misc_flags
Miscellaneous flags.
VehicleCallbackMasks callback_mask
Bitmask of vehicle callbacks that have to be called.
Information about engine autorenews and autoreplacements.
EngineID to
Engine to replace to.
bool replace_when_old
Do replacement only when vehicle is old.
Information about GRF, used in the game and (part of it) in savegames.
GRFBugs grf_bugs
NOSAVE: bugs in this GRF in this run,.
std::string GetName() const
Get the name of this grf.
GrfID grfid
grfid that introduced this entity.
uint16_t local_id
id defined by the grf file for this entity
Dynamic data of a loaded NewGRF.
Definition newgrf.h:126
uint8_t grf_version
GRF version (See https://newgrf-specs.tt-wiki.net/wiki/Version_numbers#GRF_version).
Definition newgrf.h:129
bool vehicle_income_warn
if a vehicle isn't generating income, show a warning
uint8_t liveries
options for displaying company liveries, 0=none, 1=self, 2=all
Position information of a vehicle after it moved.
TileIndex new_tile
Tile of the vehicle after moving.
int y
x and y position of the vehicle after moving
TileIndex old_tile
Current tile of the vehicle.
Cached, frequently calculated values.
EngineID first_engine
Cached EngineID of the front vehicle. EngineID::Invalid() for the front vehicle itself.
uint32_t cached_power
Total power of the consist (valid only for the first engine).
uint8_t cached_veh_length
Length of this vehicle in units of 1/VEHICLE_LENGTH of normal length. It is cached because this can b...
GroundVehicleCache gcache
Cache of often calculated values.
bool IsRearDualheaded() const
Tell if we are dealing with the rear end of a multiheaded engine.
bool IsMultiheaded() const
Check if the vehicle is a multiheaded engine.
GroundVehicleFlags gv_flags
static void CountVehicle(const Vehicle *v, int delta)
Update num_vehicle when adding or removing a vehicle.
static void VehicleReachedMinAge(const Vehicle *v)
Add a vehicle to the profit sum of its group.
static void CountEngine(const Vehicle *v, int delta)
Update num_engines when adding/removing an engine.
static void UpdateAutoreplace(CompanyID company)
Update autoreplace_defined and autoreplace_finished of all statistics of a company.
static void UpdateProfits()
Recompute the profits for all groups.
Group data.
Definition group.h:77
Livery livery
Custom colour scheme for vehicles in this group.
Definition group.h:83
GroupID parent
Parent group.
Definition group.h:91
Information about a particular livery.
Definition livery.h:82
Flags in_use
Livery flags.
Definition livery.h:92
uint8_t GetRecolourOffset(bool use_secondary=true) const
Get offset for recolour palette.
Definition livery.h:101
bool revalidate_before_draw
We need to do a GetImage() and check bounds before drawing this sprite.
VehicleSpriteSeq sprite_seq
Vehicle appearance.
static void ClearVehicle(const Vehicle *v)
Clear/update the (clone) vehicle from an order backup.
void AddVehicle(Vehicle *v)
Adds the given vehicle to this shared order list.
Definition order_base.h:511
If you change this, keep in mind that it is also saved in 2 other places:
Definition order_base.h:33
OrderDepotTypeFlags GetDepotOrderType() const
What caused us going to the depot?
Definition order_base.h:169
DestinationID GetDestination() const
Gets the destination of this order.
Definition order_base.h:99
bool IsType(OrderType type) const
Check whether this order is of the given type.
Definition order_base.h:66
CargoType GetRefitCargo() const
Get the cargo to to refit to.
Definition order_base.h:127
bool IsFullLoadOrder() const
Is this order a OrderLoadType::FullLoad or OrderLoadType::FullLoadAny?
Definition order_base.h:135
void MakeDummy()
Makes this order a Dummy order.
OrderLoadType GetLoadType() const
How must the consist be loaded?
Definition order_base.h:145
OrderDepotActionFlags GetDepotActionType() const
What are we going to do when in the depot.
Definition order_base.h:175
bool ShouldStopAtStation(const Vehicle *v, StationID station) const
Check whether the given vehicle should stop at the given station based on this order and the non-stop...
void MakeImplicit(StationID destination)
Makes this order an implicit order.
bool IsRefit() const
Is this order a refit order.
Definition order_base.h:113
static Pool::IterateWrapper< Vehicle > Iterate(size_t from=0)
static Company * Get(auto index)
static Group * GetIfValid(auto index)
Information about a rail vehicle.
Definition engine_type.h:73
RailVehicleType railveh_type
Type of rail vehicle.
Definition engine_type.h:75
EngineClass engclass
Class of engine for this vehicle.
Definition engine_type.h:85
Specification of a rectangle with absolute coordinates of all edges.
A Stop for a Road Vehicle.
void Leave(RoadVehicle *rv)
Leave the road stop.
Definition roadstop.cpp:203
RoadStop * next
Next stop of the given type at this station.
TileIndex xy
Position on the map.
static RoadStop * GetByTile(TileIndex tile, RoadStopType type)
Find a roadstop at given tile.
Definition roadstop.cpp:253
Information about a road vehicle.
RoadType roadtype
Road type.
Buses, trucks and trams belong to this class.
Definition roadveh.h:105
uint8_t state
Definition roadveh.h:107
RoadTypes compatible_roadtypes
NOSAVE: Roadtypes this consist is powered on.
Definition roadveh.h:117
bool IsBus() const
Check whether a roadvehicle is a bus.
RoadType roadtype
NOSAVE: Roadtype of this vehicle.
Definition roadveh.h:115
VehicleID disaster_vehicle
NOSAVE: Disaster vehicle targetting this vehicle.
Definition roadveh.h:116
Information about a ship vehicle.
Definition engine_type.h:98
All ships have this type.
Definition ship.h:39
TrackBits state
The "track" the ship is following.
Definition ship.h:41
void UpdateCache()
Update the caches of this ship.
Definition ship_cmd.cpp:236
static Pool::IterateWrapper< Station > Iterate(size_t from=0)
static Station * Get(auto index)
static Station * GetIfValid(auto index)
T * GetMovingFront() const
Get the moving front of the vehicle chain.
T * Next() const
Get next vehicle in the chain.
static Train * From(Vehicle *v)
void UpdateViewport(bool force_update, bool update_delta)
Update vehicle sprite- and position caches.
T * GetFirstEnginePart()
Get the first part of an articulated engine.
Data structure describing a sprite.
uint16_t width
Width of the sprite.
uint16_t height
Height of the sprite.
int16_t y_offs
Number of pixels to shift the sprite downwards.
int16_t x_offs
Number of pixels to shift the sprite to the right.
Station data structure.
std::array< GoodsEntry, NUM_CARGO > goods
Goods at this station.
Airport airport
Tile area the airport covers.
'Train' is either a loco or a wagon.
Definition train.h:97
Train * GetNextUnit() const
Get the next real (non-articulated part and non rear part of dualheaded engine) vehicle in the consis...
Definition train.h:156
Train * other_multiheaded_part
Link between the two ends of a multiheaded engine.
Definition train.h:105
TrainForceProceeding force_proceed
How the train should behave when it encounters next obstacle.
Definition train.h:111
TrackBits track
On which track the train currently is.
Definition train.h:110
VehicleRailFlags flags
Which flags has this train currently set.
Definition train.h:98
void ConsistChanged(ConsistChangeFlags allowed_changes)
Recalculates the cached stuff of a train.
uint16_t wait_counter
Ticks waiting in front of a signal, ticks being stuck or a counter for forced proceeding through sign...
Definition train.h:100
uint8_t cached_vis_effect
Visual effect to show (see VisualEffect).
uint16_t cached_cargo_age_period
Number of ticks before carried cargo is aged.
The information about a vehicle list.
Definition vehiclelist.h:32
WindowNumber ToWindowNumber() const
Pack a VehicleListIdentifier in 32 bits so it can be used as unique WindowNumber.
Sprite sequence for a vehicle part.
bool IsValid() const
Check whether the sequence contains any sprites.
void GetBounds(Rect *bounds) const
Determine shared bounds of all sprites.
Definition vehicle.cpp:126
void Draw(int x, int y, PaletteID default_pal, bool force_pal) const
Draw the sprite sequence.
Definition vehicle.cpp:154
Vehicle sub-coordinate data for moving into a new tile.
Definition vehicle.cpp:3365
Direction dir
new direction.
Definition vehicle.cpp:3366
Vehicle data structure.
Money GetDisplayProfitThisYear() const
Gets the profit vehicle had this year.
CargoPayment * cargo_payment
The cargo payment we're currently in.
EngineID engine_type
The type of engine used for this vehicle.
uint16_t cargo_age_counter
Ticks till cargo is aged next.
int32_t z_pos
z coordinate.
Vehicle * last
NOSAVE: pointer for the last vehicle in the chain.
Direction direction
facing
void ShiftDates(TimerGameEconomy::Date interval)
Shift all dates by given interval.
Definition vehicle.cpp:782
const Order * GetLastOrder() const
Returns the last order of a vehicle, or nullptr if it doesn't exists.
TimerGameEconomy::Date economy_age
Age in economy days.
bool IsOrderListShared() const
Check if we share our orders with another vehicle.
const Engine * GetEngine() const
Retrieves the engine of the vehicle.
Definition vehicle.cpp:752
Direction GetMovingDirection() const
Get the moving direction of this vehicle chain.
void IncrementRealOrderIndex()
Advanced cur_real_order_index to the next real order, keeps care of the wrap-around and invalidates t...
virtual uint Crash(bool flooded=false)
Crash the (whole) vehicle chain.
Definition vehicle.cpp:304
bool IsStoppedInDepot() const
Check whether the vehicle is in the depot and stopped.
Order * GetOrder(int index) const
Returns order 'index' of a vehicle or nullptr when it doesn't exists.
bool HasDepotOrder() const
Checks if a vehicle has a depot in its order list.
void LeaveStation()
Perform all actions when leaving a station.
Definition vehicle.cpp:2375
void AddToShared(Vehicle *shared_chain)
Adds this vehicle to a shared vehicle chain.
Definition vehicle.cpp:3026
VehicleCargoList cargo
The cargo this vehicle is carrying.
Vehicle ** hash_tile_prev
NOSAVE: Previous vehicle in the tile location hash.
bool HasUnbunchingOrder() const
Check if the current vehicle has an unbunching order.
Definition vehicle.cpp:2511
TimerGameEconomy::Date date_of_last_service
Last economy date the vehicle had a service at a depot.
uint16_t cargo_cap
total capacity
StationID last_loading_station
Last station the vehicle has stopped at and could possibly leave from with any cargo loaded.
VehicleOrderID GetNumOrders() const
Get the number of orders this vehicle has.
const Order * GetFirstOrder() const
Get the first order of the vehicles order list.
CommandCost SendToDepot(DoCommandFlags flags, DepotCommandFlags command)
Send this vehicle to the depot using the given command(s).
Definition vehicle.cpp:2605
void ReleaseUnitNumber()
Release the vehicle's unit number.
Definition vehicle.cpp:2445
virtual void SetDestTile(TileIndex tile)
Set the destination of this vehicle.
void UpdateBoundingBoxCoordinates(bool update_cache) const
Update the bounding box co-ordinates of the vehicle.
Definition vehicle.cpp:1712
uint8_t day_counter
Increased by one for each day.
void HandleLoading(bool mode=false)
Handle the loading of the vehicle; when not it skips through dummy orders and does nothing in all oth...
Definition vehicle.cpp:2456
Money profit_this_year
Profit this year << 8, low 8 bits are fract.
bool HasArticulatedPart() const
Check if an engine has an articulated part.
SpriteID colourmap
NOSAVE: cached colour mapping.
uint8_t breakdown_ctr
Counter for managing breakdown events.
uint8_t breakdown_delay
Counter for managing breakdown length.
Vehicle * GetNextVehicle() const
Get the next real (non-articulated part) vehicle in the consist.
GroupID group_id
Index of group Pool array.
void IncrementImplicitOrderIndex()
Increments cur_implicit_order_index, keeps care of the wrap-around and invalidates the GUI.
bool IsGroundVehicle() const
Check if the vehicle is a ground vehicle.
VehStates vehstatus
Status.
TimerGameCalendar::Date date_of_last_service_newgrf
Last calendar date the vehicle had a service at a depot, unchanged by the date cheat to protect again...
Vehicle * first
NOSAVE: pointer to the first vehicle in the chain.
void CancelReservation(StationID next, Station *st)
Return all reserved cargo packets to the station and reset all packets staged for transfer.
Definition vehicle.cpp:2359
Money profit_last_year
Profit last year << 8, low 8 bits are fract.
bool IsEngineCountable() const
Check if a vehicle is counted in num_engines in each company struct.
Definition vehicle.cpp:719
bool IsArticulatedPart() const
Check if the vehicle is an articulated part of an engine.
bool NeedsAutorenewing(const Company *c, bool use_renew_setting=true) const
Function to tell if a vehicle needs to be autorenewed.
Definition vehicle.cpp:168
void UpdateVisualEffect(bool allow_power_change=true)
Update the cached visual effect.
Definition vehicle.cpp:2684
void LeaveUnbunchingDepot()
Leave an unbunching depot and calculate the next departure time for shared order vehicles.
Definition vehicle.cpp:2536
CargoType cargo_type
type of cargo this vehicle is carrying
Vehicle * previous_shared
NOSAVE: pointer to the previous vehicle in the shared order chain.
VehicleOrderID GetNumManualOrders() const
Get the number of manually added orders this vehicle has.
Vehicle * First() const
Get the first vehicle of this vehicle chain.
int8_t trip_occupancy
NOSAVE: Occupancy of vehicle of the current trip (updated after leaving a station).
Order current_order
The current order (+ status, like: loading).
Vehicle(VehicleID index, VehicleType type=VehicleType::Invalid)
Vehicle constructor.
Definition vehicle.cpp:383
void PreDestructor()
Destroy all stuff that (still) needs the virtual functions to work properly.
Definition vehicle.cpp:830
TimerGameTick::TickCounter last_loading_tick
Last TimerGameTick::counter tick that the vehicle has stopped at a station and could possibly leave w...
void HandlePathfindingResult(bool path_found)
Handle the pathfinding result, especially the lost status.
Definition vehicle.cpp:796
Vehicle * Next() const
Get the next vehicle of this vehicle.
int32_t y_pos
y coordinate.
int32_t x_pos
x coordinate.
const GRFFile * GetGRF() const
Retrieve the NewGRF the vehicle is tied to.
Definition vehicle.cpp:762
OrderList * orders
Pointer to the order list for this vehicle.
uint32_t GetDisplayMinPowerToWeight() const
Calculates the minimum power-to-weight ratio using the maximum weight of the ground vehicle.
Definition vehicle.cpp:3318
Vehicle * GetMovingFront() const
Get the moving front of the vehicle chain.
virtual ClosestDepot FindClosestDepot()
Find the closest depot for this vehicle and tell us the location, DestinationID and whether we should...
void UpdateViewport(bool dirty)
Update the vehicle on the viewport, updating the right hash and setting the new coordinates.
Definition vehicle.cpp:1757
Money value
Value of the vehicle.
bool MarkAllViewportsDirty() const
Marks viewports dirty where the vehicle's image is.
Definition vehicle.cpp:1796
uint16_t refit_cap
Capacity left over from before last refit.
VehicleCache vcache
Cache of often used vehicle values.
uint32_t motion_counter
counter to occasionally play a vehicle sound.
SpriteBounds bounds
Bounding box of vehicle.
GroundVehicleCache * GetGroundVehicleCache()
Access the ground vehicle cache of the vehicle.
Definition vehicle.cpp:3214
virtual void OnNewEconomyDay()
Calls the new economy day handler of the vehicle.
Vehicle ** hash_tile_current
NOSAVE: Cache of the current hash chain.
virtual void OnNewCalendarDay()
Calls the new calendar day handler of the vehicle.
Vehicle * NextShared() const
Get the next vehicle of the shared vehicle chain.
virtual int GetCurrentMaxSpeed() const
Calculates the maximum speed of the vehicle under its current conditions.
bool HasFullLoadOrder() const
Check if the current vehicle has a full load order.
Definition vehicle.cpp:2491
virtual bool IsPrimaryVehicle() const
Whether this is the primary vehicle in the chain.
void BeginLoading()
Prepare everything to begin the loading when arriving at a station.
Definition vehicle.cpp:2231
Vehicle * hash_tile_next
NOSAVE: Next vehicle in the tile location hash.
uint16_t cur_speed
current speed
Vehicle * previous
NOSAVE: pointer to the previous vehicle in the chain.
~Vehicle() override
We want to 'destruct' the right class.
Definition vehicle.cpp:897
bool IsFrontEngine() const
Check if the vehicle is a front engine.
bool HasEngineType() const
Check whether Vehicle::engine_type has any meaning.
Definition vehicle.cpp:736
TimerGameCalendar::Date age
Age in calendar days.
bool IsWaitingForUnbunching() const
Check whether a vehicle inside a depot is waiting for unbunching.
Definition vehicle.cpp:2583
TextEffectID fill_percent_te_id
a text-effect id to a loading indicator object
void SetNext(Vehicle *next)
Set the next vehicle of this vehicle.
Definition vehicle.cpp:2990
uint8_t breakdowns_since_last_service
Counter for the amount of breakdowns.
Vehicle * next
pointer to the next vehicle in the chain
TimerGameCalendar::Date max_age
Maximum age.
MutableSpriteCache sprite_cache
Cache of sprites and values related to recalculating them, see MutableSpriteCache.
uint16_t reliability
Reliability.
uint32_t GetDisplayMaxWeight() const
Calculates the maximum weight of the ground vehicle when loaded.
Definition vehicle.cpp:3303
Vehicle * FirstShared() const
Get the first vehicle of this vehicle chain.
void RemoveFromShared()
Removes the vehicle from the shared order list.
Definition vehicle.cpp:3049
bool HandleBreakdown()
Handle all of the aspects of a vehicle breakdown This includes adding smoke and sounds,...
Definition vehicle.cpp:1378
void UpdatePositionAndViewport()
Update the position of the vehicle, and update the viewport.
Definition vehicle.cpp:1786
Vehicle * Previous() const
Get the previous vehicle of this vehicle.
virtual void PlayLeaveStationSound(bool force=false) const
Play the sound associated with leaving the station.
Rect coord
NOSAVE: Graphical bounding box of the vehicle, i.e. what to redraw on moves.
uint16_t reliability_spd_dec
Reliability decrease speed.
uint8_t tick_counter
Increased by one for each tick.
virtual bool IsInDepot() const
Check whether the vehicle is in the depot.
TileIndex tile
Current tile index.
virtual bool Tick()
Calls the tick handler of the vehicle.
TileIndex dest_tile
Heading for this tile.
bool NeedsServicing() const
Check if the vehicle needs to go to a depot in near future (if a opportunity presents itself) for ser...
Definition vehicle.cpp:213
bool HasConditionalOrder() const
Check if the current vehicle has a conditional order.
Definition vehicle.cpp:2502
void UpdatePosition()
Update the position of the vehicle.
Definition vehicle.cpp:1703
GroundVehicleFlags & GetGroundVehicleFlags()
Access the ground vehicle flags of the vehicle.
Definition vehicle.cpp:3244
StationID last_station_visited
The last station we stopped at.
void ResetRefitCaps()
Reset all refit_cap in the consist to cargo_cap.
Definition vehicle.cpp:2437
bool IsDrivingBackwards() const
Is this vehicle moving backwards?
uint8_t breakdown_chance
Current chance of breakdowns.
void ShowVisualEffect() const
Draw visual effects (smoke and/or sparks) for a vehicle chain.
Definition vehicle.cpp:2838
Owner owner
Which company owns the vehicle?
UnitID unitnumber
unit number, for display purposes only
Vehicle * next_shared
pointer to the next vehicle that shares the order
bool NeedsAutomaticServicing() const
Checks if the current order should be interrupted for a service-in-depot order.
Definition vehicle.cpp:296
void DeleteUnreachedImplicitOrders()
Delete all implicit orders which were not reached.
Definition vehicle.cpp:2193
Vehicle ** hash_viewport_prev
NOSAVE: Previous vehicle in the visual location hash.
virtual void GetImage(Direction direction, EngineImageType image_type, VehicleSpriteSeq *result) const
Gets the sprite to show for the given direction.
Vehicle * hash_viewport_next
NOSAVE: Next vehicle in the visual location hash.
GrfID GetGRFID() const
Retrieve the GRF ID of the NewGRF the vehicle is tied to.
Definition vehicle.cpp:772
Data structure for viewport, display of a part of the world.
int top
Screen coordinate top edge of the viewport.
int width
Screen width of the viewport.
ZoomLevel zoom
The zoom level of the viewport.
int virtual_top
Virtual top coordinate.
int virtual_left
Virtual left coordinate.
int left
Screen coordinate left edge of the viewport.
int height
Screen height of the viewport.
VehicleEnterTileStates VehicleEnterTile(Vehicle *v, TileIndex tile, int x, int y)
Call the tile callback function for a vehicle entering a tile.
Definition vehicle.cpp:1867
EnumBitSet< VehicleEnterTileState, uint8_t > VehicleEnterTileStates
Bitset of VehicleEnterTileState elements.
Definition tile_cmd.h:31
static bool IsTileType(Tile tile, TileType type)
Checks if a tile is a given tiletype.
Definition tile_map.h:150
int GetTileMaxPixelZ(TileIndex tile)
Get top height of the tile.
Definition tile_map.h:312
static TileType GetTileType(Tile tile)
Get the tiletype of a given tile.
Definition tile_map.h:96
static constexpr uint TILE_UNIT_MASK
For masking in/out the inner-tile world coordinate units.
Definition tile_type.h:16
static constexpr int MAX_VEHICLE_PIXEL_Y
Maximum height of a vehicle in pixels in ZOOM_BASE.
Definition tile_type.h:22
StrongType::Typedef< uint32_t, struct TileIndexTag, StrongType::Compare, StrongType::Integer, StrongType::Compatible< int32_t >, StrongType::Compatible< int64_t > > TileIndex
The index/ID of a Tile.
Definition tile_type.h:92
static constexpr uint TILE_SIZE
Tile size in world coordinates.
Definition tile_type.h:15
static constexpr int MAX_VEHICLE_PIXEL_X
Maximum width of a vehicle in pixels in ZOOM_BASE.
Definition tile_type.h:21
@ Station
A tile of a station or airport.
Definition tile_type.h:54
Definition of Interval and OneShot timers.
Definition of the game-calendar-timer.
Definition of the game-economy-timer.
Definition of the tick-based game-timer.
Functions related to time tabling.
void UpdateVehicleTimetable(Vehicle *v, bool travelling)
Update the timetable for the vehicle.
bool TracksOverlap(TrackBits bits)
Checks if the given tracks overlap, ie form a crossing.
Definition track_func.h:540
EnumBitSet< Track, uint8_t > TrackBits
Bitset of Track elements.
Definition track_type.h:43
Track
These are used to specify a single track.
Definition track_type.h:19
@ Depot
Special flag indicating a vehicle is inside a depot.
Definition track_type.h:30
Base for the train class.
@ Reversed
Used for vehicle var 0xFE bit 8 (toggled each time the train is reversed, accurate for first vehicle ...
Definition train.h:31
@ LeavingStation
Train is just leaving a station.
Definition train.h:33
@ Reversing
Train is slowing down to reverse.
Definition train.h:26
@ Flipped
Reverse the visible direction of the vehicle.
Definition train.h:28
@ TFP_NONE
Normal operation.
Definition train.h:40
static constexpr ConsistChangeFlags CCF_ARRANGE
Valid changes for arranging the consist in a depot.
Definition train.h:57
Command definitions related to trains.
bool IsTransparencySet(TransparencyOption to)
Check if the transparency option bit is set and if we aren't in the game menu (there's never transpar...
bool IsInvisibilitySet(TransparencyOption to)
Check if the invisibility option bit is set and if we aren't in the game menu (there's never transpar...
TransparencyOption
Transparency option bits: which position in _transparency_opt stands for which transparency.
@ Invalid
Invalid transparency option.
uint16_t UnitID
Type for the company global vehicle unit number.
Map accessors for tunnels.
bool IsTunnelTile(Tile t)
Is this a tunnel (entrance)?
Definition tunnel_map.h:34
void ShowNewGrfVehicleError(EngineID engine, StringID part1, StringID part2, GRFBug bug_type, bool critical)
Displays a "NewGrf Bug" error message for a engine, and pauses the game if not networking.
Definition vehicle.cpp:341
constexpr uint TILE_HASH_MASK
Definition vehicle.cpp:404
static uint GetTileHash(uint x, uint y)
Compute hash for tile coordinate.
Definition vehicle.cpp:451
static const uint GEN_HASHX_MASK
Definition vehicle.cpp:113
static const uint GEN_HASHY_MASK
Definition vehicle.cpp:114
static void VehicleEnteredDepotThisTick(Vehicle *v)
Adds a vehicle to the list of vehicles that visited a depot this tick.
Definition vehicle.cpp:925
static void SpawnAdvancedVisualEffect(const Vehicle *v)
Call CBID_VEHICLE_SPAWN_VISUAL_EFFECT and spawn requested effects.
Definition vehicle.cpp:2753
constexpr uint TOTAL_TILE_HASH_SIZE
Definition vehicle.cpp:405
static const uint GEN_HASHY_INC
Definition vehicle.cpp:108
static uint GetTileHash1D(uint p)
Compute hash for 1D tile coordinate.
Definition vehicle.cpp:419
void VehicleLengthChanged(const Vehicle *u)
Logs a bug in GRF and shows a warning message if this is for the first time this happened.
Definition vehicle.cpp:367
static constexpr DirectionIndexArray< int8_t > _vehicle_smoke_pos
Vehicle smoke effect position offsets.
Definition vehicle.cpp:2745
static const uint GEN_HASHY_BITS
Definition vehicle.cpp:74
VehiclePool _vehicle_pool("Vehicle")
The pool with all our precious vehicles.
void VehicleServiceInDepot(Vehicle *v)
Service a vehicle and all subsequent vehicles in the consist.
Definition vehicle.cpp:190
static const IntervalTimer< TimerGameEconomy > _economy_vehicles_yearly({TimerGameEconomy::Trigger::Year, TimerGameEconomy::Priority::Vehicle}, [](auto) { for(Vehicle *v :Vehicle::Iterate()) { if(v->IsPrimaryVehicle()) { Money profit=v->GetDisplayProfitThisYear();if(v->economy_age >=VEHICLE_PROFIT_MIN_AGE &&profit< 0) { if(_settings_client.gui.vehicle_income_warn &&v->owner==_local_company) { AddVehicleAdviceNewsItem(AdviceType::VehicleUnprofitable, GetEncodedString(TimerGameEconomy::UsingWallclockUnits() ? STR_NEWS_VEHICLE_UNPROFITABLE_PERIOD :STR_NEWS_VEHICLE_UNPROFITABLE_YEAR, v->index, profit), v->index);} AI::NewEvent(v->owner, new ScriptEventVehicleUnprofitable(v->index));} v->profit_last_year=v->profit_this_year;v->profit_this_year=0;SetWindowDirty(WindowClass::VehicleDetails, v->index);} } GroupStatistics::UpdateProfits();SetWindowClassesDirty(WindowClass::TrainList);SetWindowClassesDirty(WindowClass::ShipList);SetWindowClassesDirty(WindowClass::RoadVehicleList);SetWindowClassesDirty(WindowClass::AircraftList);})
Yearly callback for vehicles.
static const uint GEN_HASHY_BUCKET_BITS
Definition vehicle.cpp:80
static void RunEconomyVehicleDayProc()
Increases the day counter for all vehicles and calls 1-day and 32-day handlers.
Definition vehicle.cpp:958
constexpr uint TILE_HASH_SIZE
Definition vehicle.cpp:403
static const uint GEN_HASHY_SIZE
Definition vehicle.cpp:102
constexpr uint TILE_HASH_BITS
Definition vehicle.cpp:402
static uint ComposeTileHash(uint hx, uint hy)
Compose two 1D hashes into 2D hash.
Definition vehicle.cpp:440
static constexpr DiagDirectionIndexArray< TrackIndexArray< VehicleSubcoordData > > _vehicle_subcoord
Table of subtile coordinates and direction for each combination of chosen track and tile enter direct...
Definition vehicle.cpp:3373
static const uint GEN_HASHX_BUCKET_BITS
Definition vehicle.cpp:79
VisualEffectSpawnModel
Models for spawning visual effects.
Definition vehicle.cpp:2825
@ Steam
Steam model.
Definition vehicle.cpp:2827
@ None
No visual effect.
Definition vehicle.cpp:2826
@ Diesel
Diesel model.
Definition vehicle.cpp:2828
@ Electric
Electric model.
Definition vehicle.cpp:2829
static uint IncTileHash1D(uint h)
Increment 1D hash to next bucket.
Definition vehicle.cpp:429
bool CanVehicleUseStation(EngineID engine_type, const Station *st)
Can this station be used by the given engine type?
Definition vehicle.cpp:3117
static const uint GEN_HASHX_BITS
Definition vehicle.cpp:73
Vehicle * CheckClickOnVehicle(const Viewport &vp, int x, int y)
Find the vehicle close to the clicked coordinates.
Definition vehicle.cpp:1246
static const uint GEN_HASHX_INC
Definition vehicle.cpp:107
static const uint GEN_HASHX_SIZE
Definition vehicle.cpp:101
std::map< VehicleID, bool > AutoreplaceMap
List of vehicles that should check for autoreplace this tick.
Definition vehicle.cpp:699
static bool IsBridgeAboveVehicle(const Vehicle *v)
Test if a bridge is above a vehicle.
Definition vehicle.cpp:2812
constexpr uint TILE_HASH_RES
Resolution of the hash, 0 = 1*1 tile, 1 = 2*2 tiles, 2 = 4*4 tiles, etc.
Definition vehicle.cpp:412
static bool PreviousOrderIsUnbunching(const Vehicle *v)
Check if the previous order is a depot unbunching order.
Definition vehicle.cpp:2523
static void DoDrawVehicle(const Vehicle *v)
Add vehicle sprite for drawing to the screen.
Definition vehicle.cpp:1123
@ Crashed
Vehicle is crashed.
@ Shadow
Vehicle is a shadow vehicle.
@ AircraftBroken
Aircraft is broken down.
@ Hidden
Vehicle is not visible.
@ DefaultPalette
Use default vehicle palette.
@ Stopped
Vehicle is stopped by the player.
Pool< Vehicle, VehicleID, 512 > VehiclePool
A vehicle pool for a little over 1 million vehicles.
static const int32_t INVALID_COORD
Sentinel for an invalid coordinate.
Command definitions for vehicles.
Functions related to vehicles.
void ShowNewGrfVehicleError(EngineID engine, StringID part1, StringID part2, GRFBug bug_type, bool critical)
Displays a "NewGrf Bug" error message for a engine, and pauses the game if not networking.
Definition vehicle.cpp:341
CommandCost EnsureNoVehicleOnGround(TileIndex tile)
Ensure there is no vehicle at the ground at the given position.
Definition vehicle.cpp:561
bool VehiclesHaveSameEngineList(const Vehicle *v1, const Vehicle *v2)
Checks if two vehicle chains have the same list of engines.
Definition vehicle.cpp:3331
bool VehiclesHaveSameOrderList(const Vehicle *v1, const Vehicle *v2)
Checks if two vehicles have the same list of orders.
Definition vehicle.cpp:3348
SpriteID GetEnginePalette(EngineID engine_type, CompanyID company)
Get the colour map for an engine.
Definition vehicle.cpp:2171
void VehicleEnterDepot(Vehicle *v)
Vehicle entirely entered the depot, update its status, orders, vehicle windows, service it,...
Definition vehicle.cpp:1566
static const TimerGameEconomy::Date VEHICLE_PROFIT_MIN_AGE
Only vehicles older than this have a meaningful profit.
void GetVehicleSet(VehicleSet &set, Vehicle *v, uint8_t num_vehicles)
Calculates the set of vehicles that will be affected by a given selection.
Definition vehicle.cpp:3277
UnitID GetFreeUnitNumber(VehicleType type)
Get an unused unit number for a vehicle (if allowed).
Definition vehicle.cpp:1924
void RunVehicleCalendarDayProc()
Age all vehicles, spreading out the action using the current TimerGameCalendar::date_fract.
Definition vehicle.cpp:941
bool VehiclesHaveSameSharedOrderList(const Vehicle *v1, const Vehicle *v2)
Checks if two vehicles have the same shared list of orders.
Definition vehicle.cpp:3359
void VehicleServiceInDepot(Vehicle *v)
Service a vehicle and all subsequent vehicles in the consist.
Definition vehicle.cpp:190
CommandCost EnsureNoTrainOnTrackBits(TileIndex tile, TrackBits track_bits)
Tests if a vehicle interacts with the specified track bits.
Definition vehicle.cpp:609
LiveryScheme GetEngineLiveryScheme(EngineID engine_type, EngineID parent_engine_type, const Vehicle *v)
Determines the LiveryScheme for a vehicle.
Definition vehicle.cpp:2000
void CheckVehicleBreakdown(Vehicle *v)
Periodic check for a vehicle to maybe break down.
Definition vehicle.cpp:1322
void ViewportAddVehicles(DrawPixelInfo *dpi)
Add the vehicle sprites that should be drawn at a part of the screen.
Definition vehicle.cpp:1152
GetNewVehiclePosResult GetNewVehiclePos(const Vehicle *v)
Get position information of a vehicle when moving one pixel in the direction it is facing.
Definition vehicle.cpp:1806
StringID GetVehicleCannotUseStationReason(const Vehicle *v, const Station *st)
Get reason string why this station can't be used by the given vehicle.
Definition vehicle.cpp:3163
void ReleaseDisasterVehicle(VehicleID vehicle)
Notify disasters that we are about to delete a vehicle.
void DecreaseVehicleValue(Vehicle *v)
Decrease the value of a vehicle.
Definition vehicle.cpp:1301
void EconomyAgeVehicle(Vehicle *v)
Update economy age of a vehicle.
Definition vehicle.cpp:1444
const struct Livery * GetEngineLivery(EngineID engine_type, CompanyID company, EngineID parent_engine_type, const Vehicle *v, uint8_t livery_setting)
Determines the livery for a vehicle.
Definition vehicle.cpp:2094
CommandCost TunnelBridgeIsFree(TileIndex tile, TileIndex endtile, const Vehicle *ignore=nullptr)
Finds vehicle in tunnel / bridge.
Definition vehicle.cpp:585
void AgeVehicle(Vehicle *v)
Update age of a vehicle.
Definition vehicle.cpp:1456
Direction VehicleEnterTileCoordinates(GetNewVehiclePosResult &gp, DiagDirection enterdir, Track track)
Lookup new subposition coordinates and direction to use when entering a new tile, applying the subcoo...
Definition vehicle.cpp:3415
SpriteID GetVehiclePalette(const Vehicle *v)
Get the colour map for a vehicle.
Definition vehicle.cpp:2181
uint8_t CalcPercentVehicleFilled(const Vehicle *v, StringID *colour)
Calculates how full a vehicle is.
Definition vehicle.cpp:1507
bool IsCompanyBuildableVehicleType(VehicleType type)
Is the given vehicle type buildable by a company?
bool CanBuildVehicleInfrastructure(VehicleType type, RoadTramType subtype=RoadTramType::Invalid)
Check whether we can build infrastructure for the given vehicle type.
Definition vehicle.cpp:1952
Functions related to the vehicle's GUIs.
@ VIWD_MODIFY_ORDERS
Other order modifications.
Definition vehicle_gui.h:35
WindowClass GetWindowClassForVehicleType(VehicleType vt)
Get WindowClass for vehicle list of given vehicle type.
Definition vehicle_gui.h:96
EnumBitSet< DepotCommandFlag, uint8_t > DepotCommandFlags
Bitset of DepotCommandFlag elements.
@ OnMap
Vehicle drawn in viewport.
PoolID< uint32_t, struct VehicleIDTag, 0xFF000, 0xFFFFF > VehicleID
The type all our vehicle IDs have.
VehicleType
Available vehicle types.
@ Ship
Ship vehicle type.
@ Effect
Effect vehicle type (smoke, explosions, sparks, bubbles).
@ Aircraft
Aircraft vehicle type.
@ Road
Road vehicle type.
@ Disaster
Disaster vehicle type.
@ Train
Train vehicle type.
@ Callback32
All vehicles in consist: 32 day callback requested rerandomisation.
@ Depot
Front vehicle only: Consist arrived in depot.
@ DontCancel
Don't cancel current goto depot command if any.
@ Service
The vehicle will leave the depot right after arrival (service only).
EnumBitSet< GroundVehicleFlag, uint16_t > GroundVehicleFlags
Bitset of GroundVehicleFlag elements.
EnumIndexArray< T, VehicleType, Tend > VehicleTypeIndexArray
Array with VehicleType as index.
@ SuppressImplicitOrders
Disable insertion and removal of automatic orders until the vehicle completes the real order.
static const uint VEHICLE_LENGTH
The length of a vehicle in tile units.
@ WID_VV_START_STOP
Start or stop this vehicle, and show information about the current state.
Functions and type for generating vehicle lists.
@ VehicleSharedOrders
Index is the first vehicle of the shared orders.
Definition vehiclelist.h:24
void StartSpriteCombine()
Starts a block of sprites, which are "combined" into a single bounding box.
Definition viewport.cpp:766
void AddSortableSpriteToDraw(SpriteID image, PaletteID pal, int x, int y, int z, const SpriteBounds &bounds, bool transparent, const SubSprite *sub)
Draw a (transparent) sprite at given coordinates with a given bounding box.
Definition viewport.cpp:665
void EndSpriteCombine()
Terminates a block of sprites started by StartSpriteCombine.
Definition viewport.cpp:776
Functions related to (drawing on) viewports.
void CloseWindowById(WindowClass cls, WindowNumber number, bool force, int data)
Close a window by its class and window number (if it is open).
Definition window.cpp:1242
void SetWindowClassesDirty(WindowClass cls)
Mark all windows of a particular class as dirty (in need of repainting).
Definition window.cpp:3285
void InvalidateWindowData(WindowClass cls, WindowNumber number, int data, bool gui_scope)
Mark window data of the window of a given class and specific window number as invalid (in need of re-...
Definition window.cpp:3377
void SetWindowWidgetDirty(WindowClass cls, WindowNumber number, WidgetID widget_index)
Mark a particular widget in a particular window as dirty (in need of repainting).
Definition window.cpp:3271
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting).
Definition window.cpp:3255
void InvalidateWindowClassesData(WindowClass cls, int data, bool gui_scope)
Mark window data of all windows of a given class as invalid (in need of re-computing) Note that by de...
Definition window.cpp:3395
@ Station
station encountered (could be a target next time)
Definition yapf_type.hpp:26
Functions related to zooming.
int ScaleByZoom(int value, ZoomLevel zoom)
Scale by zoom level, usually shift left (when zoom > ZoomLevel::Min) When shifting right,...
Definition zoom_func.h:22