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/>.
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"
33 CommandCost
CmdRefitVehicle(TileIndex
, DoCommandFlag
, uint32
, uint32
, const char*);
35 /** Vehicle status bits in #Vehicle::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. */
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 */
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. */
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
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
{
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.
160 return this->count
!= 0;
164 * Clear all information.
172 * Assign a single sprite to the sequence.
174 void Set(SpriteID sprite
)
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 */
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();
211 /** %Vehicle data structure. */
212 struct Vehicle
: VehiclePool::PoolItem
<&_vehicle_pool
>, BaseVehicle
, BaseConsist
{
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)
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.
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.
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
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. */
344 uint32
GetLastLoadingStationValidCargoMask() const;
347 void CancelReservation(StationID next
, Station
*st
);
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.
372 virtual void MarkDirty() {}
375 * Updates the x and y offsets and the size of the sprite used
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
!= NULL
; 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 NULL 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 NULL 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()
619 while (v
->Next() != NULL
) v
= v
->Next();
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() != NULL
) v
= v
->Next();
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 NULL if the offset is out-of-bounds.
639 inline Vehicle
*Move(int n
)
643 for (int i
= 0; i
!= n
&& v
!= NULL
; i
--) v
= v
->Previous();
645 for (int i
= 0; i
!= n
&& v
!= NULL
; i
++) v
= v
->Next();
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 NULL if the offset is out-of-bounds.
655 inline const Vehicle
*Move(int n
) const
657 const Vehicle
*v
= this;
659 for (int i
= 0; i
!= n
&& v
!= NULL
; i
--) v
= v
->Previous();
661 for (int i
= 0; i
!= n
&& v
!= NULL
; i
++) v
= v
->Next();
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
== NULL
) ? NULL
: 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 NULL 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 NULL 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
== NULL
) ? 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
!= NULL
; }
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
!= NULL
&& 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
== NULL
) ? 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
== NULL
) ? 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
!= NULL
) set
.FillNextStoppingStation(this, this->orders
.list
);
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
); }
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 */
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
;
814 this->cur_real_order_index
= 0;
815 this->cur_timetable_order_index
= INVALID_VEH_ORDER_ID
;
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 */
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();
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;
876 this->cur_real_order_index
= 0;
881 * Returns order 'index' of a vehicle or NULL when it doesn't exists
882 * @param index the order to fetch
883 * @return the found (or not) order
885 inline Order
*GetOrder(int index
) const
887 return (this->orders
.list
== NULL
) ? NULL
: 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 NULL if it doesn't exists
902 * @return last order of a vehicle, if available
904 inline Order
*GetLastOrder() const
906 return (this->orders
.list
== NULL
) ? NULL
: this->orders
.list
->GetLastOrder();
910 * Get a certain order of the order chain.
911 * @param index zero-based index of the order within the chain.
912 * @return the order at position index or null if there are no orders.
914 Order
* GetOrderAt(int index
) const
916 return (this->orders
.list
== nullptr) ? nullptr : this->orders
.list
->GetOrderAt(index
);
920 * Get the order after the given one or the first one, if the given one is the
922 * @param curr Order to find the next one for.
923 * @return Next order or nullptr if there are no orders.
925 inline const Order
*GetNextOrder(const Order
*curr
) const
927 return (this->orders
.list
== nullptr) ? nullptr : this->orders
.list
->GetNext(curr
);
931 * Gets the known duration of the vehicles orders, timetabled or not.
932 * @return known order duration.
934 inline Ticks
GetTotalOrderListDuration() const
936 return (this->orders
.list
== nullptr) ? 0 : this->orders
.list
->GetTotalDuration();
940 * Gets the known duration of the vehicles timetable even if the timetable is not complete.
941 * @return known timetable duration
943 inline Ticks
GetTimetableDurationIncomplete() const
945 return (this->orders
.list
== nullptr) ? 0 : this->orders
.list
->GetTimetableDurationIncomplete();
949 * Gets the total duration of the vehicles timetable or INVALID_TICKS is the timetable is not complete.
950 * @return total timetable duration or INVALID_TICKS for incomplete timetables
952 inline Ticks
GetTimetableTotalDuration() const
954 return (this->orders
.list
== nullptr) ? INVALID_TICKS
: this->orders
.list
->GetTimetableTotalDuration();
958 * Checks whether all orders of the orders list have a filled timetable.
959 * @return whether all orders have a filled timetable.
961 inline bool HasCompleteTimetable() const
963 return (this->orders
.list
!= nullptr) && this->orders
.list
->IsCompleteTimetable();
967 * Gets whether the timetable separation is currently valid or not.
968 * @return whether the timetable separation is currently valid or not.
970 inline bool IsTimetableSeparationValid() const
972 return (this->orders
.list
!= nullptr) && this->orders
.list
->IsSeparationValid();
976 * Gets whether timetable separation is currently switched on or not.
977 * @return whether the timetable separation is currently switched on or not.
979 inline bool IsTimetableSeparationOn() const
981 return (this->orders
.list
!= nullptr) && this->orders
.list
->IsSeparationOn();
985 * Must be called if an order's timetable is changed to update internal book keeping.
986 * @param delta By how many ticks has the timetable duration changed
988 inline void UpdateTimetableDuration(Ticks delta
)
990 assert(this->orders
.list
!= nullptr);
992 this->orders
.list
->UpdateTimetableDuration(delta
);
996 * Must be called if an order's timetable is changed to update internal book keeping.
997 * @param delta By how many ticks has the total duration changed
999 inline void UpdateTotalDuration(Ticks delta
)
1001 assert(this->orders
.list
!= nullptr);
1003 this->orders
.list
->UpdateTotalDuration(delta
);
1007 * Delete all orders from this vehicle
1008 * @param keep_orderlist If true, do not free the order list, only empty it.
1009 * @param reset_order_indices If true, reset cur_implicit_order_index and cur_real_order_index
1010 * and cancel the current full load order (if the vehicle is loading).
1011 * If false, _you_ have to make sure the order indices are valid after
1012 * your messing with them!
1014 void DeleteVehicleOrders(bool keep_orderlist
= false, bool reset_order_indices
= true)
1016 DeleteOrderWarnings(this);
1018 if (this->HasSharedOrdersList()) {
1019 /* Remove ourself from the shared order list. */
1020 this->RemoveFromShared();
1021 this->orders
.list
= nullptr;
1023 else if (this->orders
.list
!= nullptr) {
1024 /* Remove the orders */
1025 this->FreeOrderChain(keep_orderlist
);
1026 if (!keep_orderlist
) this->orders
.list
= nullptr;
1029 if (reset_order_indices
) {
1030 this->cur_implicit_order_index
= this->cur_real_order_index
= 0;
1031 this->cur_timetable_order_index
= INVALID_VEH_ORDER_ID
;
1032 if (this->current_order
.IsType(OT_LOADING
)) {
1033 CancelLoadingDueToDeletedOrder(this);
1039 * Free the complete order chain.
1040 * @param keep_orderlist If this is true only delete the orders, otherwise also delete the OrderList.
1042 inline void FreeOrderChain(bool keep_orderlist
= false)
1044 assert(this->orders
.list
!= nullptr);
1046 this->orders
.list
->FreeChain(keep_orderlist
);
1047 this->orders
.list
= nullptr;
1051 * Sets the orders list to the specified value.
1053 inline void SetOrdersList(OrderList
* orders_list
)
1055 this->orders
.list
= orders_list
;
1059 * Sets the orders list to the specified value and deletes the old list.
1061 inline void DeleteAndReplaceOrdersList(OrderList
* orders_list
)
1063 delete this->orders
.list
;
1065 assert(OrderList::CanAllocateItem());
1067 this->orders
.list
= orders_list
;
1071 * Checks for internal consistency of order list. Triggers assertion if something is wrong.
1073 inline void DebugCheckSanity() const
1075 if (this->orders
.list
== nullptr) return;
1077 this->orders
.list
->DebugCheckSanity();
1081 * Returns the current timetable separation settings.
1082 * @return the current timetable separation settings or default settings if there are no orders.
1084 inline TTSepSettings
GetTimetableSeparationSettings() const
1086 return (this->orders
.list
== nullptr) ? TTSepSettings() : this->orders
.list
->GetSepSettings();
1090 * Prepares command to set new separation settings.
1091 * @param s Contains the new settings to be used for separation.
1093 inline void SetTimetableSeparationSettings(TTSepSettings settings
) const
1095 assert(this->orders
.list
!= nullptr);
1097 this->orders
.list
->SetSepSettings(settings
);
1101 * Get the next order which will make the given vehicle stop at a station
1102 * or refit at a depot or evaluate a non-trivial condition.
1103 * @param next The order to start looking at.
1104 * @param hops The number of orders we have already looked at.
1105 * @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.
1107 * \li a station order
1108 * \li a refitting depot order
1109 * \li a non-trivial conditional order
1110 * \li NULL if the vehicle won't stop anymore or there is no orders list.
1112 inline const Order
* GetNextDecisionNode(const Order
*next
, uint hops
, uint32
&cargo_mask
) const
1114 return (this->orders
.list
== nullptr) ? nullptr : this->orders
.list
->GetNextDecisionNode(next
, hops
, cargo_mask
);
1118 * Checks whether the orders list is identical to the specified one. Only used for sanity checks.
1119 * @return whether the orders list is identical to the specified one.
1121 inline bool HasSpecificOrderList(const OrderList
* order_list
) const
1123 return this->orders
.list
== order_list
;
1127 * Insert a new order into the order chain.
1128 * @param new_order is the order to insert into the chain.
1129 * @param index is the position where the order is supposed to be inserted.
1131 inline void InsertOrderAt(Order
*new_order
, int index
)
1133 assert(this->orders
.list
!= nullptr);
1135 this->orders
.list
->InsertOrderAt(new_order
, index
);
1139 * Remove an order from the order list and delete it.
1140 * @param index is the position of the order which is to be deleted.
1142 inline void DeleteOrderAt(int index
)
1144 assert(this->orders
.list
!= nullptr);
1146 this->orders
.list
->DeleteOrderAt(index
);
1150 * Move an order to another position within the order list.
1151 * @param from is the zero-based position of the order to move.
1152 * @param to is the zero-based position where the order is moved to.
1154 inline void MoveOrder(int from
, int to
)
1156 assert(this->orders
.list
!= nullptr);
1158 this->orders
.list
->MoveOrder(from
, to
);
1162 * Shares the orders list of the specified vehicle
1164 inline void ShareOrdersWith(const Vehicle
* vehicle
)
1166 assert(vehicle
!= nullptr);
1168 this->orders
.list
= vehicle
->orders
.list
;
1172 * Checks whether this vehicle has the same orders list as the specified one.
1173 * @return whether this vehicle has the same orders list as the specified one.
1175 inline bool IsSharingOrdersWith(const Vehicle
* vehicle
) const
1177 assert(vehicle
!= nullptr);
1179 return this->orders
.list
== vehicle
->orders
.list
;
1182 bool IsEngineCountable() const;
1183 bool HasEngineType() const;
1184 bool HasDepotOrder() const;
1185 void HandlePathfindingResult(bool path_found
);
1186 void MarkSeparationInvalid();
1187 void SetSepSettings(TTSepMode Mode
, uint Parameter
);
1190 * Check if the vehicle is a front engine.
1191 * @return Returns true if the vehicle is a front engine.
1193 inline bool IsFrontEngine() const
1195 return this->IsGroundVehicle() && HasBit(this->subtype
, GVSF_FRONT
);
1199 * Check if the vehicle is an articulated part of an engine.
1200 * @return Returns true if the vehicle is an articulated part.
1202 inline bool IsArticulatedPart() const
1204 return this->IsGroundVehicle() && HasBit(this->subtype
, GVSF_ARTICULATED_PART
);
1208 * Check if an engine has an articulated part.
1209 * @return True if the engine has an articulated part.
1211 inline bool HasArticulatedPart() const
1213 return this->Next() != NULL
&& this->Next()->IsArticulatedPart();
1217 * Get the next part of an articulated engine.
1218 * @return Next part of the articulated engine.
1219 * @pre The vehicle is an articulated engine.
1221 inline Vehicle
*GetNextArticulatedPart() const
1223 assert(this->HasArticulatedPart());
1224 return this->Next();
1228 * Get the first part of an articulated engine.
1229 * @return First part of the engine.
1231 inline Vehicle
*GetFirstEnginePart()
1234 while (v
->IsArticulatedPart()) v
= v
->Previous();
1239 * Get the first part of an articulated engine.
1240 * @return First part of the engine.
1242 inline const Vehicle
*GetFirstEnginePart() const
1244 const Vehicle
*v
= this;
1245 while (v
->IsArticulatedPart()) v
= v
->Previous();
1250 * Get the last part of an articulated engine.
1251 * @return Last part of the engine.
1253 inline Vehicle
*GetLastEnginePart()
1256 while (v
->HasArticulatedPart()) v
= v
->GetNextArticulatedPart();
1261 * Get the next real (non-articulated part) vehicle in the consist.
1262 * @return Next vehicle in the consist.
1264 inline Vehicle
*GetNextVehicle() const
1266 const Vehicle
*v
= this;
1267 while (v
->HasArticulatedPart()) v
= v
->GetNextArticulatedPart();
1269 /* v now contains the last articulated part in the engine */
1274 * Get the previous real (non-articulated part) vehicle in the consist.
1275 * @return Previous vehicle in the consist.
1277 inline Vehicle
*GetPrevVehicle() const
1279 Vehicle
*v
= this->Previous();
1280 while (v
!= NULL
&& v
->IsArticulatedPart()) v
= v
->Previous();
1285 bool IsDrawn() const;
1287 inline void UpdateSpriteSeqBound()
1289 this->sprite_seq_bounds
= this->sprite_seq
.GetBounds();
1294 * Iterate over all vehicles from a given point.
1295 * @param var The variable used to iterate over.
1296 * @param start The vehicle to start the iteration at.
1298 #define FOR_ALL_VEHICLES_FROM(var, start) FOR_ALL_ITEMS_FROM(Vehicle, vehicle_index, var, start)
1301 * Iterate over all vehicles.
1302 * @param var The variable used to iterate over.
1304 #define FOR_ALL_VEHICLES(var) FOR_ALL_VEHICLES_FROM(var, 0)
1307 * Class defining several overloaded accessors so we don't
1308 * have to cast vehicle types that often
1310 template <class T
, VehicleType Type
>
1311 struct SpecializedVehicle
: public Vehicle
{
1312 static const VehicleType EXPECTED_TYPE
= Type
; ///< Specialized type
1314 typedef SpecializedVehicle
<T
, Type
> SpecializedVehicleBase
; ///< Our type
1317 * Set vehicle type correctly
1319 inline SpecializedVehicle
<T
, Type
>() : Vehicle(Type
)
1321 this->sprite_seq
.count
= 1;
1325 * Get the first vehicle in the chain
1326 * @return first vehicle in the chain
1328 inline T
*First() const { return (T
*)this->Vehicle::First(); }
1331 * Get the last vehicle in the chain
1332 * @return last vehicle in the chain
1334 inline T
*Last() { return (T
*)this->Vehicle::Last(); }
1337 * Get the last vehicle in the chain
1338 * @return last vehicle in the chain
1340 inline const T
*Last() const { return (const T
*)this->Vehicle::Last(); }
1343 * Get next vehicle in the chain
1344 * @return next vehicle in the chain
1346 inline T
*Next() const { return (T
*)this->Vehicle::Next(); }
1349 * Get previous vehicle in the chain
1350 * @return previous vehicle in the chain
1352 inline T
*Previous() const { return (T
*)this->Vehicle::Previous(); }
1355 * Get the next part of an articulated engine.
1356 * @return Next part of the articulated engine.
1357 * @pre The vehicle is an articulated engine.
1359 inline T
*GetNextArticulatedPart() { return (T
*)this->Vehicle::GetNextArticulatedPart(); }
1362 * Get the next part of an articulated engine.
1363 * @return Next part of the articulated engine.
1364 * @pre The vehicle is an articulated engine.
1366 inline T
*GetNextArticulatedPart() const { return (T
*)this->Vehicle::GetNextArticulatedPart(); }
1369 * Get the first part of an articulated engine.
1370 * @return First part of the engine.
1372 inline T
*GetFirstEnginePart() { return (T
*)this->Vehicle::GetFirstEnginePart(); }
1375 * Get the first part of an articulated engine.
1376 * @return First part of the engine.
1378 inline const T
*GetFirstEnginePart() const { return (const T
*)this->Vehicle::GetFirstEnginePart(); }
1381 * Get the last part of an articulated engine.
1382 * @return Last part of the engine.
1384 inline T
*GetLastEnginePart() { return (T
*)this->Vehicle::GetLastEnginePart(); }
1387 * Get the next real (non-articulated part) vehicle in the consist.
1388 * @return Next vehicle in the consist.
1390 inline T
*GetNextVehicle() const { return (T
*)this->Vehicle::GetNextVehicle(); }
1393 * Get the previous real (non-articulated part) vehicle in the consist.
1394 * @return Previous vehicle in the consist.
1396 inline T
*GetPrevVehicle() const { return (T
*)this->Vehicle::GetPrevVehicle(); }
1399 * Tests whether given index is a valid index for vehicle of this type
1400 * @param index tested index
1401 * @return is this index valid index of T?
1403 static inline bool IsValidID(size_t index
)
1405 return Vehicle::IsValidID(index
) && Vehicle::Get(index
)->type
== Type
;
1409 * Gets vehicle with given index
1410 * @return pointer to vehicle with given index casted to T *
1412 static inline T
*Get(size_t index
)
1414 return (T
*)Vehicle::Get(index
);
1418 * Returns vehicle if the index is a valid index for this vehicle type
1419 * @return pointer to vehicle with given index if it's a vehicle of this type
1421 static inline T
*GetIfValid(size_t index
)
1423 return IsValidID(index
) ? Get(index
) : NULL
;
1427 * Converts a Vehicle to SpecializedVehicle with type checking.
1428 * @param v Vehicle pointer
1429 * @return pointer to SpecializedVehicle
1431 static inline T
*From(Vehicle
*v
)
1433 assert(v
->type
== Type
);
1438 * Converts a const Vehicle to const SpecializedVehicle with type checking.
1439 * @param v Vehicle pointer
1440 * @return pointer to SpecializedVehicle
1442 static inline const T
*From(const Vehicle
*v
)
1444 assert(v
->type
== Type
);
1445 return (const T
*)v
;
1449 * Update vehicle sprite- and position caches
1450 * @param force_update Force updating the vehicle on the viewport.
1451 * @param update_delta Also update the delta?
1453 inline void UpdateViewport(bool force_update
, bool update_delta
)
1455 /* Skip updating sprites on dedicated servers without screen */
1456 if (_network_dedicated
) return;
1458 /* Explicitly choose method to call to prevent vtable dereference -
1459 * it gives ~3% runtime improvements in games with many vehicles */
1460 if (update_delta
) ((T
*)this)->T::UpdateDeltaXY(this->direction
);
1461 VehicleSpriteSeq seq
;
1462 ((T
*)this)->T::GetImage(this->direction
, EIT_ON_MAP
, &seq
);
1463 if (force_update
|| this->sprite_seq
!= seq
) {
1464 this->sprite_seq
= seq
;
1465 this->UpdateSpriteSeqBound();
1466 this->Vehicle::UpdateViewport(true);
1472 * Iterate over all vehicles of a particular type.
1473 * @param name The type of vehicle to iterate over.
1474 * @param var The variable used to iterate over.
1476 #define FOR_ALL_VEHICLES_OF_TYPE(name, var) \
1477 for (size_t vehicle_index = 0; var = NULL, vehicle_index < name::GetPoolSize(); vehicle_index++) \
1478 if ((var = name::GetIfValid(vehicle_index)) != NULL)
1480 /** Generates sequence of free UnitID numbers */
1481 struct FreeUnitIDGenerator
{
1482 bool *cache
; ///< array of occupied unit id numbers
1483 UnitID maxid
; ///< maximum ID at the moment of constructor call
1484 UnitID curid
; ///< last ID returned; 0 if none
1486 FreeUnitIDGenerator(VehicleType type
, CompanyID owner
);
1489 /** Releases allocated memory */
1490 ~FreeUnitIDGenerator() { free(this->cache
); }
1493 /** Sentinel for an invalid coordinate. */
1494 static const int32 INVALID_COORD
= 0x7fffffff;
1496 #endif /* VEHICLE_BASE_H */