OpenTTD: src/vehicle_base.h Source File

OpenTTD

- Main Page
- Related Pages
- Modules
- Namespaces
- Data Structures
- Files

- File List
- Globals

vehicle_base.h
Go to the documentation of this file.
1 /* $Id: vehicle_base.h 27579 2016-05-22 11:30:25Z frosch $ */
2
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 */
9
12 #ifndef VEHICLE_BASE_H
13 #define VEHICLE_BASE_H
14
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>
29
31 enum VehStatus {
32 VS_HIDDEN = 0x01,
33 VS_STOPPED = 0x02,
34 VS_UNCLICKABLE = 0x04,
35 VS_DEFPAL = 0x08,
36 VS_TRAIN_SLOWING = 0x10,
37 VS_SHADOW = 0x20,
38 VS_AIRCRAFT_BROKEN = 0x40,
39 VS_CRASHED = 0x80,
40 };
41
43 enum VehicleFlags {
44 VF_LOADING_FINISHED,
45 VF_CARGO_UNLOADING,
46 VF_BUILT_AS_PROTOTYPE,
47 VF_TIMETABLE_STARTED,
48 VF_AUTOFILL_TIMETABLE,
49 VF_AUTOFILL_PRES_WAIT_TIME,
50 VF_STOP_LOADING,
51 VF_PATHFINDER_LOST,
52 VF_SERVINT_IS_CUSTOM,
53 VF_SERVINT_IS_PERCENT,
54 };
55
57 enum NewGRFCacheValidValues {
58 NCVV_POSITION_CONSIST_LENGTH = 0,
59 NCVV_POSITION_SAME_ID_LENGTH = 1,
60 NCVV_CONSIST_CARGO_INFORMATION = 2,
61 NCVV_COMPANY_INFORMATION = 3,
62 NCVV_POSITION_IN_VEHICLE = 4,
63 NCVV_END,
64 };
65
67 struct NewGRFCache {
68 /* Values calculated when they are requested for the first time after invalidating the NewGRF cache. */
69 uint32 position_consist_length;
70 uint32 position_same_id_length;
71 uint32 consist_cargo_information;
72 uint32 company_information;
73 uint32 position_in_vehicle;
74 uint8 cache_valid;
75 };
76
78 enum VisualEffect {
79 VE_OFFSET_START = 0,
80 VE_OFFSET_COUNT = 4,
81 VE_OFFSET_CENTRE = 8,
82
83 VE_TYPE_START = 4,
84 VE_TYPE_COUNT = 2,
85 VE_TYPE_DEFAULT = 0,
86 VE_TYPE_STEAM = 1,
87 VE_TYPE_DIESEL = 2,
88 VE_TYPE_ELECTRIC = 3,
89
90 VE_DISABLE_EFFECT = 6,
91 VE_ADVANCED_EFFECT = VE_DISABLE_EFFECT,
92 VE_DISABLE_WAGON_POWER = 7,
93
94 VE_DEFAULT = 0xFF,
95 };
96
98 enum VisualEffectSpawnModel {
99 VESM_NONE = 0,
100 VESM_STEAM,
101 VESM_DIESEL,
102 VESM_ELECTRIC,
103
104 VESM_END
105 };
106
112 enum GroundVehicleSubtypeFlags {
113 GVSF_FRONT = 0,
114 GVSF_ARTICULATED_PART = 1,
115 GVSF_WAGON = 2,
116 GVSF_ENGINE = 3,
117 GVSF_FREE_WAGON = 4,
118 GVSF_MULTIHEADED = 5,
119 };
120
122 struct VehicleCache {
123 uint16 cached_max_speed;
124 uint16 cached_cargo_age_period;
125
126 byte cached_vis_effect;
127 };
128
130 typedef Pool<Vehicle, VehicleID, 512, 0xFF000> VehiclePool;
131 extern VehiclePool _vehicle_pool;
132
133 /* Some declarations of functions, so we can make them friendly */
134 struct SaveLoad;
135 struct GroundVehicleCache;
136 extern const SaveLoad *GetVehicleDescription(VehicleType vt);
137 struct LoadgameState;
138 extern bool LoadOldVehicle(LoadgameState *ls, int num);
139 extern void FixOldVehicles();
140
141 struct GRFFile;
142
146 struct RefitDesc {
147 CargoID cargo;
148 uint16 capacity;
149 uint16 remaining;
150 RefitDesc(CargoID cargo, uint16 capacity, uint16 remaining) :
151 cargo(cargo), capacity(capacity), remaining(remaining) {}
152 };
153
155 struct Vehicle : VehiclePool::PoolItem<&_vehicle_pool>, BaseVehicle, BaseConsist {
156 private:
157 typedef std::list<RefitDesc> RefitList;
158 typedef std::map<CargoID, uint> CapacitiesMap;
159
160 Vehicle *next;
161 Vehicle *previous;
162 Vehicle *first;
163
164 Vehicle *next_shared;
165 Vehicle *previous_shared;
166
167 public:
168 friend const SaveLoad *GetVehicleDescription(VehicleType vt);
169 friend void FixOldVehicles();
170 friend void AfterLoadVehicles(bool part_of_load);
171 friend bool LoadOldVehicle(LoadgameState *ls, int num);
172
173 TileIndex tile;
174
180 TileIndex dest_tile;
181
182 Money profit_this_year;
183 Money profit_last_year;
184 Money value;
185
186 CargoPayment *cargo_payment;
187
188 Rect coord;
189
190 Vehicle *hash_viewport_next;
191 Vehicle **hash_viewport_prev;
192
193 Vehicle *hash_tile_next;
194 Vehicle **hash_tile_prev;
195 Vehicle **hash_tile_current;
196
197 SpriteID colourmap;
198
199 /* Related to age and service time */
200 Year build_year;
201 Date age;
202 Date max_age;
203 Date date_of_last_service;
204 uint16 reliability;
205 uint16 reliability_spd_dec;
206 byte breakdown_ctr;
207 byte breakdown_delay;
208 byte breakdowns_since_last_service;
209 byte breakdown_chance;
210
211 int32 x_pos;
212 int32 y_pos;
213 int32 z_pos;
214 DirectionByte direction;
215
216 OwnerByte owner;
217
222 byte spritenum;
223 SpriteID cur_image;
224 byte x_extent;
225 byte y_extent;
226 byte z_extent;
227 int8 x_bb_offs;
228 int8 y_bb_offs;
229 int8 x_offs;
230 int8 y_offs;
231 EngineID engine_type;
232
233 TextEffectID fill_percent_te_id;
234 UnitID unitnumber;
235
236 uint16 cur_speed;
237 byte subspeed;
238 byte acceleration;
239 uint32 motion_counter;
240 byte progress;
241
242 byte random_bits;
243 byte waiting_triggers;
244
245 StationID last_station_visited;
246 StationID last_loading_station;
247
248 CargoID cargo_type;
249 byte cargo_subtype;
250 uint16 cargo_cap;
251 uint16 refit_cap;
252 VehicleCargoList cargo;
253 uint16 cargo_age_counter;
254
255 byte day_counter;
256 byte tick_counter;
257 byte running_ticks;
258
259 byte vehstatus;
260 Order current_order;
261
262 union {
263 OrderList *list;
264 Order *old;
265 } orders;
266
267 uint16 load_unload_ticks;
268 GroupID group_id;
269 byte subtype;
270
271 NewGRFCache grf_cache;
272 VehicleCache vcache;
273
274 Vehicle(VehicleType type = VEH_INVALID);
275
276 void PreDestructor();
278 virtual ~Vehicle();
279
280 void BeginLoading();
281 void CancelReservation(StationID next, Station *st);
282 void LeaveStation();
283
284 GroundVehicleCache *GetGroundVehicleCache();
285 const GroundVehicleCache *GetGroundVehicleCache() const;
286
287 uint16 &GetGroundVehicleFlags();
288 const uint16 &GetGroundVehicleFlags() const;
289
290 void DeleteUnreachedImplicitOrders();
291
292 void HandleLoading(bool mode = false);
293
294 void GetConsistFreeCapacities(SmallMap<CargoID, uint> &capacities) const;
295
296 uint GetConsistTotalCapacity() const;
297
306 virtual void MarkDirty() {}
307
313 virtual void UpdateDeltaXY(Direction direction) {}
314
328 inline uint GetOldAdvanceSpeed(uint speed)
329 {
330 return (this->direction & 1) ? speed : speed * 3 / 4;
331 }
332
345 static inline uint GetAdvanceSpeed(uint speed)
346 {
347 return speed * 3 / 4;
348 }
349
357 inline uint GetAdvanceDistance()
358 {
359 return (this->direction & 1) ? 192 : 256;
360 }
361
366 virtual ExpensesType GetExpenseType(bool income) const { return EXPENSES_OTHER; }
367
371 virtual void PlayLeaveStationSound() const {}
372
376 virtual bool IsPrimaryVehicle() const { return false; }
377
378 const Engine *GetEngine() const;
379
385 virtual SpriteID GetImage(Direction direction, EngineImageType image_type) const { return 0; }
386
387 const GRFFile *GetGRF() const;
388 uint32 GetGRFID() const;
389
394 inline void InvalidateNewGRFCache()
395 {
396 this->grf_cache.cache_valid = 0;
397 }
398
403 inline void InvalidateNewGRFCacheOfChain()
404 {
405 for (Vehicle *u = this; u != NULL; u = u->Next()) {
406 u->InvalidateNewGRFCache();
407 }
408 }
409
414 inline bool IsGroundVehicle() const
415 {
416 return this->type == VEH_TRAIN || this->type == VEH_ROAD;
417 }
418
423 virtual int GetDisplaySpeed() const { return 0; }
424
429 virtual int GetDisplayMaxSpeed() const { return 0; }
430
435 virtual int GetCurrentMaxSpeed() const { return 0; }
436
441 virtual Money GetRunningCost() const { return 0; }
442
447 virtual bool IsInDepot() const { return false; }
448
453 virtual bool IsChainInDepot() const { return this->IsInDepot(); }
454
459 bool IsStoppedInDepot() const
460 {
461 assert(this == this->First());
462 /* Free wagons have no VS_STOPPED state */
463 if (this->IsPrimaryVehicle() && !(this->vehstatus & VS_STOPPED)) return false;
464 return this->IsChainInDepot();
465 }
466
471 virtual bool Tick() { return true; };
472
476 virtual void OnNewDay() {};
477
483 virtual uint Crash(bool flooded = false);
484
497 virtual Trackdir GetVehicleTrackdir() const { return INVALID_TRACKDIR; }
498
503 Money GetDisplayRunningCost() const { return (this->GetRunningCost() >> 8); }
504
509 Money GetDisplayProfitThisYear() const { return (this->profit_this_year >> 8); }
510
515 Money GetDisplayProfitLastYear() const { return (this->profit_last_year >> 8); }
516
517 void SetNext(Vehicle *next);
518
524 inline Vehicle *Next() const { return this->next; }
525
531 inline Vehicle *Previous() const { return this->previous; }
532
537 inline Vehicle *First() const { return this->first; }
538
543 inline Vehicle *Last()
544 {
545 Vehicle *v = this;
546 while (v->Next() != NULL) v = v->Next();
547 return v;
548 }
549
554 inline const Vehicle *Last() const
555 {
556 const Vehicle *v = this;
557 while (v->Next() != NULL) v = v->Next();
558 return v;
559 }
560
566 inline Vehicle *Move(int n)
567 {
568 Vehicle *v = this;
569 if (n < 0) {
570 for (int i = 0; i != n && v != NULL; i--) v = v->Previous();
571 } else {
572 for (int i = 0; i != n && v != NULL; i++) v = v->Next();
573 }
574 return v;
575 }
576
582 inline const Vehicle *Move(int n) const
583 {
584 const Vehicle *v = this;
585 if (n < 0) {
586 for (int i = 0; i != n && v != NULL; i--) v = v->Previous();
587 } else {
588 for (int i = 0; i != n && v != NULL; i++) v = v->Next();
589 }
590 return v;
591 }
592
597 inline Order *GetFirstOrder() const { return (this->orders.list == NULL) ? NULL : this->orders.list->GetFirstOrder(); }
598
599 void AddToShared(Vehicle *shared_chain);
600 void RemoveFromShared();
601
606 inline Vehicle *NextShared() const { return this->next_shared; }
607
612 inline Vehicle *PreviousShared() const { return this->previous_shared; }
613
618 inline Vehicle *FirstShared() const { return (this->orders.list == NULL) ? this->First() : this->orders.list->GetFirstSharedVehicle(); }
619
624 inline bool IsOrderListShared() const { return this->orders.list != NULL && this->orders.list->IsShared(); }
625
630 inline VehicleOrderID GetNumOrders() const { return (this->orders.list == NULL) ? 0 : this->orders.list->GetNumOrders(); }
631
636 inline VehicleOrderID GetNumManualOrders() const { return (this->orders.list == NULL) ? 0 : this->orders.list->GetNumManualOrders(); }
637
642 inline StationIDStack GetNextStoppingStation() const
643 {
644 return (this->orders.list == NULL) ? INVALID_STATION : this->orders.list->GetNextStoppingStation(this);
645 }
646
647 void ResetRefitCaps();
648
655 inline void CopyVehicleConfigAndStatistics(const Vehicle *src)
656 {
657 this->CopyConsistPropertiesFrom(src);
658
659 this->unitnumber = src->unitnumber;
660
661 this->current_order = src->current_order;
662 this->dest_tile = src->dest_tile;
663
664 this->profit_this_year = src->profit_this_year;
665 this->profit_last_year = src->profit_last_year;
666 }
667
668
669 bool HandleBreakdown();
670
671 bool NeedsAutorenewing(const Company *c, bool use_renew_setting = true) const;
672
673 bool NeedsServicing() const;
674 bool NeedsAutomaticServicing() const;
675
683 virtual TileIndex GetOrderStationLocation(StationID station) { return INVALID_TILE; }
684
693 virtual bool FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse) { return false; }
694
695 CommandCost SendToDepot(DoCommandFlag flags, DepotCommand command);
696
697 void UpdateVisualEffect(bool allow_power_change = true);
698 void ShowVisualEffect() const;
699
700 void UpdatePosition();
701 void UpdateViewport(bool dirty);
702 void UpdatePositionAndViewport();
703 void MarkAllViewportsDirty() const;
704
705 inline uint16 GetServiceInterval() const { return this->service_interval; }
706
707 inline void SetServiceInterval(uint16 interval) { this->service_interval = interval; }
708
709 inline bool ServiceIntervalIsCustom() const { return HasBit(this->vehicle_flags, VF_SERVINT_IS_CUSTOM); }
710
711 inline bool ServiceIntervalIsPercent() const { return HasBit(this->vehicle_flags, VF_SERVINT_IS_PERCENT); }
712
713 inline void SetServiceIntervalIsCustom(bool on) { SB(this->vehicle_flags, VF_SERVINT_IS_CUSTOM, 1, on); }
714
715 inline void SetServiceIntervalIsPercent(bool on) { SB(this->vehicle_flags, VF_SERVINT_IS_PERCENT, 1, on); }
716
717 private:
722 void SkipToNextRealOrderIndex()
723 {
724 if (this->GetNumManualOrders() > 0) {
725 /* Advance to next real order */
726 do {
727 this->cur_real_order_index++;
728 if (this->cur_real_order_index >= this->GetNumOrders()) this->cur_real_order_index = 0;
729 } while (this->GetOrder(this->cur_real_order_index)->IsType(OT_IMPLICIT));
730 } else {
731 this->cur_real_order_index = 0;
732 }
733 }
734
735 public:
741 void IncrementImplicitOrderIndex()
742 {
743 if (this->cur_implicit_order_index == this->cur_real_order_index) {
744 /* Increment real order index as well */
745 this->SkipToNextRealOrderIndex();
746 }
747
748 assert(this->cur_real_order_index == 0 || this->cur_real_order_index < this->GetNumOrders());
749
750 /* Advance to next implicit order */
751 do {
752 this->cur_implicit_order_index++;
753 if (this->cur_implicit_order_index >= this->GetNumOrders()) this->cur_implicit_order_index = 0;
754 } while (this->cur_implicit_order_index != this->cur_real_order_index && !this->GetOrder(this->cur_implicit_order_index)->IsType(OT_IMPLICIT));
755
756 InvalidateVehicleOrder(this, 0);
757 }
758
765 void IncrementRealOrderIndex()
766 {
767 if (this->cur_implicit_order_index == this->cur_real_order_index) {
768 /* Increment both real and implicit order */
769 this->IncrementImplicitOrderIndex();
770 } else {
771 /* Increment real order only */
772 this->SkipToNextRealOrderIndex();
773 InvalidateVehicleOrder(this, 0);
774 }
775 }
776
780 void UpdateRealOrderIndex()
781 {
782 /* Make sure the index is valid */
783 if (this->cur_real_order_index >= this->GetNumOrders()) this->cur_real_order_index = 0;
784
785 if (this->GetNumManualOrders() > 0) {
786 /* Advance to next real order */
787 while (this->GetOrder(this->cur_real_order_index)->IsType(OT_IMPLICIT)) {
788 this->cur_real_order_index++;
789 if (this->cur_real_order_index >= this->GetNumOrders()) this->cur_real_order_index = 0;
790 }
791 } else {
792 this->cur_real_order_index = 0;
793 }
794 }
795
801 inline Order *GetOrder(int index) const
802 {
803 return (this->orders.list == NULL) ? NULL : this->orders.list->GetOrderAt(index);
804 }
805
810 inline Order *GetLastOrder() const
811 {
812 return (this->orders.list == NULL) ? NULL : this->orders.list->GetLastOrder();
813 }
814
815 bool IsEngineCountable() const;
816 bool HasEngineType() const;
817 bool HasDepotOrder() const;
818 void HandlePathfindingResult(bool path_found);
819
824 inline bool IsFrontEngine() const
825 {
826 return this->IsGroundVehicle() && HasBit(this->subtype, GVSF_FRONT);
827 }
828
833 inline bool IsArticulatedPart() const
834 {
835 return this->IsGroundVehicle() && HasBit(this->subtype, GVSF_ARTICULATED_PART);
836 }
837
842 inline bool HasArticulatedPart() const
843 {
844 return this->Next() != NULL && this->Next()->IsArticulatedPart();
845 }
846
852 inline Vehicle *GetNextArticulatedPart() const
853 {
854 assert(this->HasArticulatedPart());
855 return this->Next();
856 }
857
862 inline Vehicle *GetFirstEnginePart()
863 {
864 Vehicle *v = this;
865 while (v->IsArticulatedPart()) v = v->Previous();
866 return v;
867 }
868
873 inline const Vehicle *GetFirstEnginePart() const
874 {
875 const Vehicle *v = this;
876 while (v->IsArticulatedPart()) v = v->Previous();
877 return v;
878 }
879
884 inline Vehicle *GetLastEnginePart()
885 {
886 Vehicle *v = this;
887 while (v->HasArticulatedPart()) v = v->GetNextArticulatedPart();
888 return v;
889 }
890
895 inline Vehicle *GetNextVehicle() const
896 {
897 const Vehicle *v = this;
898 while (v->HasArticulatedPart()) v = v->GetNextArticulatedPart();
899
900 /* v now contains the last articulated part in the engine */
901 return v->Next();
902 }
903
908 inline Vehicle *GetPrevVehicle() const
909 {
910 Vehicle *v = this->Previous();
911 while (v != NULL && v->IsArticulatedPart()) v = v->Previous();
912
913 return v;
914 }
915 };
916
922 #define FOR_ALL_VEHICLES_FROM(var, start) FOR_ALL_ITEMS_FROM(Vehicle, vehicle_index, var, start)
923
928 #define FOR_ALL_VEHICLES(var) FOR_ALL_VEHICLES_FROM(var, 0)
929
934 template <class T, VehicleType Type>
935 struct SpecializedVehicle : public Vehicle {
936 static const VehicleType EXPECTED_TYPE = Type;
937
938 typedef SpecializedVehicle<T, Type> SpecializedVehicleBase;
939
943 inline SpecializedVehicle<T, Type>() : Vehicle(Type) { }
944
949 inline T *First() const { return (T *)this->Vehicle::First(); }
950
955 inline T *Last() { return (T *)this->Vehicle::Last(); }
956
961 inline const T *Last() const { return (const T *)this->Vehicle::Last(); }
962
967 inline T *Next() const { return (T *)this->Vehicle::Next(); }
968
973 inline T *Previous() const { return (T *)this->Vehicle::Previous(); }
974
980 inline T *GetNextArticulatedPart() { return (T *)this->Vehicle::GetNextArticulatedPart(); }
981
987 inline T *GetNextArticulatedPart() const { return (T *)this->Vehicle::GetNextArticulatedPart(); }
988
993 inline T *GetFirstEnginePart() { return (T *)this->Vehicle::GetFirstEnginePart(); }
994
999 inline const T *GetFirstEnginePart() const { return (const T *)this->Vehicle::GetFirstEnginePart(); }
1000
1005 inline T *GetLastEnginePart() { return (T *)this->Vehicle::GetLastEnginePart(); }
1006
1011 inline T *GetNextVehicle() const { return (T *)this->Vehicle::GetNextVehicle(); }
1012
1017 inline T *GetPrevVehicle() const { return (T *)this->Vehicle::GetPrevVehicle(); }
1018
1024 static inline bool IsValidID(size_t index)
1025 {
1026 return Vehicle::IsValidID(index) && Vehicle::Get(index)->type == Type;
1027 }
1028
1033 static inline T *Get(size_t index)
1034 {
1035 return (T *)Vehicle::Get(index);
1036 }
1037
1042 static inline T *GetIfValid(size_t index)
1043 {
1044 return IsValidID(index) ? Get(index) : NULL;
1045 }
1046
1052 static inline T *From(Vehicle *v)
1053 {
1054 assert(v->type == Type);
1055 return (T *)v;
1056 }
1057
1063 static inline const T *From(const Vehicle *v)
1064 {
1065 assert(v->type == Type);
1066 return (const T *)v;
1067 }
1068
1074 inline void UpdateViewport(bool force_update, bool update_delta)
1075 {
1076 /* Skip updating sprites on dedicated servers without screen */
1077 if (_network_dedicated) return;
1078
1079 /* Explicitly choose method to call to prevent vtable dereference -
1080 * it gives ~3% runtime improvements in games with many vehicles */
1081 if (update_delta) ((T *)this)->T::UpdateDeltaXY(this->direction);
1082 SpriteID old_image = this->cur_image;
1083 this->cur_image = ((T *)this)->T::GetImage(this->direction, EIT_ON_MAP);
1084 if (force_update || this->cur_image != old_image) this->Vehicle::UpdateViewport(true);
1085 }
1086 };
1087
1093 #define FOR_ALL_VEHICLES_OF_TYPE(name, var) FOR_ALL_ITEMS_FROM(name, vehicle_index, var, 0) if (var->type == name::EXPECTED_TYPE)
1094
1096 struct FreeUnitIDGenerator {
1097 bool *cache;
1098 UnitID maxid;
1099 UnitID curid;
1100
1101 FreeUnitIDGenerator(VehicleType type, CompanyID owner);
1102 UnitID NextID();
1103
1105 ~FreeUnitIDGenerator() { free(this->cache); }
1106 };
1107
1109 static const int32 INVALID_COORD = 0x7fffffff;
1110
1111 #endif /* VEHICLE_BASE_H */