Translations update
[openttd/fttd.git] / src / vehicle_base.h
blobfda02daa7db67eb894b9a912819724031bff65ce
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 (BlitArea *dpi, int x, int y, PaletteID default_pal, bool force_pal) const;
186 /* Some declarations of functions, so we can make them friendly */
187 struct SaveLoad;
188 extern const SaveLoad *GetVehicleDescription(VehicleType vt);
189 struct LoadgameState;
190 extern bool LoadOldVehicle(LoadgameState *ls, int num);
191 extern void FixOldVehicles(const SavegameTypeVersion *stv);
193 struct GRFFile;
196 * Link struct for vehicle hash chains
198 struct VehicleHashLink {
199 Vehicle *next;
200 Vehicle **pprev;
203 /** %Vehicle data structure. */
204 struct Vehicle : PooledItem <Vehicle, VehicleID, 512, 0xFF000>, BaseVehicle, BaseConsist {
205 private:
206 Vehicle *next; ///< pointer to the next vehicle in the chain
207 Vehicle *previous; ///< NOSAVE: pointer to the previous vehicle in the chain
208 Vehicle *first; ///< NOSAVE: pointer to the first vehicle in the chain
210 Vehicle *next_shared; ///< pointer to the next vehicle that shares the order
211 Vehicle *previous_shared; ///< NOSAVE: pointer to the previous vehicle in the shared order chain
213 public:
214 friend const SaveLoad *GetVehicleDescription(VehicleType vt); ///< So we can use private/protected variables in the saveload code
215 friend void FixOldVehicles(const SavegameTypeVersion *stv);
216 friend void AfterLoadVehicles(const SavegameTypeVersion *stv); ///< So we can set the #previous and #first pointers while loading
217 friend bool LoadOldVehicle(LoadgameState *ls, int num); ///< So we can set the proper next pointer while loading
219 TileIndex tile; ///< Current tile index
222 * Heading for this tile.
223 * For airports and train stations this tile does not necessarily belong to the destination station,
224 * but it can be used for heuristic purposes to estimate the distance.
226 TileIndex dest_tile;
228 Money profit_this_year; ///< Profit this year << 8, low 8 bits are fract
229 Money profit_last_year; ///< Profit last year << 8, low 8 bits are fract
230 Money value; ///< Value of the vehicle
232 CargoPayment *cargo_payment; ///< The cargo payment we're currently in
234 Rect coord; ///< NOSAVE: Graphical bounding box of the vehicle, i.e. what to redraw on moves.
236 VehicleHashLink hash_viewport_link; ///< NOSAVE: Visual location hash link.
238 VehicleHashLink hash_tile_link; ///< NOSAVE: Tile location hash link.
239 Vehicle **hash_tile_current; ///< NOSAVE: Cache of the current hash chain.
241 SpriteID colourmap; ///< NOSAVE: cached colour mapping
243 /* Related to age and service time */
244 Year build_year; ///< Year the vehicle has been built.
245 Date age; ///< Age in days
246 Date max_age; ///< Maximum age
247 Date date_of_last_service; ///< Last date the vehicle had a service at a depot.
248 uint16 reliability; ///< Reliability.
249 uint16 reliability_spd_dec; ///< Reliability decrease speed.
250 byte breakdown_ctr; ///< Counter for managing breakdown events. @see Vehicle::HandleBreakdown
251 byte breakdown_delay; ///< Counter for managing breakdown length.
252 byte breakdowns_since_last_service; ///< Counter for the amount of breakdowns.
253 byte breakdown_chance; ///< Current chance of breakdowns.
255 int32 x_pos; ///< x coordinate.
256 int32 y_pos; ///< y coordinate.
257 int32 z_pos; ///< z coordinate.
258 DirectionByte direction; ///< facing
260 OwnerByte owner; ///< Which company owns the vehicle?
262 * currently displayed sprite index
263 * 0xfd == custom sprite, 0xfe == custom second head sprite
264 * 0xff == reserved for another custom sprite
266 byte spritenum;
267 VehicleSpriteSeq sprite_seq; ///< Vehicle appearance.
268 byte x_extent; ///< x-extent of vehicle bounding box
269 byte y_extent; ///< y-extent of vehicle bounding box
270 byte z_extent; ///< z-extent of vehicle bounding box
271 int8 x_bb_offs; ///< x offset of vehicle bounding box
272 int8 y_bb_offs; ///< y offset of vehicle bounding box
273 int8 x_offs; ///< x offset for vehicle sprite
274 int8 y_offs; ///< y offset for vehicle sprite
275 EngineID engine_type; ///< The type of engine used for this vehicle.
277 TextEffectID fill_percent_te_id; ///< a text-effect id to a loading indicator object
278 UnitID unitnumber; ///< unit number, for display purposes only
280 uint16 cur_speed; ///< current speed
281 byte subspeed; ///< fractional speed
282 byte acceleration; ///< used by train & aircraft
283 uint32 motion_counter; ///< counter to occasionally play a vehicle sound.
284 byte progress; ///< The percentage (if divided by 256) this vehicle already crossed the tile unit.
286 byte random_bits; ///< Bits used for determining which randomized variational spritegroups to use when drawing.
287 byte waiting_triggers; ///< Triggers to be yet matched before rerandomizing the random bits.
289 StationID last_station_visited; ///< The last station we stopped at.
290 StationID last_loading_station; ///< Last station the vehicle has stopped at and could possibly leave from with any cargo loaded.
292 CargoID cargo_type; ///< type of cargo this vehicle is carrying
293 byte cargo_subtype; ///< Used for livery refits (NewGRF variations)
294 uint16 cargo_cap; ///< total capacity
295 uint16 refit_cap; ///< Capacity left over from before last refit.
296 VehicleCargoList cargo; ///< The cargo this vehicle is carrying
297 uint16 cargo_age_counter; ///< Ticks till cargo is aged next.
298 int8 trip_occupancy; ///< NOSAVE: Occupancy of vehicle of the current trip (updated after leaving a station).
300 byte day_counter; ///< Increased by one for each day
301 byte tick_counter; ///< Increased by one for each tick
302 byte running_ticks; ///< Number of ticks this vehicle was not stopped this day
304 byte vehstatus; ///< Status
305 BaseOrder current_order; ///< The current order (+ status, like: loading)
307 union {
308 OrderList *list; ///< Pointer to the order list for this vehicle
309 Order *old; ///< Only used during conversion of old save games
310 } orders; ///< The orders currently assigned to the vehicle.
312 uint16 load_unload_ticks; ///< Ticks to wait before starting next cycle.
313 GroupID group_id; ///< Index of group Pool array
314 byte subtype; ///< subtype (Filled with values from #EffectVehicles/#TrainSubTypes/#AircraftSubTypes)
316 NewGRFCache grf_cache; ///< Cache of often used calculated NewGRF values
317 VehicleCache vcache; ///< Cache of often used vehicle values.
319 Vehicle(VehicleType type = VEH_INVALID);
321 void PreDestructor();
322 /** We want to 'destruct' the right class. */
323 virtual ~Vehicle();
325 void BeginLoading();
326 void CancelReservation (Station *st);
327 void LeaveStation();
329 void DeleteUnreachedImplicitOrders();
331 void HandleLoading(bool mode = false);
334 * Marks the vehicles to be redrawn and updates cached variables
336 * This method marks the area of the vehicle on the screen as dirty.
337 * It can be use to repaint the vehicle.
339 * @ingroup dirty
341 virtual void MarkDirty() {}
344 * Updates the x and y offsets and the size of the sprite used
345 * for this vehicle.
346 * @param direction the direction the vehicle is facing
348 virtual void UpdateDeltaXY(Direction direction) {}
351 * Determines the effective direction-specific vehicle movement speed.
353 * This method belongs to the old vehicle movement method:
354 * A vehicle moves a step every 256 progress units.
355 * The vehicle speed is scaled by 3/4 when moving in X or Y direction due to the longer distance.
357 * However, this method is slightly wrong in corners, as the leftover progress is not scaled correctly
358 * when changing movement direction. #GetAdvanceSpeed() and #GetAdvanceDistance() are better wrt. this.
360 * @param speed Direction-independent unscaled speed.
361 * @return speed scaled by movement direction. 256 units are required for each movement step.
363 inline uint GetOldAdvanceSpeed(uint speed) const
365 return (this->direction & 1) ? speed : speed * 3 / 4;
369 * Determines the effective vehicle movement speed.
371 * Together with #GetAdvanceDistance() this function is a replacement for #GetOldAdvanceSpeed().
373 * A vehicle progresses independent of it's movement direction.
374 * However different amounts of "progress" are needed for moving a step in a specific direction.
375 * That way the leftover progress does not need any adaption when changing movement direction.
377 * @param speed Direction-independent unscaled speed.
378 * @return speed, scaled to match #GetAdvanceDistance().
380 static inline uint GetAdvanceSpeed(uint speed)
382 return speed * 3 / 4;
386 * Determines the vehicle "progress" needed for moving a step.
388 * Together with #GetAdvanceSpeed() this function is a replacement for #GetOldAdvanceSpeed().
390 * @return distance to drive for a movement step on the map.
392 inline uint GetAdvanceDistance() const
394 return (this->direction & 1) ? 192 : 256;
398 * Sets the expense type associated to this vehicle type
399 * @param income whether this is income or (running) expenses of the vehicle
401 virtual ExpensesType GetExpenseType(bool income) const { return EXPENSES_OTHER; }
404 * Play the sound associated with leaving the station
406 virtual void PlayLeaveStationSound() const {}
409 * Whether this is the primary vehicle in the chain.
411 virtual bool IsPrimaryVehicle() const { return false; }
413 const Engine *GetEngine() const;
416 * Gets the sprite to show for the given direction
417 * @param direction the direction the vehicle is facing
418 * @param [out] result Vehicle sprite sequence.
420 virtual void GetImage(Direction direction, EngineImageType image_type, VehicleSpriteSeq *result) const { result->Clear(); }
422 const GRFFile *GetGRF() const;
423 uint32 GetGRFID() const;
426 * Invalidates cached NewGRF variables
427 * @see InvalidateNewGRFCacheOfChain
429 inline void InvalidateNewGRFCache()
431 this->grf_cache.cache_valid = 0;
435 * Invalidates cached NewGRF variables of all vehicles in the chain (after the current vehicle)
436 * @see InvalidateNewGRFCache
438 inline void InvalidateNewGRFCacheOfChain()
440 for (Vehicle *u = this; u != NULL; u = u->Next()) {
441 u->InvalidateNewGRFCache();
446 * Check if the vehicle is a ground vehicle.
447 * @return True iff the vehicle is a train or a road vehicle.
449 inline bool IsGroundVehicle() const
451 return this->type == VEH_TRAIN || this->type == VEH_ROAD;
455 * Gets the speed in km-ish/h that can be sent into SetDParam for string processing.
456 * @return the vehicle's speed
458 virtual int GetDisplaySpeed() const { return 0; }
461 * Gets the maximum speed in km-ish/h that can be sent into SetDParam for string processing.
462 * @return the vehicle's maximum speed
464 virtual int GetDisplayMaxSpeed() const { return 0; }
467 * Calculates the maximum speed of the vehicle under its current conditions.
468 * @return Current maximum speed in native units.
470 virtual int GetCurrentMaxSpeed() const { return 0; }
473 * Gets the running cost of a vehicle
474 * @return the vehicle's running cost
476 virtual Money GetRunningCost() const { return 0; }
479 * Check whether the vehicle is in the depot.
480 * @return true if and only if the vehicle is in the depot.
482 virtual bool IsInDepot() const { return false; }
485 * Check whether the whole vehicle chain is in the depot.
486 * @return true if and only if the whole chain is in the depot.
488 virtual bool IsChainInDepot() const { return this->IsInDepot(); }
491 * Check whether the vehicle is in the depot *and* stopped.
492 * @return true if and only if the vehicle is in the depot and stopped.
494 bool IsStoppedInDepot() const
496 assert(this == this->First());
497 /* Free wagons have no VS_STOPPED state */
498 if (this->IsPrimaryVehicle() && !(this->vehstatus & VS_STOPPED)) return false;
499 return this->IsChainInDepot();
503 * Calls the tick handler of the vehicle
504 * @return is this vehicle still valid?
506 virtual bool Tick() { return true; };
509 * Calls the new day handler of the vehicle
511 virtual void OnNewDay() {};
514 * Crash the (whole) vehicle chain.
515 * @param flooded whether the cause of the crash is flooding or not.
516 * @return the number of lost souls.
518 virtual uint Crash(bool flooded = false);
521 * Gets the running cost of a vehicle that can be sent into SetDParam for string processing.
522 * @return the vehicle's running cost
524 Money GetDisplayRunningCost() const { return (this->GetRunningCost() >> 8); }
527 * Gets the profit vehicle had this year. It can be sent into SetDParam for string processing.
528 * @return the vehicle's profit this year
530 Money GetDisplayProfitThisYear() const { return (this->profit_this_year >> 8); }
533 * Gets the profit vehicle had last year. It can be sent into SetDParam for string processing.
534 * @return the vehicle's profit last year
536 Money GetDisplayProfitLastYear() const { return (this->profit_last_year >> 8); }
538 void SetNext(Vehicle *next);
541 * Get the next vehicle of this vehicle.
542 * @note articulated parts are also counted as vehicles.
543 * @return the next vehicle or NULL when there isn't a next vehicle.
545 inline Vehicle *Next() const { return this->next; }
548 * Get the previous vehicle of this vehicle.
549 * @note articulated parts are also counted as vehicles.
550 * @return the previous vehicle or NULL when there isn't a previous vehicle.
552 inline Vehicle *Previous() const { return this->previous; }
555 * Get the first vehicle of this vehicle chain.
556 * @return the first vehicle of the chain.
558 inline Vehicle *First() const { return this->first; }
561 * Get the last vehicle of this vehicle chain.
562 * @return the last vehicle of the chain.
564 inline Vehicle *Last()
566 Vehicle *v = this;
567 while (v->Next() != NULL) v = v->Next();
568 return v;
572 * Get the last vehicle of this vehicle chain.
573 * @return the last vehicle of the chain.
575 inline const Vehicle *Last() const
577 const Vehicle *v = this;
578 while (v->Next() != NULL) v = v->Next();
579 return v;
583 * Get the vehicle at offset \a n of this vehicle chain.
584 * @param n Offset from the current vehicle.
585 * @return The new vehicle or NULL if the offset is out-of-bounds.
587 inline Vehicle *Move(int n)
589 Vehicle *v = this;
590 if (n < 0) {
591 for (int i = 0; i != n && v != NULL; i--) v = v->Previous();
592 } else {
593 for (int i = 0; i != n && v != NULL; i++) v = v->Next();
595 return v;
599 * Get the vehicle at offset \a n of this vehicle chain.
600 * @param n Offset from the current vehicle.
601 * @return The new vehicle or NULL if the offset is out-of-bounds.
603 inline const Vehicle *Move(int n) const
605 const Vehicle *v = this;
606 if (n < 0) {
607 for (int i = 0; i != n && v != NULL; i--) v = v->Previous();
608 } else {
609 for (int i = 0; i != n && v != NULL; i++) v = v->Next();
611 return v;
615 * Get the first order of the vehicles order list.
616 * @return first order of order list.
618 inline Order *GetFirstOrder() const { return (this->orders.list == NULL) ? NULL : this->orders.list->GetFirstOrder(); }
620 void AddToShared(Vehicle *shared_chain);
621 void RemoveFromShared();
624 * Get the next vehicle of the shared vehicle chain.
625 * @return the next shared vehicle or NULL when there isn't a next vehicle.
627 inline Vehicle *NextShared() const { return this->next_shared; }
630 * Get the previous vehicle of the shared vehicle chain
631 * @return the previous shared vehicle or NULL when there isn't a previous vehicle.
633 inline Vehicle *PreviousShared() const { return this->previous_shared; }
636 * Get the first vehicle of this vehicle chain.
637 * @return the first vehicle of the chain.
639 inline Vehicle *FirstShared() const { return (this->orders.list == NULL) ? this->First() : this->orders.list->GetFirstSharedVehicle(); }
642 * Check if we share our orders with another vehicle.
643 * @return true if there are other vehicles sharing the same order
645 inline bool IsOrderListShared() const { return this->orders.list != NULL && this->orders.list->IsShared(); }
648 * Get the number of orders this vehicle has.
649 * @return the number of orders this vehicle has.
651 inline VehicleOrderID GetNumOrders() const { return (this->orders.list == NULL) ? 0 : this->orders.list->GetNumOrders(); }
654 * Get the number of manually added orders this vehicle has.
655 * @return the number of manually added orders this vehicle has.
657 inline VehicleOrderID GetNumManualOrders() const { return (this->orders.list == NULL) ? 0 : this->orders.list->GetNumManualOrders(); }
660 * Get the next station the vehicle will stop at.
661 * @param result Station id stack to append the next stations to.
663 inline void AppendNextStoppingStations (StationIDStack *result) const
665 if (this->orders.list == NULL) {
666 result->push_back (INVALID_STATION);
667 } else {
668 this->orders.list->AppendNextStoppingStations (result, this);
672 void ResetRefitCaps();
675 * Copy certain configurations and statistics of a vehicle after successful autoreplace/renew
676 * The function shall copy everything that cannot be copied by a command (like orders / group etc),
677 * and that shall not be resetted for the new vehicle.
678 * @param src The old vehicle
680 inline void CopyVehicleConfigAndStatistics(const Vehicle *src)
682 this->CopyConsistPropertiesFrom(src);
684 this->unitnumber = src->unitnumber;
686 this->current_order = src->current_order;
687 this->dest_tile = src->dest_tile;
689 this->profit_this_year = src->profit_this_year;
690 this->profit_last_year = src->profit_last_year;
694 bool HandleBreakdown();
696 bool NeedsAutorenewing (const Company *c) const;
698 bool NeedsServicing (bool scheduled = true) const;
699 bool NeedsAutomaticServicing() const;
702 * Determine the location for the station where the vehicle goes to next.
703 * Things done for example are allocating slots in a road stop or exact
704 * location of the platform is determined for ships.
705 * @param station the station to make the next location of the vehicle.
706 * @return the location (tile) to aim for.
708 virtual TileIndex GetOrderStationLocation(StationID station) { return INVALID_TILE; }
711 * Find the closest depot for this vehicle and tell us the location,
712 * DestinationID and whether we should reverse.
713 * @param location where do we go to?
714 * @param destination what hangar do we go to?
715 * @param reverse should the vehicle be reversed?
716 * @return true if a depot could be found.
718 virtual bool FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse) { return false; }
720 CommandCost SendToDepot(DoCommandFlag flags, DepotCommand command);
722 void UpdateVisualEffect(bool allow_power_change = true);
723 void ShowVisualEffect() const;
725 void UpdatePosition();
726 void UpdateViewport(bool dirty);
727 void UpdatePositionAndViewport();
728 void MarkAllViewportsDirty() const;
730 inline uint16 GetServiceInterval() const { return this->service_interval; }
732 inline void SetServiceInterval(uint16 interval) { this->service_interval = interval; }
734 inline bool ServiceIntervalIsCustom() const { return HasBit(this->vehicle_flags, VF_SERVINT_IS_CUSTOM); }
736 inline bool ServiceIntervalIsPercent() const { return HasBit(this->vehicle_flags, VF_SERVINT_IS_PERCENT); }
738 inline void SetServiceIntervalIsCustom(bool on) { SB(this->vehicle_flags, VF_SERVINT_IS_CUSTOM, 1, on); }
740 inline void SetServiceIntervalIsPercent(bool on) { SB(this->vehicle_flags, VF_SERVINT_IS_PERCENT, 1, on); }
742 private:
744 * Advance cur_real_order_index to the next real order.
745 * cur_implicit_order_index is not touched.
747 void SkipToNextRealOrderIndex()
749 if (this->GetNumManualOrders() > 0) {
750 /* Advance to next real order */
751 do {
752 this->cur_real_order_index++;
753 if (this->cur_real_order_index >= this->GetNumOrders()) this->cur_real_order_index = 0;
754 } while (this->GetOrder(this->cur_real_order_index)->IsType(OT_IMPLICIT));
755 } else {
756 this->cur_real_order_index = 0;
760 public:
762 * Increments cur_implicit_order_index, keeps care of the wrap-around and invalidates the GUI.
763 * cur_real_order_index is incremented as well, if needed.
764 * Note: current_order is not invalidated.
766 void IncrementImplicitOrderIndex()
768 if (this->cur_implicit_order_index == this->cur_real_order_index) {
769 /* Increment real order index as well */
770 this->SkipToNextRealOrderIndex();
773 assert(this->cur_real_order_index == 0 || this->cur_real_order_index < this->GetNumOrders());
775 /* Advance to next implicit order */
776 do {
777 this->cur_implicit_order_index++;
778 if (this->cur_implicit_order_index >= this->GetNumOrders()) this->cur_implicit_order_index = 0;
779 } while (this->cur_implicit_order_index != this->cur_real_order_index && !this->GetOrder(this->cur_implicit_order_index)->IsType(OT_IMPLICIT));
781 InvalidateVehicleOrder(this, 0);
785 * Advanced cur_real_order_index to the next real order, keeps care of the wrap-around and invalidates the GUI.
786 * 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
787 * but not any implicit orders.
788 * Note: current_order is not invalidated.
790 void IncrementRealOrderIndex()
792 if (this->cur_implicit_order_index == this->cur_real_order_index) {
793 /* Increment both real and implicit order */
794 this->IncrementImplicitOrderIndex();
795 } else {
796 /* Increment real order only */
797 this->SkipToNextRealOrderIndex();
798 InvalidateVehicleOrder(this, 0);
803 * Skip implicit orders until cur_real_order_index is a non-implicit order.
805 void UpdateRealOrderIndex()
807 /* Make sure the index is valid */
808 if (this->cur_real_order_index >= this->GetNumOrders()) this->cur_real_order_index = 0;
810 if (this->GetNumManualOrders() > 0) {
811 /* Advance to next real order */
812 while (this->GetOrder(this->cur_real_order_index)->IsType(OT_IMPLICIT)) {
813 this->cur_real_order_index++;
814 if (this->cur_real_order_index >= this->GetNumOrders()) this->cur_real_order_index = 0;
816 } else {
817 this->cur_real_order_index = 0;
822 * Returns order 'index' of a vehicle or NULL when it doesn't exists
823 * @param index the order to fetch
824 * @return the found (or not) order
826 inline Order *GetOrder(int index) const
828 return (this->orders.list == NULL) ? NULL : this->orders.list->GetOrderAt(index);
832 * Returns the last order of a vehicle, or NULL if it doesn't exists
833 * @return last order of a vehicle, if available
835 inline Order *GetLastOrder() const
837 return (this->orders.list == NULL) ? NULL : this->orders.list->GetLastOrder();
840 bool IsEngineCountable() const;
841 bool HasEngineType() const;
842 bool HasDepotOrder() const;
843 void HandlePathfindingResult(bool path_found);
846 * Check if the vehicle is a front engine.
847 * @return Returns true if the vehicle is a front engine.
849 inline bool IsFrontEngine() const
851 return this->IsGroundVehicle() && HasBit(this->subtype, GVSF_FRONT);
855 * Check if the vehicle is an articulated part of an engine.
856 * @return Returns true if the vehicle is an articulated part.
858 inline bool IsArticulatedPart() const
860 return this->IsGroundVehicle() && HasBit(this->subtype, GVSF_ARTICULATED_PART);
864 * Check if an engine has an articulated part.
865 * @return True if the engine has an articulated part.
867 inline bool HasArticulatedPart() const
869 return this->Next() != NULL && this->Next()->IsArticulatedPart();
873 * Get the next part of an articulated engine.
874 * @return Next part of the articulated engine.
875 * @pre The vehicle is an articulated engine.
877 inline Vehicle *GetNextArticulatedPart() const
879 assert(this->HasArticulatedPart());
880 return this->Next();
884 * Get the first part of an articulated engine.
885 * @return First part of the engine.
887 inline Vehicle *GetFirstEnginePart()
889 Vehicle *v = this;
890 while (v->IsArticulatedPart()) v = v->Previous();
891 return v;
895 * Get the first part of an articulated engine.
896 * @return First part of the engine.
898 inline const Vehicle *GetFirstEnginePart() const
900 const Vehicle *v = this;
901 while (v->IsArticulatedPart()) v = v->Previous();
902 return v;
906 * Get the last part of an articulated engine.
907 * @return Last part of the engine.
909 inline Vehicle *GetLastEnginePart()
911 Vehicle *v = this;
912 while (v->HasArticulatedPart()) v = v->GetNextArticulatedPart();
913 return v;
917 * Get the next real (non-articulated part) vehicle in the consist.
918 * @return Next vehicle in the consist.
920 inline Vehicle *GetNextVehicle() const
922 const Vehicle *v = this;
923 while (v->HasArticulatedPart()) v = v->GetNextArticulatedPart();
925 /* v now contains the last articulated part in the engine */
926 return v->Next();
930 * Get the previous real (non-articulated part) vehicle in the consist.
931 * @return Previous vehicle in the consist.
933 inline Vehicle *GetPrevVehicle() const
935 Vehicle *v = this->Previous();
936 while (v != NULL && v->IsArticulatedPart()) v = v->Previous();
938 return v;
943 * Iterate over all vehicles from a given point.
944 * @param var The variable used to iterate over.
945 * @param start The vehicle to start the iteration at.
947 #define FOR_ALL_VEHICLES_FROM(var, start) FOR_ALL_ITEMS_FROM(Vehicle, vehicle_index, var, start)
950 * Iterate over all vehicles.
951 * @param var The variable used to iterate over.
953 #define FOR_ALL_VEHICLES(var) FOR_ALL_VEHICLES_FROM(var, 0)
956 * Iterator for vehicles at a tile. This uses the tile hash VehicleTileHash
957 * defined in vehicle.cpp to run through all vehicles at a given tile.
959 * NOTE! The order in which vehicles are iterated over is unspecified, and
960 * can be different between machines. As such, and to prevent a simulation
961 * mismatch in multiplayer, you must ensure that whatever you are doing
962 * with the vehicles does not depend on their ordering. To help enforce
963 * this, the iterator will assert if you break the iteration before
964 * reaching the end.
966 struct VehicleTileIterator {
967 protected:
968 const TileIndex tile;
969 Vehicle *v;
971 static Vehicle *first (TileIndex tile);
973 public:
974 VehicleTileIterator (TileIndex tile) : tile(tile), v(first(tile))
976 if (v != NULL && v->tile != tile) next();
979 ~VehicleTileIterator()
981 assert(finished());
984 bool finished() const
986 return v == NULL;
989 Vehicle *next()
991 Vehicle *r = v;
993 do {
994 v = v->hash_tile_link.next;
995 } while (v != NULL && v->tile != tile);
997 return r;
1002 * Iterator for vehicles at a tile, to check if a vehicle matching given
1003 * conditions exists on a tile.
1005 * This iterator is designed to check if a vehicle that matches a given
1006 * set of conditions exists on a tile. Since we are only interested in
1007 * whether such a vehicle exists or not, it can break as soon as one is
1008 * found, because ordering does not matter in that case.
1010 struct VehicleTileFinder : VehicleTileIterator {
1011 protected:
1012 bool found;
1014 public:
1015 VehicleTileFinder (TileIndex tile) : VehicleTileIterator(tile), found(false)
1019 void set_found()
1021 v = NULL; // stop iterating
1022 found = true;
1025 bool was_found () const
1027 /* do not call this until finished */
1028 assert(finished());
1030 return found;
1034 /** Helper class to define several cast methods. */
1035 template <class T, class B>
1036 struct VehicleAdapter : public B {
1037 private:
1038 /** Cast to the right class (non-const version). */
1039 static T *cast (B *p)
1041 return static_cast <T *> (p);
1044 /** Cast to the right class (const version). */
1045 static const T *cast (const B *p)
1047 return static_cast <const T *> (p);
1050 public:
1051 /** Constructor. */
1052 VehicleAdapter (VehicleType type) : B (type)
1056 /** Get the first vehicle in the chain. */
1057 T *First (void) const
1059 return this->cast (this->B::First());
1062 /** Get the last vehicle in the chain. */
1063 T *Last (void)
1065 return this->cast (this->B::Last());
1068 /** Get the last vehicle in the chain. */
1069 const T *Last (void) const
1071 return this->cast (this->B::Last());
1074 /** Get next vehicle in the chain. */
1075 T *Next (void) const
1077 return this->cast (this->B::Next());
1080 /** Get previous vehicle in the chain. */
1081 T *Previous (void) const
1083 return this->cast (this->B::Previous());
1086 /** Get the next part of an articulated engine. */
1087 T *GetNextArticulatedPart (void)
1089 return this->cast (this->B::GetNextArticulatedPart());
1092 /** Get the next part of an articulated engine. */
1093 T *GetNextArticulatedPart (void) const
1095 return this->cast (this->B::GetNextArticulatedPart());
1098 /** Get the first part of an articulated engine. */
1099 T *GetFirstEnginePart (void)
1101 return this->cast (this->B::GetFirstEnginePart());
1104 /** Get the first part of an articulated engine. */
1105 const T *GetFirstEnginePart (void) const
1107 return this->cast (this->B::GetFirstEnginePart());
1110 /** Get the last part of an articulated engine. */
1111 T *GetLastEnginePart (void)
1113 return this->cast (this->B::GetLastEnginePart());
1116 /** Get the next real (non-articulated part) vehicle in the consist. */
1117 T *GetNextVehicle (void) const
1119 return this->cast (this->B::GetNextVehicle());
1122 /** Get the previous real (non-articulated part) vehicle in the consist. */
1123 T *GetPrevVehicle (void) const
1125 return this->cast (this->B::GetPrevVehicle());
1130 * Class defining several overloaded accessors so we don't
1131 * have to cast vehicle types that often
1133 template <class T, VehicleType Type, class B = Vehicle>
1134 struct SpecializedVehicle : public VehicleAdapter <T, B> {
1135 static const VehicleType EXPECTED_TYPE = Type; ///< Specialized type
1137 typedef SpecializedVehicle <T, Type, B> SpecializedVehicleBase; ///< Our type
1140 * Set vehicle type correctly
1142 SpecializedVehicle <T, Type, B> () : VehicleAdapter <T, B> (Type)
1144 this->sprite_seq.count = 1;
1148 * Tests whether given index is a valid index for vehicle of this type
1149 * @param index tested index
1150 * @return is this index valid index of T?
1152 static inline bool IsValidID(size_t index)
1154 return Vehicle::IsValidID(index) && Vehicle::Get(index)->type == Type;
1158 * Gets vehicle with given index
1159 * @return pointer to vehicle with given index casted to T *
1161 static inline T *Get(size_t index)
1163 return (T *)Vehicle::Get(index);
1167 * Returns vehicle if the index is a valid index for this vehicle type
1168 * @return pointer to vehicle with given index if it's a vehicle of this type
1170 static inline T *GetIfValid(size_t index)
1172 return IsValidID(index) ? Get(index) : NULL;
1176 * Converts a Vehicle to SpecializedVehicle with type checking.
1177 * @param v Vehicle pointer
1178 * @return pointer to SpecializedVehicle
1180 static inline T *From(Vehicle *v)
1182 assert(v->type == Type);
1183 return (T *)v;
1187 * Converts a const Vehicle to const SpecializedVehicle with type checking.
1188 * @param v Vehicle pointer
1189 * @return pointer to SpecializedVehicle
1191 static inline const T *From(const Vehicle *v)
1193 assert(v->type == Type);
1194 return (const T *)v;
1198 * Update vehicle sprite- and position caches
1199 * @param force_update Force updating the vehicle on the viewport.
1200 * @param update_delta Also update the delta?
1202 inline void UpdateViewport(bool force_update, bool update_delta)
1204 /* Skip updating sprites on dedicated servers without screen */
1205 if (_network_dedicated) return;
1207 /* Explicitly choose method to call to prevent vtable dereference -
1208 * it gives ~3% runtime improvements in games with many vehicles */
1209 if (update_delta) ((T *)this)->T::UpdateDeltaXY(this->direction);
1210 VehicleSpriteSeq seq;
1211 ((T *)this)->T::GetImage(this->direction, EIT_ON_MAP, &seq);
1212 if (force_update || this->sprite_seq != seq) {
1213 this->sprite_seq = seq;
1214 this->Vehicle::UpdateViewport(true);
1220 * Iterate over all vehicles of a particular type.
1221 * @param name The type of vehicle to iterate over.
1222 * @param var The variable used to iterate over.
1224 #define FOR_ALL_VEHICLES_OF_TYPE(name, var) FOR_ALL_ITEMS_FROM(name, vehicle_index, var, 0) if (var->type == name::EXPECTED_TYPE)
1226 /** Generates sequence of free UnitID numbers */
1227 struct FreeUnitIDGenerator {
1228 bool *cache; ///< array of occupied unit id numbers
1229 UnitID maxid; ///< maximum ID at the moment of constructor call
1230 UnitID curid; ///< last ID returned; 0 if none
1232 FreeUnitIDGenerator(VehicleType type, CompanyID owner);
1233 UnitID NextID();
1235 /** Releases allocated memory */
1236 ~FreeUnitIDGenerator() { free(this->cache); }
1239 /** Sentinel for an invalid coordinate. */
1240 static const int32 INVALID_COORD = 0x7fffffff;
1242 #endif /* VEHICLE_BASE_H */