2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8 /** @file vehicle_base.h Base class for all vehicles. */
10 #ifndef VEHICLE_BASE_H
11 #define VEHICLE_BASE_H
13 #include "core/smallmap_type.hpp"
14 #include "track_type.h"
15 #include "command_type.h"
16 #include "order_base.h"
17 #include "cargopacket.h"
18 #include "texteff.hpp"
19 #include "engine_type.h"
20 #include "order_func.h"
21 #include "transport_type.h"
22 #include "group_type.h"
23 #include "base_consist.h"
24 #include "network/network.h"
25 #include "saveload/saveload.h"
29 const uint TILE_AXIAL_DISTANCE
= 192; // Logical length of the tile in any DiagDirection used in vehicle movement.
30 const uint TILE_CORNER_DISTANCE
= 128; // Logical length of the tile corner crossing in any non-diagonal direction used in vehicle movement.
32 /** Vehicle status bits in #Vehicle::vehstatus. */
34 VS_HIDDEN
= 0x01, ///< Vehicle is not visible.
35 VS_STOPPED
= 0x02, ///< Vehicle is stopped by the player.
36 VS_UNCLICKABLE
= 0x04, ///< Vehicle is not clickable by the user (shadow vehicles).
37 VS_DEFPAL
= 0x08, ///< Use default vehicle palette. @see DoDrawVehicle
38 VS_TRAIN_SLOWING
= 0x10, ///< Train is slowing down.
39 VS_SHADOW
= 0x20, ///< Vehicle is a shadow vehicle.
40 VS_AIRCRAFT_BROKEN
= 0x40, ///< Aircraft is broken down.
41 VS_CRASHED
= 0x80, ///< Vehicle is crashed.
44 /** Bit numbers in #Vehicle::vehicle_flags. */
46 VF_LOADING_FINISHED
, ///< Vehicle has finished loading.
47 VF_CARGO_UNLOADING
, ///< Vehicle is unloading cargo.
48 VF_BUILT_AS_PROTOTYPE
, ///< Vehicle is a prototype (accepted as exclusive preview).
49 VF_TIMETABLE_STARTED
, ///< Whether the vehicle has started running on the timetable yet.
50 VF_AUTOFILL_TIMETABLE
, ///< Whether the vehicle should fill in the timetable automatically.
51 VF_AUTOFILL_PRES_WAIT_TIME
, ///< Whether non-destructive auto-fill should preserve waiting times
52 VF_STOP_LOADING
, ///< Don't load anymore during the next load cycle.
53 VF_PATHFINDER_LOST
, ///< Vehicle's pathfinder is lost.
54 VF_SERVINT_IS_CUSTOM
, ///< Service interval is custom.
55 VF_SERVINT_IS_PERCENT
, ///< Service interval is percent.
58 /** Bit numbers used to indicate which of the #NewGRFCache values are valid. */
59 enum NewGRFCacheValidValues
{
60 NCVV_POSITION_CONSIST_LENGTH
= 0, ///< This bit will be set if the NewGRF var 40 currently stored is valid.
61 NCVV_POSITION_SAME_ID_LENGTH
= 1, ///< This bit will be set if the NewGRF var 41 currently stored is valid.
62 NCVV_CONSIST_CARGO_INFORMATION
= 2, ///< This bit will be set if the NewGRF var 42 currently stored is valid.
63 NCVV_COMPANY_INFORMATION
= 3, ///< This bit will be set if the NewGRF var 43 currently stored is valid.
64 NCVV_POSITION_IN_VEHICLE
= 4, ///< This bit will be set if the NewGRF var 4D currently stored is valid.
65 NCVV_END
, ///< End of the bits.
68 /** Cached often queried (NewGRF) values */
70 /* Values calculated when they are requested for the first time after invalidating the NewGRF cache. */
71 uint32 position_consist_length
; ///< Cache for NewGRF var 40.
72 uint32 position_same_id_length
; ///< Cache for NewGRF var 41.
73 uint32 consist_cargo_information
; ///< Cache for NewGRF var 42. (Note: The cargotype is untranslated in the cache because the accessing GRF is yet unknown.)
74 uint32 company_information
; ///< Cache for NewGRF var 43.
75 uint32 position_in_vehicle
; ///< Cache for NewGRF var 4D.
76 uint8 cache_valid
; ///< Bitset that indicates which cache values are valid.
79 /** Meaning of the various bits of the visual effect. */
81 VE_OFFSET_START
= 0, ///< First bit that contains the offset (0 = front, 8 = centre, 15 = rear)
82 VE_OFFSET_COUNT
= 4, ///< Number of bits used for the offset
83 VE_OFFSET_CENTRE
= 8, ///< Value of offset corresponding to a position above the centre of the vehicle
85 VE_TYPE_START
= 4, ///< First bit used for the type of effect
86 VE_TYPE_COUNT
= 2, ///< Number of bits used for the effect type
87 VE_TYPE_DEFAULT
= 0, ///< Use default from engine class
88 VE_TYPE_STEAM
= 1, ///< Steam plumes
89 VE_TYPE_DIESEL
= 2, ///< Diesel fumes
90 VE_TYPE_ELECTRIC
= 3, ///< Electric sparks
92 VE_DISABLE_EFFECT
= 6, ///< Flag to disable visual effect
93 VE_ADVANCED_EFFECT
= VE_DISABLE_EFFECT
, ///< Flag for advanced effects
94 VE_DISABLE_WAGON_POWER
= 7, ///< Flag to disable wagon power
96 VE_DEFAULT
= 0xFF, ///< Default value to indicate that visual effect should be based on engine class
99 /** Models for spawning visual effects. */
100 enum VisualEffectSpawnModel
{
101 VESM_NONE
= 0, ///< No visual effect
102 VESM_STEAM
, ///< Steam model
103 VESM_DIESEL
, ///< Diesel model
104 VESM_ELECTRIC
, ///< Electric model
110 * Enum to handle ground vehicle subtypes.
111 * This is defined here instead of at #GroundVehicle because some common function require access to these flags.
112 * Do not access it directly unless you have to. Use the subtype access functions.
114 enum GroundVehicleSubtypeFlags
{
115 GVSF_FRONT
= 0, ///< Leading engine of a consist.
116 GVSF_ARTICULATED_PART
= 1, ///< Articulated part of an engine.
117 GVSF_WAGON
= 2, ///< Wagon (not used for road vehicles).
118 GVSF_ENGINE
= 3, ///< Engine that can be front engine, but might be placed behind another engine (not used for road vehicles).
119 GVSF_FREE_WAGON
= 4, ///< First in a wagon chain (in depot) (not used for road vehicles).
120 GVSF_MULTIHEADED
= 5, ///< Engine is multiheaded (not used for road vehicles).
123 /** Cached often queried values common to all vehicles. */
124 struct VehicleCache
{
125 uint16 cached_max_speed
; ///< Maximum speed of the consist (minimum of the max speed of all vehicles in the consist).
126 uint16 cached_cargo_age_period
; ///< Number of ticks before carried cargo is aged.
128 byte cached_vis_effect
; ///< Visual effect to show (see #VisualEffect)
131 /** Sprite sequence for a vehicle part. */
132 struct VehicleSpriteSeq
{
136 bool operator==(const VehicleSpriteSeq
&other
) const
138 return this->count
== other
.count
&& MemCmpT
<PalSpriteID
>(this->seq
, other
.seq
, this->count
) == 0;
141 bool operator!=(const VehicleSpriteSeq
&other
) const
143 return !this->operator==(other
);
147 * Check whether the sequence contains any sprites.
151 return this->count
!= 0;
155 * Clear all information.
163 * Assign a single sprite to the sequence.
165 void Set(SpriteID sprite
)
168 this->seq
[0].sprite
= sprite
;
169 this->seq
[0].pal
= 0;
173 * Copy data from another sprite sequence, while dropping all recolouring information.
175 void CopyWithoutPalette(const VehicleSpriteSeq
&src
)
177 this->count
= src
.count
;
178 for (uint i
= 0; i
< src
.count
; ++i
) {
179 this->seq
[i
].sprite
= src
.seq
[i
].sprite
;
180 this->seq
[i
].pal
= 0;
184 void GetBounds(Rect
*bounds
) const;
185 void Draw(int x
, int y
, PaletteID default_pal
, bool force_pal
) const;
189 * Cache for vehicle sprites and values relating to whether they should be updated before drawing,
190 * or calculating the viewport.
192 struct MutableSpriteCache
{
193 Direction last_direction
; ///< Last direction we obtained sprites for
194 bool revalidate_before_draw
; ///< We need to do a GetImage() and check bounds before drawing this sprite
195 Rect old_coord
; ///< Co-ordinates from the last valid bounding box
196 bool is_viewport_candidate
; ///< This vehicle can potentially be drawn on a viewport
197 VehicleSpriteSeq sprite_seq
; ///< Vehicle appearance.
200 /** A vehicle pool for a little over 1 million vehicles. */
201 typedef Pool
<Vehicle
, VehicleID
, 512, 0xFF000> VehiclePool
;
202 extern VehiclePool _vehicle_pool
;
204 /* Some declarations of functions, so we can make them friendly */
205 struct GroundVehicleCache
;
206 struct LoadgameState
;
207 extern bool LoadOldVehicle(LoadgameState
*ls
, int num
);
208 extern void FixOldVehicles();
213 * Simulated cargo type and capacity for prediction of future links.
216 CargoID cargo
; ///< Cargo type the vehicle will be carrying.
217 uint16 capacity
; ///< Capacity the vehicle will have.
218 uint16 remaining
; ///< Capacity remaining from before the previous refit.
219 RefitDesc(CargoID cargo
, uint16 capacity
, uint16 remaining
) :
220 cargo(cargo
), capacity(capacity
), remaining(remaining
) {}
223 /** %Vehicle data structure. */
224 struct Vehicle
: VehiclePool::PoolItem
<&_vehicle_pool
>, BaseVehicle
, BaseConsist
{
226 typedef std::list
<RefitDesc
> RefitList
;
227 typedef std::map
<CargoID
, uint
> CapacitiesMap
;
229 Vehicle
*next
; ///< pointer to the next vehicle in the chain
230 Vehicle
*previous
; ///< NOSAVE: pointer to the previous vehicle in the chain
231 Vehicle
*first
; ///< NOSAVE: pointer to the first vehicle in the chain
233 Vehicle
*next_shared
; ///< pointer to the next vehicle that shares the order
234 Vehicle
*previous_shared
; ///< NOSAVE: pointer to the previous vehicle in the shared order chain
237 friend void FixOldVehicles();
238 friend void AfterLoadVehicles(bool part_of_load
); ///< So we can set the #previous and #first pointers while loading
239 friend bool LoadOldVehicle(LoadgameState
*ls
, int num
); ///< So we can set the proper next pointer while loading
240 /* So we can use private/protected variables in the saveload code */
241 friend class SlVehicleCommon
;
242 friend class SlVehicleDisaster
;
243 friend void Ptrs_VEHS();
245 TileIndex tile
; ///< Current tile index
248 * Heading for this tile.
249 * For airports and train stations this tile does not necessarily belong to the destination station,
250 * but it can be used for heuristic purposes to estimate the distance.
254 Money profit_this_year
; ///< Profit this year << 8, low 8 bits are fract
255 Money profit_last_year
; ///< Profit last year << 8, low 8 bits are fract
256 Money value
; ///< Value of the vehicle
258 CargoPayment
*cargo_payment
; ///< The cargo payment we're currently in
260 mutable Rect coord
; ///< NOSAVE: Graphical bounding box of the vehicle, i.e. what to redraw on moves.
262 Vehicle
*hash_viewport_next
; ///< NOSAVE: Next vehicle in the visual location hash.
263 Vehicle
**hash_viewport_prev
; ///< NOSAVE: Previous vehicle in the visual location hash.
265 Vehicle
*hash_tile_next
; ///< NOSAVE: Next vehicle in the tile location hash.
266 Vehicle
**hash_tile_prev
; ///< NOSAVE: Previous vehicle in the tile location hash.
267 Vehicle
**hash_tile_current
; ///< NOSAVE: Cache of the current hash chain.
269 SpriteID colourmap
; ///< NOSAVE: cached colour mapping
271 /* Related to age and service time */
272 Year build_year
; ///< Year the vehicle has been built.
273 Date age
; ///< Age in days
274 Date max_age
; ///< Maximum age
275 Date date_of_last_service
; ///< Last date the vehicle had a service at a depot.
276 uint16 reliability
; ///< Reliability.
277 uint16 reliability_spd_dec
; ///< Reliability decrease speed.
278 byte breakdown_ctr
; ///< Counter for managing breakdown events. @see Vehicle::HandleBreakdown
279 byte breakdown_delay
; ///< Counter for managing breakdown length.
280 byte breakdowns_since_last_service
; ///< Counter for the amount of breakdowns.
281 byte breakdown_chance
; ///< Current chance of breakdowns.
283 int32 x_pos
; ///< x coordinate.
284 int32 y_pos
; ///< y coordinate.
285 int32 z_pos
; ///< z coordinate.
286 Direction direction
; ///< facing
288 Owner owner
; ///< Which company owns the vehicle?
290 * currently displayed sprite index
291 * 0xfd == custom sprite, 0xfe == custom second head sprite
292 * 0xff == reserved for another custom sprite
295 byte x_extent
; ///< x-extent of vehicle bounding box
296 byte y_extent
; ///< y-extent of vehicle bounding box
297 byte z_extent
; ///< z-extent of vehicle bounding box
298 int8 x_bb_offs
; ///< x offset of vehicle bounding box
299 int8 y_bb_offs
; ///< y offset of vehicle bounding box
300 int8 x_offs
; ///< x offset for vehicle sprite
301 int8 y_offs
; ///< y offset for vehicle sprite
302 EngineID engine_type
; ///< The type of engine used for this vehicle.
304 TextEffectID fill_percent_te_id
; ///< a text-effect id to a loading indicator object
305 UnitID unitnumber
; ///< unit number, for display purposes only
307 uint16 cur_speed
; ///< current speed
308 byte subspeed
; ///< fractional speed
309 byte acceleration
; ///< used by train & aircraft
310 uint32 motion_counter
; ///< counter to occasionally play a vehicle sound.
311 byte progress
; ///< The percentage (if divided by 256) this vehicle already crossed the tile unit.
313 byte random_bits
; ///< Bits used for determining which randomized variational spritegroups to use when drawing.
314 byte waiting_triggers
; ///< Triggers to be yet matched before rerandomizing the random bits.
316 StationID last_station_visited
; ///< The last station we stopped at.
317 StationID last_loading_station
; ///< Last station the vehicle has stopped at and could possibly leave from with any cargo loaded.
319 CargoID cargo_type
; ///< type of cargo this vehicle is carrying
320 byte cargo_subtype
; ///< Used for livery refits (NewGRF variations)
321 uint16 cargo_cap
; ///< total capacity
322 uint16 refit_cap
; ///< Capacity left over from before last refit.
323 VehicleCargoList cargo
; ///< The cargo this vehicle is carrying
324 uint16 cargo_age_counter
; ///< Ticks till cargo is aged next.
325 int8 trip_occupancy
; ///< NOSAVE: Occupancy of vehicle of the current trip (updated after leaving a station).
327 byte day_counter
; ///< Increased by one for each day
328 byte tick_counter
; ///< Increased by one for each tick
329 byte running_ticks
; ///< Number of ticks this vehicle was not stopped this day
331 byte vehstatus
; ///< Status
332 Order current_order
; ///< The current order (+ status, like: loading)
335 OrderList
*orders
; ///< Pointer to the order list for this vehicle
336 Order
*old_orders
; ///< Only used during conversion of old save games
339 uint16 load_unload_ticks
; ///< Ticks to wait before starting next cycle.
340 GroupID group_id
; ///< Index of group Pool array
341 byte subtype
; ///< subtype (Filled with values from #AircraftSubType/#DisasterSubType/#EffectVehicleType/#GroundVehicleSubtypeFlags)
343 NewGRFCache grf_cache
; ///< Cache of often used calculated NewGRF values
344 VehicleCache vcache
; ///< Cache of often used vehicle values.
346 mutable MutableSpriteCache sprite_cache
; ///< Cache of sprites and values related to recalculating them, see #MutableSpriteCache
348 Vehicle(VehicleType type
= VEH_INVALID
);
350 void PreDestructor();
351 /** We want to 'destruct' the right class. */
355 void CancelReservation(StationID next
, Station
*st
);
358 GroundVehicleCache
*GetGroundVehicleCache();
359 const GroundVehicleCache
*GetGroundVehicleCache() const;
361 uint16
&GetGroundVehicleFlags();
362 const uint16
&GetGroundVehicleFlags() const;
364 void DeleteUnreachedImplicitOrders();
366 void HandleLoading(bool mode
= false);
368 void GetConsistFreeCapacities(SmallMap
<CargoID
, uint
> &capacities
) const;
370 uint
GetConsistTotalCapacity() const;
373 * Marks the vehicles to be redrawn and updates cached variables
375 * This method marks the area of the vehicle on the screen as dirty.
376 * It can be use to repaint the vehicle.
380 virtual void MarkDirty() {}
383 * Updates the x and y offsets and the size of the sprite used
386 virtual void UpdateDeltaXY() {}
389 * Determines the effective direction-specific vehicle movement speed.
391 * This method belongs to the old vehicle movement method:
392 * A vehicle moves a step every 256 progress units.
393 * The vehicle speed is scaled by 3/4 when moving in X or Y direction due to the longer distance.
395 * However, this method is slightly wrong in corners, as the leftover progress is not scaled correctly
396 * when changing movement direction. #GetAdvanceSpeed() and #GetAdvanceDistance() are better wrt. this.
398 * @param speed Direction-independent unscaled speed.
399 * @return speed scaled by movement direction. 256 units are required for each movement step.
401 inline uint
GetOldAdvanceSpeed(uint speed
)
403 return (this->direction
& 1) ? speed
: speed
* 3 / 4;
407 * Determines the effective vehicle movement speed.
409 * Together with #GetAdvanceDistance() this function is a replacement for #GetOldAdvanceSpeed().
411 * A vehicle progresses independent of it's movement direction.
412 * However different amounts of "progress" are needed for moving a step in a specific direction.
413 * That way the leftover progress does not need any adaption when changing movement direction.
415 * @param speed Direction-independent unscaled speed.
416 * @return speed, scaled to match #GetAdvanceDistance().
418 static inline uint
GetAdvanceSpeed(uint speed
)
420 return speed
* 3 / 4;
424 * Determines the vehicle "progress" needed for moving a step.
426 * Together with #GetAdvanceSpeed() this function is a replacement for #GetOldAdvanceSpeed().
428 * @return distance to drive for a movement step on the map.
430 inline uint
GetAdvanceDistance()
432 return (this->direction
& 1) ? TILE_AXIAL_DISTANCE
: TILE_CORNER_DISTANCE
* 2;
436 * Sets the expense type associated to this vehicle type
437 * @param income whether this is income or (running) expenses of the vehicle
439 virtual ExpensesType
GetExpenseType(bool income
) const { return EXPENSES_OTHER
; }
442 * Play the sound associated with leaving the station
444 virtual void PlayLeaveStationSound() const {}
447 * Whether this is the primary vehicle in the chain.
449 virtual bool IsPrimaryVehicle() const { return false; }
451 const Engine
*GetEngine() const;
454 * Gets the sprite to show for the given direction
455 * @param direction the direction the vehicle is facing
456 * @param[out] result Vehicle sprite sequence.
458 virtual void GetImage(Direction direction
, EngineImageType image_type
, VehicleSpriteSeq
*result
) const { result
->Clear(); }
460 const GRFFile
*GetGRF() const;
461 uint32
GetGRFID() const;
464 * Invalidates cached NewGRF variables
465 * @see InvalidateNewGRFCacheOfChain
467 inline void InvalidateNewGRFCache()
469 this->grf_cache
.cache_valid
= 0;
473 * Invalidates cached NewGRF variables of all vehicles in the chain (after the current vehicle)
474 * @see InvalidateNewGRFCache
476 inline void InvalidateNewGRFCacheOfChain()
478 for (Vehicle
*u
= this; u
!= nullptr; u
= u
->Next()) {
479 u
->InvalidateNewGRFCache();
484 * Check if the vehicle is a ground vehicle.
485 * @return True iff the vehicle is a train or a road vehicle.
487 inline bool IsGroundVehicle() const
489 return this->type
== VEH_TRAIN
|| this->type
== VEH_ROAD
;
493 * Gets the speed in km-ish/h that can be sent into SetDParam for string processing.
494 * @return the vehicle's speed
496 virtual int GetDisplaySpeed() const { return 0; }
499 * Gets the maximum speed in km-ish/h that can be sent into SetDParam for string processing.
500 * @return the vehicle's maximum speed
502 virtual int GetDisplayMaxSpeed() const { return 0; }
505 * Calculates the maximum speed of the vehicle under its current conditions.
506 * @return Current maximum speed in native units.
508 virtual int GetCurrentMaxSpeed() const { return 0; }
511 * Gets the running cost of a vehicle
512 * @return the vehicle's running cost
514 virtual Money
GetRunningCost() const { return 0; }
517 * Check whether the vehicle is in the depot.
518 * @return true if and only if the vehicle is in the depot.
520 virtual bool IsInDepot() const { return false; }
523 * Check whether the whole vehicle chain is in the depot.
524 * @return true if and only if the whole chain is in the depot.
526 virtual bool IsChainInDepot() const { return this->IsInDepot(); }
529 * Check whether the vehicle is in the depot *and* stopped.
530 * @return true if and only if the vehicle is in the depot and stopped.
532 bool IsStoppedInDepot() const
534 assert(this == this->First());
535 /* Free wagons have no VS_STOPPED state */
536 if (this->IsPrimaryVehicle() && !(this->vehstatus
& VS_STOPPED
)) return false;
537 return this->IsChainInDepot();
541 * Calls the tick handler of the vehicle
542 * @return is this vehicle still valid?
544 virtual bool Tick() { return true; };
547 * Calls the new day handler of the vehicle
549 virtual void OnNewDay() {};
551 void ShiftDates(int interval
);
554 * Crash the (whole) vehicle chain.
555 * @param flooded whether the cause of the crash is flooding or not.
556 * @return the number of lost souls.
558 virtual uint
Crash(bool flooded
= false);
561 * Returns the Trackdir on which the vehicle is currently located.
562 * Works for trains and ships.
563 * Currently works only sortof for road vehicles, since they have a fuzzy
564 * concept of being "on" a trackdir. Dunno really what it returns for a road
565 * vehicle that is halfway a tile, never really understood that part. For road
566 * vehicles that are at the beginning or end of the tile, should just return
567 * the diagonal trackdir on which they are driving. I _think_.
568 * For other vehicles types, or vehicles with no clear trackdir (such as those
569 * in depots), returns 0xFF.
570 * @return the trackdir of the vehicle
572 virtual Trackdir
GetVehicleTrackdir() const { return INVALID_TRACKDIR
; }
575 * Gets the running cost of a vehicle that can be sent into SetDParam for string processing.
576 * @return the vehicle's running cost
578 Money
GetDisplayRunningCost() const { return (this->GetRunningCost() >> 8); }
581 * Gets the profit vehicle had this year. It can be sent into SetDParam for string processing.
582 * @return the vehicle's profit this year
584 Money
GetDisplayProfitThisYear() const { return (this->profit_this_year
>> 8); }
587 * Gets the profit vehicle had last year. It can be sent into SetDParam for string processing.
588 * @return the vehicle's profit last year
590 Money
GetDisplayProfitLastYear() const { return (this->profit_last_year
>> 8); }
592 void SetNext(Vehicle
*next
);
595 * Get the next vehicle of this vehicle.
596 * @note articulated parts are also counted as vehicles.
597 * @return the next vehicle or nullptr when there isn't a next vehicle.
599 inline Vehicle
*Next() const { return this->next
; }
602 * Get the previous vehicle of this vehicle.
603 * @note articulated parts are also counted as vehicles.
604 * @return the previous vehicle or nullptr when there isn't a previous vehicle.
606 inline Vehicle
*Previous() const { return this->previous
; }
609 * Get the first vehicle of this vehicle chain.
610 * @return the first vehicle of the chain.
612 inline Vehicle
*First() const { return this->first
; }
615 * Get the last vehicle of this vehicle chain.
616 * @return the last vehicle of the chain.
618 inline Vehicle
*Last()
621 while (v
->Next() != nullptr) v
= v
->Next();
626 * Get the last vehicle of this vehicle chain.
627 * @return the last vehicle of the chain.
629 inline const Vehicle
*Last() const
631 const Vehicle
*v
= this;
632 while (v
->Next() != nullptr) v
= v
->Next();
637 * Get the vehicle at offset \a n of this vehicle chain.
638 * @param n Offset from the current vehicle.
639 * @return The new vehicle or nullptr if the offset is out-of-bounds.
641 inline Vehicle
*Move(int n
)
645 for (int i
= 0; i
!= n
&& v
!= nullptr; i
--) v
= v
->Previous();
647 for (int i
= 0; i
!= n
&& v
!= nullptr; i
++) v
= v
->Next();
653 * Get the vehicle at offset \a n of this vehicle chain.
654 * @param n Offset from the current vehicle.
655 * @return The new vehicle or nullptr if the offset is out-of-bounds.
657 inline const Vehicle
*Move(int n
) const
659 const Vehicle
*v
= this;
661 for (int i
= 0; i
!= n
&& v
!= nullptr; i
--) v
= v
->Previous();
663 for (int i
= 0; i
!= n
&& v
!= nullptr; i
++) v
= v
->Next();
669 * Get the first order of the vehicles order list.
670 * @return first order of order list.
672 inline Order
*GetFirstOrder() const { return (this->orders
== nullptr) ? nullptr : this->orders
->GetFirstOrder(); }
674 void AddToShared(Vehicle
*shared_chain
);
675 void RemoveFromShared();
678 * Get the next vehicle of the shared vehicle chain.
679 * @return the next shared vehicle or nullptr when there isn't a next vehicle.
681 inline Vehicle
*NextShared() const { return this->next_shared
; }
684 * Get the previous vehicle of the shared vehicle chain
685 * @return the previous shared vehicle or nullptr when there isn't a previous vehicle.
687 inline Vehicle
*PreviousShared() const { return this->previous_shared
; }
690 * Get the first vehicle of this vehicle chain.
691 * @return the first vehicle of the chain.
693 inline Vehicle
*FirstShared() const { return (this->orders
== nullptr) ? this->First() : this->orders
->GetFirstSharedVehicle(); }
696 * Check if we share our orders with another vehicle.
697 * @return true if there are other vehicles sharing the same order
699 inline bool IsOrderListShared() const { return this->orders
!= nullptr && this->orders
->IsShared(); }
702 * Get the number of orders this vehicle has.
703 * @return the number of orders this vehicle has.
705 inline VehicleOrderID
GetNumOrders() const { return (this->orders
== nullptr) ? 0 : this->orders
->GetNumOrders(); }
708 * Get the number of manually added orders this vehicle has.
709 * @return the number of manually added orders this vehicle has.
711 inline VehicleOrderID
GetNumManualOrders() const { return (this->orders
== nullptr) ? 0 : this->orders
->GetNumManualOrders(); }
714 * Get the next station the vehicle will stop at.
715 * @return ID of the next station the vehicle will stop at or INVALID_STATION.
717 inline StationIDStack
GetNextStoppingStation() const
719 return (this->orders
== nullptr) ? INVALID_STATION
: this->orders
->GetNextStoppingStation(this);
722 void ResetRefitCaps();
725 * Copy certain configurations and statistics of a vehicle after successful autoreplace/renew
726 * The function shall copy everything that cannot be copied by a command (like orders / group etc),
727 * and that shall not be resetted for the new vehicle.
728 * @param src The old vehicle
730 inline void CopyVehicleConfigAndStatistics(const Vehicle
*src
)
732 this->CopyConsistPropertiesFrom(src
);
734 this->unitnumber
= src
->unitnumber
;
736 this->current_order
= src
->current_order
;
737 this->dest_tile
= src
->dest_tile
;
739 this->profit_this_year
= src
->profit_this_year
;
740 this->profit_last_year
= src
->profit_last_year
;
744 bool HandleBreakdown();
746 bool NeedsAutorenewing(const Company
*c
, bool use_renew_setting
= true) const;
748 bool NeedsServicing() const;
749 bool NeedsAutomaticServicing() const;
752 * Determine the location for the station where the vehicle goes to next.
753 * Things done for example are allocating slots in a road stop or exact
754 * location of the platform is determined for ships.
755 * @param station the station to make the next location of the vehicle.
756 * @return the location (tile) to aim for.
758 virtual TileIndex
GetOrderStationLocation(StationID station
) { return INVALID_TILE
; }
761 * Find the closest depot for this vehicle and tell us the location,
762 * DestinationID and whether we should reverse.
763 * @param location where do we go to?
764 * @param destination what hangar do we go to?
765 * @param reverse should the vehicle be reversed?
766 * @return true if a depot could be found.
768 virtual bool FindClosestDepot(TileIndex
*location
, DestinationID
*destination
, bool *reverse
) { return false; }
770 virtual void SetDestTile(TileIndex tile
) { this->dest_tile
= tile
; }
772 CommandCost
SendToDepot(DoCommandFlag flags
, DepotCommand command
);
774 void UpdateVisualEffect(bool allow_power_change
= true);
775 void ShowVisualEffect() const;
777 void UpdatePosition();
778 void UpdateViewport(bool dirty
);
779 void UpdateBoundingBoxCoordinates(bool update_cache
) const;
780 void UpdatePositionAndViewport();
781 bool MarkAllViewportsDirty() const;
783 inline uint16
GetServiceInterval() const { return this->service_interval
; }
785 inline void SetServiceInterval(uint16 interval
) { this->service_interval
= interval
; }
787 inline bool ServiceIntervalIsCustom() const { return HasBit(this->vehicle_flags
, VF_SERVINT_IS_CUSTOM
); }
789 inline bool ServiceIntervalIsPercent() const { return HasBit(this->vehicle_flags
, VF_SERVINT_IS_PERCENT
); }
791 inline void SetServiceIntervalIsCustom(bool on
) { SB(this->vehicle_flags
, VF_SERVINT_IS_CUSTOM
, 1, on
); }
793 inline void SetServiceIntervalIsPercent(bool on
) { SB(this->vehicle_flags
, VF_SERVINT_IS_PERCENT
, 1, on
); }
797 * Advance cur_real_order_index to the next real order.
798 * cur_implicit_order_index is not touched.
800 void SkipToNextRealOrderIndex()
802 if (this->GetNumManualOrders() > 0) {
803 /* Advance to next real order */
805 this->cur_real_order_index
++;
806 if (this->cur_real_order_index
>= this->GetNumOrders()) this->cur_real_order_index
= 0;
807 } while (this->GetOrder(this->cur_real_order_index
)->IsType(OT_IMPLICIT
));
809 this->cur_real_order_index
= 0;
815 * Increments cur_implicit_order_index, keeps care of the wrap-around and invalidates the GUI.
816 * cur_real_order_index is incremented as well, if needed.
817 * Note: current_order is not invalidated.
819 void IncrementImplicitOrderIndex()
821 if (this->cur_implicit_order_index
== this->cur_real_order_index
) {
822 /* Increment real order index as well */
823 this->SkipToNextRealOrderIndex();
826 assert(this->cur_real_order_index
== 0 || this->cur_real_order_index
< this->GetNumOrders());
828 /* Advance to next implicit order */
830 this->cur_implicit_order_index
++;
831 if (this->cur_implicit_order_index
>= this->GetNumOrders()) this->cur_implicit_order_index
= 0;
832 } while (this->cur_implicit_order_index
!= this->cur_real_order_index
&& !this->GetOrder(this->cur_implicit_order_index
)->IsType(OT_IMPLICIT
));
834 InvalidateVehicleOrder(this, 0);
838 * Advanced cur_real_order_index to the next real order, keeps care of the wrap-around and invalidates the GUI.
839 * 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
840 * but not any implicit orders.
841 * Note: current_order is not invalidated.
843 void IncrementRealOrderIndex()
845 if (this->cur_implicit_order_index
== this->cur_real_order_index
) {
846 /* Increment both real and implicit order */
847 this->IncrementImplicitOrderIndex();
849 /* Increment real order only */
850 this->SkipToNextRealOrderIndex();
851 InvalidateVehicleOrder(this, 0);
856 * Skip implicit orders until cur_real_order_index is a non-implicit order.
858 void UpdateRealOrderIndex()
860 /* Make sure the index is valid */
861 if (this->cur_real_order_index
>= this->GetNumOrders()) this->cur_real_order_index
= 0;
863 if (this->GetNumManualOrders() > 0) {
864 /* Advance to next real order */
865 while (this->GetOrder(this->cur_real_order_index
)->IsType(OT_IMPLICIT
)) {
866 this->cur_real_order_index
++;
867 if (this->cur_real_order_index
>= this->GetNumOrders()) this->cur_real_order_index
= 0;
870 this->cur_real_order_index
= 0;
875 * Returns order 'index' of a vehicle or nullptr when it doesn't exists
876 * @param index the order to fetch
877 * @return the found (or not) order
879 inline Order
*GetOrder(int index
) const
881 return (this->orders
== nullptr) ? nullptr : this->orders
->GetOrderAt(index
);
885 * Returns the last order of a vehicle, or nullptr if it doesn't exists
886 * @return last order of a vehicle, if available
888 inline Order
*GetLastOrder() const
890 return (this->orders
== nullptr) ? nullptr : this->orders
->GetLastOrder();
893 bool IsEngineCountable() const;
894 bool HasEngineType() const;
895 bool HasDepotOrder() const;
896 void HandlePathfindingResult(bool path_found
);
899 * Check if the vehicle is a front engine.
900 * @return Returns true if the vehicle is a front engine.
902 inline bool IsFrontEngine() const
904 return this->IsGroundVehicle() && HasBit(this->subtype
, GVSF_FRONT
);
908 * Check if the vehicle is an articulated part of an engine.
909 * @return Returns true if the vehicle is an articulated part.
911 inline bool IsArticulatedPart() const
913 return this->IsGroundVehicle() && HasBit(this->subtype
, GVSF_ARTICULATED_PART
);
917 * Check if an engine has an articulated part.
918 * @return True if the engine has an articulated part.
920 inline bool HasArticulatedPart() const
922 return this->Next() != nullptr && this->Next()->IsArticulatedPart();
926 * Get the next part of an articulated engine.
927 * @return Next part of the articulated engine.
928 * @pre The vehicle is an articulated engine.
930 inline Vehicle
*GetNextArticulatedPart() const
932 assert(this->HasArticulatedPart());
937 * Get the first part of an articulated engine.
938 * @return First part of the engine.
940 inline Vehicle
*GetFirstEnginePart()
943 while (v
->IsArticulatedPart()) v
= v
->Previous();
948 * Get the first part of an articulated engine.
949 * @return First part of the engine.
951 inline const Vehicle
*GetFirstEnginePart() const
953 const Vehicle
*v
= this;
954 while (v
->IsArticulatedPart()) v
= v
->Previous();
959 * Get the last part of an articulated engine.
960 * @return Last part of the engine.
962 inline Vehicle
*GetLastEnginePart()
965 while (v
->HasArticulatedPart()) v
= v
->GetNextArticulatedPart();
970 * Get the next real (non-articulated part) vehicle in the consist.
971 * @return Next vehicle in the consist.
973 inline Vehicle
*GetNextVehicle() const
975 const Vehicle
*v
= this;
976 while (v
->HasArticulatedPart()) v
= v
->GetNextArticulatedPart();
978 /* v now contains the last articulated part in the engine */
983 * Get the previous real (non-articulated part) vehicle in the consist.
984 * @return Previous vehicle in the consist.
986 inline Vehicle
*GetPrevVehicle() const
988 Vehicle
*v
= this->Previous();
989 while (v
!= nullptr && v
->IsArticulatedPart()) v
= v
->Previous();
995 * Iterator to iterate orders
996 * Supports deletion of current order
998 struct OrderIterator
{
999 typedef Order value_type
;
1000 typedef Order
* pointer
;
1001 typedef Order
& reference
;
1002 typedef size_t difference_type
;
1003 typedef std::forward_iterator_tag iterator_category
;
1005 explicit OrderIterator(OrderList
*list
) : list(list
), prev(nullptr)
1007 this->order
= (this->list
== nullptr) ? nullptr : this->list
->GetFirstOrder();
1010 bool operator==(const OrderIterator
&other
) const { return this->order
== other
.order
; }
1011 bool operator!=(const OrderIterator
&other
) const { return !(*this == other
); }
1012 Order
* operator*() const { return this->order
; }
1013 OrderIterator
& operator++()
1015 this->prev
= (this->prev
== nullptr) ? this->list
->GetFirstOrder() : this->prev
->next
;
1016 this->order
= (this->prev
== nullptr) ? nullptr : this->prev
->next
;
1027 * Iterable ensemble of orders
1029 struct IterateWrapper
{
1031 IterateWrapper(OrderList
*list
= nullptr) : list(list
) {}
1032 OrderIterator
begin() { return OrderIterator(this->list
); }
1033 OrderIterator
end() { return OrderIterator(nullptr); }
1034 bool empty() { return this->begin() == this->end(); }
1038 * Returns an iterable ensemble of orders of a vehicle
1039 * @return an iterable ensemble of orders of a vehicle
1041 IterateWrapper
Orders() const { return IterateWrapper(this->orders
); }
1045 * Class defining several overloaded accessors so we don't
1046 * have to cast vehicle types that often
1048 template <class T
, VehicleType Type
>
1049 struct SpecializedVehicle
: public Vehicle
{
1050 static const VehicleType EXPECTED_TYPE
= Type
; ///< Specialized type
1052 typedef SpecializedVehicle
<T
, Type
> SpecializedVehicleBase
; ///< Our type
1055 * Set vehicle type correctly
1057 inline SpecializedVehicle
<T
, Type
>() : Vehicle(Type
)
1059 this->sprite_cache
.sprite_seq
.count
= 1;
1063 * Get the first vehicle in the chain
1064 * @return first vehicle in the chain
1066 inline T
*First() const { return (T
*)this->Vehicle::First(); }
1069 * Get the last vehicle in the chain
1070 * @return last vehicle in the chain
1072 inline T
*Last() { return (T
*)this->Vehicle::Last(); }
1075 * Get the last vehicle in the chain
1076 * @return last vehicle in the chain
1078 inline const T
*Last() const { return (const T
*)this->Vehicle::Last(); }
1081 * Get next vehicle in the chain
1082 * @return next vehicle in the chain
1084 inline T
*Next() const { return (T
*)this->Vehicle::Next(); }
1087 * Get previous vehicle in the chain
1088 * @return previous vehicle in the chain
1090 inline T
*Previous() const { return (T
*)this->Vehicle::Previous(); }
1093 * Get the next part of an articulated engine.
1094 * @return Next part of the articulated engine.
1095 * @pre The vehicle is an articulated engine.
1097 inline T
*GetNextArticulatedPart() { return (T
*)this->Vehicle::GetNextArticulatedPart(); }
1100 * Get the next part of an articulated engine.
1101 * @return Next part of the articulated engine.
1102 * @pre The vehicle is an articulated engine.
1104 inline T
*GetNextArticulatedPart() const { return (T
*)this->Vehicle::GetNextArticulatedPart(); }
1107 * Get the first part of an articulated engine.
1108 * @return First part of the engine.
1110 inline T
*GetFirstEnginePart() { return (T
*)this->Vehicle::GetFirstEnginePart(); }
1113 * Get the first part of an articulated engine.
1114 * @return First part of the engine.
1116 inline const T
*GetFirstEnginePart() const { return (const T
*)this->Vehicle::GetFirstEnginePart(); }
1119 * Get the last part of an articulated engine.
1120 * @return Last part of the engine.
1122 inline T
*GetLastEnginePart() { return (T
*)this->Vehicle::GetLastEnginePart(); }
1125 * Get the next real (non-articulated part) vehicle in the consist.
1126 * @return Next vehicle in the consist.
1128 inline T
*GetNextVehicle() const { return (T
*)this->Vehicle::GetNextVehicle(); }
1131 * Get the previous real (non-articulated part) vehicle in the consist.
1132 * @return Previous vehicle in the consist.
1134 inline T
*GetPrevVehicle() const { return (T
*)this->Vehicle::GetPrevVehicle(); }
1137 * Tests whether given index is a valid index for vehicle of this type
1138 * @param index tested index
1139 * @return is this index valid index of T?
1141 static inline bool IsValidID(size_t index
)
1143 return Vehicle::IsValidID(index
) && Vehicle::Get(index
)->type
== Type
;
1147 * Gets vehicle with given index
1148 * @return pointer to vehicle with given index casted to T *
1150 static inline T
*Get(size_t index
)
1152 return (T
*)Vehicle::Get(index
);
1156 * Returns vehicle if the index is a valid index for this vehicle type
1157 * @return pointer to vehicle with given index if it's a vehicle of this type
1159 static inline T
*GetIfValid(size_t index
)
1161 return IsValidID(index
) ? Get(index
) : nullptr;
1165 * Converts a Vehicle to SpecializedVehicle with type checking.
1166 * @param v Vehicle pointer
1167 * @return pointer to SpecializedVehicle
1169 static inline T
*From(Vehicle
*v
)
1171 assert(v
->type
== Type
);
1176 * Converts a const Vehicle to const SpecializedVehicle with type checking.
1177 * @param v Vehicle pointer
1178 * @return pointer to SpecializedVehicle
1180 static inline const T
*From(const Vehicle
*v
)
1182 assert(v
->type
== Type
);
1183 return (const T
*)v
;
1187 * Update vehicle sprite- and position caches
1188 * @param force_update Force updating the vehicle on the viewport.
1189 * @param update_delta Also update the delta?
1191 inline void UpdateViewport(bool force_update
, bool update_delta
)
1193 bool sprite_has_changed
= false;
1195 /* Skip updating sprites on dedicated servers without screen */
1196 if (_network_dedicated
) return;
1198 /* Explicitly choose method to call to prevent vtable dereference -
1199 * it gives ~3% runtime improvements in games with many vehicles */
1200 if (update_delta
) ((T
*)this)->T::UpdateDeltaXY();
1203 * Only check for a new sprite sequence if the vehicle direction
1204 * has changed since we last checked it, assuming that otherwise
1205 * there won't be enough change in bounding box or offsets to need
1206 * to resolve a new sprite.
1208 if (this->direction
!= this->sprite_cache
.last_direction
|| this->sprite_cache
.is_viewport_candidate
) {
1209 VehicleSpriteSeq seq
;
1211 ((T
*)this)->T::GetImage(this->direction
, EIT_ON_MAP
, &seq
);
1212 if (this->sprite_cache
.sprite_seq
!= seq
) {
1213 sprite_has_changed
= true;
1214 this->sprite_cache
.sprite_seq
= seq
;
1217 this->sprite_cache
.last_direction
= this->direction
;
1218 this->sprite_cache
.revalidate_before_draw
= false;
1221 * A change that could potentially invalidate the sprite has been
1222 * made, signal that we should still resolve it before drawing on a
1225 this->sprite_cache
.revalidate_before_draw
= true;
1228 if (force_update
|| sprite_has_changed
) {
1229 this->Vehicle::UpdateViewport(true);
1234 * Returns an iterable ensemble of all valid vehicles of type T
1235 * @param from index of the first vehicle to consider
1236 * @return an iterable ensemble of all valid vehicles of type T
1238 static Pool::IterateWrapper
<T
> Iterate(size_t from
= 0) { return Pool::IterateWrapper
<T
>(from
); }
1241 /** Generates sequence of free UnitID numbers */
1242 struct FreeUnitIDGenerator
{
1243 bool *cache
; ///< array of occupied unit id numbers
1244 UnitID maxid
; ///< maximum ID at the moment of constructor call
1245 UnitID curid
; ///< last ID returned; 0 if none
1247 FreeUnitIDGenerator(VehicleType type
, CompanyID owner
);
1250 /** Releases allocated memory */
1251 ~FreeUnitIDGenerator() { free(this->cache
); }
1254 /** Sentinel for an invalid coordinate. */
1255 static const int32 INVALID_COORD
= 0x7fffffff;
1257 #endif /* VEHICLE_BASE_H */