Add: allow making heightmap screenshot via console
[openttd-github.git] / src / vehicle_base.h
blobf80faf1e395e0bdfdec50d64e68f974b359b3d16
1 /*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6 */
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 <list>
26 #include <map>
28 /** Vehicle status bits in #Vehicle::vehstatus. */
29 enum VehStatus {
30 VS_HIDDEN = 0x01, ///< Vehicle is not visible.
31 VS_STOPPED = 0x02, ///< Vehicle is stopped by the player.
32 VS_UNCLICKABLE = 0x04, ///< Vehicle is not clickable by the user (shadow vehicles).
33 VS_DEFPAL = 0x08, ///< Use default vehicle palette. @see DoDrawVehicle
34 VS_TRAIN_SLOWING = 0x10, ///< Train is slowing down.
35 VS_SHADOW = 0x20, ///< Vehicle is a shadow vehicle.
36 VS_AIRCRAFT_BROKEN = 0x40, ///< Aircraft is broken down.
37 VS_CRASHED = 0x80, ///< Vehicle is crashed.
40 /** Bit numbers in #Vehicle::vehicle_flags. */
41 enum VehicleFlags {
42 VF_LOADING_FINISHED, ///< Vehicle has finished loading.
43 VF_CARGO_UNLOADING, ///< Vehicle is unloading cargo.
44 VF_BUILT_AS_PROTOTYPE, ///< Vehicle is a prototype (accepted as exclusive preview).
45 VF_TIMETABLE_STARTED, ///< Whether the vehicle has started running on the timetable yet.
46 VF_AUTOFILL_TIMETABLE, ///< Whether the vehicle should fill in the timetable automatically.
47 VF_AUTOFILL_PRES_WAIT_TIME, ///< Whether non-destructive auto-fill should preserve waiting times
48 VF_STOP_LOADING, ///< Don't load anymore during the next load cycle.
49 VF_PATHFINDER_LOST, ///< Vehicle's pathfinder is lost.
50 VF_SERVINT_IS_CUSTOM, ///< Service interval is custom.
51 VF_SERVINT_IS_PERCENT, ///< Service interval is percent.
54 /** Bit numbers used to indicate which of the #NewGRFCache values are valid. */
55 enum NewGRFCacheValidValues {
56 NCVV_POSITION_CONSIST_LENGTH = 0, ///< This bit will be set if the NewGRF var 40 currently stored is valid.
57 NCVV_POSITION_SAME_ID_LENGTH = 1, ///< This bit will be set if the NewGRF var 41 currently stored is valid.
58 NCVV_CONSIST_CARGO_INFORMATION = 2, ///< This bit will be set if the NewGRF var 42 currently stored is valid.
59 NCVV_COMPANY_INFORMATION = 3, ///< This bit will be set if the NewGRF var 43 currently stored is valid.
60 NCVV_POSITION_IN_VEHICLE = 4, ///< This bit will be set if the NewGRF var 4D currently stored is valid.
61 NCVV_END, ///< End of the bits.
64 /** Cached often queried (NewGRF) values */
65 struct NewGRFCache {
66 /* Values calculated when they are requested for the first time after invalidating the NewGRF cache. */
67 uint32 position_consist_length; ///< Cache for NewGRF var 40.
68 uint32 position_same_id_length; ///< Cache for NewGRF var 41.
69 uint32 consist_cargo_information; ///< Cache for NewGRF var 42. (Note: The cargotype is untranslated in the cache because the accessing GRF is yet unknown.)
70 uint32 company_information; ///< Cache for NewGRF var 43.
71 uint32 position_in_vehicle; ///< Cache for NewGRF var 4D.
72 uint8 cache_valid; ///< Bitset that indicates which cache values are valid.
75 /** Meaning of the various bits of the visual effect. */
76 enum VisualEffect {
77 VE_OFFSET_START = 0, ///< First bit that contains the offset (0 = front, 8 = centre, 15 = rear)
78 VE_OFFSET_COUNT = 4, ///< Number of bits used for the offset
79 VE_OFFSET_CENTRE = 8, ///< Value of offset corresponding to a position above the centre of the vehicle
81 VE_TYPE_START = 4, ///< First bit used for the type of effect
82 VE_TYPE_COUNT = 2, ///< Number of bits used for the effect type
83 VE_TYPE_DEFAULT = 0, ///< Use default from engine class
84 VE_TYPE_STEAM = 1, ///< Steam plumes
85 VE_TYPE_DIESEL = 2, ///< Diesel fumes
86 VE_TYPE_ELECTRIC = 3, ///< Electric sparks
88 VE_DISABLE_EFFECT = 6, ///< Flag to disable visual effect
89 VE_ADVANCED_EFFECT = VE_DISABLE_EFFECT, ///< Flag for advanced effects
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
95 /** Models for spawning visual effects. */
96 enum VisualEffectSpawnModel {
97 VESM_NONE = 0, ///< No visual effect
98 VESM_STEAM, ///< Steam model
99 VESM_DIESEL, ///< Diesel model
100 VESM_ELECTRIC, ///< Electric model
102 VESM_END
106 * Enum to handle ground vehicle subtypes.
107 * This is defined here instead of at #GroundVehicle because some common function require access to these flags.
108 * Do not access it directly unless you have to. Use the subtype access functions.
110 enum GroundVehicleSubtypeFlags {
111 GVSF_FRONT = 0, ///< Leading engine of a consist.
112 GVSF_ARTICULATED_PART = 1, ///< Articulated part of an engine.
113 GVSF_WAGON = 2, ///< Wagon (not used for road vehicles).
114 GVSF_ENGINE = 3, ///< Engine that can be front engine, but might be placed behind another engine (not used for road vehicles).
115 GVSF_FREE_WAGON = 4, ///< First in a wagon chain (in depot) (not used for road vehicles).
116 GVSF_MULTIHEADED = 5, ///< Engine is multiheaded (not used for road vehicles).
119 /** Cached often queried values common to all vehicles. */
120 struct VehicleCache {
121 uint16 cached_max_speed; ///< Maximum speed of the consist (minimum of the max speed of all vehicles in the consist).
122 uint16 cached_cargo_age_period; ///< Number of ticks before carried cargo is aged.
124 byte cached_vis_effect; ///< Visual effect to show (see #VisualEffect)
127 /** Sprite sequence for a vehicle part. */
128 struct VehicleSpriteSeq {
129 PalSpriteID seq[4];
130 uint count;
132 bool operator==(const VehicleSpriteSeq &other) const
134 return this->count == other.count && MemCmpT<PalSpriteID>(this->seq, other.seq, this->count) == 0;
137 bool operator!=(const VehicleSpriteSeq &other) const
139 return !this->operator==(other);
143 * Check whether the sequence contains any sprites.
145 bool IsValid() const
147 return this->count != 0;
151 * Clear all information.
153 void Clear()
155 this->count = 0;
159 * Assign a single sprite to the sequence.
161 void Set(SpriteID sprite)
163 this->count = 1;
164 this->seq[0].sprite = sprite;
165 this->seq[0].pal = 0;
169 * Copy data from another sprite sequence, while dropping all recolouring information.
171 void CopyWithoutPalette(const VehicleSpriteSeq &src)
173 this->count = src.count;
174 for (uint i = 0; i < src.count; ++i) {
175 this->seq[i].sprite = src.seq[i].sprite;
176 this->seq[i].pal = 0;
180 void GetBounds(Rect *bounds) const;
181 void Draw(int x, int y, PaletteID default_pal, bool force_pal) const;
185 * Cache for vehicle sprites and values relating to whether they should be updated before drawing,
186 * or calculating the viewport.
188 struct MutableSpriteCache {
189 Direction last_direction; ///< Last direction we obtained sprites for
190 bool revalidate_before_draw; ///< We need to do a GetImage() and check bounds before drawing this sprite
191 Rect old_coord; ///< Co-ordinates from the last valid bounding box
192 bool is_viewport_candidate; ///< This vehicle can potentially be drawn on a viewport
193 VehicleSpriteSeq sprite_seq; ///< Vehicle appearance.
196 /** A vehicle pool for a little over 1 million vehicles. */
197 typedef Pool<Vehicle, VehicleID, 512, 0xFF000> VehiclePool;
198 extern VehiclePool _vehicle_pool;
200 /* Some declarations of functions, so we can make them friendly */
201 struct SaveLoad;
202 struct GroundVehicleCache;
203 extern const SaveLoad *GetVehicleDescription(VehicleType vt);
204 struct LoadgameState;
205 extern bool LoadOldVehicle(LoadgameState *ls, int num);
206 extern void FixOldVehicles();
208 struct GRFFile;
211 * Simulated cargo type and capacity for prediction of future links.
213 struct RefitDesc {
214 CargoID cargo; ///< Cargo type the vehicle will be carrying.
215 uint16 capacity; ///< Capacity the vehicle will have.
216 uint16 remaining; ///< Capacity remaining from before the previous refit.
217 RefitDesc(CargoID cargo, uint16 capacity, uint16 remaining) :
218 cargo(cargo), capacity(capacity), remaining(remaining) {}
221 /** %Vehicle data structure. */
222 struct Vehicle : VehiclePool::PoolItem<&_vehicle_pool>, BaseVehicle, BaseConsist {
223 private:
224 typedef std::list<RefitDesc> RefitList;
225 typedef std::map<CargoID, uint> CapacitiesMap;
227 Vehicle *next; ///< pointer to the next vehicle in the chain
228 Vehicle *previous; ///< NOSAVE: pointer to the previous vehicle in the chain
229 Vehicle *first; ///< NOSAVE: pointer to the first vehicle in the chain
231 Vehicle *next_shared; ///< pointer to the next vehicle that shares the order
232 Vehicle *previous_shared; ///< NOSAVE: pointer to the previous vehicle in the shared order chain
234 public:
235 friend const SaveLoad *GetVehicleDescription(VehicleType vt); ///< So we can use private/protected variables in the saveload code
236 friend void FixOldVehicles();
237 friend void AfterLoadVehicles(bool part_of_load); ///< So we can set the #previous and #first pointers while loading
238 friend bool LoadOldVehicle(LoadgameState *ls, int num); ///< So we can set the proper next pointer while loading
240 TileIndex tile; ///< Current tile index
243 * Heading for this tile.
244 * For airports and train stations this tile does not necessarily belong to the destination station,
245 * but it can be used for heuristic purposes to estimate the distance.
247 TileIndex dest_tile;
249 Money profit_this_year; ///< Profit this year << 8, low 8 bits are fract
250 Money profit_last_year; ///< Profit last year << 8, low 8 bits are fract
251 Money value; ///< Value of the vehicle
253 CargoPayment *cargo_payment; ///< The cargo payment we're currently in
255 mutable 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 Direction direction; ///< facing
283 Owner owner; ///< Which company owns the vehicle?
285 * currently displayed sprite index
286 * 0xfd == custom sprite, 0xfe == custom second head sprite
287 * 0xff == reserved for another custom sprite
289 byte spritenum;
290 byte x_extent; ///< x-extent of vehicle bounding box
291 byte y_extent; ///< y-extent of vehicle bounding box
292 byte z_extent; ///< z-extent of vehicle bounding box
293 int8 x_bb_offs; ///< x offset of vehicle bounding box
294 int8 y_bb_offs; ///< y offset of vehicle bounding box
295 int8 x_offs; ///< x offset for vehicle sprite
296 int8 y_offs; ///< y offset for vehicle sprite
297 EngineID engine_type; ///< The type of engine used for this vehicle.
299 TextEffectID fill_percent_te_id; ///< a text-effect id to a loading indicator object
300 UnitID unitnumber; ///< unit number, for display purposes only
302 uint16 cur_speed; ///< current speed
303 byte subspeed; ///< fractional speed
304 byte acceleration; ///< used by train & aircraft
305 uint32 motion_counter; ///< counter to occasionally play a vehicle sound.
306 byte progress; ///< The percentage (if divided by 256) this vehicle already crossed the tile unit.
308 byte random_bits; ///< Bits used for determining which randomized variational spritegroups to use when drawing.
309 byte waiting_triggers; ///< Triggers to be yet matched before rerandomizing the random bits.
311 StationID last_station_visited; ///< The last station we stopped at.
312 StationID last_loading_station; ///< Last station the vehicle has stopped at and could possibly leave from with any cargo loaded.
314 CargoID cargo_type; ///< type of cargo this vehicle is carrying
315 byte cargo_subtype; ///< Used for livery refits (NewGRF variations)
316 uint16 cargo_cap; ///< total capacity
317 uint16 refit_cap; ///< Capacity left over from before last refit.
318 VehicleCargoList cargo; ///< The cargo this vehicle is carrying
319 uint16 cargo_age_counter; ///< Ticks till cargo is aged next.
320 int8 trip_occupancy; ///< NOSAVE: Occupancy of vehicle of the current trip (updated after leaving a station).
322 byte day_counter; ///< Increased by one for each day
323 byte tick_counter; ///< Increased by one for each tick
324 byte running_ticks; ///< Number of ticks this vehicle was not stopped this day
326 byte vehstatus; ///< Status
327 Order current_order; ///< The current order (+ status, like: loading)
329 union {
330 OrderList *list; ///< Pointer to the order list for this vehicle
331 Order *old; ///< Only used during conversion of old save games
332 } orders; ///< The orders currently assigned to the vehicle.
334 uint16 load_unload_ticks; ///< Ticks to wait before starting next cycle.
335 GroupID group_id; ///< Index of group Pool array
336 byte subtype; ///< subtype (Filled with values from #AircraftSubType/#DisasterSubType/#EffectVehicleType/#GroundVehicleSubtypeFlags)
338 NewGRFCache grf_cache; ///< Cache of often used calculated NewGRF values
339 VehicleCache vcache; ///< Cache of often used vehicle values.
341 mutable MutableSpriteCache sprite_cache; ///< Cache of sprites and values related to recalculating them, see #MutableSpriteCache
343 Vehicle(VehicleType type = VEH_INVALID);
345 void PreDestructor();
346 /** We want to 'destruct' the right class. */
347 virtual ~Vehicle();
349 void BeginLoading();
350 void CancelReservation(StationID next, Station *st);
351 void LeaveStation();
353 GroundVehicleCache *GetGroundVehicleCache();
354 const GroundVehicleCache *GetGroundVehicleCache() const;
356 uint16 &GetGroundVehicleFlags();
357 const uint16 &GetGroundVehicleFlags() const;
359 void DeleteUnreachedImplicitOrders();
361 void HandleLoading(bool mode = false);
363 void GetConsistFreeCapacities(SmallMap<CargoID, uint> &capacities) const;
365 uint GetConsistTotalCapacity() const;
368 * Marks the vehicles to be redrawn and updates cached variables
370 * This method marks the area of the vehicle on the screen as dirty.
371 * It can be use to repaint the vehicle.
373 * @ingroup dirty
375 virtual void MarkDirty() {}
378 * Updates the x and y offsets and the size of the sprite used
379 * for this vehicle.
381 virtual void UpdateDeltaXY() {}
384 * Determines the effective direction-specific vehicle movement speed.
386 * This method belongs to the old vehicle movement method:
387 * A vehicle moves a step every 256 progress units.
388 * The vehicle speed is scaled by 3/4 when moving in X or Y direction due to the longer distance.
390 * However, this method is slightly wrong in corners, as the leftover progress is not scaled correctly
391 * when changing movement direction. #GetAdvanceSpeed() and #GetAdvanceDistance() are better wrt. this.
393 * @param speed Direction-independent unscaled speed.
394 * @return speed scaled by movement direction. 256 units are required for each movement step.
396 inline uint GetOldAdvanceSpeed(uint speed)
398 return (this->direction & 1) ? speed : speed * 3 / 4;
402 * Determines the effective vehicle movement speed.
404 * Together with #GetAdvanceDistance() this function is a replacement for #GetOldAdvanceSpeed().
406 * A vehicle progresses independent of it's movement direction.
407 * However different amounts of "progress" are needed for moving a step in a specific direction.
408 * That way the leftover progress does not need any adaption when changing movement direction.
410 * @param speed Direction-independent unscaled speed.
411 * @return speed, scaled to match #GetAdvanceDistance().
413 static inline uint GetAdvanceSpeed(uint speed)
415 return speed * 3 / 4;
419 * Determines the vehicle "progress" needed for moving a step.
421 * Together with #GetAdvanceSpeed() this function is a replacement for #GetOldAdvanceSpeed().
423 * @return distance to drive for a movement step on the map.
425 inline uint GetAdvanceDistance()
427 return (this->direction & 1) ? 192 : 256;
431 * Sets the expense type associated to this vehicle type
432 * @param income whether this is income or (running) expenses of the vehicle
434 virtual ExpensesType GetExpenseType(bool income) const { return EXPENSES_OTHER; }
437 * Play the sound associated with leaving the station
439 virtual void PlayLeaveStationSound() const {}
442 * Whether this is the primary vehicle in the chain.
444 virtual bool IsPrimaryVehicle() const { return false; }
446 const Engine *GetEngine() const;
449 * Gets the sprite to show for the given direction
450 * @param direction the direction the vehicle is facing
451 * @param[out] result Vehicle sprite sequence.
453 virtual void GetImage(Direction direction, EngineImageType image_type, VehicleSpriteSeq *result) const { result->Clear(); }
455 const GRFFile *GetGRF() const;
456 uint32 GetGRFID() const;
459 * Invalidates cached NewGRF variables
460 * @see InvalidateNewGRFCacheOfChain
462 inline void InvalidateNewGRFCache()
464 this->grf_cache.cache_valid = 0;
468 * Invalidates cached NewGRF variables of all vehicles in the chain (after the current vehicle)
469 * @see InvalidateNewGRFCache
471 inline void InvalidateNewGRFCacheOfChain()
473 for (Vehicle *u = this; u != nullptr; u = u->Next()) {
474 u->InvalidateNewGRFCache();
479 * Check if the vehicle is a ground vehicle.
480 * @return True iff the vehicle is a train or a road vehicle.
482 inline bool IsGroundVehicle() const
484 return this->type == VEH_TRAIN || this->type == VEH_ROAD;
488 * Gets the speed in km-ish/h that can be sent into SetDParam for string processing.
489 * @return the vehicle's speed
491 virtual int GetDisplaySpeed() const { return 0; }
494 * Gets the maximum speed in km-ish/h that can be sent into SetDParam for string processing.
495 * @return the vehicle's maximum speed
497 virtual int GetDisplayMaxSpeed() const { return 0; }
500 * Calculates the maximum speed of the vehicle under its current conditions.
501 * @return Current maximum speed in native units.
503 virtual int GetCurrentMaxSpeed() const { return 0; }
506 * Gets the running cost of a vehicle
507 * @return the vehicle's running cost
509 virtual Money GetRunningCost() const { return 0; }
512 * Check whether the vehicle is in the depot.
513 * @return true if and only if the vehicle is in the depot.
515 virtual bool IsInDepot() const { return false; }
518 * Check whether the whole vehicle chain is in the depot.
519 * @return true if and only if the whole chain is in the depot.
521 virtual bool IsChainInDepot() const { return this->IsInDepot(); }
524 * Check whether the vehicle is in the depot *and* stopped.
525 * @return true if and only if the vehicle is in the depot and stopped.
527 bool IsStoppedInDepot() const
529 assert(this == this->First());
530 /* Free wagons have no VS_STOPPED state */
531 if (this->IsPrimaryVehicle() && !(this->vehstatus & VS_STOPPED)) return false;
532 return this->IsChainInDepot();
536 * Calls the tick handler of the vehicle
537 * @return is this vehicle still valid?
539 virtual bool Tick() { return true; };
542 * Calls the new day handler of the vehicle
544 virtual void OnNewDay() {};
547 * Crash the (whole) vehicle chain.
548 * @param flooded whether the cause of the crash is flooding or not.
549 * @return the number of lost souls.
551 virtual uint Crash(bool flooded = false);
554 * Returns the Trackdir on which the vehicle is currently located.
555 * Works for trains and ships.
556 * Currently works only sortof for road vehicles, since they have a fuzzy
557 * concept of being "on" a trackdir. Dunno really what it returns for a road
558 * vehicle that is halfway a tile, never really understood that part. For road
559 * vehicles that are at the beginning or end of the tile, should just return
560 * the diagonal trackdir on which they are driving. I _think_.
561 * For other vehicles types, or vehicles with no clear trackdir (such as those
562 * in depots), returns 0xFF.
563 * @return the trackdir of the vehicle
565 virtual Trackdir GetVehicleTrackdir() const { return INVALID_TRACKDIR; }
568 * Gets the running cost of a vehicle that can be sent into SetDParam for string processing.
569 * @return the vehicle's running cost
571 Money GetDisplayRunningCost() const { return (this->GetRunningCost() >> 8); }
574 * Gets the profit vehicle had this year. It can be sent into SetDParam for string processing.
575 * @return the vehicle's profit this year
577 Money GetDisplayProfitThisYear() const { return (this->profit_this_year >> 8); }
580 * Gets the profit vehicle had last year. It can be sent into SetDParam for string processing.
581 * @return the vehicle's profit last year
583 Money GetDisplayProfitLastYear() const { return (this->profit_last_year >> 8); }
585 void SetNext(Vehicle *next);
588 * Get the next vehicle of this vehicle.
589 * @note articulated parts are also counted as vehicles.
590 * @return the next vehicle or nullptr when there isn't a next vehicle.
592 inline Vehicle *Next() const { return this->next; }
595 * Get the previous vehicle of this vehicle.
596 * @note articulated parts are also counted as vehicles.
597 * @return the previous vehicle or nullptr when there isn't a previous vehicle.
599 inline Vehicle *Previous() const { return this->previous; }
602 * Get the first vehicle of this vehicle chain.
603 * @return the first vehicle of the chain.
605 inline Vehicle *First() const { return this->first; }
608 * Get the last vehicle of this vehicle chain.
609 * @return the last vehicle of the chain.
611 inline Vehicle *Last()
613 Vehicle *v = this;
614 while (v->Next() != nullptr) v = v->Next();
615 return v;
619 * Get the last vehicle of this vehicle chain.
620 * @return the last vehicle of the chain.
622 inline const Vehicle *Last() const
624 const Vehicle *v = this;
625 while (v->Next() != nullptr) v = v->Next();
626 return v;
630 * Get the vehicle at offset \a n of this vehicle chain.
631 * @param n Offset from the current vehicle.
632 * @return The new vehicle or nullptr if the offset is out-of-bounds.
634 inline Vehicle *Move(int n)
636 Vehicle *v = this;
637 if (n < 0) {
638 for (int i = 0; i != n && v != nullptr; i--) v = v->Previous();
639 } else {
640 for (int i = 0; i != n && v != nullptr; i++) v = v->Next();
642 return v;
646 * Get the vehicle at offset \a n of this vehicle chain.
647 * @param n Offset from the current vehicle.
648 * @return The new vehicle or nullptr if the offset is out-of-bounds.
650 inline const Vehicle *Move(int n) const
652 const Vehicle *v = this;
653 if (n < 0) {
654 for (int i = 0; i != n && v != nullptr; i--) v = v->Previous();
655 } else {
656 for (int i = 0; i != n && v != nullptr; i++) v = v->Next();
658 return v;
662 * Get the first order of the vehicles order list.
663 * @return first order of order list.
665 inline Order *GetFirstOrder() const { return (this->orders.list == nullptr) ? nullptr : this->orders.list->GetFirstOrder(); }
667 void AddToShared(Vehicle *shared_chain);
668 void RemoveFromShared();
671 * Get the next vehicle of the shared vehicle chain.
672 * @return the next shared vehicle or nullptr when there isn't a next vehicle.
674 inline Vehicle *NextShared() const { return this->next_shared; }
677 * Get the previous vehicle of the shared vehicle chain
678 * @return the previous shared vehicle or nullptr when there isn't a previous vehicle.
680 inline Vehicle *PreviousShared() const { return this->previous_shared; }
683 * Get the first vehicle of this vehicle chain.
684 * @return the first vehicle of the chain.
686 inline Vehicle *FirstShared() const { return (this->orders.list == nullptr) ? this->First() : this->orders.list->GetFirstSharedVehicle(); }
689 * Check if we share our orders with another vehicle.
690 * @return true if there are other vehicles sharing the same order
692 inline bool IsOrderListShared() const { return this->orders.list != nullptr && this->orders.list->IsShared(); }
695 * Get the number of orders this vehicle has.
696 * @return the number of orders this vehicle has.
698 inline VehicleOrderID GetNumOrders() const { return (this->orders.list == nullptr) ? 0 : this->orders.list->GetNumOrders(); }
701 * Get the number of manually added orders this vehicle has.
702 * @return the number of manually added orders this vehicle has.
704 inline VehicleOrderID GetNumManualOrders() const { return (this->orders.list == nullptr) ? 0 : this->orders.list->GetNumManualOrders(); }
707 * Get the next station the vehicle will stop at.
708 * @return ID of the next station the vehicle will stop at or INVALID_STATION.
710 inline StationIDStack GetNextStoppingStation() const
712 return (this->orders.list == nullptr) ? INVALID_STATION : this->orders.list->GetNextStoppingStation(this);
715 void ResetRefitCaps();
718 * Copy certain configurations and statistics of a vehicle after successful autoreplace/renew
719 * The function shall copy everything that cannot be copied by a command (like orders / group etc),
720 * and that shall not be resetted for the new vehicle.
721 * @param src The old vehicle
723 inline void CopyVehicleConfigAndStatistics(const Vehicle *src)
725 this->CopyConsistPropertiesFrom(src);
727 this->unitnumber = src->unitnumber;
729 this->current_order = src->current_order;
730 this->dest_tile = src->dest_tile;
732 this->profit_this_year = src->profit_this_year;
733 this->profit_last_year = src->profit_last_year;
737 bool HandleBreakdown();
739 bool NeedsAutorenewing(const Company *c, bool use_renew_setting = true) const;
741 bool NeedsServicing() const;
742 bool NeedsAutomaticServicing() const;
745 * Determine the location for the station where the vehicle goes to next.
746 * Things done for example are allocating slots in a road stop or exact
747 * location of the platform is determined for ships.
748 * @param station the station to make the next location of the vehicle.
749 * @return the location (tile) to aim for.
751 virtual TileIndex GetOrderStationLocation(StationID station) { return INVALID_TILE; }
754 * Find the closest depot for this vehicle and tell us the location,
755 * DestinationID and whether we should reverse.
756 * @param location where do we go to?
757 * @param destination what hangar do we go to?
758 * @param reverse should the vehicle be reversed?
759 * @return true if a depot could be found.
761 virtual bool FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse) { return false; }
763 virtual void SetDestTile(TileIndex tile) { this->dest_tile = tile; }
765 CommandCost SendToDepot(DoCommandFlag flags, DepotCommand command);
767 void UpdateVisualEffect(bool allow_power_change = true);
768 void ShowVisualEffect() const;
770 void UpdatePosition();
771 void UpdateViewport(bool dirty);
772 void UpdateBoundingBoxCoordinates(bool update_cache) const;
773 void UpdatePositionAndViewport();
774 bool MarkAllViewportsDirty() const;
776 inline uint16 GetServiceInterval() const { return this->service_interval; }
778 inline void SetServiceInterval(uint16 interval) { this->service_interval = interval; }
780 inline bool ServiceIntervalIsCustom() const { return HasBit(this->vehicle_flags, VF_SERVINT_IS_CUSTOM); }
782 inline bool ServiceIntervalIsPercent() const { return HasBit(this->vehicle_flags, VF_SERVINT_IS_PERCENT); }
784 inline void SetServiceIntervalIsCustom(bool on) { SB(this->vehicle_flags, VF_SERVINT_IS_CUSTOM, 1, on); }
786 inline void SetServiceIntervalIsPercent(bool on) { SB(this->vehicle_flags, VF_SERVINT_IS_PERCENT, 1, on); }
788 private:
790 * Advance cur_real_order_index to the next real order.
791 * cur_implicit_order_index is not touched.
793 void SkipToNextRealOrderIndex()
795 if (this->GetNumManualOrders() > 0) {
796 /* Advance to next real order */
797 do {
798 this->cur_real_order_index++;
799 if (this->cur_real_order_index >= this->GetNumOrders()) this->cur_real_order_index = 0;
800 } while (this->GetOrder(this->cur_real_order_index)->IsType(OT_IMPLICIT));
801 } else {
802 this->cur_real_order_index = 0;
806 public:
808 * Increments cur_implicit_order_index, keeps care of the wrap-around and invalidates the GUI.
809 * cur_real_order_index is incremented as well, if needed.
810 * Note: current_order is not invalidated.
812 void IncrementImplicitOrderIndex()
814 if (this->cur_implicit_order_index == this->cur_real_order_index) {
815 /* Increment real order index as well */
816 this->SkipToNextRealOrderIndex();
819 assert(this->cur_real_order_index == 0 || this->cur_real_order_index < this->GetNumOrders());
821 /* Advance to next implicit order */
822 do {
823 this->cur_implicit_order_index++;
824 if (this->cur_implicit_order_index >= this->GetNumOrders()) this->cur_implicit_order_index = 0;
825 } while (this->cur_implicit_order_index != this->cur_real_order_index && !this->GetOrder(this->cur_implicit_order_index)->IsType(OT_IMPLICIT));
827 InvalidateVehicleOrder(this, 0);
831 * Advanced cur_real_order_index to the next real order, keeps care of the wrap-around and invalidates the GUI.
832 * 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
833 * but not any implicit orders.
834 * Note: current_order is not invalidated.
836 void IncrementRealOrderIndex()
838 if (this->cur_implicit_order_index == this->cur_real_order_index) {
839 /* Increment both real and implicit order */
840 this->IncrementImplicitOrderIndex();
841 } else {
842 /* Increment real order only */
843 this->SkipToNextRealOrderIndex();
844 InvalidateVehicleOrder(this, 0);
849 * Skip implicit orders until cur_real_order_index is a non-implicit order.
851 void UpdateRealOrderIndex()
853 /* Make sure the index is valid */
854 if (this->cur_real_order_index >= this->GetNumOrders()) this->cur_real_order_index = 0;
856 if (this->GetNumManualOrders() > 0) {
857 /* Advance to next real order */
858 while (this->GetOrder(this->cur_real_order_index)->IsType(OT_IMPLICIT)) {
859 this->cur_real_order_index++;
860 if (this->cur_real_order_index >= this->GetNumOrders()) this->cur_real_order_index = 0;
862 } else {
863 this->cur_real_order_index = 0;
868 * Returns order 'index' of a vehicle or nullptr when it doesn't exists
869 * @param index the order to fetch
870 * @return the found (or not) order
872 inline Order *GetOrder(int index) const
874 return (this->orders.list == nullptr) ? nullptr : this->orders.list->GetOrderAt(index);
878 * Returns the last order of a vehicle, or nullptr if it doesn't exists
879 * @return last order of a vehicle, if available
881 inline Order *GetLastOrder() const
883 return (this->orders.list == nullptr) ? nullptr : this->orders.list->GetLastOrder();
886 bool IsEngineCountable() const;
887 bool HasEngineType() const;
888 bool HasDepotOrder() const;
889 void HandlePathfindingResult(bool path_found);
892 * Check if the vehicle is a front engine.
893 * @return Returns true if the vehicle is a front engine.
895 inline bool IsFrontEngine() const
897 return this->IsGroundVehicle() && HasBit(this->subtype, GVSF_FRONT);
901 * Check if the vehicle is an articulated part of an engine.
902 * @return Returns true if the vehicle is an articulated part.
904 inline bool IsArticulatedPart() const
906 return this->IsGroundVehicle() && HasBit(this->subtype, GVSF_ARTICULATED_PART);
910 * Check if an engine has an articulated part.
911 * @return True if the engine has an articulated part.
913 inline bool HasArticulatedPart() const
915 return this->Next() != nullptr && this->Next()->IsArticulatedPart();
919 * Get the next part of an articulated engine.
920 * @return Next part of the articulated engine.
921 * @pre The vehicle is an articulated engine.
923 inline Vehicle *GetNextArticulatedPart() const
925 assert(this->HasArticulatedPart());
926 return this->Next();
930 * Get the first part of an articulated engine.
931 * @return First part of the engine.
933 inline Vehicle *GetFirstEnginePart()
935 Vehicle *v = this;
936 while (v->IsArticulatedPart()) v = v->Previous();
937 return v;
941 * Get the first part of an articulated engine.
942 * @return First part of the engine.
944 inline const Vehicle *GetFirstEnginePart() const
946 const Vehicle *v = this;
947 while (v->IsArticulatedPart()) v = v->Previous();
948 return v;
952 * Get the last part of an articulated engine.
953 * @return Last part of the engine.
955 inline Vehicle *GetLastEnginePart()
957 Vehicle *v = this;
958 while (v->HasArticulatedPart()) v = v->GetNextArticulatedPart();
959 return v;
963 * Get the next real (non-articulated part) vehicle in the consist.
964 * @return Next vehicle in the consist.
966 inline Vehicle *GetNextVehicle() const
968 const Vehicle *v = this;
969 while (v->HasArticulatedPart()) v = v->GetNextArticulatedPart();
971 /* v now contains the last articulated part in the engine */
972 return v->Next();
976 * Get the previous real (non-articulated part) vehicle in the consist.
977 * @return Previous vehicle in the consist.
979 inline Vehicle *GetPrevVehicle() const
981 Vehicle *v = this->Previous();
982 while (v != nullptr && v->IsArticulatedPart()) v = v->Previous();
984 return v;
988 * Iterator to iterate orders
989 * Supports deletion of current order
991 struct OrderIterator {
992 typedef Order value_type;
993 typedef Order* pointer;
994 typedef Order& reference;
995 typedef size_t difference_type;
996 typedef std::forward_iterator_tag iterator_category;
998 explicit OrderIterator(OrderList *list) : list(list), prev(nullptr)
1000 this->order = (this->list == nullptr) ? nullptr : this->list->GetFirstOrder();
1003 bool operator==(const OrderIterator &other) const { return this->order == other.order; }
1004 bool operator!=(const OrderIterator &other) const { return !(*this == other); }
1005 Order * operator*() const { return this->order; }
1006 OrderIterator & operator++()
1008 this->prev = (this->prev == nullptr) ? this->list->GetFirstOrder() : this->prev->next;
1009 this->order = (this->prev == nullptr) ? nullptr : this->prev->next;
1010 return *this;
1013 private:
1014 OrderList *list;
1015 Order *order;
1016 Order *prev;
1020 * Iterable ensemble of orders
1022 struct IterateWrapper {
1023 OrderList *list;
1024 IterateWrapper(OrderList *list = nullptr) : list(list) {}
1025 OrderIterator begin() { return OrderIterator(this->list); }
1026 OrderIterator end() { return OrderIterator(nullptr); }
1027 bool empty() { return this->begin() == this->end(); }
1031 * Returns an iterable ensemble of orders of a vehicle
1032 * @return an iterable ensemble of orders of a vehicle
1034 IterateWrapper Orders() const { return IterateWrapper(this->orders.list); }
1038 * Class defining several overloaded accessors so we don't
1039 * have to cast vehicle types that often
1041 template <class T, VehicleType Type>
1042 struct SpecializedVehicle : public Vehicle {
1043 static const VehicleType EXPECTED_TYPE = Type; ///< Specialized type
1045 typedef SpecializedVehicle<T, Type> SpecializedVehicleBase; ///< Our type
1048 * Set vehicle type correctly
1050 inline SpecializedVehicle<T, Type>() : Vehicle(Type)
1052 this->sprite_cache.sprite_seq.count = 1;
1056 * Get the first vehicle in the chain
1057 * @return first vehicle in the chain
1059 inline T *First() const { return (T *)this->Vehicle::First(); }
1062 * Get the last vehicle in the chain
1063 * @return last vehicle in the chain
1065 inline T *Last() { return (T *)this->Vehicle::Last(); }
1068 * Get the last vehicle in the chain
1069 * @return last vehicle in the chain
1071 inline const T *Last() const { return (const T *)this->Vehicle::Last(); }
1074 * Get next vehicle in the chain
1075 * @return next vehicle in the chain
1077 inline T *Next() const { return (T *)this->Vehicle::Next(); }
1080 * Get previous vehicle in the chain
1081 * @return previous vehicle in the chain
1083 inline T *Previous() const { return (T *)this->Vehicle::Previous(); }
1086 * Get the next part of an articulated engine.
1087 * @return Next part of the articulated engine.
1088 * @pre The vehicle is an articulated engine.
1090 inline T *GetNextArticulatedPart() { return (T *)this->Vehicle::GetNextArticulatedPart(); }
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() const { return (T *)this->Vehicle::GetNextArticulatedPart(); }
1100 * Get the first part of an articulated engine.
1101 * @return First part of the engine.
1103 inline T *GetFirstEnginePart() { return (T *)this->Vehicle::GetFirstEnginePart(); }
1106 * Get the first part of an articulated engine.
1107 * @return First part of the engine.
1109 inline const T *GetFirstEnginePart() const { return (const T *)this->Vehicle::GetFirstEnginePart(); }
1112 * Get the last part of an articulated engine.
1113 * @return Last part of the engine.
1115 inline T *GetLastEnginePart() { return (T *)this->Vehicle::GetLastEnginePart(); }
1118 * Get the next real (non-articulated part) vehicle in the consist.
1119 * @return Next vehicle in the consist.
1121 inline T *GetNextVehicle() const { return (T *)this->Vehicle::GetNextVehicle(); }
1124 * Get the previous real (non-articulated part) vehicle in the consist.
1125 * @return Previous vehicle in the consist.
1127 inline T *GetPrevVehicle() const { return (T *)this->Vehicle::GetPrevVehicle(); }
1130 * Tests whether given index is a valid index for vehicle of this type
1131 * @param index tested index
1132 * @return is this index valid index of T?
1134 static inline bool IsValidID(size_t index)
1136 return Vehicle::IsValidID(index) && Vehicle::Get(index)->type == Type;
1140 * Gets vehicle with given index
1141 * @return pointer to vehicle with given index casted to T *
1143 static inline T *Get(size_t index)
1145 return (T *)Vehicle::Get(index);
1149 * Returns vehicle if the index is a valid index for this vehicle type
1150 * @return pointer to vehicle with given index if it's a vehicle of this type
1152 static inline T *GetIfValid(size_t index)
1154 return IsValidID(index) ? Get(index) : nullptr;
1158 * Converts a Vehicle to SpecializedVehicle with type checking.
1159 * @param v Vehicle pointer
1160 * @return pointer to SpecializedVehicle
1162 static inline T *From(Vehicle *v)
1164 assert(v->type == Type);
1165 return (T *)v;
1169 * Converts a const Vehicle to const SpecializedVehicle with type checking.
1170 * @param v Vehicle pointer
1171 * @return pointer to SpecializedVehicle
1173 static inline const T *From(const Vehicle *v)
1175 assert(v->type == Type);
1176 return (const T *)v;
1180 * Update vehicle sprite- and position caches
1181 * @param force_update Force updating the vehicle on the viewport.
1182 * @param update_delta Also update the delta?
1184 inline void UpdateViewport(bool force_update, bool update_delta)
1186 bool sprite_has_changed = false;
1188 /* Skip updating sprites on dedicated servers without screen */
1189 if (_network_dedicated) return;
1191 /* Explicitly choose method to call to prevent vtable dereference -
1192 * it gives ~3% runtime improvements in games with many vehicles */
1193 if (update_delta) ((T *)this)->T::UpdateDeltaXY();
1196 * Only check for a new sprite sequence if the vehicle direction
1197 * has changed since we last checked it, assuming that otherwise
1198 * there won't be enough change in bounding box or offsets to need
1199 * to resolve a new sprite.
1201 if (this->direction != this->sprite_cache.last_direction || this->sprite_cache.is_viewport_candidate) {
1202 VehicleSpriteSeq seq;
1204 ((T*)this)->T::GetImage(this->direction, EIT_ON_MAP, &seq);
1205 if (this->sprite_cache.sprite_seq != seq) {
1206 sprite_has_changed = true;
1207 this->sprite_cache.sprite_seq = seq;
1210 this->sprite_cache.last_direction = this->direction;
1211 this->sprite_cache.revalidate_before_draw = false;
1212 } else {
1214 * A change that could potentially invalidate the sprite has been
1215 * made, signal that we should still resolve it before drawing on a
1216 * viewport.
1218 this->sprite_cache.revalidate_before_draw = true;
1221 if (force_update || sprite_has_changed) {
1222 this->Vehicle::UpdateViewport(true);
1227 * Returns an iterable ensemble of all valid vehicles of type T
1228 * @param from index of the first vehicle to consider
1229 * @return an iterable ensemble of all valid vehicles of type T
1231 static Pool::IterateWrapper<T> Iterate(size_t from = 0) { return Pool::IterateWrapper<T>(from); }
1234 /** Generates sequence of free UnitID numbers */
1235 struct FreeUnitIDGenerator {
1236 bool *cache; ///< array of occupied unit id numbers
1237 UnitID maxid; ///< maximum ID at the moment of constructor call
1238 UnitID curid; ///< last ID returned; 0 if none
1240 FreeUnitIDGenerator(VehicleType type, CompanyID owner);
1241 UnitID NextID();
1243 /** Releases allocated memory */
1244 ~FreeUnitIDGenerator() { free(this->cache); }
1247 /** Sentinel for an invalid coordinate. */
1248 static const int32 INVALID_COORD = 0x7fffffff;
1250 #endif /* VEHICLE_BASE_H */