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 "cargopacket.h"
20 #include "texteff.hpp"
21 #include "engine_type.h"
22 #include "order_func.h"
23 #include "transport_type.h"
24 #include "group_type.h"
25 #include "base_consist.h"
29 /** Vehicle status bits in #Vehicle::vehstatus. */
31 VS_HIDDEN
= 0x01, ///< Vehicle is not visible.
32 VS_STOPPED
= 0x02, ///< Vehicle is stopped by the player.
33 VS_UNCLICKABLE
= 0x04, ///< Vehicle is not clickable by the user (shadow vehicles).
34 VS_DEFPAL
= 0x08, ///< Use default vehicle palette. @see DoDrawVehicle
35 VS_TRAIN_SLOWING
= 0x10, ///< Train is slowing down.
36 VS_SHADOW
= 0x20, ///< Vehicle is a shadow vehicle.
37 VS_AIRCRAFT_BROKEN
= 0x40, ///< Aircraft is broken down.
38 VS_CRASHED
= 0x80, ///< Vehicle is crashed.
41 /** Bit numbers in #Vehicle::vehicle_flags. */
43 VF_LOADING_FINISHED
, ///< Vehicle has finished loading.
44 VF_CARGO_UNLOADING
, ///< Vehicle is unloading cargo.
45 VF_BUILT_AS_PROTOTYPE
, ///< Vehicle is a prototype (accepted as exclusive preview).
46 VF_TIMETABLE_STARTED
, ///< Whether the vehicle has started running on the timetable yet.
47 VF_AUTOFILL_TIMETABLE
, ///< Whether the vehicle should fill in the timetable automatically.
48 VF_AUTOFILL_PRES_WAIT_TIME
, ///< Whether non-destructive auto-fill should preserve waiting times
49 VF_STOP_LOADING
, ///< Don't load anymore during the next load cycle.
50 VF_PATHFINDER_LOST
, ///< Vehicle's pathfinder is lost.
51 VF_SERVINT_IS_CUSTOM
, ///< Service interval is custom.
52 VF_SERVINT_IS_PERCENT
, ///< Service interval is percent.
55 /** Bit numbers used to indicate which of the #NewGRFCache values are valid. */
56 enum NewGRFCacheValidValues
{
57 NCVV_POSITION_CONSIST_LENGTH
= 0, ///< This bit will be set if the NewGRF var 40 currently stored is valid.
58 NCVV_POSITION_SAME_ID_LENGTH
= 1, ///< This bit will be set if the NewGRF var 41 currently stored is valid.
59 NCVV_CONSIST_CARGO_INFORMATION
= 2, ///< This bit will be set if the NewGRF var 42 currently stored is valid.
60 NCVV_COMPANY_INFORMATION
= 3, ///< This bit will be set if the NewGRF var 43 currently stored is valid.
61 NCVV_POSITION_IN_VEHICLE
= 4, ///< This bit will be set if the NewGRF var 4D currently stored is valid.
62 NCVV_END
, ///< End of the bits.
65 /** Cached often queried (NewGRF) values */
67 /* Values calculated when they are requested for the first time after invalidating the NewGRF cache. */
68 uint32 position_consist_length
; ///< Cache for NewGRF var 40.
69 uint32 position_same_id_length
; ///< Cache for NewGRF var 41.
70 uint32 consist_cargo_information
; ///< Cache for NewGRF var 42. (Note: The cargotype is untranslated in the cache because the accessing GRF is yet unknown.)
71 uint32 company_information
; ///< Cache for NewGRF var 43.
72 uint32 position_in_vehicle
; ///< Cache for NewGRF var 4D.
73 uint8 cache_valid
; ///< Bitset that indicates which cache values are valid.
76 /** Meaning of the various bits of the visual effect. */
78 VE_OFFSET_START
= 0, ///< First bit that contains the offset (0 = front, 8 = centre, 15 = rear)
79 VE_OFFSET_COUNT
= 4, ///< Number of bits used for the offset
80 VE_OFFSET_CENTRE
= 8, ///< Value of offset corresponding to a position above the centre of the vehicle
82 VE_TYPE_START
= 4, ///< First bit used for the type of effect
83 VE_TYPE_COUNT
= 2, ///< Number of bits used for the effect type
84 VE_TYPE_DEFAULT
= 0, ///< Use default from engine class
85 VE_TYPE_STEAM
= 1, ///< Steam plumes
86 VE_TYPE_DIESEL
= 2, ///< Diesel fumes
87 VE_TYPE_ELECTRIC
= 3, ///< Electric sparks
89 VE_DISABLE_EFFECT
= 6, ///< Flag to disable visual effect
90 VE_DISABLE_WAGON_POWER
= 7, ///< Flag to disable wagon power
92 VE_DEFAULT
= 0xFF, ///< Default value to indicate that visual effect should be based on engine class
96 * Enum to handle ground vehicle subtypes.
97 * This is defined here instead of at #GroundVehicle because some common function require access to these flags.
98 * Do not access it directly unless you have to. Use the subtype access functions.
100 enum GroundVehicleSubtypeFlags
{
101 GVSF_FRONT
= 0, ///< Leading engine of a consist.
102 GVSF_ARTICULATED_PART
= 1, ///< Articulated part of an engine.
103 GVSF_WAGON
= 2, ///< Wagon (not used for road vehicles).
104 GVSF_ENGINE
= 3, ///< Engine that can be front engine, but might be placed behind another engine (not used for road vehicles).
105 GVSF_FREE_WAGON
= 4, ///< First in a wagon chain (in depot) (not used for road vehicles).
106 GVSF_MULTIHEADED
= 5, ///< Engine is multiheaded (not used for road vehicles).
109 /** Cached often queried values common to all vehicles. */
110 struct VehicleCache
{
111 uint16 cached_max_speed
; ///< Maximum speed of the consist (minimum of the max speed of all vehicles in the consist).
112 uint16 cached_cargo_age_period
; ///< Number of ticks before carried cargo is aged.
114 byte cached_vis_effect
; ///< Visual effect to show (see #VisualEffect)
117 /** A vehicle pool for a little over 1 million vehicles. */
118 typedef Pool
<Vehicle
, VehicleID
, 512, 0xFF000> VehiclePool
;
119 extern VehiclePool _vehicle_pool
;
121 /* Some declarations of functions, so we can make them friendly */
123 struct GroundVehicleCache
;
124 extern const SaveLoad
*GetVehicleDescription(VehicleType vt
);
125 struct LoadgameState
;
126 extern bool LoadOldVehicle(LoadgameState
*ls
, int num
);
127 extern void FixOldVehicles(const SavegameTypeVersion
*stv
);
132 * Simulated cargo type and capacity for prediction of future links.
135 CargoID cargo
; ///< Cargo type the vehicle will be carrying.
136 uint16 capacity
; ///< Capacity the vehicle will have.
137 uint16 remaining
; ///< Capacity remaining from before the previous refit.
138 RefitDesc(CargoID cargo
, uint16 capacity
, uint16 remaining
) :
139 cargo(cargo
), capacity(capacity
), remaining(remaining
) {}
143 * Link struct for vehicle hash chains
145 struct VehicleHashLink
{
150 /** %Vehicle data structure. */
151 struct Vehicle
: VehiclePool::PoolItem
<&_vehicle_pool
>, BaseVehicle
, BaseConsist
{
153 typedef std::list
<RefitDesc
> RefitList
;
154 typedef std::map
<CargoID
, uint
> CapacitiesMap
;
156 Vehicle
*next
; ///< pointer to the next vehicle in the chain
157 Vehicle
*previous
; ///< NOSAVE: pointer to the previous vehicle in the chain
158 Vehicle
*first
; ///< NOSAVE: pointer to the first vehicle in the chain
160 Vehicle
*next_shared
; ///< pointer to the next vehicle that shares the order
161 Vehicle
*previous_shared
; ///< NOSAVE: pointer to the previous vehicle in the shared order chain
164 friend const SaveLoad
*GetVehicleDescription(VehicleType vt
); ///< So we can use private/protected variables in the saveload code
165 friend void FixOldVehicles(const SavegameTypeVersion
*stv
);
166 friend void AfterLoadVehicles(const SavegameTypeVersion
*stv
); ///< So we can set the #previous and #first pointers while loading
167 friend bool LoadOldVehicle(LoadgameState
*ls
, int num
); ///< So we can set the proper next pointer while loading
169 TileIndex tile
; ///< Current tile index
172 * Heading for this tile.
173 * For airports and train stations this tile does not necessarily belong to the destination station,
174 * but it can be used for heuristic purposes to estimate the distance.
178 Money profit_this_year
; ///< Profit this year << 8, low 8 bits are fract
179 Money profit_last_year
; ///< Profit last year << 8, low 8 bits are fract
180 Money value
; ///< Value of the vehicle
182 CargoPayment
*cargo_payment
; ///< The cargo payment we're currently in
184 Rect coord
; ///< NOSAVE: Graphical bounding box of the vehicle, i.e. what to redraw on moves.
186 VehicleHashLink hash_viewport_link
; ///< NOSAVE: Visual location hash link.
188 VehicleHashLink hash_tile_link
; ///< NOSAVE: Tile location hash link.
189 Vehicle
**hash_tile_current
; ///< NOSAVE: Cache of the current hash chain.
191 SpriteID colourmap
; ///< NOSAVE: cached colour mapping
193 /* Related to age and service time */
194 Year build_year
; ///< Year the vehicle has been built.
195 Date age
; ///< Age in days
196 Date max_age
; ///< Maximum age
197 Date date_of_last_service
; ///< Last date the vehicle had a service at a depot.
198 uint16 reliability
; ///< Reliability.
199 uint16 reliability_spd_dec
; ///< Reliability decrease speed.
200 byte breakdown_ctr
; ///< Counter for managing breakdown events. @see Vehicle::HandleBreakdown
201 byte breakdown_delay
; ///< Counter for managing breakdown length.
202 byte breakdowns_since_last_service
; ///< Counter for the amount of breakdowns.
203 byte breakdown_chance
; ///< Current chance of breakdowns.
205 int32 x_pos
; ///< x coordinate.
206 int32 y_pos
; ///< y coordinate.
207 int32 z_pos
; ///< z coordinate.
208 DirectionByte direction
; ///< facing
210 OwnerByte owner
; ///< Which company owns the vehicle?
212 * currently displayed sprite index
213 * 0xfd == custom sprite, 0xfe == custom second head sprite
214 * 0xff == reserved for another custom sprite
217 SpriteID cur_image
; ///< sprite number for this vehicle
218 byte x_extent
; ///< x-extent of vehicle bounding box
219 byte y_extent
; ///< y-extent of vehicle bounding box
220 byte z_extent
; ///< z-extent of vehicle bounding box
221 int8 x_bb_offs
; ///< x offset of vehicle bounding box
222 int8 y_bb_offs
; ///< y offset of vehicle bounding box
223 int8 x_offs
; ///< x offset for vehicle sprite
224 int8 y_offs
; ///< y offset for vehicle sprite
225 EngineID engine_type
; ///< The type of engine used for this vehicle.
227 TextEffectID fill_percent_te_id
; ///< a text-effect id to a loading indicator object
228 UnitID unitnumber
; ///< unit number, for display purposes only
230 uint16 cur_speed
; ///< current speed
231 byte subspeed
; ///< fractional speed
232 byte acceleration
; ///< used by train & aircraft
233 uint32 motion_counter
; ///< counter to occasionally play a vehicle sound.
234 byte progress
; ///< The percentage (if divided by 256) this vehicle already crossed the tile unit.
236 byte random_bits
; ///< Bits used for determining which randomized variational spritegroups to use when drawing.
237 byte waiting_triggers
; ///< Triggers to be yet matched before rerandomizing the random bits.
239 StationID last_station_visited
; ///< The last station we stopped at.
240 StationID last_loading_station
; ///< Last station the vehicle has stopped at and could possibly leave from with any cargo loaded.
242 CargoID cargo_type
; ///< type of cargo this vehicle is carrying
243 byte cargo_subtype
; ///< Used for livery refits (NewGRF variations)
244 uint16 cargo_cap
; ///< total capacity
245 uint16 refit_cap
; ///< Capacity left over from before last refit.
246 VehicleCargoList cargo
; ///< The cargo this vehicle is carrying
247 uint16 cargo_age_counter
; ///< Ticks till cargo is aged next.
249 byte day_counter
; ///< Increased by one for each day
250 byte tick_counter
; ///< Increased by one for each tick
251 byte running_ticks
; ///< Number of ticks this vehicle was not stopped this day
253 byte vehstatus
; ///< Status
254 Order current_order
; ///< The current order (+ status, like: loading)
257 OrderList
*list
; ///< Pointer to the order list for this vehicle
258 Order
*old
; ///< Only used during conversion of old save games
259 } orders
; ///< The orders currently assigned to the vehicle.
261 uint16 load_unload_ticks
; ///< Ticks to wait before starting next cycle.
262 GroupID group_id
; ///< Index of group Pool array
263 byte subtype
; ///< subtype (Filled with values from #EffectVehicles/#TrainSubTypes/#AircraftSubTypes)
265 NewGRFCache grf_cache
; ///< Cache of often used calculated NewGRF values
266 VehicleCache vcache
; ///< Cache of often used vehicle values.
268 Vehicle(VehicleType type
= VEH_INVALID
);
270 void PreDestructor();
271 /** We want to 'destruct' the right class. */
275 void CancelReservation(StationID next
, Station
*st
);
278 GroundVehicleCache
*GetGroundVehicleCache();
279 const GroundVehicleCache
*GetGroundVehicleCache() const;
281 uint16
&GetGroundVehicleFlags();
282 const uint16
&GetGroundVehicleFlags() const;
284 void DeleteUnreachedImplicitOrders();
286 void HandleLoading(bool mode
= false);
288 void GetConsistFreeCapacities(SmallMap
<CargoID
, uint
> &capacities
) const;
290 uint
GetConsistTotalCapacity() const;
293 * Marks the vehicles to be redrawn and updates cached variables
295 * This method marks the area of the vehicle on the screen as dirty.
296 * It can be use to repaint the vehicle.
300 virtual void MarkDirty() {}
303 * Updates the x and y offsets and the size of the sprite used
305 * @param direction the direction the vehicle is facing
307 virtual void UpdateDeltaXY(Direction direction
) {}
310 * Determines the effective direction-specific vehicle movement speed.
312 * This method belongs to the old vehicle movement method:
313 * A vehicle moves a step every 256 progress units.
314 * The vehicle speed is scaled by 3/4 when moving in X or Y direction due to the longer distance.
316 * However, this method is slightly wrong in corners, as the leftover progress is not scaled correctly
317 * when changing movement direction. #GetAdvanceSpeed() and #GetAdvanceDistance() are better wrt. this.
319 * @param speed Direction-independent unscaled speed.
320 * @return speed scaled by movement direction. 256 units are required for each movement step.
322 inline uint
GetOldAdvanceSpeed(uint speed
) const
324 return (this->direction
& 1) ? speed
: speed
* 3 / 4;
328 * Determines the effective vehicle movement speed.
330 * Together with #GetAdvanceDistance() this function is a replacement for #GetOldAdvanceSpeed().
332 * A vehicle progresses independent of it's movement direction.
333 * However different amounts of "progress" are needed for moving a step in a specific direction.
334 * That way the leftover progress does not need any adaption when changing movement direction.
336 * @param speed Direction-independent unscaled speed.
337 * @return speed, scaled to match #GetAdvanceDistance().
339 static inline uint
GetAdvanceSpeed(uint speed
)
341 return speed
* 3 / 4;
345 * Determines the vehicle "progress" needed for moving a step.
347 * Together with #GetAdvanceSpeed() this function is a replacement for #GetOldAdvanceSpeed().
349 * @return distance to drive for a movement step on the map.
351 inline uint
GetAdvanceDistance() const
353 return (this->direction
& 1) ? 192 : 256;
357 * Sets the expense type associated to this vehicle type
358 * @param income whether this is income or (running) expenses of the vehicle
360 virtual ExpensesType
GetExpenseType(bool income
) const { return EXPENSES_OTHER
; }
363 * Play the sound associated with leaving the station
365 virtual void PlayLeaveStationSound() const {}
368 * Whether this is the primary vehicle in the chain.
370 virtual bool IsPrimaryVehicle() const { return false; }
372 const Engine
*GetEngine() const;
375 * Gets the sprite to show for the given direction
376 * @param direction the direction the vehicle is facing
377 * @return the sprite for the given vehicle in the given direction
379 virtual SpriteID
GetImage(Direction direction
, EngineImageType image_type
) const { return 0; }
381 const GRFFile
*GetGRF() const;
382 uint32
GetGRFID() const;
385 * Invalidates cached NewGRF variables
386 * @see InvalidateNewGRFCacheOfChain
388 inline void InvalidateNewGRFCache()
390 this->grf_cache
.cache_valid
= 0;
394 * Invalidates cached NewGRF variables of all vehicles in the chain (after the current vehicle)
395 * @see InvalidateNewGRFCache
397 inline void InvalidateNewGRFCacheOfChain()
399 for (Vehicle
*u
= this; u
!= NULL
; u
= u
->Next()) {
400 u
->InvalidateNewGRFCache();
405 * Check if the vehicle is a ground vehicle.
406 * @return True iff the vehicle is a train or a road vehicle.
408 inline bool IsGroundVehicle() const
410 return this->type
== VEH_TRAIN
|| this->type
== VEH_ROAD
;
414 * Gets the speed in km-ish/h that can be sent into SetDParam for string processing.
415 * @return the vehicle's speed
417 virtual int GetDisplaySpeed() const { return 0; }
420 * Gets the maximum speed in km-ish/h that can be sent into SetDParam for string processing.
421 * @return the vehicle's maximum speed
423 virtual int GetDisplayMaxSpeed() const { return 0; }
426 * Calculates the maximum speed of the vehicle under its current conditions.
427 * @return Current maximum speed in native units.
429 virtual int GetCurrentMaxSpeed() const { return 0; }
432 * Gets the running cost of a vehicle
433 * @return the vehicle's running cost
435 virtual Money
GetRunningCost() const { return 0; }
438 * Check whether the vehicle is in the depot.
439 * @return true if and only if the vehicle is in the depot.
441 virtual bool IsInDepot() const { return false; }
444 * Check whether the whole vehicle chain is in the depot.
445 * @return true if and only if the whole chain is in the depot.
447 virtual bool IsChainInDepot() const { return this->IsInDepot(); }
450 * Check whether the vehicle is in the depot *and* stopped.
451 * @return true if and only if the vehicle is in the depot and stopped.
453 bool IsStoppedInDepot() const
455 assert(this == this->First());
456 /* Free wagons have no VS_STOPPED state */
457 if (this->IsPrimaryVehicle() && !(this->vehstatus
& VS_STOPPED
)) return false;
458 return this->IsChainInDepot();
462 * Calls the tick handler of the vehicle
463 * @return is this vehicle still valid?
465 virtual bool Tick() { return true; };
468 * Calls the new day handler of the vehicle
470 virtual void OnNewDay() {};
473 * Crash the (whole) vehicle chain.
474 * @param flooded whether the cause of the crash is flooding or not.
475 * @return the number of lost souls.
477 virtual uint
Crash(bool flooded
= false);
480 * Gets the running cost of a vehicle that can be sent into SetDParam for string processing.
481 * @return the vehicle's running cost
483 Money
GetDisplayRunningCost() const { return (this->GetRunningCost() >> 8); }
486 * Gets the profit vehicle had this year. It can be sent into SetDParam for string processing.
487 * @return the vehicle's profit this year
489 Money
GetDisplayProfitThisYear() const { return (this->profit_this_year
>> 8); }
492 * Gets the profit vehicle had last year. It can be sent into SetDParam for string processing.
493 * @return the vehicle's profit last year
495 Money
GetDisplayProfitLastYear() const { return (this->profit_last_year
>> 8); }
497 void SetNext(Vehicle
*next
);
500 * Get the next vehicle of this vehicle.
501 * @note articulated parts are also counted as vehicles.
502 * @return the next vehicle or NULL when there isn't a next vehicle.
504 inline Vehicle
*Next() const { return this->next
; }
507 * Get the previous vehicle of this vehicle.
508 * @note articulated parts are also counted as vehicles.
509 * @return the previous vehicle or NULL when there isn't a previous vehicle.
511 inline Vehicle
*Previous() const { return this->previous
; }
514 * Get the first vehicle of this vehicle chain.
515 * @return the first vehicle of the chain.
517 inline Vehicle
*First() const { return this->first
; }
520 * Get the last vehicle of this vehicle chain.
521 * @return the last vehicle of the chain.
523 inline Vehicle
*Last()
526 while (v
->Next() != NULL
) v
= v
->Next();
531 * Get the last vehicle of this vehicle chain.
532 * @return the last vehicle of the chain.
534 inline const Vehicle
*Last() const
536 const Vehicle
*v
= this;
537 while (v
->Next() != NULL
) v
= v
->Next();
542 * Get the vehicle at offset \a n of this vehicle chain.
543 * @param n Offset from the current vehicle.
544 * @return The new vehicle or NULL if the offset is out-of-bounds.
546 inline Vehicle
*Move(int n
)
550 for (int i
= 0; i
!= n
&& v
!= NULL
; i
--) v
= v
->Previous();
552 for (int i
= 0; i
!= n
&& v
!= NULL
; i
++) v
= v
->Next();
558 * Get the vehicle at offset \a n of this vehicle chain.
559 * @param n Offset from the current vehicle.
560 * @return The new vehicle or NULL if the offset is out-of-bounds.
562 inline const Vehicle
*Move(int n
) const
564 const Vehicle
*v
= this;
566 for (int i
= 0; i
!= n
&& v
!= NULL
; i
--) v
= v
->Previous();
568 for (int i
= 0; i
!= n
&& v
!= NULL
; i
++) v
= v
->Next();
574 * Get the first order of the vehicles order list.
575 * @return first order of order list.
577 inline Order
*GetFirstOrder() const { return (this->orders
.list
== NULL
) ? NULL
: this->orders
.list
->GetFirstOrder(); }
579 void AddToShared(Vehicle
*shared_chain
);
580 void RemoveFromShared();
583 * Get the next vehicle of the shared vehicle chain.
584 * @return the next shared vehicle or NULL when there isn't a next vehicle.
586 inline Vehicle
*NextShared() const { return this->next_shared
; }
589 * Get the previous vehicle of the shared vehicle chain
590 * @return the previous shared vehicle or NULL when there isn't a previous vehicle.
592 inline Vehicle
*PreviousShared() const { return this->previous_shared
; }
595 * Get the first vehicle of this vehicle chain.
596 * @return the first vehicle of the chain.
598 inline Vehicle
*FirstShared() const { return (this->orders
.list
== NULL
) ? this->First() : this->orders
.list
->GetFirstSharedVehicle(); }
601 * Check if we share our orders with another vehicle.
602 * @return true if there are other vehicles sharing the same order
604 inline bool IsOrderListShared() const { return this->orders
.list
!= NULL
&& this->orders
.list
->IsShared(); }
607 * Get the number of orders this vehicle has.
608 * @return the number of orders this vehicle has.
610 inline VehicleOrderID
GetNumOrders() const { return (this->orders
.list
== NULL
) ? 0 : this->orders
.list
->GetNumOrders(); }
613 * Get the number of manually added orders this vehicle has.
614 * @return the number of manually added orders this vehicle has.
616 inline VehicleOrderID
GetNumManualOrders() const { return (this->orders
.list
== NULL
) ? 0 : this->orders
.list
->GetNumManualOrders(); }
619 * Get the next station the vehicle will stop at.
620 * @return ID of the next station the vehicle will stop at or INVALID_STATION.
622 inline StationIDStack
GetNextStoppingStation() const
624 return (this->orders
.list
== NULL
) ? INVALID_STATION
: this->orders
.list
->GetNextStoppingStation(this);
627 void ResetRefitCaps();
630 * Copy certain configurations and statistics of a vehicle after successful autoreplace/renew
631 * The function shall copy everything that cannot be copied by a command (like orders / group etc),
632 * and that shall not be resetted for the new vehicle.
633 * @param src The old vehicle
635 inline void CopyVehicleConfigAndStatistics(const Vehicle
*src
)
637 this->CopyConsistPropertiesFrom(src
);
639 this->unitnumber
= src
->unitnumber
;
641 this->current_order
= src
->current_order
;
642 this->dest_tile
= src
->dest_tile
;
644 this->profit_this_year
= src
->profit_this_year
;
645 this->profit_last_year
= src
->profit_last_year
;
649 bool HandleBreakdown();
651 bool NeedsAutorenewing(const Company
*c
, bool use_renew_setting
= true) const;
653 bool NeedsServicing() const;
654 bool NeedsAutomaticServicing() const;
657 * Determine the location for the station where the vehicle goes to next.
658 * Things done for example are allocating slots in a road stop or exact
659 * location of the platform is determined for ships.
660 * @param station the station to make the next location of the vehicle.
661 * @return the location (tile) to aim for.
663 virtual TileIndex
GetOrderStationLocation(StationID station
) { return INVALID_TILE
; }
666 * Find the closest depot for this vehicle and tell us the location,
667 * DestinationID and whether we should reverse.
668 * @param location where do we go to?
669 * @param destination what hangar do we go to?
670 * @param reverse should the vehicle be reversed?
671 * @return true if a depot could be found.
673 virtual bool FindClosestDepot(TileIndex
*location
, DestinationID
*destination
, bool *reverse
) { return false; }
675 CommandCost
SendToDepot(DoCommandFlag flags
, DepotCommand command
);
677 void UpdateVisualEffect(bool allow_power_change
= true);
678 void ShowVisualEffect() const;
680 inline uint16
GetServiceInterval() const { return this->service_interval
; }
682 inline void SetServiceInterval(uint16 interval
) { this->service_interval
= interval
; }
684 inline bool ServiceIntervalIsCustom() const { return HasBit(this->vehicle_flags
, VF_SERVINT_IS_CUSTOM
); }
686 inline bool ServiceIntervalIsPercent() const { return HasBit(this->vehicle_flags
, VF_SERVINT_IS_PERCENT
); }
688 inline void SetServiceIntervalIsCustom(bool on
) { SB(this->vehicle_flags
, VF_SERVINT_IS_CUSTOM
, 1, on
); }
690 inline void SetServiceIntervalIsPercent(bool on
) { SB(this->vehicle_flags
, VF_SERVINT_IS_PERCENT
, 1, on
); }
694 * Advance cur_real_order_index to the next real order.
695 * cur_implicit_order_index is not touched.
697 void SkipToNextRealOrderIndex()
699 if (this->GetNumManualOrders() > 0) {
700 /* Advance to next real order */
702 this->cur_real_order_index
++;
703 if (this->cur_real_order_index
>= this->GetNumOrders()) this->cur_real_order_index
= 0;
704 } while (this->GetOrder(this->cur_real_order_index
)->IsType(OT_IMPLICIT
));
706 this->cur_real_order_index
= 0;
712 * Increments cur_implicit_order_index, keeps care of the wrap-around and invalidates the GUI.
713 * cur_real_order_index is incremented as well, if needed.
714 * Note: current_order is not invalidated.
716 void IncrementImplicitOrderIndex()
718 if (this->cur_implicit_order_index
== this->cur_real_order_index
) {
719 /* Increment real order index as well */
720 this->SkipToNextRealOrderIndex();
723 assert(this->cur_real_order_index
== 0 || this->cur_real_order_index
< this->GetNumOrders());
725 /* Advance to next implicit order */
727 this->cur_implicit_order_index
++;
728 if (this->cur_implicit_order_index
>= this->GetNumOrders()) this->cur_implicit_order_index
= 0;
729 } while (this->cur_implicit_order_index
!= this->cur_real_order_index
&& !this->GetOrder(this->cur_implicit_order_index
)->IsType(OT_IMPLICIT
));
731 InvalidateVehicleOrder(this, 0);
735 * Advanced cur_real_order_index to the next real order, keeps care of the wrap-around and invalidates the GUI.
736 * 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
737 * but not any implicit orders.
738 * Note: current_order is not invalidated.
740 void IncrementRealOrderIndex()
742 if (this->cur_implicit_order_index
== this->cur_real_order_index
) {
743 /* Increment both real and implicit order */
744 this->IncrementImplicitOrderIndex();
746 /* Increment real order only */
747 this->SkipToNextRealOrderIndex();
748 InvalidateVehicleOrder(this, 0);
753 * Skip implicit orders until cur_real_order_index is a non-implicit order.
755 void UpdateRealOrderIndex()
757 /* Make sure the index is valid */
758 if (this->cur_real_order_index
>= this->GetNumOrders()) this->cur_real_order_index
= 0;
760 if (this->GetNumManualOrders() > 0) {
761 /* Advance to next real order */
762 while (this->GetOrder(this->cur_real_order_index
)->IsType(OT_IMPLICIT
)) {
763 this->cur_real_order_index
++;
764 if (this->cur_real_order_index
>= this->GetNumOrders()) this->cur_real_order_index
= 0;
767 this->cur_real_order_index
= 0;
772 * Returns order 'index' of a vehicle or NULL when it doesn't exists
773 * @param index the order to fetch
774 * @return the found (or not) order
776 inline Order
*GetOrder(int index
) const
778 return (this->orders
.list
== NULL
) ? NULL
: this->orders
.list
->GetOrderAt(index
);
782 * Returns the last order of a vehicle, or NULL if it doesn't exists
783 * @return last order of a vehicle, if available
785 inline Order
*GetLastOrder() const
787 return (this->orders
.list
== NULL
) ? NULL
: this->orders
.list
->GetLastOrder();
790 bool IsEngineCountable() const;
791 bool HasEngineType() const;
792 bool HasDepotOrder() const;
793 void HandlePathfindingResult(bool path_found
);
796 * Check if the vehicle is a front engine.
797 * @return Returns true if the vehicle is a front engine.
799 inline bool IsFrontEngine() const
801 return this->IsGroundVehicle() && HasBit(this->subtype
, GVSF_FRONT
);
805 * Check if the vehicle is an articulated part of an engine.
806 * @return Returns true if the vehicle is an articulated part.
808 inline bool IsArticulatedPart() const
810 return this->IsGroundVehicle() && HasBit(this->subtype
, GVSF_ARTICULATED_PART
);
814 * Check if an engine has an articulated part.
815 * @return True if the engine has an articulated part.
817 inline bool HasArticulatedPart() const
819 return this->Next() != NULL
&& this->Next()->IsArticulatedPart();
823 * Get the next part of an articulated engine.
824 * @return Next part of the articulated engine.
825 * @pre The vehicle is an articulated engine.
827 inline Vehicle
*GetNextArticulatedPart() const
829 assert(this->HasArticulatedPart());
834 * Get the first part of an articulated engine.
835 * @return First part of the engine.
837 inline Vehicle
*GetFirstEnginePart()
840 while (v
->IsArticulatedPart()) v
= v
->Previous();
845 * Get the first part of an articulated engine.
846 * @return First part of the engine.
848 inline const Vehicle
*GetFirstEnginePart() const
850 const Vehicle
*v
= this;
851 while (v
->IsArticulatedPart()) v
= v
->Previous();
856 * Get the last part of an articulated engine.
857 * @return Last part of the engine.
859 inline Vehicle
*GetLastEnginePart()
862 while (v
->HasArticulatedPart()) v
= v
->GetNextArticulatedPart();
867 * Get the next real (non-articulated part) vehicle in the consist.
868 * @return Next vehicle in the consist.
870 inline Vehicle
*GetNextVehicle() const
872 const Vehicle
*v
= this;
873 while (v
->HasArticulatedPart()) v
= v
->GetNextArticulatedPart();
875 /* v now contains the last articulated part in the engine */
880 * Get the previous real (non-articulated part) vehicle in the consist.
881 * @return Previous vehicle in the consist.
883 inline Vehicle
*GetPrevVehicle() const
885 Vehicle
*v
= this->Previous();
886 while (v
!= NULL
&& v
->IsArticulatedPart()) v
= v
->Previous();
893 * Iterate over all vehicles from a given point.
894 * @param var The variable used to iterate over.
895 * @param start The vehicle to start the iteration at.
897 #define FOR_ALL_VEHICLES_FROM(var, start) FOR_ALL_ITEMS_FROM(Vehicle, vehicle_index, var, start)
900 * Iterate over all vehicles.
901 * @param var The variable used to iterate over.
903 #define FOR_ALL_VEHICLES(var) FOR_ALL_VEHICLES_FROM(var, 0)
906 * Iterator for vehicles at a tile. This uses the tile hash VehicleTileHash
907 * defined in vehicle.cpp to run through all vehicles at a given tile.
909 * NOTE! The order in which vehicles are iterated over is unspecified, and
910 * can be different between machines. As such, and to prevent a simulation
911 * mismatch in multiplayer, you must ensure that whatever you are doing
912 * with the vehicles does not depend on their ordering. To help enforce
913 * this, the iterator will assert if you break the iteration before
916 struct VehicleTileIterator
{
918 const TileIndex tile
;
921 static Vehicle
*first (TileIndex tile
);
924 VehicleTileIterator (TileIndex tile
) : tile(tile
), v(first(tile
))
926 if (v
!= NULL
&& v
->tile
!= tile
) next();
929 ~VehicleTileIterator()
934 bool finished() const
944 v
= v
->hash_tile_link
.next
;
945 } while (v
!= NULL
&& v
->tile
!= tile
);
952 * Iterator for vehicles at a tile, to check if a vehicle matching given
953 * conditions exists on a tile.
955 * This iterator is designed to check if a vehicle that matches a given
956 * set of conditions exists on a tile. Since we are only interested in
957 * whether such a vehicle exists or not, it can break as soon as one is
958 * found, because ordering does not matter in that case.
960 struct VehicleTileFinder
: VehicleTileIterator
{
965 VehicleTileFinder (TileIndex tile
) : VehicleTileIterator(tile
), found(false)
971 v
= NULL
; // stop iterating
975 bool was_found () const
977 /* do not call this until finished */
985 * Class defining several overloaded accessors so we don't
986 * have to cast vehicle types that often
988 template <class T
, VehicleType Type
>
989 struct SpecializedVehicle
: public Vehicle
{
990 static const VehicleType EXPECTED_TYPE
= Type
; ///< Specialized type
992 typedef SpecializedVehicle
<T
, Type
> SpecializedVehicleBase
; ///< Our type
995 * Set vehicle type correctly
997 inline SpecializedVehicle
<T
, Type
>() : Vehicle(Type
) { }
1000 * Get the first vehicle in the chain
1001 * @return first vehicle in the chain
1003 inline T
*First() const { return (T
*)this->Vehicle::First(); }
1006 * Get the last vehicle in the chain
1007 * @return last vehicle in the chain
1009 inline T
*Last() { return (T
*)this->Vehicle::Last(); }
1012 * Get the last vehicle in the chain
1013 * @return last vehicle in the chain
1015 inline const T
*Last() const { return (const T
*)this->Vehicle::Last(); }
1018 * Get next vehicle in the chain
1019 * @return next vehicle in the chain
1021 inline T
*Next() const { return (T
*)this->Vehicle::Next(); }
1024 * Get previous vehicle in the chain
1025 * @return previous vehicle in the chain
1027 inline T
*Previous() const { return (T
*)this->Vehicle::Previous(); }
1030 * Get the next part of an articulated engine.
1031 * @return Next part of the articulated engine.
1032 * @pre The vehicle is an articulated engine.
1034 inline T
*GetNextArticulatedPart() { return (T
*)this->Vehicle::GetNextArticulatedPart(); }
1037 * Get the next part of an articulated engine.
1038 * @return Next part of the articulated engine.
1039 * @pre The vehicle is an articulated engine.
1041 inline T
*GetNextArticulatedPart() const { return (T
*)this->Vehicle::GetNextArticulatedPart(); }
1044 * Get the first part of an articulated engine.
1045 * @return First part of the engine.
1047 inline T
*GetFirstEnginePart() { return (T
*)this->Vehicle::GetFirstEnginePart(); }
1050 * Get the first part of an articulated engine.
1051 * @return First part of the engine.
1053 inline const T
*GetFirstEnginePart() const { return (const T
*)this->Vehicle::GetFirstEnginePart(); }
1056 * Get the last part of an articulated engine.
1057 * @return Last part of the engine.
1059 inline T
*GetLastEnginePart() { return (T
*)this->Vehicle::GetLastEnginePart(); }
1062 * Get the next real (non-articulated part) vehicle in the consist.
1063 * @return Next vehicle in the consist.
1065 inline T
*GetNextVehicle() const { return (T
*)this->Vehicle::GetNextVehicle(); }
1068 * Get the previous real (non-articulated part) vehicle in the consist.
1069 * @return Previous vehicle in the consist.
1071 inline T
*GetPrevVehicle() const { return (T
*)this->Vehicle::GetPrevVehicle(); }
1074 * Tests whether given index is a valid index for vehicle of this type
1075 * @param index tested index
1076 * @return is this index valid index of T?
1078 static inline bool IsValidID(size_t index
)
1080 return Vehicle::IsValidID(index
) && Vehicle::Get(index
)->type
== Type
;
1084 * Gets vehicle with given index
1085 * @return pointer to vehicle with given index casted to T *
1087 static inline T
*Get(size_t index
)
1089 return (T
*)Vehicle::Get(index
);
1093 * Returns vehicle if the index is a valid index for this vehicle type
1094 * @return pointer to vehicle with given index if it's a vehicle of this type
1096 static inline T
*GetIfValid(size_t index
)
1098 return IsValidID(index
) ? Get(index
) : NULL
;
1102 * Converts a Vehicle to SpecializedVehicle with type checking.
1103 * @param v Vehicle pointer
1104 * @return pointer to SpecializedVehicle
1106 static inline T
*From(Vehicle
*v
)
1108 assert(v
->type
== Type
);
1113 * Converts a const Vehicle to const SpecializedVehicle with type checking.
1114 * @param v Vehicle pointer
1115 * @return pointer to SpecializedVehicle
1117 static inline const T
*From(const Vehicle
*v
)
1119 assert(v
->type
== Type
);
1120 return (const T
*)v
;
1124 * Update vehicle sprite- and position caches
1125 * @param force_update Force updating the vehicle on the viewport.
1126 * @param update_delta Also update the delta?
1128 inline void UpdateViewport(bool force_update
, bool update_delta
)
1130 extern void VehicleUpdateViewport(Vehicle
*v
, bool dirty
);
1132 /* Explicitly choose method to call to prevent vtable dereference -
1133 * it gives ~3% runtime improvements in games with many vehicles */
1134 if (update_delta
) ((T
*)this)->T::UpdateDeltaXY(this->direction
);
1135 SpriteID old_image
= this->cur_image
;
1136 this->cur_image
= ((T
*)this)->T::GetImage(this->direction
, EIT_ON_MAP
);
1137 if (force_update
|| this->cur_image
!= old_image
) VehicleUpdateViewport(this, true);
1142 * Iterate over all vehicles of a particular type.
1143 * @param name The type of vehicle to iterate over.
1144 * @param var The variable used to iterate over.
1146 #define FOR_ALL_VEHICLES_OF_TYPE(name, var) FOR_ALL_ITEMS_FROM(name, vehicle_index, var, 0) if (var->type == name::EXPECTED_TYPE)
1149 * Disasters, like submarines, skyrangers and their shadows, belong to this class.
1151 struct DisasterVehicle FINAL
: public SpecializedVehicle
<DisasterVehicle
, VEH_DISASTER
> {
1152 SpriteID image_override
; ///< Override for the default disaster vehicle sprite.
1153 VehicleID big_ufo_destroyer_target
; ///< The big UFO that this destroyer is supposed to bomb.
1155 /** We don't want GCC to zero our struct! It already is zeroed and has an index! */
1156 DisasterVehicle() : SpecializedVehicleBase() {}
1157 /** We want to 'destruct' the right class. */
1158 virtual ~DisasterVehicle() {}
1160 void UpdateDeltaXY(Direction direction
);
1165 * Iterate over disaster vehicles.
1166 * @param var The variable used to iterate over.
1168 #define FOR_ALL_DISASTERVEHICLES(var) FOR_ALL_VEHICLES_OF_TYPE(DisasterVehicle, var)
1170 /** Generates sequence of free UnitID numbers */
1171 struct FreeUnitIDGenerator
{
1172 bool *cache
; ///< array of occupied unit id numbers
1173 UnitID maxid
; ///< maximum ID at the moment of constructor call
1174 UnitID curid
; ///< last ID returned; 0 if none
1176 FreeUnitIDGenerator(VehicleType type
, CompanyID owner
);
1179 /** Releases allocated memory */
1180 ~FreeUnitIDGenerator() { free(this->cache
); }
1183 /** Sentinel for an invalid coordinate. */
1184 static const int32 INVALID_COORD
= 0x7fffffff;
1186 #endif /* VEHICLE_BASE_H */