(svn r25652) -Fix: Improve text caret movement for complex scripts.
[openttd/fttd.git] / src / vehicle_base.h
blobbe3a4058f78d77c049a998f5b7073cff2cd4c44c
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"
27 /** Vehicle status bits in #Vehicle::vehstatus. */
28 enum VehStatus {
29 VS_HIDDEN = 0x01, ///< Vehicle is not visible.
30 VS_STOPPED = 0x02, ///< Vehicle is stopped by the player.
31 VS_UNCLICKABLE = 0x04, ///< Vehicle is not clickable by the user (shadow vehicles).
32 VS_DEFPAL = 0x08, ///< Use default vehicle palette. @see DoDrawVehicle
33 VS_TRAIN_SLOWING = 0x10, ///< Train is slowing down.
34 VS_SHADOW = 0x20, ///< Vehicle is a shadow vehicle.
35 VS_AIRCRAFT_BROKEN = 0x40, ///< Aircraft is broken down.
36 VS_CRASHED = 0x80, ///< Vehicle is crashed.
39 /** Bit numbers in #Vehicle::vehicle_flags. */
40 enum VehicleFlags {
41 VF_LOADING_FINISHED, ///< Vehicle has finished loading.
42 VF_CARGO_UNLOADING, ///< Vehicle is unloading cargo.
43 VF_BUILT_AS_PROTOTYPE, ///< Vehicle is a prototype (accepted as exclusive preview).
44 VF_TIMETABLE_STARTED, ///< Whether the vehicle has started running on the timetable yet.
45 VF_AUTOFILL_TIMETABLE, ///< Whether the vehicle should fill in the timetable automatically.
46 VF_AUTOFILL_PRES_WAIT_TIME, ///< Whether non-destructive auto-fill should preserve waiting times
47 VF_STOP_LOADING, ///< Don't load anymore during the next load cycle.
48 VF_PATHFINDER_LOST, ///< Vehicle's pathfinder is lost.
49 VF_SERVINT_IS_CUSTOM, ///< Service interval is custom.
50 VF_SERVINT_IS_PERCENT, ///< Service interval is percent.
53 /** Bit numbers used to indicate which of the #NewGRFCache values are valid. */
54 enum NewGRFCacheValidValues {
55 NCVV_POSITION_CONSIST_LENGTH = 0, ///< This bit will be set if the NewGRF var 40 currently stored is valid.
56 NCVV_POSITION_SAME_ID_LENGTH = 1, ///< This bit will be set if the NewGRF var 41 currently stored is valid.
57 NCVV_CONSIST_CARGO_INFORMATION = 2, ///< This bit will be set if the NewGRF var 42 currently stored is valid.
58 NCVV_COMPANY_INFORMATION = 3, ///< This bit will be set if the NewGRF var 43 currently stored is valid.
59 NCVV_END, ///< End of the bits.
62 /** Cached often queried (NewGRF) values */
63 struct NewGRFCache {
64 /* Values calculated when they are requested for the first time after invalidating the NewGRF cache. */
65 uint32 position_consist_length; ///< Cache for NewGRF var 40.
66 uint32 position_same_id_length; ///< Cache for NewGRF var 41.
67 uint32 consist_cargo_information; ///< Cache for NewGRF var 42. (Note: The cargotype is untranslated in the cache because the accessing GRF is yet unknown.)
68 uint32 company_information; ///< Cache for NewGRF var 43.
69 uint8 cache_valid; ///< Bitset that indicates which cache values are valid.
72 /** Meaning of the various bits of the visual effect. */
73 enum VisualEffect {
74 VE_OFFSET_START = 0, ///< First bit that contains the offset (0 = front, 8 = centre, 15 = rear)
75 VE_OFFSET_COUNT = 4, ///< Number of bits used for the offset
76 VE_OFFSET_CENTRE = 8, ///< Value of offset corresponding to a position above the centre of the vehicle
78 VE_TYPE_START = 4, ///< First bit used for the type of effect
79 VE_TYPE_COUNT = 2, ///< Number of bits used for the effect type
80 VE_TYPE_DEFAULT = 0, ///< Use default from engine class
81 VE_TYPE_STEAM = 1, ///< Steam plumes
82 VE_TYPE_DIESEL = 2, ///< Diesel fumes
83 VE_TYPE_ELECTRIC = 3, ///< Electric sparks
85 VE_DISABLE_EFFECT = 6, ///< Flag to disable visual effect
86 VE_DISABLE_WAGON_POWER = 7, ///< Flag to disable wagon power
88 VE_DEFAULT = 0xFF, ///< Default value to indicate that visual effect should be based on engine class
91 /**
92 * Enum to handle ground vehicle subtypes.
93 * This is defined here instead of at #GroundVehicle because some common function require access to these flags.
94 * Do not access it directly unless you have to. Use the subtype access functions.
96 enum GroundVehicleSubtypeFlags {
97 GVSF_FRONT = 0, ///< Leading engine of a consist.
98 GVSF_ARTICULATED_PART = 1, ///< Articulated part of an engine.
99 GVSF_WAGON = 2, ///< Wagon (not used for road vehicles).
100 GVSF_ENGINE = 3, ///< Engine that can be front engine, but might be placed behind another engine (not used for road vehicles).
101 GVSF_FREE_WAGON = 4, ///< First in a wagon chain (in depot) (not used for road vehicles).
102 GVSF_MULTIHEADED = 5, ///< Engine is multiheaded (not used for road vehicles).
105 /** Cached often queried values common to all vehicles. */
106 struct VehicleCache {
107 uint16 cached_max_speed; ///< Maximum speed of the consist (minimum of the max speed of all vehicles in the consist).
108 uint16 cached_cargo_age_period; ///< Number of ticks before carried cargo is aged.
110 byte cached_vis_effect; ///< Visual effect to show (see #VisualEffect)
113 /** A vehicle pool for a little over 1 million vehicles. */
114 typedef Pool<Vehicle, VehicleID, 512, 0xFF000> VehiclePool;
115 extern VehiclePool _vehicle_pool;
117 /* Some declarations of functions, so we can make them friendly */
118 struct SaveLoad;
119 struct GroundVehicleCache;
120 extern const SaveLoad *GetVehicleDescription(VehicleType vt);
121 struct LoadgameState;
122 extern bool LoadOldVehicle(LoadgameState *ls, int num);
123 extern void FixOldVehicles();
125 struct GRFFile;
127 /** %Vehicle data structure. */
128 struct Vehicle : VehiclePool::PoolItem<&_vehicle_pool>, BaseVehicle, BaseConsist {
129 private:
130 Vehicle *next; ///< pointer to the next vehicle in the chain
131 Vehicle *previous; ///< NOSAVE: pointer to the previous vehicle in the chain
132 Vehicle *first; ///< NOSAVE: pointer to the first vehicle in the chain
134 Vehicle *next_shared; ///< pointer to the next vehicle that shares the order
135 Vehicle *previous_shared; ///< NOSAVE: pointer to the previous vehicle in the shared order chain
136 public:
137 friend const SaveLoad *GetVehicleDescription(VehicleType vt); ///< So we can use private/protected variables in the saveload code
138 friend void FixOldVehicles();
139 friend void AfterLoadVehicles(bool part_of_load); ///< So we can set the #previous and #first pointers while loading
140 friend bool LoadOldVehicle(LoadgameState *ls, int num); ///< So we can set the proper next pointer while loading
142 TileIndex tile; ///< Current tile index
145 * Heading for this tile.
146 * For airports and train stations this tile does not necessarily belong to the destination station,
147 * but it can be used for heuristic purposes to estimate the distance.
149 TileIndex dest_tile;
151 Money profit_this_year; ///< Profit this year << 8, low 8 bits are fract
152 Money profit_last_year; ///< Profit last year << 8, low 8 bits are fract
153 Money value; ///< Value of the vehicle
155 CargoPayment *cargo_payment; ///< The cargo payment we're currently in
157 Rect coord; ///< NOSAVE: Graphical bounding box of the vehicle, i.e. what to redraw on moves.
159 Vehicle *hash_viewport_next; ///< NOSAVE: Next vehicle in the visual location hash.
160 Vehicle **hash_viewport_prev; ///< NOSAVE: Previous vehicle in the visual location hash.
162 Vehicle *hash_tile_next; ///< NOSAVE: Next vehicle in the tile location hash.
163 Vehicle **hash_tile_prev; ///< NOSAVE: Previous vehicle in the tile location hash.
164 Vehicle **hash_tile_current; ///< NOSAVE: Cache of the current hash chain.
166 SpriteID colourmap; ///< NOSAVE: cached colour mapping
168 /* Related to age and service time */
169 Year build_year; ///< Year the vehicle has been built.
170 Date age; ///< Age in days
171 Date max_age; ///< Maximum age
172 Date date_of_last_service; ///< Last date the vehicle had a service at a depot.
173 uint16 reliability; ///< Reliability.
174 uint16 reliability_spd_dec; ///< Reliability decrease speed.
175 byte breakdown_ctr; ///< Counter for managing breakdown events. @see Vehicle::HandleBreakdown
176 byte breakdown_delay; ///< Counter for managing breakdown length.
177 byte breakdowns_since_last_service; ///< Counter for the amount of breakdowns.
178 byte breakdown_chance; ///< Current chance of breakdowns.
180 int32 x_pos; ///< x coordinate.
181 int32 y_pos; ///< y coordinate.
182 int32 z_pos; ///< z coordinate.
183 DirectionByte direction; ///< facing
185 OwnerByte owner; ///< Which company owns the vehicle?
187 * currently displayed sprite index
188 * 0xfd == custom sprite, 0xfe == custom second head sprite
189 * 0xff == reserved for another custom sprite
191 byte spritenum;
192 SpriteID cur_image; ///< sprite number for this vehicle
193 byte x_extent; ///< x-extent of vehicle bounding box
194 byte y_extent; ///< y-extent of vehicle bounding box
195 byte z_extent; ///< z-extent of vehicle bounding box
196 int8 x_bb_offs; ///< x offset of vehicle bounding box
197 int8 y_bb_offs; ///< y offset of vehicle bounding box
198 int8 x_offs; ///< x offset for vehicle sprite
199 int8 y_offs; ///< y offset for vehicle sprite
200 EngineID engine_type; ///< The type of engine used for this vehicle.
202 TextEffectID fill_percent_te_id; ///< a text-effect id to a loading indicator object
203 UnitID unitnumber; ///< unit number, for display purposes only
205 uint16 cur_speed; ///< current speed
206 byte subspeed; ///< fractional speed
207 byte acceleration; ///< used by train & aircraft
208 uint32 motion_counter; ///< counter to occasionally play a vehicle sound.
209 byte progress; ///< The percentage (if divided by 256) this vehicle already crossed the tile unit.
211 byte random_bits; ///< Bits used for determining which randomized variational spritegroups to use when drawing.
212 byte waiting_triggers; ///< Triggers to be yet matched before rerandomizing the random bits.
214 StationID last_station_visited; ///< The last station we stopped at.
215 StationID last_loading_station; ///< Last station the vehicle has stopped at and could possibly leave from with any cargo loaded.
217 CargoID cargo_type; ///< type of cargo this vehicle is carrying
218 byte cargo_subtype; ///< Used for livery refits (NewGRF variations)
219 uint16 cargo_cap; ///< total capacity
220 uint16 refit_cap; ///< Capacity left over from before last refit.
221 VehicleCargoList cargo; ///< The cargo this vehicle is carrying
222 uint16 cargo_age_counter; ///< Ticks till cargo is aged next.
224 byte day_counter; ///< Increased by one for each day
225 byte tick_counter; ///< Increased by one for each tick
226 byte running_ticks; ///< Number of ticks this vehicle was not stopped this day
228 byte vehstatus; ///< Status
229 Order current_order; ///< The current order (+ status, like: loading)
231 union {
232 OrderList *list; ///< Pointer to the order list for this vehicle
233 Order *old; ///< Only used during conversion of old save games
234 } orders; ///< The orders currently assigned to the vehicle.
236 uint16 load_unload_ticks; ///< Ticks to wait before starting next cycle.
237 GroupID group_id; ///< Index of group Pool array
238 byte subtype; ///< subtype (Filled with values from #EffectVehicles/#TrainSubTypes/#AircraftSubTypes)
240 NewGRFCache grf_cache; ///< Cache of often used calculated NewGRF values
241 VehicleCache vcache; ///< Cache of often used vehicle values.
243 Vehicle(VehicleType type = VEH_INVALID);
245 void PreDestructor();
246 /** We want to 'destruct' the right class. */
247 virtual ~Vehicle();
249 void BeginLoading();
250 void CancelReservation(StationID next, Station *st);
251 void LeaveStation();
253 GroundVehicleCache *GetGroundVehicleCache();
254 const GroundVehicleCache *GetGroundVehicleCache() const;
256 uint16 &GetGroundVehicleFlags();
257 const uint16 &GetGroundVehicleFlags() const;
259 void DeleteUnreachedImplicitOrders();
261 void HandleLoading(bool mode = false);
263 void GetConsistFreeCapacities(SmallMap<CargoID, uint> &capacities) const;
265 uint GetConsistTotalCapacity() const;
268 * Marks the vehicles to be redrawn and updates cached variables
270 * This method marks the area of the vehicle on the screen as dirty.
271 * It can be use to repaint the vehicle.
273 * @ingroup dirty
275 virtual void MarkDirty() {}
278 * Updates the x and y offsets and the size of the sprite used
279 * for this vehicle.
280 * @param direction the direction the vehicle is facing
282 virtual void UpdateDeltaXY(Direction direction) {}
285 * Determines the effective direction-specific vehicle movement speed.
287 * This method belongs to the old vehicle movement method:
288 * A vehicle moves a step every 256 progress units.
289 * The vehicle speed is scaled by 3/4 when moving in X or Y direction due to the longer distance.
291 * However, this method is slightly wrong in corners, as the leftover progress is not scaled correctly
292 * when changing movement direction. #GetAdvanceSpeed() and #GetAdvanceDistance() are better wrt. this.
294 * @param speed Direction-independent unscaled speed.
295 * @return speed scaled by movement direction. 256 units are required for each movement step.
297 inline uint GetOldAdvanceSpeed(uint speed)
299 return (this->direction & 1) ? speed : speed * 3 / 4;
303 * Determines the effective vehicle movement speed.
305 * Together with #GetAdvanceDistance() this function is a replacement for #GetOldAdvanceSpeed().
307 * A vehicle progresses independent of it's movement direction.
308 * However different amounts of "progress" are needed for moving a step in a specific direction.
309 * That way the leftover progress does not need any adaption when changing movement direction.
311 * @param speed Direction-independent unscaled speed.
312 * @return speed, scaled to match #GetAdvanceDistance().
314 static inline uint GetAdvanceSpeed(uint speed)
316 return speed * 3 / 4;
320 * Determines the vehicle "progress" needed for moving a step.
322 * Together with #GetAdvanceSpeed() this function is a replacement for #GetOldAdvanceSpeed().
324 * @return distance to drive for a movement step on the map.
326 inline uint GetAdvanceDistance()
328 return (this->direction & 1) ? 192 : 256;
332 * Sets the expense type associated to this vehicle type
333 * @param income whether this is income or (running) expenses of the vehicle
335 virtual ExpensesType GetExpenseType(bool income) const { return EXPENSES_OTHER; }
338 * Play the sound associated with leaving the station
340 virtual void PlayLeaveStationSound() const {}
343 * Whether this is the primary vehicle in the chain.
345 virtual bool IsPrimaryVehicle() const { return false; }
347 const Engine *GetEngine() const;
350 * Gets the sprite to show for the given direction
351 * @param direction the direction the vehicle is facing
352 * @return the sprite for the given vehicle in the given direction
354 virtual SpriteID GetImage(Direction direction, EngineImageType image_type) const { return 0; }
356 const GRFFile *GetGRF() const;
357 uint32 GetGRFID() const;
360 * Invalidates cached NewGRF variables
361 * @see InvalidateNewGRFCacheOfChain
363 inline void InvalidateNewGRFCache()
365 this->grf_cache.cache_valid = 0;
369 * Invalidates cached NewGRF variables of all vehicles in the chain (after the current vehicle)
370 * @see InvalidateNewGRFCache
372 inline void InvalidateNewGRFCacheOfChain()
374 for (Vehicle *u = this; u != NULL; u = u->Next()) {
375 u->InvalidateNewGRFCache();
380 * Check if the vehicle is a ground vehicle.
381 * @return True iff the vehicle is a train or a road vehicle.
383 inline bool IsGroundVehicle() const
385 return this->type == VEH_TRAIN || this->type == VEH_ROAD;
389 * Gets the speed in km-ish/h that can be sent into SetDParam for string processing.
390 * @return the vehicle's speed
392 virtual int GetDisplaySpeed() const { return 0; }
395 * Gets the maximum speed in km-ish/h that can be sent into SetDParam for string processing.
396 * @return the vehicle's maximum speed
398 virtual int GetDisplayMaxSpeed() const { return 0; }
401 * Calculates the maximum speed of the vehicle under its current conditions.
402 * @return Current maximum speed in native units.
404 virtual int GetCurrentMaxSpeed() const { return 0; }
407 * Gets the running cost of a vehicle
408 * @return the vehicle's running cost
410 virtual Money GetRunningCost() const { return 0; }
413 * Check whether the vehicle is in the depot.
414 * @return true if and only if the vehicle is in the depot.
416 virtual bool IsInDepot() const { return false; }
419 * Check whether the whole vehicle chain is in the depot.
420 * @return true if and only if the whole chain is in the depot.
422 virtual bool IsChainInDepot() const { return this->IsInDepot(); }
425 * Check whether the vehicle is in the depot *and* stopped.
426 * @return true if and only if the vehicle is in the depot and stopped.
428 bool IsStoppedInDepot() const
430 assert(this == this->First());
431 /* Free wagons have no VS_STOPPED state */
432 if (this->IsPrimaryVehicle() && !(this->vehstatus & VS_STOPPED)) return false;
433 return this->IsChainInDepot();
437 * Calls the tick handler of the vehicle
438 * @return is this vehicle still valid?
440 virtual bool Tick() { return true; };
443 * Calls the new day handler of the vehicle
445 virtual void OnNewDay() {};
448 * Crash the (whole) vehicle chain.
449 * @param flooded whether the cause of the crash is flooding or not.
450 * @return the number of lost souls.
452 virtual uint Crash(bool flooded = false);
455 * Returns the Trackdir on which the vehicle is currently located.
456 * Works for trains and ships.
457 * Currently works only sortof for road vehicles, since they have a fuzzy
458 * concept of being "on" a trackdir. Dunno really what it returns for a road
459 * vehicle that is halfway a tile, never really understood that part. For road
460 * vehicles that are at the beginning or end of the tile, should just return
461 * the diagonal trackdir on which they are driving. I _think_.
462 * For other vehicles types, or vehicles with no clear trackdir (such as those
463 * in depots), returns 0xFF.
464 * @return the trackdir of the vehicle
466 virtual Trackdir GetVehicleTrackdir() const { return INVALID_TRACKDIR; }
469 * Gets the running cost of a vehicle that can be sent into SetDParam for string processing.
470 * @return the vehicle's running cost
472 Money GetDisplayRunningCost() const { return (this->GetRunningCost() >> 8); }
475 * Gets the profit vehicle had this year. It can be sent into SetDParam for string processing.
476 * @return the vehicle's profit this year
478 Money GetDisplayProfitThisYear() const { return (this->profit_this_year >> 8); }
481 * Gets the profit vehicle had last year. It can be sent into SetDParam for string processing.
482 * @return the vehicle's profit last year
484 Money GetDisplayProfitLastYear() const { return (this->profit_last_year >> 8); }
486 void SetNext(Vehicle *next);
489 * Get the next vehicle of this vehicle.
490 * @note articulated parts are also counted as vehicles.
491 * @return the next vehicle or NULL when there isn't a next vehicle.
493 inline Vehicle *Next() const { return this->next; }
496 * Get the previous vehicle of this vehicle.
497 * @note articulated parts are also counted as vehicles.
498 * @return the previous vehicle or NULL when there isn't a previous vehicle.
500 inline Vehicle *Previous() const { return this->previous; }
503 * Get the first vehicle of this vehicle chain.
504 * @return the first vehicle of the chain.
506 inline Vehicle *First() const { return this->first; }
509 * Get the last vehicle of this vehicle chain.
510 * @return the last vehicle of the chain.
512 inline Vehicle *Last()
514 Vehicle *v = this;
515 while (v->Next() != NULL) v = v->Next();
516 return v;
520 * Get the last vehicle of this vehicle chain.
521 * @return the last vehicle of the chain.
523 inline const Vehicle *Last() const
525 const Vehicle *v = this;
526 while (v->Next() != NULL) v = v->Next();
527 return v;
531 * Get the vehicle at offset \a n of this vehicle chain.
532 * @param n Offset from the current vehicle.
533 * @return The new vehicle or NULL if the offset is out-of-bounds.
535 inline Vehicle *Move(int n)
537 Vehicle *v = this;
538 if (n < 0) {
539 for (int i = 0; i != n && v != NULL; i--) v = v->Previous();
540 } else {
541 for (int i = 0; i != n && v != NULL; i++) v = v->Next();
543 return v;
547 * Get the vehicle at offset \a n of this vehicle chain.
548 * @param n Offset from the current vehicle.
549 * @return The new vehicle or NULL if the offset is out-of-bounds.
551 inline const Vehicle *Move(int n) const
553 const Vehicle *v = this;
554 if (n < 0) {
555 for (int i = 0; i != n && v != NULL; i--) v = v->Previous();
556 } else {
557 for (int i = 0; i != n && v != NULL; i++) v = v->Next();
559 return v;
563 * Get the first order of the vehicles order list.
564 * @return first order of order list.
566 inline Order *GetFirstOrder() const { return (this->orders.list == NULL) ? NULL : this->orders.list->GetFirstOrder(); }
568 void AddToShared(Vehicle *shared_chain);
569 void RemoveFromShared();
572 * Get the next vehicle of the shared vehicle chain.
573 * @return the next shared vehicle or NULL when there isn't a next vehicle.
575 inline Vehicle *NextShared() const { return this->next_shared; }
578 * Get the previous vehicle of the shared vehicle chain
579 * @return the previous shared vehicle or NULL when there isn't a previous vehicle.
581 inline Vehicle *PreviousShared() const { return this->previous_shared; }
584 * Get the first vehicle of this vehicle chain.
585 * @return the first vehicle of the chain.
587 inline Vehicle *FirstShared() const { return (this->orders.list == NULL) ? this->First() : this->orders.list->GetFirstSharedVehicle(); }
590 * Check if we share our orders with another vehicle.
591 * @return true if there are other vehicles sharing the same order
593 inline bool IsOrderListShared() const { return this->orders.list != NULL && this->orders.list->IsShared(); }
596 * Get the number of orders this vehicle has.
597 * @return the number of orders this vehicle has.
599 inline VehicleOrderID GetNumOrders() const { return (this->orders.list == NULL) ? 0 : this->orders.list->GetNumOrders(); }
602 * Get the number of manually added orders this vehicle has.
603 * @return the number of manually added orders this vehicle has.
605 inline VehicleOrderID GetNumManualOrders() const { return (this->orders.list == NULL) ? 0 : this->orders.list->GetNumManualOrders(); }
608 * Get the next station the vehicle will stop at.
609 * @return ID of the next station the vehicle will stop at or INVALID_STATION.
611 inline StationID GetNextStoppingStation() const
613 return (this->orders.list == NULL) ? INVALID_STATION : this->orders.list->GetNextStoppingStation(this);
616 void ResetRefitCaps();
618 void RefreshNextHopsStats();
621 * Copy certain configurations and statistics of a vehicle after successful autoreplace/renew
622 * The function shall copy everything that cannot be copied by a command (like orders / group etc),
623 * and that shall not be resetted for the new vehicle.
624 * @param src The old vehicle
626 inline void CopyVehicleConfigAndStatistics(const Vehicle *src)
628 this->CopyConsistPropertiesFrom(src);
630 this->unitnumber = src->unitnumber;
632 this->current_order = src->current_order;
633 this->dest_tile = src->dest_tile;
635 this->profit_this_year = src->profit_this_year;
636 this->profit_last_year = src->profit_last_year;
640 bool HandleBreakdown();
642 bool NeedsAutorenewing(const Company *c, bool use_renew_setting = true) const;
644 bool NeedsServicing() const;
645 bool NeedsAutomaticServicing() const;
648 * Determine the location for the station where the vehicle goes to next.
649 * Things done for example are allocating slots in a road stop or exact
650 * location of the platform is determined for ships.
651 * @param station the station to make the next location of the vehicle.
652 * @return the location (tile) to aim for.
654 virtual TileIndex GetOrderStationLocation(StationID station) { return INVALID_TILE; }
657 * Find the closest depot for this vehicle and tell us the location,
658 * DestinationID and whether we should reverse.
659 * @param location where do we go to?
660 * @param destination what hangar do we go to?
661 * @param reverse should the vehicle be reversed?
662 * @return true if a depot could be found.
664 virtual bool FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse) { return false; }
666 CommandCost SendToDepot(DoCommandFlag flags, DepotCommand command);
668 void UpdateVisualEffect(bool allow_power_change = true);
669 void ShowVisualEffect() const;
671 inline uint16 GetServiceInterval() const { return this->service_interval; }
673 inline void SetServiceInterval(uint16 interval) { this->service_interval = interval; }
675 inline bool ServiceIntervalIsCustom() const { return HasBit(this->vehicle_flags, VF_SERVINT_IS_CUSTOM); }
677 inline bool ServiceIntervalIsPercent() const { return HasBit(this->vehicle_flags, VF_SERVINT_IS_PERCENT); }
679 inline void SetServiceIntervalIsCustom(bool on) { SB(this->vehicle_flags, VF_SERVINT_IS_CUSTOM, 1, on); }
681 inline void SetServiceIntervalIsPercent(bool on) { SB(this->vehicle_flags, VF_SERVINT_IS_PERCENT, 1, on); }
683 private:
685 * Advance cur_real_order_index to the next real order.
686 * cur_implicit_order_index is not touched.
688 void SkipToNextRealOrderIndex()
690 if (this->GetNumManualOrders() > 0) {
691 /* Advance to next real order */
692 do {
693 this->cur_real_order_index++;
694 if (this->cur_real_order_index >= this->GetNumOrders()) this->cur_real_order_index = 0;
695 } while (this->GetOrder(this->cur_real_order_index)->IsType(OT_IMPLICIT));
696 } else {
697 this->cur_real_order_index = 0;
701 public:
703 * Increments cur_implicit_order_index, keeps care of the wrap-around and invalidates the GUI.
704 * cur_real_order_index is incremented as well, if needed.
705 * Note: current_order is not invalidated.
707 void IncrementImplicitOrderIndex()
709 if (this->cur_implicit_order_index == this->cur_real_order_index) {
710 /* Increment real order index as well */
711 this->SkipToNextRealOrderIndex();
714 assert(this->cur_real_order_index == 0 || this->cur_real_order_index < this->GetNumOrders());
716 /* Advance to next implicit order */
717 do {
718 this->cur_implicit_order_index++;
719 if (this->cur_implicit_order_index >= this->GetNumOrders()) this->cur_implicit_order_index = 0;
720 } while (this->cur_implicit_order_index != this->cur_real_order_index && !this->GetOrder(this->cur_implicit_order_index)->IsType(OT_IMPLICIT));
722 InvalidateVehicleOrder(this, 0);
726 * Advanced cur_real_order_index to the next real order, keeps care of the wrap-around and invalidates the GUI.
727 * 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
728 * but not any implicit orders.
729 * Note: current_order is not invalidated.
731 void IncrementRealOrderIndex()
733 if (this->cur_implicit_order_index == this->cur_real_order_index) {
734 /* Increment both real and implicit order */
735 this->IncrementImplicitOrderIndex();
736 } else {
737 /* Increment real order only */
738 this->SkipToNextRealOrderIndex();
739 InvalidateVehicleOrder(this, 0);
744 * Skip implicit orders until cur_real_order_index is a non-implicit order.
746 void UpdateRealOrderIndex()
748 /* Make sure the index is valid */
749 if (this->cur_real_order_index >= this->GetNumOrders()) this->cur_real_order_index = 0;
751 if (this->GetNumManualOrders() > 0) {
752 /* Advance to next real order */
753 while (this->GetOrder(this->cur_real_order_index)->IsType(OT_IMPLICIT)) {
754 this->cur_real_order_index++;
755 if (this->cur_real_order_index >= this->GetNumOrders()) this->cur_real_order_index = 0;
757 } else {
758 this->cur_real_order_index = 0;
763 * Returns order 'index' of a vehicle or NULL when it doesn't exists
764 * @param index the order to fetch
765 * @return the found (or not) order
767 inline Order *GetOrder(int index) const
769 return (this->orders.list == NULL) ? NULL : this->orders.list->GetOrderAt(index);
773 * Returns the last order of a vehicle, or NULL if it doesn't exists
774 * @return last order of a vehicle, if available
776 inline Order *GetLastOrder() const
778 return (this->orders.list == NULL) ? NULL : this->orders.list->GetLastOrder();
781 bool IsEngineCountable() const;
782 bool HasEngineType() const;
783 bool HasDepotOrder() const;
784 void HandlePathfindingResult(bool path_found);
787 * Check if the vehicle is a front engine.
788 * @return Returns true if the vehicle is a front engine.
790 inline bool IsFrontEngine() const
792 return this->IsGroundVehicle() && HasBit(this->subtype, GVSF_FRONT);
796 * Check if the vehicle is an articulated part of an engine.
797 * @return Returns true if the vehicle is an articulated part.
799 inline bool IsArticulatedPart() const
801 return this->IsGroundVehicle() && HasBit(this->subtype, GVSF_ARTICULATED_PART);
805 * Check if an engine has an articulated part.
806 * @return True if the engine has an articulated part.
808 inline bool HasArticulatedPart() const
810 return this->Next() != NULL && this->Next()->IsArticulatedPart();
814 * Get the next part of an articulated engine.
815 * @return Next part of the articulated engine.
816 * @pre The vehicle is an articulated engine.
818 inline Vehicle *GetNextArticulatedPart() const
820 assert(this->HasArticulatedPart());
821 return this->Next();
825 * Get the first part of an articulated engine.
826 * @return First part of the engine.
828 inline Vehicle *GetFirstEnginePart()
830 Vehicle *v = this;
831 while (v->IsArticulatedPart()) v = v->Previous();
832 return v;
836 * Get the first part of an articulated engine.
837 * @return First part of the engine.
839 inline const Vehicle *GetFirstEnginePart() const
841 const Vehicle *v = this;
842 while (v->IsArticulatedPart()) v = v->Previous();
843 return v;
847 * Get the last part of an articulated engine.
848 * @return Last part of the engine.
850 inline Vehicle *GetLastEnginePart()
852 Vehicle *v = this;
853 while (v->HasArticulatedPart()) v = v->GetNextArticulatedPart();
854 return v;
858 * Get the next real (non-articulated part) vehicle in the consist.
859 * @return Next vehicle in the consist.
861 inline Vehicle *GetNextVehicle() const
863 const Vehicle *v = this;
864 while (v->HasArticulatedPart()) v = v->GetNextArticulatedPart();
866 /* v now contains the last articulated part in the engine */
867 return v->Next();
871 * Get the previous real (non-articulated part) vehicle in the consist.
872 * @return Previous vehicle in the consist.
874 inline Vehicle *GetPrevVehicle() const
876 Vehicle *v = this->Previous();
877 while (v != NULL && v->IsArticulatedPart()) v = v->Previous();
879 return v;
884 * Iterate over all vehicles from a given point.
885 * @param var The variable used to iterate over.
886 * @param start The vehicle to start the iteration at.
888 #define FOR_ALL_VEHICLES_FROM(var, start) FOR_ALL_ITEMS_FROM(Vehicle, vehicle_index, var, start)
891 * Iterate over all vehicles.
892 * @param var The variable used to iterate over.
894 #define FOR_ALL_VEHICLES(var) FOR_ALL_VEHICLES_FROM(var, 0)
897 * Class defining several overloaded accessors so we don't
898 * have to cast vehicle types that often
900 template <class T, VehicleType Type>
901 struct SpecializedVehicle : public Vehicle {
902 static const VehicleType EXPECTED_TYPE = Type; ///< Specialized type
904 typedef SpecializedVehicle<T, Type> SpecializedVehicleBase; ///< Our type
907 * Set vehicle type correctly
909 inline SpecializedVehicle<T, Type>() : Vehicle(Type) { }
912 * Get the first vehicle in the chain
913 * @return first vehicle in the chain
915 inline T *First() const { return (T *)this->Vehicle::First(); }
918 * Get the last vehicle in the chain
919 * @return last vehicle in the chain
921 inline T *Last() { return (T *)this->Vehicle::Last(); }
924 * Get the last vehicle in the chain
925 * @return last vehicle in the chain
927 inline const T *Last() const { return (const T *)this->Vehicle::Last(); }
930 * Get next vehicle in the chain
931 * @return next vehicle in the chain
933 inline T *Next() const { return (T *)this->Vehicle::Next(); }
936 * Get previous vehicle in the chain
937 * @return previous vehicle in the chain
939 inline T *Previous() const { return (T *)this->Vehicle::Previous(); }
942 * Get the next part of an articulated engine.
943 * @return Next part of the articulated engine.
944 * @pre The vehicle is an articulated engine.
946 inline T *GetNextArticulatedPart() { return (T *)this->Vehicle::GetNextArticulatedPart(); }
949 * Get the next part of an articulated engine.
950 * @return Next part of the articulated engine.
951 * @pre The vehicle is an articulated engine.
953 inline T *GetNextArticulatedPart() const { return (T *)this->Vehicle::GetNextArticulatedPart(); }
956 * Get the first part of an articulated engine.
957 * @return First part of the engine.
959 inline T *GetFirstEnginePart() { return (T *)this->Vehicle::GetFirstEnginePart(); }
962 * Get the first part of an articulated engine.
963 * @return First part of the engine.
965 inline const T *GetFirstEnginePart() const { return (const T *)this->Vehicle::GetFirstEnginePart(); }
968 * Get the last part of an articulated engine.
969 * @return Last part of the engine.
971 inline T *GetLastEnginePart() { return (T *)this->Vehicle::GetLastEnginePart(); }
974 * Get the next real (non-articulated part) vehicle in the consist.
975 * @return Next vehicle in the consist.
977 inline T *GetNextVehicle() const { return (T *)this->Vehicle::GetNextVehicle(); }
980 * Get the previous real (non-articulated part) vehicle in the consist.
981 * @return Previous vehicle in the consist.
983 inline T *GetPrevVehicle() const { return (T *)this->Vehicle::GetPrevVehicle(); }
986 * Tests whether given index is a valid index for vehicle of this type
987 * @param index tested index
988 * @return is this index valid index of T?
990 static inline bool IsValidID(size_t index)
992 return Vehicle::IsValidID(index) && Vehicle::Get(index)->type == Type;
996 * Gets vehicle with given index
997 * @return pointer to vehicle with given index casted to T *
999 static inline T *Get(size_t index)
1001 return (T *)Vehicle::Get(index);
1005 * Returns vehicle if the index is a valid index for this vehicle type
1006 * @return pointer to vehicle with given index if it's a vehicle of this type
1008 static inline T *GetIfValid(size_t index)
1010 return IsValidID(index) ? Get(index) : NULL;
1014 * Converts a Vehicle to SpecializedVehicle with type checking.
1015 * @param v Vehicle pointer
1016 * @return pointer to SpecializedVehicle
1018 static inline T *From(Vehicle *v)
1020 assert(v->type == Type);
1021 return (T *)v;
1025 * Converts a const Vehicle to const SpecializedVehicle with type checking.
1026 * @param v Vehicle pointer
1027 * @return pointer to SpecializedVehicle
1029 static inline const T *From(const Vehicle *v)
1031 assert(v->type == Type);
1032 return (const T *)v;
1036 * Update vehicle sprite- and position caches
1037 * @param force_update Force updating the vehicle on the viewport.
1038 * @param update_delta Also update the delta?
1040 inline void UpdateViewport(bool force_update, bool update_delta)
1042 extern void VehicleUpdateViewport(Vehicle *v, bool dirty);
1044 /* Explicitly choose method to call to prevent vtable dereference -
1045 * it gives ~3% runtime improvements in games with many vehicles */
1046 if (update_delta) ((T *)this)->T::UpdateDeltaXY(this->direction);
1047 SpriteID old_image = this->cur_image;
1048 this->cur_image = ((T *)this)->T::GetImage(this->direction, EIT_ON_MAP);
1049 if (force_update || this->cur_image != old_image) VehicleUpdateViewport(this, true);
1054 * Iterate over all vehicles of a particular type.
1055 * @param name The type of vehicle to iterate over.
1056 * @param var The variable used to iterate over.
1058 #define FOR_ALL_VEHICLES_OF_TYPE(name, var) FOR_ALL_ITEMS_FROM(name, vehicle_index, var, 0) if (var->type == name::EXPECTED_TYPE)
1061 * Disasters, like submarines, skyrangers and their shadows, belong to this class.
1063 struct DisasterVehicle FINAL : public SpecializedVehicle<DisasterVehicle, VEH_DISASTER> {
1064 SpriteID image_override; ///< Override for the default disaster vehicle sprite.
1065 VehicleID big_ufo_destroyer_target; ///< The big UFO that this destroyer is supposed to bomb.
1067 /** We don't want GCC to zero our struct! It already is zeroed and has an index! */
1068 DisasterVehicle() : SpecializedVehicleBase() {}
1069 /** We want to 'destruct' the right class. */
1070 virtual ~DisasterVehicle() {}
1072 void UpdateDeltaXY(Direction direction);
1073 bool Tick();
1077 * Iterate over disaster vehicles.
1078 * @param var The variable used to iterate over.
1080 #define FOR_ALL_DISASTERVEHICLES(var) FOR_ALL_VEHICLES_OF_TYPE(DisasterVehicle, var)
1082 /** Generates sequence of free UnitID numbers */
1083 struct FreeUnitIDGenerator {
1084 bool *cache; ///< array of occupied unit id numbers
1085 UnitID maxid; ///< maximum ID at the moment of constructor call
1086 UnitID curid; ///< last ID returned; 0 if none
1088 FreeUnitIDGenerator(VehicleType type, CompanyID owner);
1089 UnitID NextID();
1091 /** Releases allocated memory */
1092 ~FreeUnitIDGenerator() { free(this->cache); }
1095 /** Sentinel for an invalid coordinate. */
1096 static const int32 INVALID_COORD = 0x7fffffff;
1098 #endif /* VEHICLE_BASE_H */