(svn r27756) -Codechange: Add StringTab enum
[openttd.git] / src / vehicle_base.h
blobf2a02072a29ca867b8b668298194b1f999d212b7
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8 */
10 /** @file vehicle_base.h Base class for all vehicles. */
12 #ifndef VEHICLE_BASE_H
13 #define VEHICLE_BASE_H
15 #include "core/smallmap_type.hpp"
16 #include "track_type.h"
17 #include "command_type.h"
18 #include "order_base.h"
19 #include "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"
26 #include "network/network.h"
27 #include <list>
28 #include <map>
30 /** Vehicle status bits in #Vehicle::vehstatus. */
31 enum VehStatus {
32 VS_HIDDEN = 0x01, ///< Vehicle is not visible.
33 VS_STOPPED = 0x02, ///< Vehicle is stopped by the player.
34 VS_UNCLICKABLE = 0x04, ///< Vehicle is not clickable by the user (shadow vehicles).
35 VS_DEFPAL = 0x08, ///< Use default vehicle palette. @see DoDrawVehicle
36 VS_TRAIN_SLOWING = 0x10, ///< Train is slowing down.
37 VS_SHADOW = 0x20, ///< Vehicle is a shadow vehicle.
38 VS_AIRCRAFT_BROKEN = 0x40, ///< Aircraft is broken down.
39 VS_CRASHED = 0x80, ///< Vehicle is crashed.
42 /** Bit numbers in #Vehicle::vehicle_flags. */
43 enum VehicleFlags {
44 VF_LOADING_FINISHED, ///< Vehicle has finished loading.
45 VF_CARGO_UNLOADING, ///< Vehicle is unloading cargo.
46 VF_BUILT_AS_PROTOTYPE, ///< Vehicle is a prototype (accepted as exclusive preview).
47 VF_TIMETABLE_STARTED, ///< Whether the vehicle has started running on the timetable yet.
48 VF_AUTOFILL_TIMETABLE, ///< Whether the vehicle should fill in the timetable automatically.
49 VF_AUTOFILL_PRES_WAIT_TIME, ///< Whether non-destructive auto-fill should preserve waiting times
50 VF_STOP_LOADING, ///< Don't load anymore during the next load cycle.
51 VF_PATHFINDER_LOST, ///< Vehicle's pathfinder is lost.
52 VF_SERVINT_IS_CUSTOM, ///< Service interval is custom.
53 VF_SERVINT_IS_PERCENT, ///< Service interval is percent.
56 /** Bit numbers used to indicate which of the #NewGRFCache values are valid. */
57 enum NewGRFCacheValidValues {
58 NCVV_POSITION_CONSIST_LENGTH = 0, ///< This bit will be set if the NewGRF var 40 currently stored is valid.
59 NCVV_POSITION_SAME_ID_LENGTH = 1, ///< This bit will be set if the NewGRF var 41 currently stored is valid.
60 NCVV_CONSIST_CARGO_INFORMATION = 2, ///< This bit will be set if the NewGRF var 42 currently stored is valid.
61 NCVV_COMPANY_INFORMATION = 3, ///< This bit will be set if the NewGRF var 43 currently stored is valid.
62 NCVV_POSITION_IN_VEHICLE = 4, ///< This bit will be set if the NewGRF var 4D currently stored is valid.
63 NCVV_END, ///< End of the bits.
66 /** Cached often queried (NewGRF) values */
67 struct NewGRFCache {
68 /* Values calculated when they are requested for the first time after invalidating the NewGRF cache. */
69 uint32 position_consist_length; ///< Cache for NewGRF var 40.
70 uint32 position_same_id_length; ///< Cache for NewGRF var 41.
71 uint32 consist_cargo_information; ///< Cache for NewGRF var 42. (Note: The cargotype is untranslated in the cache because the accessing GRF is yet unknown.)
72 uint32 company_information; ///< Cache for NewGRF var 43.
73 uint32 position_in_vehicle; ///< Cache for NewGRF var 4D.
74 uint8 cache_valid; ///< Bitset that indicates which cache values are valid.
77 /** Meaning of the various bits of the visual effect. */
78 enum VisualEffect {
79 VE_OFFSET_START = 0, ///< First bit that contains the offset (0 = front, 8 = centre, 15 = rear)
80 VE_OFFSET_COUNT = 4, ///< Number of bits used for the offset
81 VE_OFFSET_CENTRE = 8, ///< Value of offset corresponding to a position above the centre of the vehicle
83 VE_TYPE_START = 4, ///< First bit used for the type of effect
84 VE_TYPE_COUNT = 2, ///< Number of bits used for the effect type
85 VE_TYPE_DEFAULT = 0, ///< Use default from engine class
86 VE_TYPE_STEAM = 1, ///< Steam plumes
87 VE_TYPE_DIESEL = 2, ///< Diesel fumes
88 VE_TYPE_ELECTRIC = 3, ///< Electric sparks
90 VE_DISABLE_EFFECT = 6, ///< Flag to disable visual effect
91 VE_ADVANCED_EFFECT = VE_DISABLE_EFFECT, ///< Flag for advanced effects
92 VE_DISABLE_WAGON_POWER = 7, ///< Flag to disable wagon power
94 VE_DEFAULT = 0xFF, ///< Default value to indicate that visual effect should be based on engine class
97 /** Models for spawning visual effects. */
98 enum VisualEffectSpawnModel {
99 VESM_NONE = 0, ///< No visual effect
100 VESM_STEAM, ///< Steam model
101 VESM_DIESEL, ///< Diesel model
102 VESM_ELECTRIC, ///< Electric model
104 VESM_END
108 * Enum to handle ground vehicle subtypes.
109 * This is defined here instead of at #GroundVehicle because some common function require access to these flags.
110 * Do not access it directly unless you have to. Use the subtype access functions.
112 enum GroundVehicleSubtypeFlags {
113 GVSF_FRONT = 0, ///< Leading engine of a consist.
114 GVSF_ARTICULATED_PART = 1, ///< Articulated part of an engine.
115 GVSF_WAGON = 2, ///< Wagon (not used for road vehicles).
116 GVSF_ENGINE = 3, ///< Engine that can be front engine, but might be placed behind another engine (not used for road vehicles).
117 GVSF_FREE_WAGON = 4, ///< First in a wagon chain (in depot) (not used for road vehicles).
118 GVSF_MULTIHEADED = 5, ///< Engine is multiheaded (not used for road vehicles).
121 /** Cached often queried values common to all vehicles. */
122 struct VehicleCache {
123 uint16 cached_max_speed; ///< Maximum speed of the consist (minimum of the max speed of all vehicles in the consist).
124 uint16 cached_cargo_age_period; ///< Number of ticks before carried cargo is aged.
126 byte cached_vis_effect; ///< Visual effect to show (see #VisualEffect)
129 /** Sprite sequence for a vehicle part. */
130 struct VehicleSpriteSeq {
131 PalSpriteID seq[4];
132 uint count;
134 bool operator==(const VehicleSpriteSeq &other) const
136 return this->count == other.count && MemCmpT<PalSpriteID>(this->seq, other.seq, this->count) == 0;
139 bool operator!=(const VehicleSpriteSeq &other) const
141 return !this->operator==(other);
145 * Check whether the sequence contains any sprites.
147 bool IsValid() const
149 return this->count != 0;
153 * Clear all information.
155 void Clear()
157 this->count = 0;
161 * Assign a single sprite to the sequence.
163 void Set(SpriteID sprite)
165 this->count = 1;
166 this->seq[0].sprite = sprite;
167 this->seq[0].pal = 0;
171 * Copy data from another sprite sequence, while dropping all recolouring information.
173 void CopyWithoutPalette(const VehicleSpriteSeq &src)
175 this->count = src.count;
176 for (uint i = 0; i < src.count; ++i) {
177 this->seq[i].sprite = src.seq[i].sprite;
178 this->seq[i].pal = 0;
182 void GetBounds(Rect *bounds) const;
183 void Draw(int x, int y, PaletteID default_pal, bool force_pal) const;
186 /** A vehicle pool for a little over 1 million vehicles. */
187 typedef Pool<Vehicle, VehicleID, 512, 0xFF000> VehiclePool;
188 extern VehiclePool _vehicle_pool;
190 /* Some declarations of functions, so we can make them friendly */
191 struct SaveLoad;
192 struct GroundVehicleCache;
193 extern const SaveLoad *GetVehicleDescription(VehicleType vt);
194 struct LoadgameState;
195 extern bool LoadOldVehicle(LoadgameState *ls, int num);
196 extern void FixOldVehicles();
198 struct GRFFile;
201 * Simulated cargo type and capacity for prediction of future links.
203 struct RefitDesc {
204 CargoID cargo; ///< Cargo type the vehicle will be carrying.
205 uint16 capacity; ///< Capacity the vehicle will have.
206 uint16 remaining; ///< Capacity remaining from before the previous refit.
207 RefitDesc(CargoID cargo, uint16 capacity, uint16 remaining) :
208 cargo(cargo), capacity(capacity), remaining(remaining) {}
211 /** %Vehicle data structure. */
212 struct Vehicle : VehiclePool::PoolItem<&_vehicle_pool>, BaseVehicle, BaseConsist {
213 private:
214 typedef std::list<RefitDesc> RefitList;
215 typedef std::map<CargoID, uint> CapacitiesMap;
217 Vehicle *next; ///< pointer to the next vehicle in the chain
218 Vehicle *previous; ///< NOSAVE: pointer to the previous vehicle in the chain
219 Vehicle *first; ///< NOSAVE: pointer to the first vehicle in the chain
221 Vehicle *next_shared; ///< pointer to the next vehicle that shares the order
222 Vehicle *previous_shared; ///< NOSAVE: pointer to the previous vehicle in the shared order chain
224 public:
225 friend const SaveLoad *GetVehicleDescription(VehicleType vt); ///< So we can use private/protected variables in the saveload code
226 friend void FixOldVehicles();
227 friend void AfterLoadVehicles(bool part_of_load); ///< So we can set the #previous and #first pointers while loading
228 friend bool LoadOldVehicle(LoadgameState *ls, int num); ///< So we can set the proper next pointer while loading
230 TileIndex tile; ///< Current tile index
233 * Heading for this tile.
234 * For airports and train stations this tile does not necessarily belong to the destination station,
235 * but it can be used for heuristic purposes to estimate the distance.
237 TileIndex dest_tile;
239 Money profit_this_year; ///< Profit this year << 8, low 8 bits are fract
240 Money profit_last_year; ///< Profit last year << 8, low 8 bits are fract
241 Money value; ///< Value of the vehicle
243 CargoPayment *cargo_payment; ///< The cargo payment we're currently in
245 Rect coord; ///< NOSAVE: Graphical bounding box of the vehicle, i.e. what to redraw on moves.
247 Vehicle *hash_viewport_next; ///< NOSAVE: Next vehicle in the visual location hash.
248 Vehicle **hash_viewport_prev; ///< NOSAVE: Previous vehicle in the visual location hash.
250 Vehicle *hash_tile_next; ///< NOSAVE: Next vehicle in the tile location hash.
251 Vehicle **hash_tile_prev; ///< NOSAVE: Previous vehicle in the tile location hash.
252 Vehicle **hash_tile_current; ///< NOSAVE: Cache of the current hash chain.
254 SpriteID colourmap; ///< NOSAVE: cached colour mapping
256 /* Related to age and service time */
257 Year build_year; ///< Year the vehicle has been built.
258 Date age; ///< Age in days
259 Date max_age; ///< Maximum age
260 Date date_of_last_service; ///< Last date the vehicle had a service at a depot.
261 uint16 reliability; ///< Reliability.
262 uint16 reliability_spd_dec; ///< Reliability decrease speed.
263 byte breakdown_ctr; ///< Counter for managing breakdown events. @see Vehicle::HandleBreakdown
264 byte breakdown_delay; ///< Counter for managing breakdown length.
265 byte breakdowns_since_last_service; ///< Counter for the amount of breakdowns.
266 byte breakdown_chance; ///< Current chance of breakdowns.
268 int32 x_pos; ///< x coordinate.
269 int32 y_pos; ///< y coordinate.
270 int32 z_pos; ///< z coordinate.
271 DirectionByte direction; ///< facing
273 OwnerByte owner; ///< Which company owns the vehicle?
275 * currently displayed sprite index
276 * 0xfd == custom sprite, 0xfe == custom second head sprite
277 * 0xff == reserved for another custom sprite
279 byte spritenum;
280 VehicleSpriteSeq sprite_seq; ///< Vehicle appearance.
281 byte x_extent; ///< x-extent of vehicle bounding box
282 byte y_extent; ///< y-extent of vehicle bounding box
283 byte z_extent; ///< z-extent of vehicle bounding box
284 int8 x_bb_offs; ///< x offset of vehicle bounding box
285 int8 y_bb_offs; ///< y offset of vehicle bounding box
286 int8 x_offs; ///< x offset for vehicle sprite
287 int8 y_offs; ///< y offset for vehicle sprite
288 EngineID engine_type; ///< The type of engine used for this vehicle.
290 TextEffectID fill_percent_te_id; ///< a text-effect id to a loading indicator object
291 UnitID unitnumber; ///< unit number, for display purposes only
293 uint16 cur_speed; ///< current speed
294 byte subspeed; ///< fractional speed
295 byte acceleration; ///< used by train & aircraft
296 uint32 motion_counter; ///< counter to occasionally play a vehicle sound.
297 byte progress; ///< The percentage (if divided by 256) this vehicle already crossed the tile unit.
299 byte random_bits; ///< Bits used for determining which randomized variational spritegroups to use when drawing.
300 byte waiting_triggers; ///< Triggers to be yet matched before rerandomizing the random bits.
302 StationID last_station_visited; ///< The last station we stopped at.
303 StationID last_loading_station; ///< Last station the vehicle has stopped at and could possibly leave from with any cargo loaded.
305 CargoID cargo_type; ///< type of cargo this vehicle is carrying
306 byte cargo_subtype; ///< Used for livery refits (NewGRF variations)
307 uint16 cargo_cap; ///< total capacity
308 uint16 refit_cap; ///< Capacity left over from before last refit.
309 VehicleCargoList cargo; ///< The cargo this vehicle is carrying
310 uint16 cargo_age_counter; ///< Ticks till cargo is aged next.
312 byte day_counter; ///< Increased by one for each day
313 byte tick_counter; ///< Increased by one for each tick
314 byte running_ticks; ///< Number of ticks this vehicle was not stopped this day
316 byte vehstatus; ///< Status
317 Order current_order; ///< The current order (+ status, like: loading)
319 union {
320 OrderList *list; ///< Pointer to the order list for this vehicle
321 Order *old; ///< Only used during conversion of old save games
322 } orders; ///< The orders currently assigned to the vehicle.
324 uint16 load_unload_ticks; ///< Ticks to wait before starting next cycle.
325 GroupID group_id; ///< Index of group Pool array
326 byte subtype; ///< subtype (Filled with values from #EffectVehicles/#TrainSubTypes/#AircraftSubTypes)
328 NewGRFCache grf_cache; ///< Cache of often used calculated NewGRF values
329 VehicleCache vcache; ///< Cache of often used vehicle values.
331 Vehicle(VehicleType type = VEH_INVALID);
333 void PreDestructor();
334 /** We want to 'destruct' the right class. */
335 virtual ~Vehicle();
337 void BeginLoading();
338 void CancelReservation(StationID next, Station *st);
339 void LeaveStation();
341 GroundVehicleCache *GetGroundVehicleCache();
342 const GroundVehicleCache *GetGroundVehicleCache() const;
344 uint16 &GetGroundVehicleFlags();
345 const uint16 &GetGroundVehicleFlags() const;
347 void DeleteUnreachedImplicitOrders();
349 void HandleLoading(bool mode = false);
351 void GetConsistFreeCapacities(SmallMap<CargoID, uint> &capacities) const;
353 uint GetConsistTotalCapacity() const;
356 * Marks the vehicles to be redrawn and updates cached variables
358 * This method marks the area of the vehicle on the screen as dirty.
359 * It can be use to repaint the vehicle.
361 * @ingroup dirty
363 virtual void MarkDirty() {}
366 * Updates the x and y offsets and the size of the sprite used
367 * for this vehicle.
368 * @param direction the direction the vehicle is facing
370 virtual void UpdateDeltaXY(Direction direction) {}
373 * Determines the effective direction-specific vehicle movement speed.
375 * This method belongs to the old vehicle movement method:
376 * A vehicle moves a step every 256 progress units.
377 * The vehicle speed is scaled by 3/4 when moving in X or Y direction due to the longer distance.
379 * However, this method is slightly wrong in corners, as the leftover progress is not scaled correctly
380 * when changing movement direction. #GetAdvanceSpeed() and #GetAdvanceDistance() are better wrt. this.
382 * @param speed Direction-independent unscaled speed.
383 * @return speed scaled by movement direction. 256 units are required for each movement step.
385 inline uint GetOldAdvanceSpeed(uint speed)
387 return (this->direction & 1) ? speed : speed * 3 / 4;
391 * Determines the effective vehicle movement speed.
393 * Together with #GetAdvanceDistance() this function is a replacement for #GetOldAdvanceSpeed().
395 * A vehicle progresses independent of it's movement direction.
396 * However different amounts of "progress" are needed for moving a step in a specific direction.
397 * That way the leftover progress does not need any adaption when changing movement direction.
399 * @param speed Direction-independent unscaled speed.
400 * @return speed, scaled to match #GetAdvanceDistance().
402 static inline uint GetAdvanceSpeed(uint speed)
404 return speed * 3 / 4;
408 * Determines the vehicle "progress" needed for moving a step.
410 * Together with #GetAdvanceSpeed() this function is a replacement for #GetOldAdvanceSpeed().
412 * @return distance to drive for a movement step on the map.
414 inline uint GetAdvanceDistance()
416 return (this->direction & 1) ? 192 : 256;
420 * Sets the expense type associated to this vehicle type
421 * @param income whether this is income or (running) expenses of the vehicle
423 virtual ExpensesType GetExpenseType(bool income) const { return EXPENSES_OTHER; }
426 * Play the sound associated with leaving the station
428 virtual void PlayLeaveStationSound() const {}
431 * Whether this is the primary vehicle in the chain.
433 virtual bool IsPrimaryVehicle() const { return false; }
435 const Engine *GetEngine() const;
438 * Gets the sprite to show for the given direction
439 * @param direction the direction the vehicle is facing
440 * @param [out] result Vehicle sprite sequence.
442 virtual void GetImage(Direction direction, EngineImageType image_type, VehicleSpriteSeq *result) const { result->Clear(); }
444 const GRFFile *GetGRF() const;
445 uint32 GetGRFID() const;
448 * Invalidates cached NewGRF variables
449 * @see InvalidateNewGRFCacheOfChain
451 inline void InvalidateNewGRFCache()
453 this->grf_cache.cache_valid = 0;
457 * Invalidates cached NewGRF variables of all vehicles in the chain (after the current vehicle)
458 * @see InvalidateNewGRFCache
460 inline void InvalidateNewGRFCacheOfChain()
462 for (Vehicle *u = this; u != NULL; u = u->Next()) {
463 u->InvalidateNewGRFCache();
468 * Check if the vehicle is a ground vehicle.
469 * @return True iff the vehicle is a train or a road vehicle.
471 inline bool IsGroundVehicle() const
473 return this->type == VEH_TRAIN || this->type == VEH_ROAD;
477 * Gets the speed in km-ish/h that can be sent into SetDParam for string processing.
478 * @return the vehicle's speed
480 virtual int GetDisplaySpeed() const { return 0; }
483 * Gets the maximum speed in km-ish/h that can be sent into SetDParam for string processing.
484 * @return the vehicle's maximum speed
486 virtual int GetDisplayMaxSpeed() const { return 0; }
489 * Calculates the maximum speed of the vehicle under its current conditions.
490 * @return Current maximum speed in native units.
492 virtual int GetCurrentMaxSpeed() const { return 0; }
495 * Gets the running cost of a vehicle
496 * @return the vehicle's running cost
498 virtual Money GetRunningCost() const { return 0; }
501 * Check whether the vehicle is in the depot.
502 * @return true if and only if the vehicle is in the depot.
504 virtual bool IsInDepot() const { return false; }
507 * Check whether the whole vehicle chain is in the depot.
508 * @return true if and only if the whole chain is in the depot.
510 virtual bool IsChainInDepot() const { return this->IsInDepot(); }
513 * Check whether the vehicle is in the depot *and* stopped.
514 * @return true if and only if the vehicle is in the depot and stopped.
516 bool IsStoppedInDepot() const
518 assert(this == this->First());
519 /* Free wagons have no VS_STOPPED state */
520 if (this->IsPrimaryVehicle() && !(this->vehstatus & VS_STOPPED)) return false;
521 return this->IsChainInDepot();
525 * Calls the tick handler of the vehicle
526 * @return is this vehicle still valid?
528 virtual bool Tick() { return true; };
531 * Calls the new day handler of the vehicle
533 virtual void OnNewDay() {};
536 * Crash the (whole) vehicle chain.
537 * @param flooded whether the cause of the crash is flooding or not.
538 * @return the number of lost souls.
540 virtual uint Crash(bool flooded = false);
543 * Returns the Trackdir on which the vehicle is currently located.
544 * Works for trains and ships.
545 * Currently works only sortof for road vehicles, since they have a fuzzy
546 * concept of being "on" a trackdir. Dunno really what it returns for a road
547 * vehicle that is halfway a tile, never really understood that part. For road
548 * vehicles that are at the beginning or end of the tile, should just return
549 * the diagonal trackdir on which they are driving. I _think_.
550 * For other vehicles types, or vehicles with no clear trackdir (such as those
551 * in depots), returns 0xFF.
552 * @return the trackdir of the vehicle
554 virtual Trackdir GetVehicleTrackdir() const { return INVALID_TRACKDIR; }
557 * Gets the running cost of a vehicle that can be sent into SetDParam for string processing.
558 * @return the vehicle's running cost
560 Money GetDisplayRunningCost() const { return (this->GetRunningCost() >> 8); }
563 * Gets the profit vehicle had this year. It can be sent into SetDParam for string processing.
564 * @return the vehicle's profit this year
566 Money GetDisplayProfitThisYear() const { return (this->profit_this_year >> 8); }
569 * Gets the profit vehicle had last year. It can be sent into SetDParam for string processing.
570 * @return the vehicle's profit last year
572 Money GetDisplayProfitLastYear() const { return (this->profit_last_year >> 8); }
574 void SetNext(Vehicle *next);
577 * Get the next vehicle of this vehicle.
578 * @note articulated parts are also counted as vehicles.
579 * @return the next vehicle or NULL when there isn't a next vehicle.
581 inline Vehicle *Next() const { return this->next; }
584 * Get the previous vehicle of this vehicle.
585 * @note articulated parts are also counted as vehicles.
586 * @return the previous vehicle or NULL when there isn't a previous vehicle.
588 inline Vehicle *Previous() const { return this->previous; }
591 * Get the first vehicle of this vehicle chain.
592 * @return the first vehicle of the chain.
594 inline Vehicle *First() const { return this->first; }
597 * Get the last vehicle of this vehicle chain.
598 * @return the last vehicle of the chain.
600 inline Vehicle *Last()
602 Vehicle *v = this;
603 while (v->Next() != NULL) v = v->Next();
604 return v;
608 * Get the last vehicle of this vehicle chain.
609 * @return the last vehicle of the chain.
611 inline const Vehicle *Last() const
613 const Vehicle *v = this;
614 while (v->Next() != NULL) v = v->Next();
615 return v;
619 * Get the vehicle at offset \a n of this vehicle chain.
620 * @param n Offset from the current vehicle.
621 * @return The new vehicle or NULL if the offset is out-of-bounds.
623 inline Vehicle *Move(int n)
625 Vehicle *v = this;
626 if (n < 0) {
627 for (int i = 0; i != n && v != NULL; i--) v = v->Previous();
628 } else {
629 for (int i = 0; i != n && v != NULL; i++) v = v->Next();
631 return v;
635 * Get the vehicle at offset \a n of this vehicle chain.
636 * @param n Offset from the current vehicle.
637 * @return The new vehicle or NULL if the offset is out-of-bounds.
639 inline const Vehicle *Move(int n) const
641 const Vehicle *v = this;
642 if (n < 0) {
643 for (int i = 0; i != n && v != NULL; i--) v = v->Previous();
644 } else {
645 for (int i = 0; i != n && v != NULL; i++) v = v->Next();
647 return v;
651 * Get the first order of the vehicles order list.
652 * @return first order of order list.
654 inline Order *GetFirstOrder() const { return (this->orders.list == NULL) ? NULL : this->orders.list->GetFirstOrder(); }
656 void AddToShared(Vehicle *shared_chain);
657 void RemoveFromShared();
660 * Get the next vehicle of the shared vehicle chain.
661 * @return the next shared vehicle or NULL when there isn't a next vehicle.
663 inline Vehicle *NextShared() const { return this->next_shared; }
666 * Get the previous vehicle of the shared vehicle chain
667 * @return the previous shared vehicle or NULL when there isn't a previous vehicle.
669 inline Vehicle *PreviousShared() const { return this->previous_shared; }
672 * Get the first vehicle of this vehicle chain.
673 * @return the first vehicle of the chain.
675 inline Vehicle *FirstShared() const { return (this->orders.list == NULL) ? this->First() : this->orders.list->GetFirstSharedVehicle(); }
678 * Check if we share our orders with another vehicle.
679 * @return true if there are other vehicles sharing the same order
681 inline bool IsOrderListShared() const { return this->orders.list != NULL && this->orders.list->IsShared(); }
684 * Get the number of orders this vehicle has.
685 * @return the number of orders this vehicle has.
687 inline VehicleOrderID GetNumOrders() const { return (this->orders.list == NULL) ? 0 : this->orders.list->GetNumOrders(); }
690 * Get the number of manually added orders this vehicle has.
691 * @return the number of manually added orders this vehicle has.
693 inline VehicleOrderID GetNumManualOrders() const { return (this->orders.list == NULL) ? 0 : this->orders.list->GetNumManualOrders(); }
696 * Get the next station the vehicle will stop at.
697 * @return ID of the next station the vehicle will stop at or INVALID_STATION.
699 inline StationIDStack GetNextStoppingStation() const
701 return (this->orders.list == NULL) ? INVALID_STATION : this->orders.list->GetNextStoppingStation(this);
704 void ResetRefitCaps();
707 * Copy certain configurations and statistics of a vehicle after successful autoreplace/renew
708 * The function shall copy everything that cannot be copied by a command (like orders / group etc),
709 * and that shall not be resetted for the new vehicle.
710 * @param src The old vehicle
712 inline void CopyVehicleConfigAndStatistics(const Vehicle *src)
714 this->CopyConsistPropertiesFrom(src);
716 this->unitnumber = src->unitnumber;
718 this->current_order = src->current_order;
719 this->dest_tile = src->dest_tile;
721 this->profit_this_year = src->profit_this_year;
722 this->profit_last_year = src->profit_last_year;
726 bool HandleBreakdown();
728 bool NeedsAutorenewing(const Company *c, bool use_renew_setting = true) const;
730 bool NeedsServicing() const;
731 bool NeedsAutomaticServicing() const;
734 * Determine the location for the station where the vehicle goes to next.
735 * Things done for example are allocating slots in a road stop or exact
736 * location of the platform is determined for ships.
737 * @param station the station to make the next location of the vehicle.
738 * @return the location (tile) to aim for.
740 virtual TileIndex GetOrderStationLocation(StationID station) { return INVALID_TILE; }
743 * Find the closest depot for this vehicle and tell us the location,
744 * DestinationID and whether we should reverse.
745 * @param location where do we go to?
746 * @param destination what hangar do we go to?
747 * @param reverse should the vehicle be reversed?
748 * @return true if a depot could be found.
750 virtual bool FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse) { return false; }
752 CommandCost SendToDepot(DoCommandFlag flags, DepotCommand command);
754 void UpdateVisualEffect(bool allow_power_change = true);
755 void ShowVisualEffect() const;
757 void UpdatePosition();
758 void UpdateViewport(bool dirty);
759 void UpdatePositionAndViewport();
760 void MarkAllViewportsDirty() const;
762 inline uint16 GetServiceInterval() const { return this->service_interval; }
764 inline void SetServiceInterval(uint16 interval) { this->service_interval = interval; }
766 inline bool ServiceIntervalIsCustom() const { return HasBit(this->vehicle_flags, VF_SERVINT_IS_CUSTOM); }
768 inline bool ServiceIntervalIsPercent() const { return HasBit(this->vehicle_flags, VF_SERVINT_IS_PERCENT); }
770 inline void SetServiceIntervalIsCustom(bool on) { SB(this->vehicle_flags, VF_SERVINT_IS_CUSTOM, 1, on); }
772 inline void SetServiceIntervalIsPercent(bool on) { SB(this->vehicle_flags, VF_SERVINT_IS_PERCENT, 1, on); }
774 private:
776 * Advance cur_real_order_index to the next real order.
777 * cur_implicit_order_index is not touched.
779 void SkipToNextRealOrderIndex()
781 if (this->GetNumManualOrders() > 0) {
782 /* Advance to next real order */
783 do {
784 this->cur_real_order_index++;
785 if (this->cur_real_order_index >= this->GetNumOrders()) this->cur_real_order_index = 0;
786 } while (this->GetOrder(this->cur_real_order_index)->IsType(OT_IMPLICIT));
787 } else {
788 this->cur_real_order_index = 0;
792 public:
794 * Increments cur_implicit_order_index, keeps care of the wrap-around and invalidates the GUI.
795 * cur_real_order_index is incremented as well, if needed.
796 * Note: current_order is not invalidated.
798 void IncrementImplicitOrderIndex()
800 if (this->cur_implicit_order_index == this->cur_real_order_index) {
801 /* Increment real order index as well */
802 this->SkipToNextRealOrderIndex();
805 assert(this->cur_real_order_index == 0 || this->cur_real_order_index < this->GetNumOrders());
807 /* Advance to next implicit order */
808 do {
809 this->cur_implicit_order_index++;
810 if (this->cur_implicit_order_index >= this->GetNumOrders()) this->cur_implicit_order_index = 0;
811 } while (this->cur_implicit_order_index != this->cur_real_order_index && !this->GetOrder(this->cur_implicit_order_index)->IsType(OT_IMPLICIT));
813 InvalidateVehicleOrder(this, 0);
817 * Advanced cur_real_order_index to the next real order, keeps care of the wrap-around and invalidates the GUI.
818 * 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
819 * but not any implicit orders.
820 * Note: current_order is not invalidated.
822 void IncrementRealOrderIndex()
824 if (this->cur_implicit_order_index == this->cur_real_order_index) {
825 /* Increment both real and implicit order */
826 this->IncrementImplicitOrderIndex();
827 } else {
828 /* Increment real order only */
829 this->SkipToNextRealOrderIndex();
830 InvalidateVehicleOrder(this, 0);
835 * Skip implicit orders until cur_real_order_index is a non-implicit order.
837 void UpdateRealOrderIndex()
839 /* Make sure the index is valid */
840 if (this->cur_real_order_index >= this->GetNumOrders()) this->cur_real_order_index = 0;
842 if (this->GetNumManualOrders() > 0) {
843 /* Advance to next real order */
844 while (this->GetOrder(this->cur_real_order_index)->IsType(OT_IMPLICIT)) {
845 this->cur_real_order_index++;
846 if (this->cur_real_order_index >= this->GetNumOrders()) this->cur_real_order_index = 0;
848 } else {
849 this->cur_real_order_index = 0;
854 * Returns order 'index' of a vehicle or NULL when it doesn't exists
855 * @param index the order to fetch
856 * @return the found (or not) order
858 inline Order *GetOrder(int index) const
860 return (this->orders.list == NULL) ? NULL : this->orders.list->GetOrderAt(index);
864 * Returns the last order of a vehicle, or NULL if it doesn't exists
865 * @return last order of a vehicle, if available
867 inline Order *GetLastOrder() const
869 return (this->orders.list == NULL) ? NULL : this->orders.list->GetLastOrder();
872 bool IsEngineCountable() const;
873 bool HasEngineType() const;
874 bool HasDepotOrder() const;
875 void HandlePathfindingResult(bool path_found);
878 * Check if the vehicle is a front engine.
879 * @return Returns true if the vehicle is a front engine.
881 inline bool IsFrontEngine() const
883 return this->IsGroundVehicle() && HasBit(this->subtype, GVSF_FRONT);
887 * Check if the vehicle is an articulated part of an engine.
888 * @return Returns true if the vehicle is an articulated part.
890 inline bool IsArticulatedPart() const
892 return this->IsGroundVehicle() && HasBit(this->subtype, GVSF_ARTICULATED_PART);
896 * Check if an engine has an articulated part.
897 * @return True if the engine has an articulated part.
899 inline bool HasArticulatedPart() const
901 return this->Next() != NULL && this->Next()->IsArticulatedPart();
905 * Get the next part of an articulated engine.
906 * @return Next part of the articulated engine.
907 * @pre The vehicle is an articulated engine.
909 inline Vehicle *GetNextArticulatedPart() const
911 assert(this->HasArticulatedPart());
912 return this->Next();
916 * Get the first part of an articulated engine.
917 * @return First part of the engine.
919 inline Vehicle *GetFirstEnginePart()
921 Vehicle *v = this;
922 while (v->IsArticulatedPart()) v = v->Previous();
923 return v;
927 * Get the first part of an articulated engine.
928 * @return First part of the engine.
930 inline const Vehicle *GetFirstEnginePart() const
932 const Vehicle *v = this;
933 while (v->IsArticulatedPart()) v = v->Previous();
934 return v;
938 * Get the last part of an articulated engine.
939 * @return Last part of the engine.
941 inline Vehicle *GetLastEnginePart()
943 Vehicle *v = this;
944 while (v->HasArticulatedPart()) v = v->GetNextArticulatedPart();
945 return v;
949 * Get the next real (non-articulated part) vehicle in the consist.
950 * @return Next vehicle in the consist.
952 inline Vehicle *GetNextVehicle() const
954 const Vehicle *v = this;
955 while (v->HasArticulatedPart()) v = v->GetNextArticulatedPart();
957 /* v now contains the last articulated part in the engine */
958 return v->Next();
962 * Get the previous real (non-articulated part) vehicle in the consist.
963 * @return Previous vehicle in the consist.
965 inline Vehicle *GetPrevVehicle() const
967 Vehicle *v = this->Previous();
968 while (v != NULL && v->IsArticulatedPart()) v = v->Previous();
970 return v;
975 * Iterate over all vehicles from a given point.
976 * @param var The variable used to iterate over.
977 * @param start The vehicle to start the iteration at.
979 #define FOR_ALL_VEHICLES_FROM(var, start) FOR_ALL_ITEMS_FROM(Vehicle, vehicle_index, var, start)
982 * Iterate over all vehicles.
983 * @param var The variable used to iterate over.
985 #define FOR_ALL_VEHICLES(var) FOR_ALL_VEHICLES_FROM(var, 0)
988 * Class defining several overloaded accessors so we don't
989 * have to cast vehicle types that often
991 template <class T, VehicleType Type>
992 struct SpecializedVehicle : public Vehicle {
993 static const VehicleType EXPECTED_TYPE = Type; ///< Specialized type
995 typedef SpecializedVehicle<T, Type> SpecializedVehicleBase; ///< Our type
998 * Set vehicle type correctly
1000 inline SpecializedVehicle<T, Type>() : Vehicle(Type)
1002 this->sprite_seq.count = 1;
1006 * Get the first vehicle in the chain
1007 * @return first vehicle in the chain
1009 inline T *First() const { return (T *)this->Vehicle::First(); }
1012 * Get the last vehicle in the chain
1013 * @return last vehicle in the chain
1015 inline T *Last() { return (T *)this->Vehicle::Last(); }
1018 * Get the last vehicle in the chain
1019 * @return last vehicle in the chain
1021 inline const T *Last() const { return (const T *)this->Vehicle::Last(); }
1024 * Get next vehicle in the chain
1025 * @return next vehicle in the chain
1027 inline T *Next() const { return (T *)this->Vehicle::Next(); }
1030 * Get previous vehicle in the chain
1031 * @return previous vehicle in the chain
1033 inline T *Previous() const { return (T *)this->Vehicle::Previous(); }
1036 * Get the next part of an articulated engine.
1037 * @return Next part of the articulated engine.
1038 * @pre The vehicle is an articulated engine.
1040 inline T *GetNextArticulatedPart() { return (T *)this->Vehicle::GetNextArticulatedPart(); }
1043 * Get the next part of an articulated engine.
1044 * @return Next part of the articulated engine.
1045 * @pre The vehicle is an articulated engine.
1047 inline T *GetNextArticulatedPart() const { return (T *)this->Vehicle::GetNextArticulatedPart(); }
1050 * Get the first part of an articulated engine.
1051 * @return First part of the engine.
1053 inline T *GetFirstEnginePart() { return (T *)this->Vehicle::GetFirstEnginePart(); }
1056 * Get the first part of an articulated engine.
1057 * @return First part of the engine.
1059 inline const T *GetFirstEnginePart() const { return (const T *)this->Vehicle::GetFirstEnginePart(); }
1062 * Get the last part of an articulated engine.
1063 * @return Last part of the engine.
1065 inline T *GetLastEnginePart() { return (T *)this->Vehicle::GetLastEnginePart(); }
1068 * Get the next real (non-articulated part) vehicle in the consist.
1069 * @return Next vehicle in the consist.
1071 inline T *GetNextVehicle() const { return (T *)this->Vehicle::GetNextVehicle(); }
1074 * Get the previous real (non-articulated part) vehicle in the consist.
1075 * @return Previous vehicle in the consist.
1077 inline T *GetPrevVehicle() const { return (T *)this->Vehicle::GetPrevVehicle(); }
1080 * Tests whether given index is a valid index for vehicle of this type
1081 * @param index tested index
1082 * @return is this index valid index of T?
1084 static inline bool IsValidID(size_t index)
1086 return Vehicle::IsValidID(index) && Vehicle::Get(index)->type == Type;
1090 * Gets vehicle with given index
1091 * @return pointer to vehicle with given index casted to T *
1093 static inline T *Get(size_t index)
1095 return (T *)Vehicle::Get(index);
1099 * Returns vehicle if the index is a valid index for this vehicle type
1100 * @return pointer to vehicle with given index if it's a vehicle of this type
1102 static inline T *GetIfValid(size_t index)
1104 return IsValidID(index) ? Get(index) : NULL;
1108 * Converts a Vehicle to SpecializedVehicle with type checking.
1109 * @param v Vehicle pointer
1110 * @return pointer to SpecializedVehicle
1112 static inline T *From(Vehicle *v)
1114 assert(v->type == Type);
1115 return (T *)v;
1119 * Converts a const Vehicle to const SpecializedVehicle with type checking.
1120 * @param v Vehicle pointer
1121 * @return pointer to SpecializedVehicle
1123 static inline const T *From(const Vehicle *v)
1125 assert(v->type == Type);
1126 return (const T *)v;
1130 * Update vehicle sprite- and position caches
1131 * @param force_update Force updating the vehicle on the viewport.
1132 * @param update_delta Also update the delta?
1134 inline void UpdateViewport(bool force_update, bool update_delta)
1136 /* Skip updating sprites on dedicated servers without screen */
1137 if (_network_dedicated) return;
1139 /* Explicitly choose method to call to prevent vtable dereference -
1140 * it gives ~3% runtime improvements in games with many vehicles */
1141 if (update_delta) ((T *)this)->T::UpdateDeltaXY(this->direction);
1142 VehicleSpriteSeq seq;
1143 ((T *)this)->T::GetImage(this->direction, EIT_ON_MAP, &seq);
1144 if (force_update || this->sprite_seq != seq) {
1145 this->sprite_seq = seq;
1146 this->Vehicle::UpdateViewport(true);
1152 * Iterate over all vehicles of a particular type.
1153 * @param name The type of vehicle to iterate over.
1154 * @param var The variable used to iterate over.
1156 #define FOR_ALL_VEHICLES_OF_TYPE(name, var) FOR_ALL_ITEMS_FROM(name, vehicle_index, var, 0) if (var->type == name::EXPECTED_TYPE)
1158 /** Generates sequence of free UnitID numbers */
1159 struct FreeUnitIDGenerator {
1160 bool *cache; ///< array of occupied unit id numbers
1161 UnitID maxid; ///< maximum ID at the moment of constructor call
1162 UnitID curid; ///< last ID returned; 0 if none
1164 FreeUnitIDGenerator(VehicleType type, CompanyID owner);
1165 UnitID NextID();
1167 /** Releases allocated memory */
1168 ~FreeUnitIDGenerator() { free(this->cache); }
1171 /** Sentinel for an invalid coordinate. */
1172 static const int32 INVALID_COORD = 0x7fffffff;
1174 #endif /* VEHICLE_BASE_H */