vehicle_base.h

Go to the documentation of this file.
00001 /* $Id$ */
00002 
00003 /*
00004  * This file is part of OpenTTD.
00005  * 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.
00006  * 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.
00007  * 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/>.
00008  */
00009 
00012 #ifndef VEHICLE_BASE_H
00013 #define VEHICLE_BASE_H
00014 
00015 #include "core/smallmap_type.hpp"
00016 #include "track_type.h"
00017 #include "command_type.h"
00018 #include "order_base.h"
00019 #include "cargopacket.h"
00020 #include "texteff.hpp"
00021 #include "engine_type.h"
00022 #include "order_func.h"
00023 #include "transport_type.h"
00024 #include "group_type.h"
00025 #include "base_consist.h"
00026 
00028 enum VehStatus {
00029   VS_HIDDEN          = 0x01, 
00030   VS_STOPPED         = 0x02, 
00031   VS_UNCLICKABLE     = 0x04, 
00032   VS_DEFPAL          = 0x08, 
00033   VS_TRAIN_SLOWING   = 0x10, 
00034   VS_SHADOW          = 0x20, 
00035   VS_AIRCRAFT_BROKEN = 0x40, 
00036   VS_CRASHED         = 0x80, 
00037 };
00038 
00040 enum VehicleFlags {
00041   VF_LOADING_FINISHED,        
00042   VF_CARGO_UNLOADING,         
00043   VF_BUILT_AS_PROTOTYPE,      
00044   VF_TIMETABLE_STARTED,       
00045   VF_AUTOFILL_TIMETABLE,      
00046   VF_AUTOFILL_PRES_WAIT_TIME, 
00047   VF_STOP_LOADING,            
00048   VF_PATHFINDER_LOST,         
00049 };
00050 
00052 enum NewGRFCacheValidValues {
00053   NCVV_POSITION_CONSIST_LENGTH   = 0, 
00054   NCVV_POSITION_SAME_ID_LENGTH   = 1, 
00055   NCVV_CONSIST_CARGO_INFORMATION = 2, 
00056   NCVV_COMPANY_INFORMATION       = 3, 
00057   NCVV_END,                           
00058 };
00059 
00061 struct NewGRFCache {
00062   /* Values calculated when they are requested for the first time after invalidating the NewGRF cache. */
00063   uint32 position_consist_length;   
00064   uint32 position_same_id_length;   
00065   uint32 consist_cargo_information; 
00066   uint32 company_information;       
00067   uint8  cache_valid;               
00068 };
00069 
00071 enum VisualEffect {
00072   VE_OFFSET_START        = 0, 
00073   VE_OFFSET_COUNT        = 4, 
00074   VE_OFFSET_CENTRE       = 8, 
00075 
00076   VE_TYPE_START          = 4, 
00077   VE_TYPE_COUNT          = 2, 
00078   VE_TYPE_DEFAULT        = 0, 
00079   VE_TYPE_STEAM          = 1, 
00080   VE_TYPE_DIESEL         = 2, 
00081   VE_TYPE_ELECTRIC       = 3, 
00082 
00083   VE_DISABLE_EFFECT      = 6, 
00084   VE_DISABLE_WAGON_POWER = 7, 
00085 
00086   VE_DEFAULT = 0xFF,          
00087 };
00088 
00094 enum GroundVehicleSubtypeFlags {
00095   GVSF_FRONT            = 0, 
00096   GVSF_ARTICULATED_PART = 1, 
00097   GVSF_WAGON            = 2, 
00098   GVSF_ENGINE           = 3, 
00099   GVSF_FREE_WAGON       = 4, 
00100   GVSF_MULTIHEADED      = 5, 
00101 };
00102 
00104 struct VehicleCache {
00105   uint16 cached_max_speed;        
00106   uint16 cached_cargo_age_period; 
00107 
00108   byte cached_vis_effect;  
00109 };
00110 
00112 typedef Pool<Vehicle, VehicleID, 512, 0xFF000> VehiclePool;
00113 extern VehiclePool _vehicle_pool;
00114 
00115 /* Some declarations of functions, so we can make them friendly */
00116 struct SaveLoad;
00117 struct GroundVehicleCache;
00118 extern const SaveLoad *GetVehicleDescription(VehicleType vt);
00119 struct LoadgameState;
00120 extern bool LoadOldVehicle(LoadgameState *ls, int num);
00121 extern void FixOldVehicles();
00122 
00123 struct GRFFile;
00124 
00126 struct Vehicle : VehiclePool::PoolItem<&_vehicle_pool>, BaseVehicle, BaseConsist {
00127 private:
00128   Vehicle *next;                      
00129   Vehicle *previous;                  
00130   Vehicle *first;                     
00131 
00132   Vehicle *next_shared;               
00133   Vehicle *previous_shared;           
00134 
00135 public:
00136   friend const SaveLoad *GetVehicleDescription(VehicleType vt); 
00137   friend void FixOldVehicles();
00138   friend void AfterLoadVehicles(bool part_of_load);             
00139   friend bool LoadOldVehicle(LoadgameState *ls, int num);       
00140 
00141   TileIndex tile;                     
00142 
00148   TileIndex dest_tile;
00149 
00150   Money profit_this_year;             
00151   Money profit_last_year;             
00152   Money value;                        
00153 
00154   CargoPayment *cargo_payment;        
00155 
00156   Rect coord;                         
00157 
00158   Vehicle *hash_viewport_next;        
00159   Vehicle **hash_viewport_prev;       
00160 
00161   Vehicle *hash_tile_next;            
00162   Vehicle **hash_tile_prev;           
00163   Vehicle **hash_tile_current;        
00164 
00165   SpriteID colourmap;                 
00166 
00167   /* Related to age and service time */
00168   Year build_year;                    
00169   Date age;                           
00170   Date max_age;                       
00171   Date date_of_last_service;          
00172   uint16 reliability;                 
00173   uint16 reliability_spd_dec;         
00174   byte breakdown_ctr;                 
00175   byte breakdown_delay;               
00176   byte breakdowns_since_last_service; 
00177   byte breakdown_chance;              
00178 
00179   int32 x_pos;                        
00180   int32 y_pos;                        
00181   int32 z_pos;                        
00182   DirectionByte direction;            
00183 
00184   OwnerByte owner;                    
00185 
00190   byte spritenum;
00191   SpriteID cur_image;                 
00192   byte x_extent;                      
00193   byte y_extent;                      
00194   byte z_extent;                      
00195   int8 x_bb_offs;                     
00196   int8 y_bb_offs;                     
00197   int8 x_offs;                        
00198   int8 y_offs;                        
00199   EngineID engine_type;               
00200 
00201   TextEffectID fill_percent_te_id;    
00202   UnitID unitnumber;                  
00203 
00204   uint16 cur_speed;                   
00205   byte subspeed;                      
00206   byte acceleration;                  
00207   uint32 motion_counter;              
00208   byte progress;                      
00209 
00210   byte random_bits;                   
00211   byte waiting_triggers;              
00212 
00213   StationID last_station_visited;     
00214   StationID last_loading_station;     
00215 
00216   CargoID cargo_type;                 
00217   byte cargo_subtype;                 
00218   uint16 cargo_cap;                   
00219   uint16 refit_cap;                   
00220   VehicleCargoList cargo;             
00221   uint16 cargo_age_counter;           
00222 
00223   byte day_counter;                   
00224   byte tick_counter;                  
00225   byte running_ticks;                 
00226 
00227   byte vehstatus;                     
00228   Order current_order;                
00229 
00230   union {
00231     OrderList *list;            
00232     Order     *old;             
00233   } orders;                           
00234 
00235   uint16 load_unload_ticks;           
00236   GroupID group_id;                   
00237   byte subtype;                       
00238 
00239   NewGRFCache grf_cache;              
00240   VehicleCache vcache;                
00241 
00242   Vehicle(VehicleType type = VEH_INVALID);
00243 
00244   void PreDestructor();
00246   virtual ~Vehicle();
00247 
00248   void BeginLoading();
00249   void CancelReservation(StationID next, Station *st);
00250   void LeaveStation();
00251 
00252   GroundVehicleCache *GetGroundVehicleCache();
00253   const GroundVehicleCache *GetGroundVehicleCache() const;
00254 
00255   uint16 &GetGroundVehicleFlags();
00256   const uint16 &GetGroundVehicleFlags() const;
00257 
00258   void DeleteUnreachedImplicitOrders();
00259 
00260   void HandleLoading(bool mode = false);
00261 
00262   void GetConsistFreeCapacities(SmallMap<CargoID, uint> &capacities) const;
00263 
00264   uint GetConsistTotalCapacity() const;
00265 
00274   virtual void MarkDirty() {}
00275 
00281   virtual void UpdateDeltaXY(Direction direction) {}
00282 
00296   inline uint GetOldAdvanceSpeed(uint speed)
00297   {
00298     return (this->direction & 1) ? speed : speed * 3 / 4;
00299   }
00300 
00313   static inline uint GetAdvanceSpeed(uint speed)
00314   {
00315     return speed * 3 / 4;
00316   }
00317 
00325   inline uint GetAdvanceDistance()
00326   {
00327     return (this->direction & 1) ? 192 : 256;
00328   }
00329 
00334   virtual ExpensesType GetExpenseType(bool income) const { return EXPENSES_OTHER; }
00335 
00339   virtual void PlayLeaveStationSound() const {}
00340 
00344   virtual bool IsPrimaryVehicle() const { return false; }
00345 
00346   const Engine *GetEngine() const;
00347 
00353   virtual SpriteID GetImage(Direction direction, EngineImageType image_type) const { return 0; }
00354 
00355   const GRFFile *GetGRF() const;
00356   uint32 GetGRFID() const;
00357 
00362   inline void InvalidateNewGRFCache()
00363   {
00364     this->grf_cache.cache_valid = 0;
00365   }
00366 
00371   inline void InvalidateNewGRFCacheOfChain()
00372   {
00373     for (Vehicle *u = this; u != NULL; u = u->Next()) {
00374       u->InvalidateNewGRFCache();
00375     }
00376   }
00377 
00382   inline bool IsGroundVehicle() const
00383   {
00384     return this->type == VEH_TRAIN || this->type == VEH_ROAD;
00385   }
00386 
00391   virtual int GetDisplaySpeed() const { return 0; }
00392 
00397   virtual int GetDisplayMaxSpeed() const { return 0; }
00398 
00403   virtual int GetCurrentMaxSpeed() const { return 0; }
00404 
00409   virtual Money GetRunningCost() const { return 0; }
00410 
00415   virtual bool IsInDepot() const { return false; }
00416 
00421   virtual bool IsChainInDepot() const { return this->IsInDepot(); }
00422 
00427   bool IsStoppedInDepot() const
00428   {
00429     assert(this == this->First());
00430     /* Free wagons have no VS_STOPPED state */
00431     if (this->IsPrimaryVehicle() && !(this->vehstatus & VS_STOPPED)) return false;
00432     return this->IsChainInDepot();
00433   }
00434 
00439   virtual bool Tick() { return true; };
00440 
00444   virtual void OnNewDay() {};
00445 
00451   virtual uint Crash(bool flooded = false);
00452 
00465   virtual Trackdir GetVehicleTrackdir() const { return INVALID_TRACKDIR; }
00466 
00471   Money GetDisplayRunningCost() const { return (this->GetRunningCost() >> 8); }
00472 
00477   Money GetDisplayProfitThisYear() const { return (this->profit_this_year >> 8); }
00478 
00483   Money GetDisplayProfitLastYear() const { return (this->profit_last_year >> 8); }
00484 
00485   void SetNext(Vehicle *next);
00486 
00492   inline Vehicle *Next() const { return this->next; }
00493 
00499   inline Vehicle *Previous() const { return this->previous; }
00500 
00505   inline Vehicle *First() const { return this->first; }
00506 
00511   inline Vehicle *Last()
00512   {
00513     Vehicle *v = this;
00514     while (v->Next() != NULL) v = v->Next();
00515     return v;
00516   }
00517 
00522   inline const Vehicle *Last() const
00523   {
00524     const Vehicle *v = this;
00525     while (v->Next() != NULL) v = v->Next();
00526     return v;
00527   }
00528 
00534   inline Vehicle *Move(int n)
00535   {
00536     Vehicle *v = this;
00537     if (n < 0) {
00538       for (int i = 0; i != n && v != NULL; i--) v = v->Previous();
00539     } else {
00540       for (int i = 0; i != n && v != NULL; i++) v = v->Next();
00541     }
00542     return v;
00543   }
00544 
00549   inline Order *GetFirstOrder() const { return (this->orders.list == NULL) ? NULL : this->orders.list->GetFirstOrder(); }
00550 
00551   void AddToShared(Vehicle *shared_chain);
00552   void RemoveFromShared();
00553 
00558   inline Vehicle *NextShared() const { return this->next_shared; }
00559 
00564   inline Vehicle *PreviousShared() const { return this->previous_shared; }
00565 
00570   inline Vehicle *FirstShared() const { return (this->orders.list == NULL) ? this->First() : this->orders.list->GetFirstSharedVehicle(); }
00571 
00576   inline bool IsOrderListShared() const { return this->orders.list != NULL && this->orders.list->IsShared(); }
00577 
00582   inline VehicleOrderID GetNumOrders() const { return (this->orders.list == NULL) ? 0 : this->orders.list->GetNumOrders(); }
00583 
00588   inline VehicleOrderID GetNumManualOrders() const { return (this->orders.list == NULL) ? 0 : this->orders.list->GetNumManualOrders(); }
00589 
00594   inline StationID GetNextStoppingStation() const
00595   {
00596     return (this->orders.list == NULL) ? INVALID_STATION : this->orders.list->GetNextStoppingStation(this);
00597   }
00598 
00599   void RefreshNextHopsStats();
00600 
00607   inline void CopyVehicleConfigAndStatistics(const Vehicle *src)
00608   {
00609     this->CopyConsistPropertiesFrom(src);
00610 
00611     this->unitnumber = src->unitnumber;
00612 
00613     this->current_order = src->current_order;
00614     this->dest_tile  = src->dest_tile;
00615 
00616     this->profit_this_year = src->profit_this_year;
00617     this->profit_last_year = src->profit_last_year;
00618   }
00619 
00620 
00621   bool HandleBreakdown();
00622 
00623   bool NeedsAutorenewing(const Company *c, bool use_renew_setting = true) const;
00624 
00625   bool NeedsServicing() const;
00626   bool NeedsAutomaticServicing() const;
00627 
00635   virtual TileIndex GetOrderStationLocation(StationID station) { return INVALID_TILE; }
00636 
00645   virtual bool FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse) { return false; }
00646 
00647   CommandCost SendToDepot(DoCommandFlag flags, DepotCommand command);
00648 
00649   void UpdateVisualEffect(bool allow_power_change = true);
00650   void ShowVisualEffect() const;
00651 
00652 private:
00657   void SkipToNextRealOrderIndex()
00658   {
00659     if (this->GetNumManualOrders() > 0) {
00660       /* Advance to next real order */
00661       do {
00662         this->cur_real_order_index++;
00663         if (this->cur_real_order_index >= this->GetNumOrders()) this->cur_real_order_index = 0;
00664       } while (this->GetOrder(this->cur_real_order_index)->IsType(OT_IMPLICIT));
00665     } else {
00666       this->cur_real_order_index = 0;
00667     }
00668   }
00669 
00670 public:
00676   void IncrementImplicitOrderIndex()
00677   {
00678     if (this->cur_implicit_order_index == this->cur_real_order_index) {
00679       /* Increment real order index as well */
00680       this->SkipToNextRealOrderIndex();
00681     }
00682 
00683     assert(this->cur_real_order_index == 0 || this->cur_real_order_index < this->GetNumOrders());
00684 
00685     /* Advance to next implicit order */
00686     do {
00687       this->cur_implicit_order_index++;
00688       if (this->cur_implicit_order_index >= this->GetNumOrders()) this->cur_implicit_order_index = 0;
00689     } while (this->cur_implicit_order_index != this->cur_real_order_index && !this->GetOrder(this->cur_implicit_order_index)->IsType(OT_IMPLICIT));
00690 
00691     InvalidateVehicleOrder(this, 0);
00692   }
00693 
00700   void IncrementRealOrderIndex()
00701   {
00702     if (this->cur_implicit_order_index == this->cur_real_order_index) {
00703       /* Increment both real and implicit order */
00704       this->IncrementImplicitOrderIndex();
00705     } else {
00706       /* Increment real order only */
00707       this->SkipToNextRealOrderIndex();
00708       InvalidateVehicleOrder(this, 0);
00709     }
00710   }
00711 
00715   void UpdateRealOrderIndex()
00716   {
00717     /* Make sure the index is valid */
00718     if (this->cur_real_order_index >= this->GetNumOrders()) this->cur_real_order_index = 0;
00719 
00720     if (this->GetNumManualOrders() > 0) {
00721       /* Advance to next real order */
00722       while (this->GetOrder(this->cur_real_order_index)->IsType(OT_IMPLICIT)) {
00723         this->cur_real_order_index++;
00724         if (this->cur_real_order_index >= this->GetNumOrders()) this->cur_real_order_index = 0;
00725       }
00726     } else {
00727       this->cur_real_order_index = 0;
00728     }
00729   }
00730 
00736   inline Order *GetOrder(int index) const
00737   {
00738     return (this->orders.list == NULL) ? NULL : this->orders.list->GetOrderAt(index);
00739   }
00740 
00745   inline Order *GetLastOrder() const
00746   {
00747     return (this->orders.list == NULL) ? NULL : this->orders.list->GetLastOrder();
00748   }
00749 
00750   bool IsEngineCountable() const;
00751   bool HasEngineType() const;
00752   bool HasDepotOrder() const;
00753   void HandlePathfindingResult(bool path_found);
00754 
00759   inline bool IsFrontEngine() const
00760   {
00761     return this->IsGroundVehicle() && HasBit(this->subtype, GVSF_FRONT);
00762   }
00763 
00768   inline bool IsArticulatedPart() const
00769   {
00770     return this->IsGroundVehicle() && HasBit(this->subtype, GVSF_ARTICULATED_PART);
00771   }
00772 
00777   inline bool HasArticulatedPart() const
00778   {
00779     return this->Next() != NULL && this->Next()->IsArticulatedPart();
00780   }
00781 
00787   inline Vehicle *GetNextArticulatedPart() const
00788   {
00789     assert(this->HasArticulatedPart());
00790     return this->Next();
00791   }
00792 
00797   inline Vehicle *GetFirstEnginePart()
00798   {
00799     Vehicle *v = this;
00800     while (v->IsArticulatedPart()) v = v->Previous();
00801     return v;
00802   }
00803 
00808   inline const Vehicle *GetFirstEnginePart() const
00809   {
00810     const Vehicle *v = this;
00811     while (v->IsArticulatedPart()) v = v->Previous();
00812     return v;
00813   }
00814 
00819   inline Vehicle *GetLastEnginePart()
00820   {
00821     Vehicle *v = this;
00822     while (v->HasArticulatedPart()) v = v->GetNextArticulatedPart();
00823     return v;
00824   }
00825 
00830   inline Vehicle *GetNextVehicle() const
00831   {
00832     const Vehicle *v = this;
00833     while (v->HasArticulatedPart()) v = v->GetNextArticulatedPart();
00834 
00835     /* v now contains the last articulated part in the engine */
00836     return v->Next();
00837   }
00838 
00843   inline Vehicle *GetPrevVehicle() const
00844   {
00845     Vehicle *v = this->Previous();
00846     while (v != NULL && v->IsArticulatedPart()) v = v->Previous();
00847 
00848     return v;
00849   }
00850 };
00851 
00857 #define FOR_ALL_VEHICLES_FROM(var, start) FOR_ALL_ITEMS_FROM(Vehicle, vehicle_index, var, start)
00858 
00863 #define FOR_ALL_VEHICLES(var) FOR_ALL_VEHICLES_FROM(var, 0)
00864 
00869 template <class T, VehicleType Type>
00870 struct SpecializedVehicle : public Vehicle {
00871   static const VehicleType EXPECTED_TYPE = Type; 
00872 
00873   typedef SpecializedVehicle<T, Type> SpecializedVehicleBase; 
00874 
00878   inline SpecializedVehicle<T, Type>() : Vehicle(Type) { }
00879 
00884   inline T *First() const { return (T *)this->Vehicle::First(); }
00885 
00890   inline T *Last() { return (T *)this->Vehicle::Last(); }
00891 
00896   inline const T *Last() const { return (const T *)this->Vehicle::Last(); }
00897 
00902   inline T *Next() const { return (T *)this->Vehicle::Next(); }
00903 
00908   inline T *Previous() const { return (T *)this->Vehicle::Previous(); }
00909 
00915   inline T *GetNextArticulatedPart() { return (T *)this->Vehicle::GetNextArticulatedPart(); }
00916 
00922   inline T *GetNextArticulatedPart() const { return (T *)this->Vehicle::GetNextArticulatedPart(); }
00923 
00928   inline T *GetFirstEnginePart() { return (T *)this->Vehicle::GetFirstEnginePart(); }
00929 
00934   inline const T *GetFirstEnginePart() const { return (const T *)this->Vehicle::GetFirstEnginePart(); }
00935 
00940   inline T *GetLastEnginePart() { return (T *)this->Vehicle::GetLastEnginePart(); }
00941 
00946   inline T *GetNextVehicle() const { return (T *)this->Vehicle::GetNextVehicle(); }
00947 
00952   inline T *GetPrevVehicle() const { return (T *)this->Vehicle::GetPrevVehicle(); }
00953 
00959   static inline bool IsValidID(size_t index)
00960   {
00961     return Vehicle::IsValidID(index) && Vehicle::Get(index)->type == Type;
00962   }
00963 
00968   static inline T *Get(size_t index)
00969   {
00970     return (T *)Vehicle::Get(index);
00971   }
00972 
00977   static inline T *GetIfValid(size_t index)
00978   {
00979     return IsValidID(index) ? Get(index) : NULL;
00980   }
00981 
00987   static inline T *From(Vehicle *v)
00988   {
00989     assert(v->type == Type);
00990     return (T *)v;
00991   }
00992 
00998   static inline const T *From(const Vehicle *v)
00999   {
01000     assert(v->type == Type);
01001     return (const T *)v;
01002   }
01003 
01009   inline void UpdateViewport(bool force_update, bool update_delta)
01010   {
01011     extern void VehicleUpdateViewport(Vehicle *v, bool dirty);
01012 
01013     /* Explicitly choose method to call to prevent vtable dereference -
01014      * it gives ~3% runtime improvements in games with many vehicles */
01015     if (update_delta) ((T *)this)->T::UpdateDeltaXY(this->direction);
01016     SpriteID old_image = this->cur_image;
01017     this->cur_image = ((T *)this)->T::GetImage(this->direction, EIT_ON_MAP);
01018     if (force_update || this->cur_image != old_image) VehicleUpdateViewport(this, true);
01019   }
01020 };
01021 
01027 #define FOR_ALL_VEHICLES_OF_TYPE(name, var) FOR_ALL_ITEMS_FROM(name, vehicle_index, var, 0) if (var->type == name::EXPECTED_TYPE)
01028 
01032 struct DisasterVehicle FINAL : public SpecializedVehicle<DisasterVehicle, VEH_DISASTER> {
01033   SpriteID image_override;            
01034   VehicleID big_ufo_destroyer_target; 
01035 
01037   DisasterVehicle() : SpecializedVehicleBase() {}
01039   virtual ~DisasterVehicle() {}
01040 
01041   void UpdateDeltaXY(Direction direction);
01042   bool Tick();
01043 };
01044 
01049 #define FOR_ALL_DISASTERVEHICLES(var) FOR_ALL_VEHICLES_OF_TYPE(DisasterVehicle, var)
01050 
01052 struct FreeUnitIDGenerator {
01053   bool *cache;  
01054   UnitID maxid; 
01055   UnitID curid; 
01056 
01057   FreeUnitIDGenerator(VehicleType type, CompanyID owner);
01058   UnitID NextID();
01059 
01061   ~FreeUnitIDGenerator() { free(this->cache); }
01062 };
01063 
01065 static const int32 INVALID_COORD = 0x7fffffff;
01066 
01067 #endif /* VEHICLE_BASE_H */