Make it possible to stop road vehicles from slowing down in curves so "diagonal"...
[openttd-joker.git] / src / vehicle_base.h
blob9eab80de8b516278c3000bf94336090bb9b089a0
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8 */
10 /** @file vehicle_base.h Base class for all vehicles. */
12 #ifndef VEHICLE_BASE_H
13 #define VEHICLE_BASE_H
15 #include "core/smallmap_type.hpp"
16 #include "track_type.h"
17 #include "command_type.h"
18 #include "order_base.h"
19 #include "triphistory.h"
20 #include "cargopacket.h"
21 #include "texteff.hpp"
22 #include "engine_type.h"
23 #include "order_func.h"
24 #include "transport_type.h"
25 #include "group_type.h"
26 #include "base_consist.h"
27 #include "settings_type.h"
28 #include "network/network.h"
29 #include <vector>
30 #include <list>
31 #include <map>
33 CommandCost CmdRefitVehicle(TileIndex, DoCommandFlag, uint32, uint32, const char*);
35 /** Vehicle status bits in #Vehicle::vehstatus. */
36 enum VehStatus {
37 VS_HIDDEN = 0x01, ///< Vehicle is not visible.
38 VS_STOPPED = 0x02, ///< Vehicle is stopped by the player.
39 VS_UNCLICKABLE = 0x04, ///< Vehicle is not clickable by the user (shadow vehicles).
40 VS_DEFPAL = 0x08, ///< Use default vehicle palette. @see DoDrawVehicle
41 VS_TRAIN_SLOWING = 0x10, ///< Train is slowing down.
42 VS_SHADOW = 0x20, ///< Vehicle is a shadow vehicle.
43 VS_AIRCRAFT_BROKEN = 0x40, ///< Aircraft is broken down.
44 VS_CRASHED = 0x80, ///< Vehicle is crashed.
47 /** Bit numbers in #Vehicle::vehicle_flags. */
48 enum VehicleFlags {
49 VF_LOADING_FINISHED, ///< Vehicle has finished loading.
50 VF_CARGO_UNLOADING, ///< Vehicle is unloading cargo.
51 VF_BUILT_AS_PROTOTYPE, ///< Vehicle is a prototype (accepted as exclusive preview).
52 VF_TIMETABLE_STARTED, ///< Whether the vehicle has started running on the timetable yet.
53 VF_AUTOMATE_TIMETABLE, ///< Whether the vehicle should fill and update in the timetable automatically.
54 VF_AUTOMATE_PRES_WAIT_TIME, ///< Whether non-destructive automate should preserve waiting times
55 VF_STOP_LOADING, ///< Don't load anymore during the next load cycle.
56 VF_PATHFINDER_LOST, ///< Vehicle's pathfinder is lost.
57 VF_SERVINT_IS_CUSTOM, ///< Service interval is custom.
58 VF_SERVINT_IS_PERCENT, ///< Service interval is percent.
59 VF_SHOULD_GOTO_DEPOT, ///< Vehicle was manually ordered to go to a depot on its orders list.
60 VF_SHOULD_SERVICE_AT_DEPOT, ///< Vehicle was manually ordered to service at a depot on its orders list.
62 VF_LAST_LOAD_ST_SEP = 13, ///< Each vehicle of this chain has its last_loading_station field set separately
63 VF_SEPARATION_IN_PROGRESS, ///< The late counter should be ignored since it was set by the vehicle separation
66 /** Bit numbers used to indicate which of the #NewGRFCache values are valid. */
67 enum NewGRFCacheValidValues {
68 NCVV_POSITION_CONSIST_LENGTH = 0, ///< This bit will be set if the NewGRF var 40 currently stored is valid.
69 NCVV_POSITION_SAME_ID_LENGTH = 1, ///< This bit will be set if the NewGRF var 41 currently stored is valid.
70 NCVV_CONSIST_CARGO_INFORMATION = 2, ///< This bit will be set if the NewGRF var 42 currently stored is valid.
71 NCVV_COMPANY_INFORMATION = 3, ///< This bit will be set if the NewGRF var 43 currently stored is valid.
72 NCVV_POSITION_IN_VEHICLE = 4, ///< This bit will be set if the NewGRF var 4D currently stored is valid.
73 NCVV_END, ///< End of the bits.
76 /** Cached often queried (NewGRF) values */
77 struct NewGRFCache {
78 /* Values calculated when they are requested for the first time after invalidating the NewGRF cache. */
79 uint32 position_consist_length; ///< Cache for NewGRF var 40.
80 uint32 position_same_id_length; ///< Cache for NewGRF var 41.
81 uint32 consist_cargo_information; ///< Cache for NewGRF var 42. (Note: The cargotype is untranslated in the cache because the accessing GRF is yet unknown.)
82 uint32 company_information; ///< Cache for NewGRF var 43.
83 uint32 position_in_vehicle; ///< Cache for NewGRF var 4D.
84 uint8 cache_valid; ///< Bitset that indicates which cache values are valid.
87 /** Meaning of the various bits of the visual effect. */
88 enum VisualEffect {
89 VE_OFFSET_START = 0, ///< First bit that contains the offset (0 = front, 8 = centre, 15 = rear)
90 VE_OFFSET_COUNT = 4, ///< Number of bits used for the offset
91 VE_OFFSET_CENTRE = 8, ///< Value of offset corresponding to a position above the centre of the vehicle
93 VE_TYPE_START = 4, ///< First bit used for the type of effect
94 VE_TYPE_COUNT = 2, ///< Number of bits used for the effect type
95 VE_TYPE_DEFAULT = 0, ///< Use default from engine class
96 VE_TYPE_STEAM = 1, ///< Steam plumes
97 VE_TYPE_DIESEL = 2, ///< Diesel fumes
98 VE_TYPE_ELECTRIC = 3, ///< Electric sparks
100 VE_DISABLE_EFFECT = 6, ///< Flag to disable visual effect
101 VE_ADVANCED_EFFECT = VE_DISABLE_EFFECT, ///< Flag for advanced effects
102 VE_DISABLE_WAGON_POWER = 7, ///< Flag to disable wagon power
104 VE_DEFAULT = 0xFF, ///< Default value to indicate that visual effect should be based on engine class
107 /** Models for spawning visual effects. */
108 enum VisualEffectSpawnModel {
109 VESM_NONE = 0, ///< No visual effect
110 VESM_STEAM, ///< Steam model
111 VESM_DIESEL, ///< Diesel model
112 VESM_ELECTRIC, ///< Electric model
114 VESM_END
118 * Enum to handle ground vehicle subtypes.
119 * This is defined here instead of at #GroundVehicle because some common function require access to these flags.
120 * Do not access it directly unless you have to. Use the subtype access functions.
122 enum GroundVehicleSubtypeFlags {
123 GVSF_FRONT = 0, ///< Leading engine of a consist.
124 GVSF_ARTICULATED_PART = 1, ///< Articulated part of an engine.
125 GVSF_WAGON = 2, ///< Wagon (not used for road vehicles).
126 GVSF_ENGINE = 3, ///< Engine that can be front engine, but might be placed behind another engine (not used for road vehicles).
127 GVSF_FREE_WAGON = 4, ///< First in a wagon chain (in depot) (not used for road vehicles).
128 GVSF_MULTIHEADED = 5, ///< Engine is multiheaded (not used for road vehicles).
129 GVSF_VIRTUAL = 6, ///< Used for virtual trains during template design, it is needed to skip checks for tile or depot status
132 /** Cached often queried values common to all vehicles. */
133 struct VehicleCache {
134 uint16 cached_max_speed; ///< Maximum speed of the consist (minimum of the max speed of all vehicles in the consist).
135 uint16 cached_cargo_age_period; ///< Number of ticks before carried cargo is aged.
137 byte cached_vis_effect; ///< Visual effect to show (see #VisualEffect)
140 /** Sprite sequence for a vehicle part. */
141 struct VehicleSpriteSeq {
142 PalSpriteID seq[4];
143 uint count;
145 bool operator==(const VehicleSpriteSeq &other) const
147 return this->count == other.count && MemCmpT<PalSpriteID>(this->seq, other.seq, this->count) == 0;
150 bool operator!=(const VehicleSpriteSeq &other) const
152 return !this->operator==(other);
156 * Check whether the sequence contains any sprites.
158 bool IsValid() const
160 return this->count != 0;
164 * Clear all information.
166 void Clear()
168 this->count = 0;
172 * Assign a single sprite to the sequence.
174 void Set(SpriteID sprite)
176 this->count = 1;
177 this->seq[0].sprite = sprite;
178 this->seq[0].pal = 0;
182 * Copy data from another sprite sequence, while dropping all recolouring information.
184 void CopyWithoutPalette(const VehicleSpriteSeq &src)
186 this->count = src.count;
187 for (uint i = 0; i < src.count; ++i) {
188 this->seq[i].sprite = src.seq[i].sprite;
189 this->seq[i].pal = 0;
193 Rect16 GetBounds() const;
194 void Draw(int x, int y, PaletteID default_pal, bool force_pal) const;
197 /** A vehicle pool for a little over 1 million vehicles. */
198 typedef Pool<Vehicle, VehicleID, 512, 0xFF000> VehiclePool;
199 extern VehiclePool _vehicle_pool;
201 /* Some declarations of functions, so we can make them friendly */
202 struct SaveLoad;
203 struct GroundVehicleCache;
204 extern const SaveLoad *GetVehicleDescription(VehicleType vt);
205 struct LoadgameState;
206 extern bool LoadOldVehicle(LoadgameState *ls, int num);
207 extern void FixOldVehicles();
209 struct GRFFile;
211 /** %Vehicle data structure. */
212 struct Vehicle : VehiclePool::PoolItem<&_vehicle_pool>, BaseVehicle, BaseConsist {
213 private:
214 typedef std::map<CargoID, uint> CapacitiesMap;
216 Vehicle *next; ///< pointer to the next vehicle in the chain
217 Vehicle *previous; ///< NOSAVE: pointer to the previous vehicle in the chain
218 Vehicle *first; ///< NOSAVE: pointer to the first vehicle in the chain
220 Vehicle *next_shared; ///< pointer to the next vehicle that shares the order
221 Vehicle *previous_shared; ///< NOSAVE: pointer to the previous vehicle in the shared order chain
223 Vehicle *ahead_separation; ///< (outdated. Only for backwards compatibility)
224 Vehicle *behind_separation; ///< (outdated. Only for backwards compatibility)
226 union {
227 OrderList *list; ///< Pointer to the order list for this vehicle
228 Order *old; ///< Only used during conversion of old save games
229 } orders; ///< The orders currently assigned to the vehicle.
231 public:
232 friend const SaveLoad *GetVehicleDescription(VehicleType vt); ///< So we can use private/protected variables in the saveload code
233 friend void FixOldVehicles();
234 friend void AfterLoadVehicles(bool part_of_load); ///< So we can set the #previous and #first pointers while loading
235 friend bool LoadOldVehicle(LoadgameState *ls, int num); ///< So we can set the proper next pointer while loading
237 TileIndex tile; ///< Current tile index
240 * Heading for this tile.
241 * For airports and train stations this tile does not necessarily belong to the destination station,
242 * but it can be used for heuristic purposes to estimate the distance.
244 TileIndex dest_tile;
246 Money profit_this_year; ///< Profit this year << 8, low 8 bits are fract
247 Money profit_last_year; ///< Profit last year << 8, low 8 bits are fract
248 Money profit_lifetime; ///< Profit lifetime << 8, low 8 bits are fract
249 Money value; ///< Value of the vehicle
251 TripHistory trip_history; ///< Trip History Info
253 CargoPayment *cargo_payment; ///< The cargo payment we're currently in
255 Rect coord; ///< NOSAVE: Graphical bounding box of the vehicle, i.e. what to redraw on moves.
257 Vehicle *hash_viewport_next; ///< NOSAVE: Next vehicle in the visual location hash.
258 Vehicle **hash_viewport_prev; ///< NOSAVE: Previous vehicle in the visual location hash.
260 Vehicle *hash_tile_next; ///< NOSAVE: Next vehicle in the tile location hash.
261 Vehicle **hash_tile_prev; ///< NOSAVE: Previous vehicle in the tile location hash.
262 Vehicle **hash_tile_current; ///< NOSAVE: Cache of the current hash chain.
264 SpriteID colourmap; ///< NOSAVE: cached colour mapping
266 /* Related to age and service time */
267 Year build_year; ///< Year the vehicle has been built.
268 Date age; ///< Age in days
269 Date max_age; ///< Maximum age
270 Date date_of_last_service; ///< Last date the vehicle had a service at a depot.
271 uint16 reliability; ///< Reliability.
272 uint16 reliability_spd_dec; ///< Reliability decrease speed.
273 byte breakdown_ctr; ///< Counter for managing breakdown events. @see Vehicle::HandleBreakdown
274 byte breakdown_delay; ///< Counter for managing breakdown length.
275 byte breakdowns_since_last_service; ///< Counter for the amount of breakdowns.
276 byte breakdown_chance; ///< Current chance of breakdowns.
278 int32 x_pos; ///< x coordinate.
279 int32 y_pos; ///< y coordinate.
280 int32 z_pos; ///< z coordinate.
281 DirectionByte direction; ///< facing
283 OwnerByte owner; ///< Which company owns the vehicle?
285 * currently displayed sprite index
286 * 0xfd == custom sprite, 0xfe == custom second head sprite
287 * 0xff == reserved for another custom sprite
289 byte spritenum;
290 VehicleSpriteSeq sprite_seq; ///< Vehicle appearance.
291 Rect16 sprite_seq_bounds;
292 byte x_extent; ///< x-extent of vehicle bounding box
293 byte y_extent; ///< y-extent of vehicle bounding box
294 byte z_extent; ///< z-extent of vehicle bounding box
295 int8 x_bb_offs; ///< x offset of vehicle bounding box
296 int8 y_bb_offs; ///< y offset of vehicle bounding box
297 int8 x_offs; ///< x offset for vehicle sprite
298 int8 y_offs; ///< y offset for vehicle sprite
299 EngineID engine_type; ///< The type of engine used for this vehicle.
301 TextEffectID fill_percent_te_id; ///< a text-effect id to a loading indicator object
302 UnitID unitnumber; ///< unit number, for display purposes only
304 uint16 cur_speed; ///< current speed
305 byte subspeed; ///< fractional speed
306 byte acceleration; ///< used by train & aircraft
307 uint32 motion_counter; ///< counter to occasionally play a vehicle sound.
308 byte progress; ///< The percentage (if divided by 256) this vehicle already crossed the tile unit.
310 byte random_bits; ///< Bits used for determining which randomized variational spritegroups to use when drawing.
311 byte waiting_triggers; ///< Triggers to be yet matched before rerandomizing the random bits.
313 StationID last_station_visited; ///< The last station we stopped at.
314 StationID last_loading_station; ///< Last station the vehicle has stopped at and could possibly leave from with any cargo loaded. (See VF_LAST_LOAD_ST_SEP).
316 CargoID cargo_type; ///< type of cargo this vehicle is carrying
317 byte cargo_subtype; ///< Used for livery refits (NewGRF variations)
318 uint16 cargo_cap; ///< total capacity
319 uint16 refit_cap; ///< Capacity left over from before last refit.
320 VehicleCargoList cargo; ///< The cargo this vehicle is carrying
321 uint16 cargo_age_counter; ///< Ticks till cargo is aged next.
322 std::vector<int8> station_occupancies; ///< Occupancies of vehicle at each station (set after leaving a station).
324 byte day_counter; ///< Increased by one for each day
325 byte tick_counter; ///< Increased by one for each tick
326 uint16 running_ticks; ///< Number of ticks this vehicle was not stopped this day
328 byte vehstatus; ///< Status
329 Order current_order; ///< The current order (+ status, like: loading)
331 uint16 load_unload_ticks; ///< Ticks to wait before starting next cycle.
332 GroupID group_id; ///< Index of group Pool array
333 byte subtype; ///< subtype (Filled with values from #EffectVehicles/#TrainSubTypes/#AircraftSubTypes)
335 NewGRFCache grf_cache; ///< Cache of often used calculated NewGRF values
336 VehicleCache vcache; ///< Cache of often used vehicle values.
338 Vehicle(VehicleType type = VEH_INVALID);
340 void PreDestructor();
341 /** We want to 'destruct' the right class. */
342 virtual ~Vehicle();
344 uint32 GetLastLoadingStationValidCargoMask() const;
346 void BeginLoading();
347 void CancelReservation(StationID next, Station *st);
348 void LeaveStation();
350 void HandleAutomaticTimetableSeparation();
352 GroundVehicleCache *GetGroundVehicleCache();
353 const GroundVehicleCache *GetGroundVehicleCache() const;
355 uint16 &GetGroundVehicleFlags();
356 const uint16 &GetGroundVehicleFlags() const;
358 void DeleteUnreachedImplicitOrders();
360 void HandleLoading(bool mode = false);
362 void HandleWaiting(bool stop_waiting = false);
365 * Marks the vehicles to be redrawn and updates cached variables
367 * This method marks the area of the vehicle on the screen as dirty.
368 * It can be use to repaint the vehicle.
370 * @ingroup dirty
372 virtual void MarkDirty() {}
375 * Updates the x and y offsets and the size of the sprite used
376 * for this vehicle.
377 * @param direction the direction the vehicle is facing
379 virtual void UpdateDeltaXY(Direction direction) {}
382 * Determines the effective direction-specific vehicle movement speed.
384 * This method belongs to the old vehicle movement method:
385 * A vehicle moves a step every 256 progress units.
386 * The vehicle speed is scaled by 3/4 when moving in X or Y direction due to the longer distance.
388 * However, this method is slightly wrong in corners, as the leftover progress is not scaled correctly
389 * when changing movement direction. #GetAdvanceSpeed() and #GetAdvanceDistance() are better wrt. this.
391 * @param speed Direction-independent unscaled speed.
392 * @return speed scaled by movement direction. 256 units are required for each movement step.
394 inline uint GetOldAdvanceSpeed(uint speed)
396 return (this->direction & 1) ? speed : speed * 3 / 4;
400 * Determines the effective vehicle movement speed.
402 * Together with #GetAdvanceDistance() this function is a replacement for #GetOldAdvanceSpeed().
404 * A vehicle progresses independent of it's movement direction.
405 * However different amounts of "progress" are needed for moving a step in a specific direction.
406 * That way the leftover progress does not need any adaption when changing movement direction.
408 * @param speed Direction-independent unscaled speed.
409 * @return speed, scaled to match #GetAdvanceDistance().
411 static inline uint GetAdvanceSpeed(uint speed)
413 return speed * 3 / 4;
417 * Determines the vehicle "progress" needed for moving a step.
419 * Together with #GetAdvanceSpeed() this function is a replacement for #GetOldAdvanceSpeed().
421 * @return distance to drive for a movement step on the map.
423 inline uint GetAdvanceDistance()
425 return (this->direction & 1) ? 192 : 256;
429 * Sets the expense type associated to this vehicle type
430 * @param income whether this is income or (running) expenses of the vehicle
432 virtual ExpensesType GetExpenseType(bool income) const { return EXPENSES_OTHER; }
435 * Play the sound associated with leaving the station
437 virtual void PlayLeaveStationSound() const {}
440 * Whether this is the primary vehicle in the chain.
442 virtual bool IsPrimaryVehicle() const { return false; }
444 const Engine *GetEngine() const;
447 * Gets the sprite to show for the given direction
448 * @param direction the direction the vehicle is facing
449 * @param [out] result Vehicle sprite sequence.
451 virtual void GetImage(Direction direction, EngineImageType image_type, VehicleSpriteSeq *result) const { result->Clear(); }
453 const GRFFile *GetGRF() const;
454 uint32 GetGRFID() const;
457 * Invalidates cached NewGRF variables
458 * @see InvalidateNewGRFCacheOfChain
460 inline void InvalidateNewGRFCache()
462 this->grf_cache.cache_valid = 0;
466 * Invalidates cached NewGRF variables of all vehicles in the chain (after the current vehicle)
467 * @see InvalidateNewGRFCache
469 inline void InvalidateNewGRFCacheOfChain()
471 for (Vehicle *u = this; u != nullptr; u = u->Next()) {
472 u->InvalidateNewGRFCache();
477 * Check if the vehicle is a ground vehicle.
478 * @return True iff the vehicle is a train or a road vehicle.
480 inline bool IsGroundVehicle() const
482 return this->type == VEH_TRAIN || this->type == VEH_ROAD;
486 * Gets the speed in km-ish/h that can be sent into SetDParam for string processing.
487 * @return the vehicle's speed
489 virtual int GetDisplaySpeed() const { return 0; }
492 * Gets the maximum speed in km-ish/h that can be sent into SetDParam for string processing.
493 * @return the vehicle's maximum speed
495 virtual int GetDisplayMaxSpeed() const { return 0; }
498 * Calculates the maximum speed of the vehicle under its current conditions.
499 * @return Current maximum speed in native units.
501 virtual int GetCurrentMaxSpeed() const { return 0; }
504 * Gets the running cost of a vehicle
505 * @return the vehicle's running cost
507 virtual Money GetRunningCost() const { return 0; }
510 * Check whether the vehicle is in the depot.
511 * @return true if and only if the vehicle is in the depot.
513 virtual bool IsInDepot() const { return false; }
516 * Check whether the whole vehicle chain is in the depot.
517 * @return true if and only if the whole chain is in the depot.
519 virtual bool IsChainInDepot() const { return this->IsInDepot(); }
522 * Check whether the vehicle is in the depot *and* stopped.
523 * @return true if and only if the vehicle is in the depot and stopped.
525 bool IsStoppedInDepot() const
527 assert(this == this->First());
528 /* Free wagons have no VS_STOPPED state */
529 if (this->IsPrimaryVehicle() && !(this->vehstatus & VS_STOPPED)) return false;
530 return this->IsChainInDepot();
534 * Calls the tick handler of the vehicle
535 * @return is this vehicle still valid?
537 virtual bool Tick() { return true; };
540 * Calls the new day handler of the vehicle
542 virtual void OnNewDay() {};
545 * Crash the (whole) vehicle chain.
546 * @param flooded whether the cause of the crash is flooding or not.
547 * @return the number of lost souls.
549 virtual uint Crash(bool flooded = false);
552 * Returns the Trackdir on which the vehicle is currently located.
553 * Works for trains and ships.
554 * Currently works only sortof for road vehicles, since they have a fuzzy
555 * concept of being "on" a trackdir. Dunno really what it returns for a road
556 * vehicle that is halfway a tile, never really understood that part. For road
557 * vehicles that are at the beginning or end of the tile, should just return
558 * the diagonal trackdir on which they are driving. I _think_.
559 * For other vehicles types, or vehicles with no clear trackdir (such as those
560 * in depots), returns 0xFF.
561 * @return the trackdir of the vehicle
563 virtual Trackdir GetVehicleTrackdir() const { return INVALID_TRACKDIR; }
566 * Gets the running cost of a vehicle that can be sent into SetDParam for string processing.
567 * @return the vehicle's running cost
569 Money GetDisplayRunningCost() const { return (this->GetRunningCost() >> 8) * _settings_game.economy.daylength; }
572 * Gets the profit vehicle had this year. It can be sent into SetDParam for string processing.
573 * @return the vehicle's profit this year
575 Money GetDisplayProfitThisYear() const { return (this->profit_this_year >> 8); }
578 * Gets the profit vehicle had last year. It can be sent into SetDParam for string processing.
579 * @return the vehicle's profit last year
581 Money GetDisplayProfitLastYear() const { return (this->profit_last_year >> 8); }
584 * Gets the lifetime profit of vehicle. It can be sent into SetDParam for string processing.
585 * @return the vehicle's lifetime profit
587 Money GetDisplayProfitLifetime() const { return ((this->profit_lifetime + this->profit_this_year) >> 8); }
589 void SetNext(Vehicle *next);
590 inline void SetFirst(Vehicle *f) { this->first=f; }
593 * Get the next vehicle of this vehicle.
594 * @note articulated parts are also counted as vehicles.
595 * @return the next vehicle or nullptr when there isn't a next vehicle.
597 inline Vehicle *Next() const { return this->next; }
600 * Get the previous vehicle of this vehicle.
601 * @note articulated parts are also counted as vehicles.
602 * @return the previous vehicle or nullptr when there isn't a previous vehicle.
604 inline Vehicle *Previous() const { return this->previous; }
607 * Get the first vehicle of this vehicle chain.
608 * @return the first vehicle of the chain.
610 inline Vehicle *First() const { return this->first; }
613 * Get the last vehicle of this vehicle chain.
614 * @return the last vehicle of the chain.
616 inline Vehicle *Last()
618 Vehicle *v = this;
619 while (v->Next() != nullptr) v = v->Next();
620 return v;
624 * Get the last vehicle of this vehicle chain.
625 * @return the last vehicle of the chain.
627 inline const Vehicle *Last() const
629 const Vehicle *v = this;
630 while (v->Next() != nullptr) v = v->Next();
631 return v;
635 * Get the vehicle at offset \a n of this vehicle chain.
636 * @param n Offset from the current vehicle.
637 * @return The new vehicle or nullptr if the offset is out-of-bounds.
639 inline Vehicle *Move(int n)
641 Vehicle *v = this;
642 if (n < 0) {
643 for (int i = 0; i != n && v != nullptr; i--) v = v->Previous();
644 } else {
645 for (int i = 0; i != n && v != nullptr; i++) v = v->Next();
647 return v;
651 * Get the vehicle at offset \a n of this vehicle chain.
652 * @param n Offset from the current vehicle.
653 * @return The new vehicle or nullptr if the offset is out-of-bounds.
655 inline const Vehicle *Move(int n) const
657 const Vehicle *v = this;
658 if (n < 0) {
659 for (int i = 0; i != n && v != nullptr; i--) v = v->Previous();
660 } else {
661 for (int i = 0; i != n && v != nullptr; i++) v = v->Next();
663 return v;
667 * Get the first order of the vehicles order list.
668 * @return first order of order list.
670 inline Order *GetFirstOrder() const { return (this->orders.list == nullptr) ? nullptr : this->orders.list->GetFirstOrder(); }
672 void AddToShared(Vehicle *shared_chain);
673 void RemoveFromShared();
676 * Get the next vehicle of the shared vehicle chain.
677 * @return the next shared vehicle or nullptr when there isn't a next vehicle.
679 inline Vehicle *NextShared() const { return this->next_shared; }
682 * Get the previous vehicle of the shared vehicle chain
683 * @return the previous shared vehicle or nullptr when there isn't a previous vehicle.
685 inline Vehicle *PreviousShared() const { return this->previous_shared; }
688 * Get the first vehicle of this vehicle chain.
689 * @return the first vehicle of the chain.
691 inline Vehicle *FirstShared() const { return (this->orders.list == nullptr) ? this->First() : this->orders.list->GetFirstSharedVehicle(); }
694 * Check if we have an orders list.
695 * @return true if we have an orders list.
697 inline bool HasOrdersList() const { return this->orders.list != nullptr; }
700 * Check if we share our orders with another vehicle.
701 * @return true if there are other vehicles sharing the same order
703 inline bool HasSharedOrdersList() const { return this->orders.list != nullptr && this->orders.list->IsShared(); }
706 * Get the number of orders this vehicle has.
707 * @return the number of orders this vehicle has.
709 inline VehicleOrderID GetNumOrders() const { return (this->orders.list == nullptr) ? 0 : this->orders.list->GetNumOrders(); }
712 * Get the number of manually added orders this vehicle has.
713 * @return the number of manually added orders this vehicle has.
715 inline VehicleOrderID GetNumManualOrders() const { return (this->orders.list == nullptr) ? 0 : this->orders.list->GetNumManualOrders(); }
718 * Get the next station the vehicle will stop at.
719 * @return ID of the next station the vehicle will stop at or INVALID_STATION.
721 inline CargoStationIDStackSet GetNextStoppingStation() const
723 CargoStationIDStackSet set;
724 if (this->orders.list != nullptr) set.FillNextStoppingStation(this, this->orders.list);
725 return set;
728 void ResetRefitCaps();
731 * Copy certain configurations and statistics of a vehicle after successful autoreplace/renew
732 * The function shall copy everything that cannot be copied by a command (like orders / group etc),
733 * and that shall not be resetted for the new vehicle.
734 * @param src The old vehicle
736 inline void CopyVehicleConfigAndStatistics(const Vehicle *src)
738 this->CopyConsistPropertiesFrom(src);
740 this->unitnumber = src->unitnumber;
742 this->current_order = src->current_order;
743 this->dest_tile = src->dest_tile;
745 this->profit_this_year = src->profit_this_year;
746 this->profit_last_year = src->profit_last_year;
747 this->profit_lifetime = -this->profit_this_year;
751 bool HandleBreakdown();
753 bool NeedsAutorenewing(const Company *c, bool use_renew_setting = true) const;
755 bool NeedsServicing() const;
756 bool NeedsAutomaticServicing() const;
759 * Determine the location for the station where the vehicle goes to next.
760 * Things done for example are allocating slots in a road stop or exact
761 * location of the platform is determined for ships.
762 * @param station the station to make the next location of the vehicle.
763 * @return the location (tile) to aim for.
765 virtual TileIndex GetOrderStationLocation(StationID station) { return INVALID_TILE; }
768 * Find the closest depot for this vehicle and tell us the location,
769 * DestinationID and whether we should reverse.
770 * @param location where do we go to?
771 * @param destination what hangar do we go to?
772 * @param reverse should the vehicle be reversed?
773 * @return true if a depot could be found.
775 virtual bool FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse) { return false; }
777 CommandCost SendToDepot(DoCommandFlag flags, DepotCommand command);
779 void UpdateVisualEffect(bool allow_power_change = true);
780 void ShowVisualEffect() const;
782 void UpdatePosition();
783 void UpdateViewport(bool dirty);
784 void UpdatePositionAndViewport();
785 void MarkAllViewportsDirty() const;
787 inline uint16 GetServiceInterval() const { return this->service_interval; }
789 inline void SetServiceInterval(uint16 interval) { this->service_interval = interval; }
791 inline bool ServiceIntervalIsCustom() const { return HasBit(this->vehicle_flags, VF_SERVINT_IS_CUSTOM); }
793 inline bool ServiceIntervalIsPercent() const { return HasBit(this->vehicle_flags, VF_SERVINT_IS_PERCENT); }
795 inline void SetServiceIntervalIsCustom(bool on) { SB(this->vehicle_flags, VF_SERVINT_IS_CUSTOM, 1, on); }
797 inline void SetServiceIntervalIsPercent(bool on) { SB(this->vehicle_flags, VF_SERVINT_IS_PERCENT, 1, on); }
799 private:
801 * Advance cur_real_order_index to the next real order.
802 * cur_implicit_order_index is not touched.
804 void SkipToNextRealOrderIndex()
806 if (this->GetNumManualOrders() > 0) {
807 /* Advance to next real order */
808 do {
809 this->cur_real_order_index++;
810 if (this->cur_real_order_index >= this->GetNumOrders()) this->cur_real_order_index = 0;
811 } while (this->GetOrder(this->cur_real_order_index)->IsType(OT_IMPLICIT));
812 this->cur_timetable_order_index = this->cur_real_order_index;
813 } else {
814 this->cur_real_order_index = 0;
815 this->cur_timetable_order_index = INVALID_VEH_ORDER_ID;
819 public:
821 * Increments cur_implicit_order_index, keeps care of the wrap-around and invalidates the GUI.
822 * cur_real_order_index is incremented as well, if needed.
823 * Note: current_order is not invalidated.
825 void IncrementImplicitOrderIndex()
827 if (this->cur_implicit_order_index == this->cur_real_order_index) {
828 /* Increment real order index as well */
829 this->SkipToNextRealOrderIndex();
832 assert(this->cur_real_order_index == 0 || this->cur_real_order_index < this->GetNumOrders());
834 /* Advance to next implicit order */
835 do {
836 this->cur_implicit_order_index++;
837 if (this->cur_implicit_order_index >= this->GetNumOrders()) this->cur_implicit_order_index = 0;
838 } while (this->cur_implicit_order_index != this->cur_real_order_index && !this->GetOrder(this->cur_implicit_order_index)->IsType(OT_IMPLICIT));
840 InvalidateVehicleOrder(this, 0);
844 * Advanced cur_real_order_index to the next real order, keeps care of the wrap-around and invalidates the GUI.
845 * cur_implicit_order_index is incremented as well, if it was equal to cur_real_order_index, i.e. cur_real_order_index is skipped
846 * but not any implicit orders.
847 * Note: current_order is not invalidated.
849 void IncrementRealOrderIndex()
851 if (this->cur_implicit_order_index == this->cur_real_order_index) {
852 /* Increment both real and implicit order */
853 this->IncrementImplicitOrderIndex();
854 } else {
855 /* Increment real order only */
856 this->SkipToNextRealOrderIndex();
857 InvalidateVehicleOrder(this, 0);
862 * Skip implicit orders until cur_real_order_index is a non-implicit order.
864 void UpdateRealOrderIndex()
866 /* Make sure the index is valid */
867 if (this->cur_real_order_index >= this->GetNumOrders()) this->cur_real_order_index = 0;
869 if (this->GetNumManualOrders() > 0) {
870 /* Advance to next real order */
871 while (this->GetOrder(this->cur_real_order_index)->IsType(OT_IMPLICIT)) {
872 this->cur_real_order_index++;
873 if (this->cur_real_order_index >= this->GetNumOrders()) this->cur_real_order_index = 0;
875 } else {
876 this->cur_real_order_index = 0;
881 * Returns order 'index' of a vehicle or nullptr when it doesn't exists
882 * @param index the order to fetch
883 * @return the found (or not) order
885 Order* GetOrder(int index) const
887 return (this->orders.list == nullptr) ? nullptr : this->orders.list->GetOrderAt(index);
891 * Get the index of an order of the order chain, or INVALID_VEH_ORDER_ID.
892 * @param order order to get the index of.
893 * @return the position index of the given order, or INVALID_VEH_ORDER_ID.
895 inline VehicleOrderID GetIndexOfOrder(const Order *order) const
897 return (this->orders.list == nullptr) ? INVALID_VEH_ORDER_ID : this->orders.list->GetIndexOfOrder(order);
901 * Returns the last order of a vehicle, or nullptr if it doesn't exists
902 * @return last order of a vehicle, if available
904 inline Order *GetLastOrder() const
906 return (this->orders.list == nullptr) ? nullptr : this->orders.list->GetLastOrder();
910 * Get the order after the given one or the first one, if the given one is the
911 * last one.
912 * @param curr Order to find the next one for.
913 * @return Next order or nullptr if there are no orders.
915 inline const Order *GetNextOrder(const Order *curr) const
917 return (this->orders.list == nullptr) ? nullptr : this->orders.list->GetNext(curr);
921 * Gets the known duration of the vehicles orders, timetabled or not.
922 * @return known order duration.
924 inline Ticks GetTotalOrderListDuration() const
926 return (this->orders.list == nullptr) ? 0 : this->orders.list->GetTotalDuration();
930 * Gets the known duration of the vehicles timetable even if the timetable is not complete.
931 * @return known timetable duration
933 inline Ticks GetTimetableDurationIncomplete() const
935 return (this->orders.list == nullptr) ? 0 : this->orders.list->GetTimetableDurationIncomplete();
939 * Gets the total duration of the vehicles timetable or INVALID_TICKS is the timetable is not complete.
940 * @return total timetable duration or INVALID_TICKS for incomplete timetables
942 inline Ticks GetTimetableTotalDuration() const
944 return (this->orders.list == nullptr) ? INVALID_TICKS : this->orders.list->GetTimetableTotalDuration();
948 * Checks whether all orders of the orders list have a filled timetable.
949 * @return whether all orders have a filled timetable.
951 inline bool HasCompleteTimetable() const
953 return (this->orders.list != nullptr) && this->orders.list->IsCompleteTimetable();
957 * Gets whether the timetable separation is currently valid or not.
958 * @return whether the timetable separation is currently valid or not.
960 inline bool IsTimetableSeparationValid() const
962 return (this->orders.list != nullptr) && this->orders.list->IsSeparationValid();
966 * Gets whether timetable separation is currently switched on or not.
967 * @return whether the timetable separation is currently switched on or not.
969 inline bool IsTimetableSeparationOn() const
971 return (this->orders.list != nullptr) && this->orders.list->IsSeparationOn();
975 * Must be called if an order's timetable is changed to update internal book keeping.
976 * @param delta By how many ticks has the timetable duration changed
978 inline void UpdateTimetableDuration(Ticks delta)
980 assert(this->orders.list != nullptr);
982 this->orders.list->UpdateTimetableDuration(delta);
986 * Must be called if an order's timetable is changed to update internal book keeping.
987 * @param delta By how many ticks has the total duration changed
989 inline void UpdateTotalDuration(Ticks delta)
991 assert(this->orders.list != nullptr);
993 this->orders.list->UpdateTotalDuration(delta);
997 * Delete all orders from this vehicle
998 * @param keep_orderlist If true, do not free the order list, only empty it.
999 * @param reset_order_indices If true, reset cur_implicit_order_index and cur_real_order_index
1000 * and cancel the current full load order (if the vehicle is loading).
1001 * If false, _you_ have to make sure the order indices are valid after
1002 * your messing with them!
1004 void DeleteVehicleOrders(bool keep_orderlist = false, bool reset_order_indices = true)
1006 DeleteOrderWarnings(this);
1008 if (this->HasSharedOrdersList()) {
1009 /* Remove ourself from the shared order list. */
1010 this->RemoveFromShared();
1011 this->orders.list = nullptr;
1013 else if (this->orders.list != nullptr) {
1014 /* Remove the orders */
1015 this->FreeOrderChain(keep_orderlist);
1016 if (!keep_orderlist) this->orders.list = nullptr;
1019 if (reset_order_indices) {
1020 this->cur_implicit_order_index = this->cur_real_order_index = 0;
1021 this->cur_timetable_order_index = INVALID_VEH_ORDER_ID;
1022 if (this->current_order.IsType(OT_LOADING)) {
1023 CancelLoadingDueToDeletedOrder(this);
1029 * Free the complete order chain.
1030 * @param keep_orderlist If this is true only delete the orders, otherwise also delete the OrderList.
1032 inline void FreeOrderChain(bool keep_orderlist = false)
1034 assert(this->orders.list != nullptr);
1036 this->orders.list->FreeChain(keep_orderlist);
1037 this->orders.list = nullptr;
1041 * Sets the orders list to the specified value.
1043 inline void SetOrdersList(OrderList* orders_list)
1045 this->orders.list = orders_list;
1049 * Sets the orders list to the specified value and deletes the old list.
1051 inline void DeleteAndReplaceOrdersList(OrderList* orders_list)
1053 delete this->orders.list;
1055 assert(OrderList::CanAllocateItem());
1057 this->orders.list = orders_list;
1061 * Checks for internal consistency of order list. Triggers assertion if something is wrong.
1063 inline void DebugCheckSanity() const
1065 if (this->orders.list == nullptr) return;
1067 this->orders.list->DebugCheckSanity();
1071 * Returns the current timetable separation settings.
1072 * @return the current timetable separation settings or default settings if there are no orders.
1074 inline TTSepSettings GetTimetableSeparationSettings() const
1076 return (this->orders.list == nullptr) ? TTSepSettings() : this->orders.list->GetSepSettings();
1080 * Prepares command to set new separation settings.
1081 * @param s Contains the new settings to be used for separation.
1083 inline void SetTimetableSeparationSettings(TTSepSettings settings) const
1085 assert(this->orders.list != nullptr);
1087 this->orders.list->SetSepSettings(settings);
1091 * Get the next order which will make the given vehicle stop at a station
1092 * or refit at a depot or evaluate a non-trivial condition.
1093 * @param next The order to start looking at.
1094 * @param hops The number of orders we have already looked at.
1095 * @param cargo_mask The bit set of cargoes that the we are looking at, this may be reduced to indicate the set of cargoes that the result is valid for.
1096 * @return Either of
1097 * \li a station order
1098 * \li a refitting depot order
1099 * \li a non-trivial conditional order
1100 * \li nullptr if the vehicle won't stop anymore or there is no orders list.
1102 inline const Order* GetNextDecisionNode(const Order *next, uint hops, uint32 &cargo_mask) const
1104 return (this->orders.list == nullptr) ? nullptr : this->orders.list->GetNextDecisionNode(next, hops, cargo_mask);
1108 * Checks whether the orders list is identical to the specified one. Only used for sanity checks.
1109 * @return whether the orders list is identical to the specified one.
1111 inline bool HasSpecificOrderList(const OrderList* order_list) const
1113 return this->orders.list == order_list;
1117 * Insert a new order into the order chain.
1118 * @param new_order is the order to insert into the chain.
1119 * @param index is the position where the order is supposed to be inserted.
1121 inline void InsertOrderAt(Order *new_order, int index)
1123 assert(this->orders.list != nullptr);
1125 this->orders.list->InsertOrderAt(new_order, index);
1129 * Remove an order from the order list and delete it.
1130 * @param index is the position of the order which is to be deleted.
1132 inline void DeleteOrderAt(int index)
1134 assert(this->orders.list != nullptr);
1136 this->orders.list->DeleteOrderAt(index);
1140 * Move an order to another position within the order list.
1141 * @param from is the zero-based position of the order to move.
1142 * @param to is the zero-based position where the order is moved to.
1144 inline void MoveOrder(int from, int to)
1146 assert(this->orders.list != nullptr);
1148 this->orders.list->MoveOrder(from, to);
1152 * Shares the orders list of the specified vehicle
1154 inline void ShareOrdersWith(const Vehicle* vehicle)
1156 assert(vehicle != nullptr);
1158 this->orders.list = vehicle->orders.list;
1162 * Checks whether this vehicle has the same orders list as the specified one.
1163 * @return whether this vehicle has the same orders list as the specified one.
1165 inline bool IsSharingOrdersWith(const Vehicle* vehicle) const
1167 assert(vehicle != nullptr);
1169 return this->orders.list == vehicle->orders.list;
1172 bool IsEngineCountable() const;
1173 bool HasEngineType() const;
1174 bool HasDepotOrder() const;
1175 void HandlePathfindingResult(bool path_found);
1176 void MarkSeparationInvalid();
1177 void SetSepSettings(TTSepMode Mode, uint Parameter);
1180 * Check if the vehicle is a front engine.
1181 * @return Returns true if the vehicle is a front engine.
1183 inline bool IsFrontEngine() const
1185 return this->IsGroundVehicle() && HasBit(this->subtype, GVSF_FRONT);
1189 * Check if the vehicle is an articulated part of an engine.
1190 * @return Returns true if the vehicle is an articulated part.
1192 inline bool IsArticulatedPart() const
1194 return this->IsGroundVehicle() && HasBit(this->subtype, GVSF_ARTICULATED_PART);
1198 * Check if an engine has an articulated part.
1199 * @return True if the engine has an articulated part.
1201 inline bool HasArticulatedPart() const
1203 return this->Next() != nullptr && this->Next()->IsArticulatedPart();
1207 * Get the next part of an articulated engine.
1208 * @return Next part of the articulated engine.
1209 * @pre The vehicle is an articulated engine.
1211 inline Vehicle *GetNextArticulatedPart() const
1213 assert(this->HasArticulatedPart());
1214 return this->Next();
1218 * Get the first part of an articulated engine.
1219 * @return First part of the engine.
1221 inline Vehicle *GetFirstEnginePart()
1223 Vehicle *v = this;
1224 while (v->IsArticulatedPart()) v = v->Previous();
1225 return v;
1229 * Get the first part of an articulated engine.
1230 * @return First part of the engine.
1232 inline const Vehicle *GetFirstEnginePart() const
1234 const Vehicle *v = this;
1235 while (v->IsArticulatedPart()) v = v->Previous();
1236 return v;
1240 * Get the last part of an articulated engine.
1241 * @return Last part of the engine.
1243 inline Vehicle *GetLastEnginePart()
1245 Vehicle *v = this;
1246 while (v->HasArticulatedPart()) v = v->GetNextArticulatedPart();
1247 return v;
1251 * Get the next real (non-articulated part) vehicle in the consist.
1252 * @return Next vehicle in the consist.
1254 inline Vehicle *GetNextVehicle() const
1256 const Vehicle *v = this;
1257 while (v->HasArticulatedPart()) v = v->GetNextArticulatedPart();
1259 /* v now contains the last articulated part in the engine */
1260 return v->Next();
1264 * Get the previous real (non-articulated part) vehicle in the consist.
1265 * @return Previous vehicle in the consist.
1267 inline Vehicle *GetPrevVehicle() const
1269 Vehicle *v = this->Previous();
1270 while (v != nullptr && v->IsArticulatedPart()) v = v->Previous();
1272 return v;
1275 bool IsDrawn() const;
1277 inline void UpdateSpriteSeqBound()
1279 this->sprite_seq_bounds = this->sprite_seq.GetBounds();
1284 * Iterate over all vehicles from a given point.
1285 * @param var The variable used to iterate over.
1286 * @param start The vehicle to start the iteration at.
1288 #define FOR_ALL_VEHICLES_FROM(var, start) FOR_ALL_ITEMS_FROM(Vehicle, vehicle_index, var, start)
1291 * Iterate over all vehicles.
1292 * @param var The variable used to iterate over.
1294 #define FOR_ALL_VEHICLES(var) FOR_ALL_VEHICLES_FROM(var, 0)
1297 * Class defining several overloaded accessors so we don't
1298 * have to cast vehicle types that often
1300 template <class T, VehicleType Type>
1301 struct SpecializedVehicle : public Vehicle {
1302 static const VehicleType EXPECTED_TYPE = Type; ///< Specialized type
1304 typedef SpecializedVehicle<T, Type> SpecializedVehicleBase; ///< Our type
1307 * Set vehicle type correctly
1309 inline SpecializedVehicle<T, Type>() : Vehicle(Type)
1311 this->sprite_seq.count = 1;
1315 * Get the first vehicle in the chain
1316 * @return first vehicle in the chain
1318 inline T *First() const { return (T *)this->Vehicle::First(); }
1321 * Get the last vehicle in the chain
1322 * @return last vehicle in the chain
1324 inline T *Last() { return (T *)this->Vehicle::Last(); }
1327 * Get the last vehicle in the chain
1328 * @return last vehicle in the chain
1330 inline const T *Last() const { return (const T *)this->Vehicle::Last(); }
1333 * Get next vehicle in the chain
1334 * @return next vehicle in the chain
1336 inline T *Next() const { return (T *)this->Vehicle::Next(); }
1339 * Get previous vehicle in the chain
1340 * @return previous vehicle in the chain
1342 inline T *Previous() const { return (T *)this->Vehicle::Previous(); }
1345 * Get the next part of an articulated engine.
1346 * @return Next part of the articulated engine.
1347 * @pre The vehicle is an articulated engine.
1349 inline T *GetNextArticulatedPart() { return (T *)this->Vehicle::GetNextArticulatedPart(); }
1352 * Get the next part of an articulated engine.
1353 * @return Next part of the articulated engine.
1354 * @pre The vehicle is an articulated engine.
1356 inline T *GetNextArticulatedPart() const { return (T *)this->Vehicle::GetNextArticulatedPart(); }
1359 * Get the first part of an articulated engine.
1360 * @return First part of the engine.
1362 inline T *GetFirstEnginePart() { return (T *)this->Vehicle::GetFirstEnginePart(); }
1365 * Get the first part of an articulated engine.
1366 * @return First part of the engine.
1368 inline const T *GetFirstEnginePart() const { return (const T *)this->Vehicle::GetFirstEnginePart(); }
1371 * Get the last part of an articulated engine.
1372 * @return Last part of the engine.
1374 inline T *GetLastEnginePart() { return (T *)this->Vehicle::GetLastEnginePart(); }
1377 * Get the next real (non-articulated part) vehicle in the consist.
1378 * @return Next vehicle in the consist.
1380 inline T *GetNextVehicle() const { return (T *)this->Vehicle::GetNextVehicle(); }
1383 * Get the previous real (non-articulated part) vehicle in the consist.
1384 * @return Previous vehicle in the consist.
1386 inline T *GetPrevVehicle() const { return (T *)this->Vehicle::GetPrevVehicle(); }
1389 * Tests whether given index is a valid index for vehicle of this type
1390 * @param index tested index
1391 * @return is this index valid index of T?
1393 static inline bool IsValidID(size_t index)
1395 return Vehicle::IsValidID(index) && Vehicle::Get(index)->type == Type;
1399 * Gets vehicle with given index
1400 * @return pointer to vehicle with given index casted to T *
1402 static inline T *Get(size_t index)
1404 return (T *)Vehicle::Get(index);
1408 * Returns vehicle if the index is a valid index for this vehicle type
1409 * @return pointer to vehicle with given index if it's a vehicle of this type
1411 static inline T *GetIfValid(size_t index)
1413 return IsValidID(index) ? Get(index) : nullptr;
1417 * Converts a Vehicle to SpecializedVehicle with type checking.
1418 * @param v Vehicle pointer
1419 * @return pointer to SpecializedVehicle
1421 static inline T *From(Vehicle *v)
1423 assert(v->type == Type);
1424 return dynamic_cast<T*>(v);
1428 * Converts a const Vehicle to const SpecializedVehicle with type checking.
1429 * @param v Vehicle pointer
1430 * @return pointer to SpecializedVehicle
1432 static inline const T *From(const Vehicle *v)
1434 assert(v->type == Type);
1435 return (const T *)v;
1439 * Update vehicle sprite- and position caches
1440 * @param force_update Force updating the vehicle on the viewport.
1441 * @param update_delta Also update the delta?
1443 inline void UpdateViewport(bool force_update, bool update_delta)
1445 /* Skip updating sprites on dedicated servers without screen */
1446 if (_network_dedicated) return;
1448 /* Explicitly choose method to call to prevent vtable dereference -
1449 * it gives ~3% runtime improvements in games with many vehicles */
1450 if (update_delta) ((T *)this)->T::UpdateDeltaXY(this->direction);
1451 VehicleSpriteSeq seq;
1452 ((T *)this)->T::GetImage(this->direction, EIT_ON_MAP, &seq);
1453 if (force_update || this->sprite_seq != seq) {
1454 this->sprite_seq = seq;
1455 this->UpdateSpriteSeqBound();
1456 this->Vehicle::UpdateViewport(true);
1462 * Iterate over all vehicles of a particular type.
1463 * @param name The type of vehicle to iterate over.
1464 * @param var The variable used to iterate over.
1466 #define FOR_ALL_VEHICLES_OF_TYPE(name, var) \
1467 for (size_t vehicle_index = 0; var = nullptr, vehicle_index < name::GetPoolSize(); vehicle_index++) \
1468 if ((var = name::GetIfValid(vehicle_index)) != nullptr)
1470 /** Generates sequence of free UnitID numbers */
1471 struct FreeUnitIDGenerator {
1472 bool *cache; ///< array of occupied unit id numbers
1473 UnitID maxid; ///< maximum ID at the moment of constructor call
1474 UnitID curid; ///< last ID returned; 0 if none
1476 FreeUnitIDGenerator(VehicleType type, CompanyID owner);
1477 UnitID NextID();
1479 /** Releases allocated memory */
1480 ~FreeUnitIDGenerator() { free(this->cache); }
1483 /** Sentinel for an invalid coordinate. */
1484 static const int32 INVALID_COORD = 0x7fffffff;
1486 #endif /* VEHICLE_BASE_H */