Update: Translations from eints
[openttd-github.git] / src / vehicle_base.h
blob8243fdbd5970c080a54cb72a4e6c3a4960a1a2b8
1 /*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6 */
8 /** @file vehicle_base.h Base class for all vehicles. */
10 #ifndef VEHICLE_BASE_H
11 #define VEHICLE_BASE_H
13 #include "track_type.h"
14 #include "command_type.h"
15 #include "order_base.h"
16 #include "cargopacket.h"
17 #include "texteff.hpp"
18 #include "engine_type.h"
19 #include "order_func.h"
20 #include "transport_type.h"
21 #include "group_type.h"
22 #include "base_consist.h"
23 #include "network/network.h"
24 #include "saveload/saveload.h"
25 #include "timer/timer_game_calendar.h"
26 #include "core/mem_func.hpp"
28 const uint TILE_AXIAL_DISTANCE = 192; // Logical length of the tile in any DiagDirection used in vehicle movement.
29 const uint TILE_CORNER_DISTANCE = 128; // Logical length of the tile corner crossing in any non-diagonal direction used in vehicle movement.
31 /** Vehicle status bits in #Vehicle::vehstatus. */
32 enum VehStatus {
33 VS_HIDDEN = 0x01, ///< Vehicle is not visible.
34 VS_STOPPED = 0x02, ///< Vehicle is stopped by the player.
35 VS_UNCLICKABLE = 0x04, ///< Vehicle is not clickable by the user (shadow vehicles).
36 VS_DEFPAL = 0x08, ///< Use default vehicle palette. @see DoDrawVehicle
37 VS_TRAIN_SLOWING = 0x10, ///< Train is slowing down.
38 VS_SHADOW = 0x20, ///< Vehicle is a shadow vehicle.
39 VS_AIRCRAFT_BROKEN = 0x40, ///< Aircraft is broken down.
40 VS_CRASHED = 0x80, ///< Vehicle is crashed.
43 /** Bit numbers in #Vehicle::vehicle_flags. */
44 enum VehicleFlags {
45 VF_LOADING_FINISHED, ///< Vehicle has finished loading.
46 VF_CARGO_UNLOADING, ///< Vehicle is unloading cargo.
47 VF_BUILT_AS_PROTOTYPE, ///< Vehicle is a prototype (accepted as exclusive preview).
48 VF_TIMETABLE_STARTED, ///< Whether the vehicle has started running on the timetable yet.
49 VF_AUTOFILL_TIMETABLE, ///< Whether the vehicle should fill in the timetable automatically.
50 VF_AUTOFILL_PRES_WAIT_TIME, ///< Whether non-destructive auto-fill should preserve waiting times
51 VF_STOP_LOADING, ///< Don't load anymore during the next load cycle.
52 VF_PATHFINDER_LOST, ///< Vehicle's pathfinder is lost.
53 VF_SERVINT_IS_CUSTOM, ///< Service interval is custom.
54 VF_SERVINT_IS_PERCENT, ///< Service interval is percent.
57 /** Bit numbers used to indicate which of the #NewGRFCache values are valid. */
58 enum NewGRFCacheValidValues {
59 NCVV_POSITION_CONSIST_LENGTH = 0, ///< This bit will be set if the NewGRF var 40 currently stored is valid.
60 NCVV_POSITION_SAME_ID_LENGTH = 1, ///< This bit will be set if the NewGRF var 41 currently stored is valid.
61 NCVV_CONSIST_CARGO_INFORMATION = 2, ///< This bit will be set if the NewGRF var 42 currently stored is valid.
62 NCVV_COMPANY_INFORMATION = 3, ///< This bit will be set if the NewGRF var 43 currently stored is valid.
63 NCVV_POSITION_IN_VEHICLE = 4, ///< This bit will be set if the NewGRF var 4D currently stored is valid.
64 NCVV_END, ///< End of the bits.
67 /** Cached often queried (NewGRF) values */
68 struct NewGRFCache {
69 /* Values calculated when they are requested for the first time after invalidating the NewGRF cache. */
70 uint32_t position_consist_length; ///< Cache for NewGRF var 40.
71 uint32_t position_same_id_length; ///< Cache for NewGRF var 41.
72 uint32_t consist_cargo_information; ///< Cache for NewGRF var 42. (Note: The cargotype is untranslated in the cache because the accessing GRF is yet unknown.)
73 uint32_t company_information; ///< Cache for NewGRF var 43.
74 uint32_t position_in_vehicle; ///< Cache for NewGRF var 4D.
75 uint8_t cache_valid; ///< Bitset that indicates which cache values are valid.
77 auto operator<=>(const NewGRFCache &) const = default;
80 /** Meaning of the various bits of the visual effect. */
81 enum VisualEffect {
82 VE_OFFSET_START = 0, ///< First bit that contains the offset (0 = front, 8 = centre, 15 = rear)
83 VE_OFFSET_COUNT = 4, ///< Number of bits used for the offset
84 VE_OFFSET_CENTRE = 8, ///< Value of offset corresponding to a position above the centre of the vehicle
86 VE_TYPE_START = 4, ///< First bit used for the type of effect
87 VE_TYPE_COUNT = 2, ///< Number of bits used for the effect type
88 VE_TYPE_DEFAULT = 0, ///< Use default from engine class
89 VE_TYPE_STEAM = 1, ///< Steam plumes
90 VE_TYPE_DIESEL = 2, ///< Diesel fumes
91 VE_TYPE_ELECTRIC = 3, ///< Electric sparks
93 VE_DISABLE_EFFECT = 6, ///< Flag to disable visual effect
94 VE_ADVANCED_EFFECT = VE_DISABLE_EFFECT, ///< Flag for advanced effects
95 VE_DISABLE_WAGON_POWER = 7, ///< Flag to disable wagon power
97 VE_DEFAULT = 0xFF, ///< Default value to indicate that visual effect should be based on engine class
100 /** Models for spawning visual effects. */
101 enum VisualEffectSpawnModel {
102 VESM_NONE = 0, ///< No visual effect
103 VESM_STEAM, ///< Steam model
104 VESM_DIESEL, ///< Diesel model
105 VESM_ELECTRIC, ///< Electric model
107 VESM_END
111 * Enum to handle ground vehicle subtypes.
112 * This is defined here instead of at #GroundVehicle because some common function require access to these flags.
113 * Do not access it directly unless you have to. Use the subtype access functions.
115 enum GroundVehicleSubtypeFlags {
116 GVSF_FRONT = 0, ///< Leading engine of a consist.
117 GVSF_ARTICULATED_PART = 1, ///< Articulated part of an engine.
118 GVSF_WAGON = 2, ///< Wagon (not used for road vehicles).
119 GVSF_ENGINE = 3, ///< Engine that can be front engine, but might be placed behind another engine (not used for road vehicles).
120 GVSF_FREE_WAGON = 4, ///< First in a wagon chain (in depot) (not used for road vehicles).
121 GVSF_MULTIHEADED = 5, ///< Engine is multiheaded (not used for road vehicles).
124 /** Cached often queried values common to all vehicles. */
125 struct VehicleCache {
126 uint16_t cached_max_speed; ///< Maximum speed of the consist (minimum of the max speed of all vehicles in the consist).
127 uint16_t cached_cargo_age_period; ///< Number of ticks before carried cargo is aged.
129 uint8_t cached_vis_effect; ///< Visual effect to show (see #VisualEffect)
131 auto operator<=>(const VehicleCache &) const = default;
134 /** Sprite sequence for a vehicle part. */
135 struct VehicleSpriteSeq {
136 PalSpriteID seq[8];
137 uint count;
139 bool operator==(const VehicleSpriteSeq &other) const
141 return this->count == other.count && MemCmpT<PalSpriteID>(this->seq, other.seq, this->count) == 0;
144 bool operator!=(const VehicleSpriteSeq &other) const
146 return !this->operator==(other);
150 * Check whether the sequence contains any sprites.
152 bool IsValid() const
154 return this->count != 0;
158 * Clear all information.
160 void Clear()
162 this->count = 0;
166 * Assign a single sprite to the sequence.
168 void Set(SpriteID sprite)
170 this->count = 1;
171 this->seq[0].sprite = sprite;
172 this->seq[0].pal = 0;
176 * Copy data from another sprite sequence, while dropping all recolouring information.
178 void CopyWithoutPalette(const VehicleSpriteSeq &src)
180 this->count = src.count;
181 for (uint i = 0; i < src.count; ++i) {
182 this->seq[i].sprite = src.seq[i].sprite;
183 this->seq[i].pal = 0;
187 void GetBounds(Rect *bounds) const;
188 void Draw(int x, int y, PaletteID default_pal, bool force_pal) const;
192 * Cache for vehicle sprites and values relating to whether they should be updated before drawing,
193 * or calculating the viewport.
195 struct MutableSpriteCache {
196 Direction last_direction; ///< Last direction we obtained sprites for
197 bool revalidate_before_draw; ///< We need to do a GetImage() and check bounds before drawing this sprite
198 bool is_viewport_candidate; ///< This vehicle can potentially be drawn on a viewport
199 Rect old_coord; ///< Co-ordinates from the last valid bounding box
200 VehicleSpriteSeq sprite_seq; ///< Vehicle appearance.
203 /** A vehicle pool for a little over 1 million vehicles. */
204 typedef Pool<Vehicle, VehicleID, 512, 0xFF000> VehiclePool;
205 extern VehiclePool _vehicle_pool;
207 /* Some declarations of functions, so we can make them friendly */
208 struct GroundVehicleCache;
209 struct LoadgameState;
210 extern bool LoadOldVehicle(LoadgameState *ls, int num);
211 extern void FixOldVehicles();
213 struct GRFFile;
216 * Simulated cargo type and capacity for prediction of future links.
218 struct RefitDesc {
219 CargoID cargo; ///< Cargo type the vehicle will be carrying.
220 uint16_t capacity; ///< Capacity the vehicle will have.
221 uint16_t remaining; ///< Capacity remaining from before the previous refit.
222 RefitDesc(CargoID cargo, uint16_t capacity, uint16_t remaining) :
223 cargo(cargo), capacity(capacity), remaining(remaining) {}
227 * Structure to return information about the closest depot location,
228 * and whether it could be found.
230 struct ClosestDepot {
231 TileIndex location;
232 DestinationID destination; ///< The DestinationID as used for orders.
233 bool reverse;
234 bool found;
236 ClosestDepot() :
237 location(INVALID_TILE), destination(0), reverse(false), found(false) {}
239 ClosestDepot(TileIndex location, DestinationID destination, bool reverse = false) :
240 location(location), destination(destination), reverse(reverse), found(true) {}
243 /** %Vehicle data structure. */
244 struct Vehicle : VehiclePool::PoolItem<&_vehicle_pool>, BaseVehicle, BaseConsist {
245 private:
246 typedef std::list<RefitDesc> RefitList;
248 Vehicle *next; ///< pointer to the next vehicle in the chain
249 Vehicle *previous; ///< NOSAVE: pointer to the previous vehicle in the chain
250 Vehicle *first; ///< NOSAVE: pointer to the first vehicle in the chain
252 Vehicle *next_shared; ///< pointer to the next vehicle that shares the order
253 Vehicle *previous_shared; ///< NOSAVE: pointer to the previous vehicle in the shared order chain
255 public:
256 friend void FixOldVehicles();
257 friend void AfterLoadVehiclesPhase1(bool part_of_load); ///< So we can set the #previous and #first pointers while loading
258 friend bool LoadOldVehicle(LoadgameState *ls, int num); ///< So we can set the proper next pointer while loading
259 /* So we can use private/protected variables in the saveload code */
260 friend class SlVehicleCommon;
261 friend class SlVehicleDisaster;
262 friend void Ptrs_VEHS();
264 TileIndex tile; ///< Current tile index
267 * Heading for this tile.
268 * For airports and train stations this tile does not necessarily belong to the destination station,
269 * but it can be used for heuristic purposes to estimate the distance.
271 TileIndex dest_tile;
273 Money profit_this_year; ///< Profit this year << 8, low 8 bits are fract
274 Money profit_last_year; ///< Profit last year << 8, low 8 bits are fract
275 Money value; ///< Value of the vehicle
277 CargoPayment *cargo_payment; ///< The cargo payment we're currently in
279 mutable Rect coord; ///< NOSAVE: Graphical bounding box of the vehicle, i.e. what to redraw on moves.
281 Vehicle *hash_viewport_next; ///< NOSAVE: Next vehicle in the visual location hash.
282 Vehicle **hash_viewport_prev; ///< NOSAVE: Previous vehicle in the visual location hash.
284 Vehicle *hash_tile_next; ///< NOSAVE: Next vehicle in the tile location hash.
285 Vehicle **hash_tile_prev; ///< NOSAVE: Previous vehicle in the tile location hash.
286 Vehicle **hash_tile_current; ///< NOSAVE: Cache of the current hash chain.
288 SpriteID colourmap; ///< NOSAVE: cached colour mapping
290 /* Related to age and service time */
291 TimerGameCalendar::Year build_year; ///< Year the vehicle has been built.
292 TimerGameCalendar::Date age; ///< Age in calendar days.
293 TimerGameEconomy::Date economy_age; ///< Age in economy days.
294 TimerGameCalendar::Date max_age; ///< Maximum age
295 TimerGameEconomy::Date date_of_last_service; ///< Last economy date the vehicle had a service at a depot.
296 TimerGameCalendar::Date date_of_last_service_newgrf; ///< Last calendar date the vehicle had a service at a depot, unchanged by the date cheat to protect against unsafe NewGRF behavior.
297 uint16_t reliability; ///< Reliability.
298 uint16_t reliability_spd_dec; ///< Reliability decrease speed.
299 uint8_t breakdown_ctr; ///< Counter for managing breakdown events. @see Vehicle::HandleBreakdown
300 uint8_t breakdown_delay; ///< Counter for managing breakdown length.
301 uint8_t breakdowns_since_last_service; ///< Counter for the amount of breakdowns.
302 uint8_t breakdown_chance; ///< Current chance of breakdowns.
304 int32_t x_pos; ///< x coordinate.
305 int32_t y_pos; ///< y coordinate.
306 int32_t z_pos; ///< z coordinate.
307 Direction direction; ///< facing
309 Owner owner; ///< Which company owns the vehicle?
311 * currently displayed sprite index
312 * 0xfd == custom sprite, 0xfe == custom second head sprite
313 * 0xff == reserved for another custom sprite
315 uint8_t spritenum;
316 uint8_t x_extent; ///< x-extent of vehicle bounding box
317 uint8_t y_extent; ///< y-extent of vehicle bounding box
318 uint8_t z_extent; ///< z-extent of vehicle bounding box
319 int8_t x_bb_offs; ///< x offset of vehicle bounding box
320 int8_t y_bb_offs; ///< y offset of vehicle bounding box
321 int8_t x_offs; ///< x offset for vehicle sprite
322 int8_t y_offs; ///< y offset for vehicle sprite
323 EngineID engine_type; ///< The type of engine used for this vehicle.
325 TextEffectID fill_percent_te_id; ///< a text-effect id to a loading indicator object
326 UnitID unitnumber; ///< unit number, for display purposes only
328 uint16_t cur_speed; ///< current speed
329 uint8_t subspeed; ///< fractional speed
330 uint8_t acceleration; ///< used by train & aircraft
331 uint32_t motion_counter; ///< counter to occasionally play a vehicle sound.
332 uint8_t progress; ///< The percentage (if divided by 256) this vehicle already crossed the tile unit.
334 uint8_t waiting_triggers; ///< Triggers to be yet matched before rerandomizing the random bits.
335 uint16_t random_bits; ///< Bits used for randomized variational spritegroups.
337 StationID last_station_visited; ///< The last station we stopped at.
338 StationID last_loading_station; ///< Last station the vehicle has stopped at and could possibly leave from with any cargo loaded.
339 TimerGameTick::TickCounter last_loading_tick; ///< Last TimerGameTick::counter tick that the vehicle has stopped at a station and could possibly leave with any cargo loaded.
341 VehicleCargoList cargo; ///< The cargo this vehicle is carrying
342 CargoID cargo_type; ///< type of cargo this vehicle is carrying
343 uint8_t cargo_subtype; ///< Used for livery refits (NewGRF variations)
344 uint16_t cargo_cap; ///< total capacity
345 uint16_t refit_cap; ///< Capacity left over from before last refit.
346 uint16_t cargo_age_counter; ///< Ticks till cargo is aged next.
347 int8_t trip_occupancy; ///< NOSAVE: Occupancy of vehicle of the current trip (updated after leaving a station).
349 uint8_t day_counter; ///< Increased by one for each day
350 uint8_t tick_counter; ///< Increased by one for each tick
351 uint8_t running_ticks; ///< Number of ticks this vehicle was not stopped this day
352 uint16_t load_unload_ticks; ///< Ticks to wait before starting next cycle.
354 uint8_t vehstatus; ///< Status
355 uint8_t subtype; ///< subtype (Filled with values from #AircraftSubType/#DisasterSubType/#EffectVehicleType/#GroundVehicleSubtypeFlags)
356 Order current_order; ///< The current order (+ status, like: loading)
358 union {
359 OrderList *orders; ///< Pointer to the order list for this vehicle
360 Order *old_orders; ///< Only used during conversion of old save games
363 NewGRFCache grf_cache; ///< Cache of often used calculated NewGRF values
364 VehicleCache vcache; ///< Cache of often used vehicle values.
366 GroupID group_id; ///< Index of group Pool array
368 mutable MutableSpriteCache sprite_cache; ///< Cache of sprites and values related to recalculating them, see #MutableSpriteCache
371 * Calculates the weight value that this vehicle will have when fully loaded with its current cargo.
372 * @return Weight value in tonnes.
374 virtual uint16_t GetMaxWeight() const
376 return 0;
379 Vehicle(VehicleType type = VEH_INVALID);
381 void PreDestructor();
382 /** We want to 'destruct' the right class. */
383 virtual ~Vehicle();
385 void BeginLoading();
386 void CancelReservation(StationID next, Station *st);
387 void LeaveStation();
389 GroundVehicleCache *GetGroundVehicleCache();
390 const GroundVehicleCache *GetGroundVehicleCache() const;
392 uint16_t &GetGroundVehicleFlags();
393 const uint16_t &GetGroundVehicleFlags() const;
395 void DeleteUnreachedImplicitOrders();
397 void HandleLoading(bool mode = false);
400 * Marks the vehicles to be redrawn and updates cached variables
402 * This method marks the area of the vehicle on the screen as dirty.
403 * It can be use to repaint the vehicle.
405 * @ingroup dirty
407 virtual void MarkDirty() {}
410 * Updates the x and y offsets and the size of the sprite used
411 * for this vehicle.
413 virtual void UpdateDeltaXY() {}
416 * Determines the effective direction-specific vehicle movement speed.
418 * This method belongs to the old vehicle movement method:
419 * A vehicle moves a step every 256 progress units.
420 * The vehicle speed is scaled by 3/4 when moving in X or Y direction due to the longer distance.
422 * However, this method is slightly wrong in corners, as the leftover progress is not scaled correctly
423 * when changing movement direction. #GetAdvanceSpeed() and #GetAdvanceDistance() are better wrt. this.
425 * @param speed Direction-independent unscaled speed.
426 * @return speed scaled by movement direction. 256 units are required for each movement step.
428 inline uint GetOldAdvanceSpeed(uint speed)
430 return (this->direction & 1) ? speed : speed * 3 / 4;
434 * Determines the effective vehicle movement speed.
436 * Together with #GetAdvanceDistance() this function is a replacement for #GetOldAdvanceSpeed().
438 * A vehicle progresses independent of it's movement direction.
439 * However different amounts of "progress" are needed for moving a step in a specific direction.
440 * That way the leftover progress does not need any adaption when changing movement direction.
442 * @param speed Direction-independent unscaled speed.
443 * @return speed, scaled to match #GetAdvanceDistance().
445 static inline uint GetAdvanceSpeed(uint speed)
447 return speed * 3 / 4;
451 * Determines the vehicle "progress" needed for moving a step.
453 * Together with #GetAdvanceSpeed() this function is a replacement for #GetOldAdvanceSpeed().
455 * @return distance to drive for a movement step on the map.
457 inline uint GetAdvanceDistance()
459 return (this->direction & 1) ? TILE_AXIAL_DISTANCE : TILE_CORNER_DISTANCE * 2;
463 * Sets the expense type associated to this vehicle type
464 * @param income whether this is income or (running) expenses of the vehicle
466 virtual ExpensesType GetExpenseType([[maybe_unused]] bool income) const { return EXPENSES_OTHER; }
469 * Play the sound associated with leaving the station
470 * @param force Should we play the sound even if sound effects are muted? (horn hotkey)
472 virtual void PlayLeaveStationSound([[maybe_unused]] bool force = false) const {}
475 * Whether this is the primary vehicle in the chain.
477 virtual bool IsPrimaryVehicle() const { return false; }
479 const Engine *GetEngine() const;
482 * Gets the sprite to show for the given direction
483 * @param direction the direction the vehicle is facing
484 * @param[out] result Vehicle sprite sequence.
486 virtual void GetImage([[maybe_unused]] Direction direction, [[maybe_unused]] EngineImageType image_type, [[maybe_unused]] VehicleSpriteSeq *result) const { result->Clear(); }
488 const GRFFile *GetGRF() const;
489 uint32_t GetGRFID() const;
492 * Invalidates cached NewGRF variables
493 * @see InvalidateNewGRFCacheOfChain
495 inline void InvalidateNewGRFCache()
497 this->grf_cache.cache_valid = 0;
501 * Invalidates cached NewGRF variables of all vehicles in the chain (after the current vehicle)
502 * @see InvalidateNewGRFCache
504 inline void InvalidateNewGRFCacheOfChain()
506 for (Vehicle *u = this; u != nullptr; u = u->Next()) {
507 u->InvalidateNewGRFCache();
512 * Check if the vehicle is a ground vehicle.
513 * @return True iff the vehicle is a train or a road vehicle.
515 debug_inline bool IsGroundVehicle() const
517 return this->type == VEH_TRAIN || this->type == VEH_ROAD;
521 * Gets the speed in km-ish/h that can be sent into SetDParam for string processing.
522 * @return the vehicle's speed
524 virtual int GetDisplaySpeed() const { return 0; }
527 * Gets the maximum speed in km-ish/h that can be sent into SetDParam for string processing.
528 * @return the vehicle's maximum speed
530 virtual int GetDisplayMaxSpeed() const { return 0; }
533 * Calculates the maximum speed of the vehicle under its current conditions.
534 * @return Current maximum speed in native units.
536 virtual int GetCurrentMaxSpeed() const { return 0; }
539 * Gets the running cost of a vehicle
540 * @return the vehicle's running cost
542 virtual Money GetRunningCost() const { return 0; }
545 * Check whether the vehicle is in the depot.
546 * @return true if and only if the vehicle is in the depot.
548 virtual bool IsInDepot() const { return false; }
551 * Check whether the whole vehicle chain is in the depot.
552 * @return true if and only if the whole chain is in the depot.
554 virtual bool IsChainInDepot() const { return this->IsInDepot(); }
557 * Check whether the vehicle is in the depot *and* stopped.
558 * @return true if and only if the vehicle is in the depot and stopped.
560 bool IsStoppedInDepot() const
562 assert(this == this->First());
563 /* Free wagons have no VS_STOPPED state */
564 if (this->IsPrimaryVehicle() && !(this->vehstatus & VS_STOPPED)) return false;
565 return this->IsChainInDepot();
569 * Calls the tick handler of the vehicle
570 * @return is this vehicle still valid?
572 virtual bool Tick() { return true; };
575 * Calls the new calendar day handler of the vehicle.
577 virtual void OnNewCalendarDay() {};
580 * Calls the new economy day handler of the vehicle.
582 virtual void OnNewEconomyDay() {};
584 void ShiftDates(TimerGameEconomy::Date interval);
587 * Crash the (whole) vehicle chain.
588 * @param flooded whether the cause of the crash is flooding or not.
589 * @return the number of lost souls.
591 virtual uint Crash(bool flooded = false);
594 * Returns the Trackdir on which the vehicle is currently located.
595 * Works for trains and ships.
596 * Currently works only sortof for road vehicles, since they have a fuzzy
597 * concept of being "on" a trackdir. Dunno really what it returns for a road
598 * vehicle that is halfway a tile, never really understood that part. For road
599 * vehicles that are at the beginning or end of the tile, should just return
600 * the diagonal trackdir on which they are driving. I _think_.
601 * For other vehicles types, or vehicles with no clear trackdir (such as those
602 * in depots), returns 0xFF.
603 * @return the trackdir of the vehicle
605 virtual Trackdir GetVehicleTrackdir() const { return INVALID_TRACKDIR; }
608 * Gets the running cost of a vehicle that can be sent into SetDParam for string processing.
609 * @return the vehicle's running cost
611 Money GetDisplayRunningCost() const { return (this->GetRunningCost() >> 8); }
614 * Gets the profit vehicle had this year. It can be sent into SetDParam for string processing.
615 * @return the vehicle's profit this year
617 Money GetDisplayProfitThisYear() const { return (this->profit_this_year >> 8); }
620 * Gets the profit vehicle had last year. It can be sent into SetDParam for string processing.
621 * @return the vehicle's profit last year
623 Money GetDisplayProfitLastYear() const { return (this->profit_last_year >> 8); }
625 void SetNext(Vehicle *next);
628 * Get the next vehicle of this vehicle.
629 * @note articulated parts are also counted as vehicles.
630 * @return the next vehicle or nullptr when there isn't a next vehicle.
632 inline Vehicle *Next() const { return this->next; }
635 * Get the previous vehicle of this vehicle.
636 * @note articulated parts are also counted as vehicles.
637 * @return the previous vehicle or nullptr when there isn't a previous vehicle.
639 inline Vehicle *Previous() const { return this->previous; }
642 * Get the first vehicle of this vehicle chain.
643 * @return the first vehicle of the chain.
645 inline Vehicle *First() const { return this->first; }
648 * Get the last vehicle of this vehicle chain.
649 * @return the last vehicle of the chain.
651 inline Vehicle *Last()
653 Vehicle *v = this;
654 while (v->Next() != nullptr) v = v->Next();
655 return v;
659 * Get the last vehicle of this vehicle chain.
660 * @return the last vehicle of the chain.
662 inline const Vehicle *Last() const
664 const Vehicle *v = this;
665 while (v->Next() != nullptr) v = v->Next();
666 return v;
670 * Get the vehicle at offset \a n of this vehicle chain.
671 * @param n Offset from the current vehicle.
672 * @return The new vehicle or nullptr if the offset is out-of-bounds.
674 inline Vehicle *Move(int n)
676 Vehicle *v = this;
677 if (n < 0) {
678 for (int i = 0; i != n && v != nullptr; i--) v = v->Previous();
679 } else {
680 for (int i = 0; i != n && v != nullptr; i++) v = v->Next();
682 return v;
686 * Get the vehicle at offset \a n of this vehicle chain.
687 * @param n Offset from the current vehicle.
688 * @return The new vehicle or nullptr if the offset is out-of-bounds.
690 inline const Vehicle *Move(int n) const
692 const Vehicle *v = this;
693 if (n < 0) {
694 for (int i = 0; i != n && v != nullptr; i--) v = v->Previous();
695 } else {
696 for (int i = 0; i != n && v != nullptr; i++) v = v->Next();
698 return v;
702 * Get the first order of the vehicles order list.
703 * @return first order of order list.
705 inline Order *GetFirstOrder() const { return (this->orders == nullptr) ? nullptr : this->orders->GetFirstOrder(); }
707 void AddToShared(Vehicle *shared_chain);
708 void RemoveFromShared();
711 * Get the next vehicle of the shared vehicle chain.
712 * @return the next shared vehicle or nullptr when there isn't a next vehicle.
714 inline Vehicle *NextShared() const { return this->next_shared; }
717 * Get the previous vehicle of the shared vehicle chain
718 * @return the previous shared vehicle or nullptr when there isn't a previous vehicle.
720 inline Vehicle *PreviousShared() const { return this->previous_shared; }
723 * Get the first vehicle of this vehicle chain.
724 * @return the first vehicle of the chain.
726 inline Vehicle *FirstShared() const { return (this->orders == nullptr) ? this->First() : this->orders->GetFirstSharedVehicle(); }
729 * Check if we share our orders with another vehicle.
730 * @return true if there are other vehicles sharing the same order
732 inline bool IsOrderListShared() const { return this->orders != nullptr && this->orders->IsShared(); }
735 * Get the number of orders this vehicle has.
736 * @return the number of orders this vehicle has.
738 inline VehicleOrderID GetNumOrders() const { return (this->orders == nullptr) ? 0 : this->orders->GetNumOrders(); }
741 * Get the number of manually added orders this vehicle has.
742 * @return the number of manually added orders this vehicle has.
744 inline VehicleOrderID GetNumManualOrders() const { return (this->orders == nullptr) ? 0 : this->orders->GetNumManualOrders(); }
747 * Get the next station the vehicle will stop at.
748 * @return ID of the next station the vehicle will stop at or INVALID_STATION.
750 inline StationIDStack GetNextStoppingStation() const
752 return (this->orders == nullptr) ? INVALID_STATION : this->orders->GetNextStoppingStation(this);
755 void ResetRefitCaps();
757 void ReleaseUnitNumber();
760 * Copy certain configurations and statistics of a vehicle after successful autoreplace/renew
761 * The function shall copy everything that cannot be copied by a command (like orders / group etc),
762 * and that shall not be resetted for the new vehicle.
763 * @param src The old vehicle
765 inline void CopyVehicleConfigAndStatistics(Vehicle *src)
767 this->CopyConsistPropertiesFrom(src);
769 this->ReleaseUnitNumber();
770 this->unitnumber = src->unitnumber;
772 this->current_order = src->current_order;
773 this->dest_tile = src->dest_tile;
775 this->profit_this_year = src->profit_this_year;
776 this->profit_last_year = src->profit_last_year;
778 src->unitnumber = 0;
782 bool HandleBreakdown();
784 bool NeedsAutorenewing(const Company *c, bool use_renew_setting = true) const;
786 bool NeedsServicing() const;
787 bool NeedsAutomaticServicing() const;
790 * Determine the location for the station where the vehicle goes to next.
791 * Things done for example are allocating slots in a road stop or exact
792 * location of the platform is determined for ships.
793 * @param station the station to make the next location of the vehicle.
794 * @return the location (tile) to aim for.
796 virtual TileIndex GetOrderStationLocation([[maybe_unused]] StationID station) { return INVALID_TILE; }
798 virtual TileIndex GetCargoTile() const { return this->tile; }
801 * Find the closest depot for this vehicle and tell us the location,
802 * DestinationID and whether we should reverse.
803 * @return A structure with information about the closest depot, if found.
805 virtual ClosestDepot FindClosestDepot() { return {}; }
807 virtual void SetDestTile(TileIndex tile) { this->dest_tile = tile; }
809 CommandCost SendToDepot(DoCommandFlag flags, DepotCommand command);
811 void UpdateVisualEffect(bool allow_power_change = true);
812 void ShowVisualEffect() const;
814 void UpdatePosition();
815 void UpdateViewport(bool dirty);
816 void UpdateBoundingBoxCoordinates(bool update_cache) const;
817 void UpdatePositionAndViewport();
818 bool MarkAllViewportsDirty() const;
820 inline uint16_t GetServiceInterval() const { return this->service_interval; }
822 inline void SetServiceInterval(uint16_t interval) { this->service_interval = interval; }
824 inline bool ServiceIntervalIsCustom() const { return HasBit(this->vehicle_flags, VF_SERVINT_IS_CUSTOM); }
826 inline bool ServiceIntervalIsPercent() const { return HasBit(this->vehicle_flags, VF_SERVINT_IS_PERCENT); }
828 inline void SetServiceIntervalIsCustom(bool on) { AssignBit(this->vehicle_flags, VF_SERVINT_IS_CUSTOM, on); }
830 inline void SetServiceIntervalIsPercent(bool on) { AssignBit(this->vehicle_flags, VF_SERVINT_IS_PERCENT, on); }
832 bool HasFullLoadOrder() const;
833 bool HasConditionalOrder() const;
834 bool HasUnbunchingOrder() const;
835 void LeaveUnbunchingDepot();
836 bool IsWaitingForUnbunching() const;
838 private:
840 * Advance cur_real_order_index to the next real order.
841 * cur_implicit_order_index is not touched.
843 void SkipToNextRealOrderIndex()
845 if (this->GetNumManualOrders() > 0) {
846 /* Advance to next real order */
847 do {
848 this->cur_real_order_index++;
849 if (this->cur_real_order_index >= this->GetNumOrders()) this->cur_real_order_index = 0;
850 } while (this->GetOrder(this->cur_real_order_index)->IsType(OT_IMPLICIT));
851 } else {
852 this->cur_real_order_index = 0;
856 public:
858 * Increments cur_implicit_order_index, keeps care of the wrap-around and invalidates the GUI.
859 * cur_real_order_index is incremented as well, if needed.
860 * Note: current_order is not invalidated.
862 void IncrementImplicitOrderIndex()
864 if (this->cur_implicit_order_index == this->cur_real_order_index) {
865 /* Increment real order index as well */
866 this->SkipToNextRealOrderIndex();
869 assert(this->cur_real_order_index == 0 || this->cur_real_order_index < this->GetNumOrders());
871 /* Advance to next implicit order */
872 do {
873 this->cur_implicit_order_index++;
874 if (this->cur_implicit_order_index >= this->GetNumOrders()) this->cur_implicit_order_index = 0;
875 } while (this->cur_implicit_order_index != this->cur_real_order_index && !this->GetOrder(this->cur_implicit_order_index)->IsType(OT_IMPLICIT));
877 InvalidateVehicleOrder(this, 0);
881 * Advanced cur_real_order_index to the next real order, keeps care of the wrap-around and invalidates the GUI.
882 * 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
883 * but not any implicit orders.
884 * Note: current_order is not invalidated.
886 void IncrementRealOrderIndex()
888 if (this->cur_implicit_order_index == this->cur_real_order_index) {
889 /* Increment both real and implicit order */
890 this->IncrementImplicitOrderIndex();
891 } else {
892 /* Increment real order only */
893 this->SkipToNextRealOrderIndex();
894 InvalidateVehicleOrder(this, 0);
899 * Skip implicit orders until cur_real_order_index is a non-implicit order.
901 void UpdateRealOrderIndex()
903 /* Make sure the index is valid */
904 if (this->cur_real_order_index >= this->GetNumOrders()) this->cur_real_order_index = 0;
906 if (this->GetNumManualOrders() > 0) {
907 /* Advance to next real order */
908 while (this->GetOrder(this->cur_real_order_index)->IsType(OT_IMPLICIT)) {
909 this->cur_real_order_index++;
910 if (this->cur_real_order_index >= this->GetNumOrders()) this->cur_real_order_index = 0;
912 } else {
913 this->cur_real_order_index = 0;
918 * Returns order 'index' of a vehicle or nullptr when it doesn't exists
919 * @param index the order to fetch
920 * @return the found (or not) order
922 inline Order *GetOrder(int index) const
924 return (this->orders == nullptr) ? nullptr : this->orders->GetOrderAt(index);
928 * Returns the last order of a vehicle, or nullptr if it doesn't exists
929 * @return last order of a vehicle, if available
931 inline Order *GetLastOrder() const
933 return (this->orders == nullptr) ? nullptr : this->orders->GetLastOrder();
936 bool IsEngineCountable() const;
937 bool HasEngineType() const;
938 bool HasDepotOrder() const;
939 void HandlePathfindingResult(bool path_found);
942 * Check if the vehicle is a front engine.
943 * @return Returns true if the vehicle is a front engine.
945 debug_inline bool IsFrontEngine() const
947 return this->IsGroundVehicle() && HasBit(this->subtype, GVSF_FRONT);
951 * Check if the vehicle is an articulated part of an engine.
952 * @return Returns true if the vehicle is an articulated part.
954 inline bool IsArticulatedPart() const
956 return this->IsGroundVehicle() && HasBit(this->subtype, GVSF_ARTICULATED_PART);
960 * Check if an engine has an articulated part.
961 * @return True if the engine has an articulated part.
963 inline bool HasArticulatedPart() const
965 return this->Next() != nullptr && this->Next()->IsArticulatedPart();
969 * Get the next part of an articulated engine.
970 * @return Next part of the articulated engine.
971 * @pre The vehicle is an articulated engine.
973 inline Vehicle *GetNextArticulatedPart() const
975 assert(this->HasArticulatedPart());
976 return this->Next();
980 * Get the first part of an articulated engine.
981 * @return First part of the engine.
983 inline Vehicle *GetFirstEnginePart()
985 Vehicle *v = this;
986 while (v->IsArticulatedPart()) v = v->Previous();
987 return v;
991 * Get the first part of an articulated engine.
992 * @return First part of the engine.
994 inline const Vehicle *GetFirstEnginePart() const
996 const Vehicle *v = this;
997 while (v->IsArticulatedPart()) v = v->Previous();
998 return v;
1002 * Get the last part of an articulated engine.
1003 * @return Last part of the engine.
1005 inline Vehicle *GetLastEnginePart()
1007 Vehicle *v = this;
1008 while (v->HasArticulatedPart()) v = v->GetNextArticulatedPart();
1009 return v;
1013 * Get the next real (non-articulated part) vehicle in the consist.
1014 * @return Next vehicle in the consist.
1016 inline Vehicle *GetNextVehicle() const
1018 const Vehicle *v = this;
1019 while (v->HasArticulatedPart()) v = v->GetNextArticulatedPart();
1021 /* v now contains the last articulated part in the engine */
1022 return v->Next();
1026 * Get the previous real (non-articulated part) vehicle in the consist.
1027 * @return Previous vehicle in the consist.
1029 inline Vehicle *GetPrevVehicle() const
1031 Vehicle *v = this->Previous();
1032 while (v != nullptr && v->IsArticulatedPart()) v = v->Previous();
1034 return v;
1038 * Iterator to iterate orders
1039 * Supports deletion of current order
1041 struct OrderIterator {
1042 typedef Order value_type;
1043 typedef Order *pointer;
1044 typedef Order &reference;
1045 typedef size_t difference_type;
1046 typedef std::forward_iterator_tag iterator_category;
1048 explicit OrderIterator(OrderList *list) : list(list), prev(nullptr)
1050 this->order = (this->list == nullptr) ? nullptr : this->list->GetFirstOrder();
1053 bool operator==(const OrderIterator &other) const { return this->order == other.order; }
1054 bool operator!=(const OrderIterator &other) const { return !(*this == other); }
1055 Order * operator*() const { return this->order; }
1056 OrderIterator & operator++()
1058 this->prev = (this->prev == nullptr) ? this->list->GetFirstOrder() : this->prev->next;
1059 this->order = (this->prev == nullptr) ? nullptr : this->prev->next;
1060 return *this;
1063 private:
1064 OrderList *list;
1065 Order *order;
1066 Order *prev;
1070 * Iterable ensemble of orders
1072 struct IterateWrapper {
1073 OrderList *list;
1074 IterateWrapper(OrderList *list = nullptr) : list(list) {}
1075 OrderIterator begin() { return OrderIterator(this->list); }
1076 OrderIterator end() { return OrderIterator(nullptr); }
1077 bool empty() { return this->begin() == this->end(); }
1081 * Returns an iterable ensemble of orders of a vehicle
1082 * @return an iterable ensemble of orders of a vehicle
1084 IterateWrapper Orders() const { return IterateWrapper(this->orders); }
1086 uint32_t GetDisplayMaxWeight() const;
1087 uint32_t GetDisplayMinPowerToWeight() const;
1091 * Class defining several overloaded accessors so we don't
1092 * have to cast vehicle types that often
1094 template <class T, VehicleType Type>
1095 struct SpecializedVehicle : public Vehicle {
1096 static const VehicleType EXPECTED_TYPE = Type; ///< Specialized type
1098 typedef SpecializedVehicle<T, Type> SpecializedVehicleBase; ///< Our type
1101 * Set vehicle type correctly
1103 inline SpecializedVehicle() : Vehicle(Type)
1105 this->sprite_cache.sprite_seq.count = 1;
1109 * Get the first vehicle in the chain
1110 * @return first vehicle in the chain
1112 inline T *First() const { return (T *)this->Vehicle::First(); }
1115 * Get the last vehicle in the chain
1116 * @return last vehicle in the chain
1118 inline T *Last() { return (T *)this->Vehicle::Last(); }
1121 * Get the last vehicle in the chain
1122 * @return last vehicle in the chain
1124 inline const T *Last() const { return (const T *)this->Vehicle::Last(); }
1127 * Get next vehicle in the chain
1128 * @return next vehicle in the chain
1130 inline T *Next() const { return (T *)this->Vehicle::Next(); }
1133 * Get previous vehicle in the chain
1134 * @return previous vehicle in the chain
1136 inline T *Previous() const { return (T *)this->Vehicle::Previous(); }
1139 * Get the next part of an articulated engine.
1140 * @return Next part of the articulated engine.
1141 * @pre The vehicle is an articulated engine.
1143 inline T *GetNextArticulatedPart() { return (T *)this->Vehicle::GetNextArticulatedPart(); }
1146 * Get the next part of an articulated engine.
1147 * @return Next part of the articulated engine.
1148 * @pre The vehicle is an articulated engine.
1150 inline T *GetNextArticulatedPart() const { return (T *)this->Vehicle::GetNextArticulatedPart(); }
1153 * Get the first part of an articulated engine.
1154 * @return First part of the engine.
1156 inline T *GetFirstEnginePart() { return (T *)this->Vehicle::GetFirstEnginePart(); }
1159 * Get the first part of an articulated engine.
1160 * @return First part of the engine.
1162 inline const T *GetFirstEnginePart() const { return (const T *)this->Vehicle::GetFirstEnginePart(); }
1165 * Get the last part of an articulated engine.
1166 * @return Last part of the engine.
1168 inline T *GetLastEnginePart() { return (T *)this->Vehicle::GetLastEnginePart(); }
1171 * Get the next real (non-articulated part) vehicle in the consist.
1172 * @return Next vehicle in the consist.
1174 inline T *GetNextVehicle() const { return (T *)this->Vehicle::GetNextVehicle(); }
1177 * Get the previous real (non-articulated part) vehicle in the consist.
1178 * @return Previous vehicle in the consist.
1180 inline T *GetPrevVehicle() const { return (T *)this->Vehicle::GetPrevVehicle(); }
1183 * Tests whether given index is a valid index for vehicle of this type
1184 * @param index tested index
1185 * @return is this index valid index of T?
1187 static inline bool IsValidID(size_t index)
1189 return Vehicle::IsValidID(index) && Vehicle::Get(index)->type == Type;
1193 * Gets vehicle with given index
1194 * @return pointer to vehicle with given index casted to T *
1196 static inline T *Get(size_t index)
1198 return (T *)Vehicle::Get(index);
1202 * Returns vehicle if the index is a valid index for this vehicle type
1203 * @return pointer to vehicle with given index if it's a vehicle of this type
1205 static inline T *GetIfValid(size_t index)
1207 return IsValidID(index) ? Get(index) : nullptr;
1211 * Converts a Vehicle to SpecializedVehicle with type checking.
1212 * @param v Vehicle pointer
1213 * @return pointer to SpecializedVehicle
1215 static inline T *From(Vehicle *v)
1217 assert(v->type == Type);
1218 return (T *)v;
1222 * Converts a const Vehicle to const SpecializedVehicle with type checking.
1223 * @param v Vehicle pointer
1224 * @return pointer to SpecializedVehicle
1226 static inline const T *From(const Vehicle *v)
1228 assert(v->type == Type);
1229 return (const T *)v;
1233 * Update vehicle sprite- and position caches
1234 * @param force_update Force updating the vehicle on the viewport.
1235 * @param update_delta Also update the delta?
1237 inline void UpdateViewport(bool force_update, bool update_delta)
1239 bool sprite_has_changed = false;
1241 /* Skip updating sprites on dedicated servers without screen */
1242 if (_network_dedicated) return;
1244 /* Explicitly choose method to call to prevent vtable dereference -
1245 * it gives ~3% runtime improvements in games with many vehicles */
1246 if (update_delta) ((T *)this)->T::UpdateDeltaXY();
1249 * Only check for a new sprite sequence if the vehicle direction
1250 * has changed since we last checked it, assuming that otherwise
1251 * there won't be enough change in bounding box or offsets to need
1252 * to resolve a new sprite.
1254 if (this->direction != this->sprite_cache.last_direction || this->sprite_cache.is_viewport_candidate) {
1255 VehicleSpriteSeq seq;
1257 ((T*)this)->T::GetImage(this->direction, EIT_ON_MAP, &seq);
1258 if (this->sprite_cache.sprite_seq != seq) {
1259 sprite_has_changed = true;
1260 this->sprite_cache.sprite_seq = seq;
1263 this->sprite_cache.last_direction = this->direction;
1264 this->sprite_cache.revalidate_before_draw = false;
1265 } else {
1267 * A change that could potentially invalidate the sprite has been
1268 * made, signal that we should still resolve it before drawing on a
1269 * viewport.
1271 this->sprite_cache.revalidate_before_draw = true;
1274 if (force_update || sprite_has_changed) {
1275 this->Vehicle::UpdateViewport(true);
1280 * Returns an iterable ensemble of all valid vehicles of type T
1281 * @param from index of the first vehicle to consider
1282 * @return an iterable ensemble of all valid vehicles of type T
1284 static Pool::IterateWrapper<T> Iterate(size_t from = 0) { return Pool::IterateWrapper<T>(from); }
1287 /** Sentinel for an invalid coordinate. */
1288 static const int32_t INVALID_COORD = 0x7fffffff;
1290 #endif /* VEHICLE_BASE_H */