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/>.
8 /** @file roadveh_cmd.cpp Handling of road vehicles. */
12 #include "command_func.h"
13 #include "error_func.h"
14 #include "news_func.h"
15 #include "station_base.h"
16 #include "company_func.h"
17 #include "articulated_vehicles.h"
18 #include "newgrf_sound.h"
19 #include "pathfinder/yapf/yapf.h"
20 #include "strings_func.h"
21 #include "tunnelbridge_map.h"
22 #include "timer/timer_game_calendar.h"
23 #include "timer/timer_game_economy.h"
24 #include "vehicle_func.h"
25 #include "sound_func.h"
27 #include "game/game.hpp"
28 #include "depot_map.h"
29 #include "effectvehicle_func.h"
30 #include "roadstop_base.h"
31 #include "spritecache.h"
32 #include "core/random_func.hpp"
33 #include "company_base.h"
34 #include "core/backup_type.hpp"
36 #include "zoom_func.h"
37 #include "framerate_type.h"
38 #include "roadveh_cmd.h"
41 #include "table/strings.h"
43 #include "safeguards.h"
45 static const uint16_t _roadveh_images
[] = {
46 0xCD4, 0xCDC, 0xCE4, 0xCEC, 0xCF4, 0xCFC, 0xD0C, 0xD14,
47 0xD24, 0xD1C, 0xD2C, 0xD04, 0xD1C, 0xD24, 0xD6C, 0xD74,
48 0xD7C, 0xC14, 0xC1C, 0xC24, 0xC2C, 0xC34, 0xC3C, 0xC4C,
49 0xC54, 0xC64, 0xC5C, 0xC6C, 0xC44, 0xC5C, 0xC64, 0xCAC,
50 0xCB4, 0xCBC, 0xD94, 0xD9C, 0xDA4, 0xDAC, 0xDB4, 0xDBC,
51 0xDCC, 0xDD4, 0xDE4, 0xDDC, 0xDEC, 0xDC4, 0xDDC, 0xDE4,
52 0xE2C, 0xE34, 0xE3C, 0xC14, 0xC1C, 0xC2C, 0xC3C, 0xC4C,
53 0xC5C, 0xC64, 0xC6C, 0xC74, 0xC84, 0xC94, 0xCA4
56 static const uint16_t _roadveh_full_adder
[] = {
57 0, 88, 0, 0, 0, 0, 48, 48,
58 48, 48, 0, 0, 64, 64, 0, 16,
59 16, 0, 88, 0, 0, 0, 0, 48,
60 48, 48, 48, 0, 0, 64, 64, 0,
61 16, 16, 0, 88, 0, 0, 0, 0,
62 48, 48, 48, 48, 0, 0, 64, 64,
63 0, 16, 16, 0, 8, 8, 8, 8,
66 static_assert(lengthof(_roadveh_images
) == lengthof(_roadveh_full_adder
));
69 bool IsValidImageIndex
<VEH_ROAD
>(uint8_t image_index
)
71 return image_index
< lengthof(_roadveh_images
);
74 static const Trackdir _road_reverse_table
[DIAGDIR_END
] = {
75 TRACKDIR_RVREV_NE
, TRACKDIR_RVREV_SE
, TRACKDIR_RVREV_SW
, TRACKDIR_RVREV_NW
79 * Check whether a roadvehicle is a bus
82 bool RoadVehicle::IsBus() const
84 assert(this->IsFrontEngine());
85 return IsCargoInClass(this->cargo_type
, CC_PASSENGERS
);
89 * Get the width of a road vehicle image in the GUI.
90 * @param offset Additional offset for positioning the sprite; set to nullptr if not needed
91 * @return Width in pixels
93 int RoadVehicle::GetDisplayImageWidth(Point
*offset
) const
95 int reference_width
= ROADVEHINFO_DEFAULT_VEHICLE_WIDTH
;
97 if (offset
!= nullptr) {
98 offset
->x
= ScaleSpriteTrad(reference_width
) / 2;
101 return ScaleSpriteTrad(this->gcache
.cached_veh_length
* reference_width
/ VEHICLE_LENGTH
);
104 static void GetRoadVehIcon(EngineID engine
, EngineImageType image_type
, VehicleSpriteSeq
*result
)
106 const Engine
*e
= Engine::Get(engine
);
107 uint8_t spritenum
= e
->u
.road
.image_index
;
109 if (is_custom_sprite(spritenum
)) {
110 GetCustomVehicleIcon(engine
, DIR_W
, image_type
, result
);
111 if (result
->IsValid()) return;
113 spritenum
= e
->original_image_index
;
116 assert(IsValidImageIndex
<VEH_ROAD
>(spritenum
));
117 result
->Set(DIR_W
+ _roadveh_images
[spritenum
]);
120 void RoadVehicle::GetImage(Direction direction
, EngineImageType image_type
, VehicleSpriteSeq
*result
) const
122 uint8_t spritenum
= this->spritenum
;
124 if (is_custom_sprite(spritenum
)) {
125 GetCustomVehicleSprite(this, (Direction
)(direction
+ 4 * IS_CUSTOM_SECONDHEAD_SPRITE(spritenum
)), image_type
, result
);
126 if (result
->IsValid()) return;
128 spritenum
= this->GetEngine()->original_image_index
;
131 assert(IsValidImageIndex
<VEH_ROAD
>(spritenum
));
132 SpriteID sprite
= direction
+ _roadveh_images
[spritenum
];
134 if (this->cargo
.StoredCount() >= this->cargo_cap
/ 2U) sprite
+= _roadveh_full_adder
[spritenum
];
140 * Draw a road vehicle engine.
141 * @param left Left edge to draw within.
142 * @param right Right edge to draw within.
143 * @param preferred_x Preferred position of the engine.
144 * @param y Vertical position of the engine.
145 * @param engine Engine to draw
146 * @param pal Palette to use.
148 void DrawRoadVehEngine(int left
, int right
, int preferred_x
, int y
, EngineID engine
, PaletteID pal
, EngineImageType image_type
)
150 VehicleSpriteSeq seq
;
151 GetRoadVehIcon(engine
, image_type
, &seq
);
154 seq
.GetBounds(&rect
);
155 preferred_x
= Clamp(preferred_x
,
156 left
- UnScaleGUI(rect
.left
),
157 right
- UnScaleGUI(rect
.right
));
159 seq
.Draw(preferred_x
, y
, pal
, pal
== PALETTE_CRASH
);
163 * Get the size of the sprite of a road vehicle sprite heading west (used for lists).
164 * @param engine The engine to get the sprite from.
165 * @param[out] width The width of the sprite.
166 * @param[out] height The height of the sprite.
167 * @param[out] xoffs Number of pixels to shift the sprite to the right.
168 * @param[out] yoffs Number of pixels to shift the sprite downwards.
169 * @param image_type Context the sprite is used in.
171 void GetRoadVehSpriteSize(EngineID engine
, uint
&width
, uint
&height
, int &xoffs
, int &yoffs
, EngineImageType image_type
)
173 VehicleSpriteSeq seq
;
174 GetRoadVehIcon(engine
, image_type
, &seq
);
177 seq
.GetBounds(&rect
);
179 width
= UnScaleGUI(rect
.Width());
180 height
= UnScaleGUI(rect
.Height());
181 xoffs
= UnScaleGUI(rect
.left
);
182 yoffs
= UnScaleGUI(rect
.top
);
186 * Get length of a road vehicle.
187 * @param v Road vehicle to query length.
188 * @return Length of the given road vehicle.
190 static uint
GetRoadVehLength(const RoadVehicle
*v
)
192 const Engine
*e
= v
->GetEngine();
193 uint length
= VEHICLE_LENGTH
;
195 uint16_t veh_len
= CALLBACK_FAILED
;
196 if (e
->GetGRF() != nullptr && e
->GetGRF()->grf_version
>= 8) {
197 /* Use callback 36 */
198 veh_len
= GetVehicleProperty(v
, PROP_ROADVEH_SHORTEN_FACTOR
, CALLBACK_FAILED
);
199 if (veh_len
!= CALLBACK_FAILED
&& veh_len
>= VEHICLE_LENGTH
) ErrorUnknownCallbackResult(e
->GetGRFID(), CBID_VEHICLE_LENGTH
, veh_len
);
201 /* Use callback 11 */
202 veh_len
= GetVehicleCallback(CBID_VEHICLE_LENGTH
, 0, 0, v
->engine_type
, v
);
204 if (veh_len
== CALLBACK_FAILED
) veh_len
= e
->u
.road
.shorten_factor
;
206 length
-= Clamp(veh_len
, 0, VEHICLE_LENGTH
- 1);
213 * Update the cache of a road vehicle.
214 * @param v Road vehicle needing an update of its cache.
215 * @param same_length should length of vehicles stay the same?
216 * @pre \a v must be first road vehicle.
218 void RoadVehUpdateCache(RoadVehicle
*v
, bool same_length
)
220 assert(v
->type
== VEH_ROAD
);
221 assert(v
->IsFrontEngine());
223 v
->InvalidateNewGRFCacheOfChain();
225 v
->gcache
.cached_total_length
= 0;
227 for (RoadVehicle
*u
= v
; u
!= nullptr; u
= u
->Next()) {
228 /* Check the v->first cache. */
229 assert(u
->First() == v
);
231 /* Update the 'first engine' */
232 u
->gcache
.first_engine
= (v
== u
) ? INVALID_ENGINE
: v
->engine_type
;
234 /* Update the length of the vehicle. */
235 uint veh_len
= GetRoadVehLength(u
);
236 /* Verify length hasn't changed. */
237 if (same_length
&& veh_len
!= u
->gcache
.cached_veh_length
) VehicleLengthChanged(u
);
239 u
->gcache
.cached_veh_length
= veh_len
;
240 v
->gcache
.cached_total_length
+= u
->gcache
.cached_veh_length
;
242 /* Update visual effect */
243 u
->UpdateVisualEffect();
245 /* Update cargo aging period. */
246 u
->vcache
.cached_cargo_age_period
= GetVehicleProperty(u
, PROP_ROADVEH_CARGO_AGE_PERIOD
, EngInfo(u
->engine_type
)->cargo_age_period
);
249 uint max_speed
= GetVehicleProperty(v
, PROP_ROADVEH_SPEED
, 0);
250 v
->vcache
.cached_max_speed
= (max_speed
!= 0) ? max_speed
* 4 : RoadVehInfo(v
->engine_type
)->max_speed
;
254 * Build a road vehicle.
255 * @param flags type of operation.
256 * @param tile tile of the depot where road vehicle is built.
257 * @param e the engine to build.
258 * @param[out] ret the vehicle that has been built.
259 * @return the cost of this operation or an error.
261 CommandCost
CmdBuildRoadVehicle(DoCommandFlag flags
, TileIndex tile
, const Engine
*e
, Vehicle
**ret
)
263 /* Check that the vehicle can drive on the road in question */
264 RoadType rt
= e
->u
.road
.roadtype
;
265 const RoadTypeInfo
*rti
= GetRoadTypeInfo(rt
);
266 if (!HasTileAnyRoadType(tile
, rti
->powered_roadtypes
)) return_cmd_error(STR_ERROR_DEPOT_WRONG_DEPOT_TYPE
);
268 if (flags
& DC_EXEC
) {
269 const RoadVehicleInfo
*rvi
= &e
->u
.road
;
271 RoadVehicle
*v
= new RoadVehicle();
273 v
->direction
= DiagDirToDir(GetRoadDepotDirection(tile
));
274 v
->owner
= _current_company
;
277 int x
= TileX(tile
) * TILE_SIZE
+ TILE_SIZE
/ 2;
278 int y
= TileY(tile
) * TILE_SIZE
+ TILE_SIZE
/ 2;
281 v
->z_pos
= GetSlopePixelZ(x
, y
, true);
283 v
->state
= RVSB_IN_DEPOT
;
284 v
->vehstatus
= VS_HIDDEN
| VS_STOPPED
| VS_DEFPAL
;
286 v
->spritenum
= rvi
->image_index
;
287 v
->cargo_type
= e
->GetDefaultCargoType();
288 assert(IsValidCargoID(v
->cargo_type
));
289 v
->cargo_cap
= rvi
->capacity
;
292 v
->last_station_visited
= INVALID_STATION
;
293 v
->last_loading_station
= INVALID_STATION
;
294 v
->engine_type
= e
->index
;
295 v
->gcache
.first_engine
= INVALID_ENGINE
; // needs to be set before first callback
297 v
->reliability
= e
->reliability
;
298 v
->reliability_spd_dec
= e
->reliability_spd_dec
;
299 v
->max_age
= e
->GetLifeLengthInDays();
301 v
->SetServiceInterval(Company::Get(v
->owner
)->settings
.vehicle
.servint_roadveh
);
303 v
->date_of_last_service
= TimerGameEconomy::date
;
304 v
->date_of_last_service_newgrf
= TimerGameCalendar::date
;
305 v
->build_year
= TimerGameCalendar::year
;
307 v
->sprite_cache
.sprite_seq
.Set(SPR_IMG_QUERY
);
308 v
->random_bits
= Random();
312 v
->compatible_roadtypes
= rti
->powered_roadtypes
;
313 v
->gcache
.cached_veh_length
= VEHICLE_LENGTH
;
315 if (e
->flags
& ENGINE_EXCLUSIVE_PREVIEW
) SetBit(v
->vehicle_flags
, VF_BUILT_AS_PROTOTYPE
);
316 v
->SetServiceIntervalIsPercent(Company::Get(_current_company
)->settings
.vehicle
.servint_ispercent
);
318 AddArticulatedParts(v
);
319 v
->InvalidateNewGRFCacheOfChain();
321 /* Call various callbacks after the whole consist has been constructed */
322 for (RoadVehicle
*u
= v
; u
!= nullptr; u
= u
->Next()) {
323 u
->cargo_cap
= u
->GetEngine()->DetermineCapacity(u
);
325 v
->InvalidateNewGRFCache();
326 u
->InvalidateNewGRFCache();
328 RoadVehUpdateCache(v
);
329 /* Initialize cached values for realistic acceleration. */
330 if (_settings_game
.vehicle
.roadveh_acceleration_model
!= AM_ORIGINAL
) v
->CargoChanged();
334 CheckConsistencyOfArticulatedVehicle(v
);
337 return CommandCost();
340 static FindDepotData
FindClosestRoadDepot(const RoadVehicle
*v
, int max_distance
)
342 if (IsRoadDepotTile(v
->tile
)) return FindDepotData(v
->tile
, 0);
344 return YapfRoadVehicleFindNearestDepot(v
, max_distance
);
347 ClosestDepot
RoadVehicle::FindClosestDepot()
349 FindDepotData rfdd
= FindClosestRoadDepot(this, 0);
350 if (rfdd
.best_length
== UINT_MAX
) return ClosestDepot();
352 return ClosestDepot(rfdd
.tile
, GetDepotIndex(rfdd
.tile
));
356 * Turn a roadvehicle around.
357 * @param flags operation to perform
358 * @param veh_id vehicle ID to turn
359 * @return the cost of this operation or an error
361 CommandCost
CmdTurnRoadVeh(DoCommandFlag flags
, VehicleID veh_id
)
363 RoadVehicle
*v
= RoadVehicle::GetIfValid(veh_id
);
364 if (v
== nullptr) return CMD_ERROR
;
366 if (!v
->IsPrimaryVehicle()) return CMD_ERROR
;
368 CommandCost ret
= CheckOwnership(v
->owner
);
369 if (ret
.Failed()) return ret
;
371 if ((v
->vehstatus
& VS_STOPPED
) ||
372 (v
->vehstatus
& VS_CRASHED
) ||
373 v
->breakdown_ctr
!= 0 ||
374 v
->overtaking
!= 0 ||
375 v
->state
== RVSB_WORMHOLE
||
377 v
->current_order
.IsType(OT_LOADING
)) {
381 if (IsNormalRoadTile(v
->tile
) && GetDisallowedRoadDirections(v
->tile
) != DRD_NONE
) return CMD_ERROR
;
383 if (IsTileType(v
->tile
, MP_TUNNELBRIDGE
) && DirToDiagDir(v
->direction
) == GetTunnelBridgeDirection(v
->tile
)) return CMD_ERROR
;
385 if (flags
& DC_EXEC
) {
386 v
->reverse_ctr
= 180;
388 /* Unbunching data is no longer valid. */
389 v
->ResetDepotUnbunching();
392 return CommandCost();
396 void RoadVehicle::MarkDirty()
398 for (RoadVehicle
*v
= this; v
!= nullptr; v
= v
->Next()) {
399 v
->colourmap
= PAL_NONE
;
400 v
->UpdateViewport(true, false);
402 this->CargoChanged();
405 void RoadVehicle::UpdateDeltaXY()
407 static const int8_t _delta_xy_table
[8][10] = {
408 /* y_extent, x_extent, y_offs, x_offs, y_bb_offs, x_bb_offs, y_extent_shorten, x_extent_shorten, y_bb_offs_shorten, x_bb_offs_shorten */
409 {3, 3, -1, -1, 0, 0, -1, -1, -1, -1}, // N
410 {3, 7, -1, -3, 0, -1, 0, -1, 0, 0}, // NE
411 {3, 3, -1, -1, 0, 0, 1, -1, 1, -1}, // E
412 {7, 3, -3, -1, -1, 0, 0, 0, 1, 0}, // SE
413 {3, 3, -1, -1, 0, 0, 1, 1, 1, 1}, // S
414 {3, 7, -1, -3, 0, -1, 0, 0, 0, 1}, // SW
415 {3, 3, -1, -1, 0, 0, -1, 1, -1, 1}, // W
416 {7, 3, -3, -1, -1, 0, -1, 0, 0, 0}, // NW
419 int shorten
= VEHICLE_LENGTH
- this->gcache
.cached_veh_length
;
420 if (!IsDiagonalDirection(this->direction
)) shorten
>>= 1;
422 const int8_t *bb
= _delta_xy_table
[this->direction
];
423 this->x_bb_offs
= bb
[5] + bb
[9] * shorten
;
424 this->y_bb_offs
= bb
[4] + bb
[8] * shorten
;;
425 this->x_offs
= bb
[3];
426 this->y_offs
= bb
[2];
427 this->x_extent
= bb
[1] + bb
[7] * shorten
;
428 this->y_extent
= bb
[0] + bb
[6] * shorten
;
433 * Calculates the maximum speed of the vehicle under its current conditions.
434 * @return Maximum speed of the vehicle.
436 inline int RoadVehicle::GetCurrentMaxSpeed() const
438 int max_speed
= this->gcache
.cached_max_track_speed
;
440 /* Limit speed to 50% while reversing, 75% in curves. */
441 for (const RoadVehicle
*u
= this; u
!= nullptr; u
= u
->Next()) {
442 if (_settings_game
.vehicle
.roadveh_acceleration_model
== AM_REALISTIC
) {
443 if (this->state
<= RVSB_TRACKDIR_MASK
&& IsReversingRoadTrackdir((Trackdir
)this->state
)) {
444 max_speed
= this->gcache
.cached_max_track_speed
/ 2;
446 } else if ((u
->direction
& 1) == 0) {
447 max_speed
= this->gcache
.cached_max_track_speed
* 3 / 4;
451 /* Vehicle is on the middle part of a bridge. */
452 if (u
->state
== RVSB_WORMHOLE
&& !(u
->vehstatus
& VS_HIDDEN
)) {
453 max_speed
= std::min(max_speed
, GetBridgeSpec(GetBridgeType(u
->tile
))->speed
* 2);
457 return std::min(max_speed
, this->current_order
.GetMaxSpeed() * 2);
461 * Delete last vehicle of a chain road vehicles.
462 * @param v First roadvehicle.
464 static void DeleteLastRoadVeh(RoadVehicle
*v
)
466 RoadVehicle
*first
= v
->First();
468 for (; v
->Next() != nullptr; v
= v
->Next()) u
= v
;
470 v
->last_station_visited
= first
->last_station_visited
; // for PreDestructor
472 /* Only leave the road stop when we're really gone. */
473 if (IsInsideMM(v
->state
, RVSB_IN_ROAD_STOP
, RVSB_IN_ROAD_STOP_END
)) RoadStop::GetByTile(v
->tile
, GetRoadStopType(v
->tile
))->Leave(v
);
478 static void RoadVehSetRandomDirection(RoadVehicle
*v
)
480 static const DirDiff delta
[] = {
481 DIRDIFF_45LEFT
, DIRDIFF_SAME
, DIRDIFF_SAME
, DIRDIFF_45RIGHT
485 uint32_t r
= Random();
487 v
->direction
= ChangeDir(v
->direction
, delta
[r
& 3]);
488 v
->UpdateViewport(true, true);
489 } while ((v
= v
->Next()) != nullptr);
493 * Road vehicle chain has crashed.
494 * @param v First roadvehicle.
495 * @return whether the chain still exists.
497 static bool RoadVehIsCrashed(RoadVehicle
*v
)
500 if (v
->crashed_ctr
== 2) {
501 CreateEffectVehicleRel(v
, 4, 4, 8, EV_EXPLOSION_LARGE
);
502 } else if (v
->crashed_ctr
<= 45) {
503 if ((v
->tick_counter
& 7) == 0) RoadVehSetRandomDirection(v
);
504 } else if (v
->crashed_ctr
>= 2220 && !(v
->tick_counter
& 0x1F)) {
505 bool ret
= v
->Next() != nullptr;
506 DeleteLastRoadVeh(v
);
514 * Check routine whether a road and a train vehicle have collided.
515 * @param v %Train vehicle to test.
516 * @param data Road vehicle to test.
517 * @return %Train vehicle if the vehicles collided, else \c nullptr.
519 static Vehicle
*EnumCheckRoadVehCrashTrain(Vehicle
*v
, void *data
)
521 const Vehicle
*u
= (Vehicle
*)data
;
523 return (v
->type
== VEH_TRAIN
&&
524 abs(v
->z_pos
- u
->z_pos
) <= 6 &&
525 abs(v
->x_pos
- u
->x_pos
) <= 4 &&
526 abs(v
->y_pos
- u
->y_pos
) <= 4) ? v
: nullptr;
529 uint
RoadVehicle::Crash(bool flooded
)
531 uint victims
= this->GroundVehicleBase::Crash(flooded
);
532 if (this->IsFrontEngine()) {
533 victims
+= 1; // driver
535 /* If we're in a drive through road stop we ought to leave it */
536 if (IsInsideMM(this->state
, RVSB_IN_DT_ROAD_STOP
, RVSB_IN_DT_ROAD_STOP_END
)) {
537 RoadStop::GetByTile(this->tile
, GetRoadStopType(this->tile
))->Leave(this);
540 this->crashed_ctr
= flooded
? 2000 : 1; // max 2220, disappear pretty fast when flooded
544 static void RoadVehCrash(RoadVehicle
*v
)
546 uint victims
= v
->Crash();
548 AI::NewEvent(v
->owner
, new ScriptEventVehicleCrashed(v
->index
, v
->tile
, ScriptEventVehicleCrashed::CRASH_RV_LEVEL_CROSSING
, victims
));
549 Game::NewEvent(new ScriptEventVehicleCrashed(v
->index
, v
->tile
, ScriptEventVehicleCrashed::CRASH_RV_LEVEL_CROSSING
, victims
));
551 SetDParam(0, victims
);
552 StringID newsitem
= (victims
== 1) ? STR_NEWS_ROAD_VEHICLE_CRASH_DRIVER
: STR_NEWS_ROAD_VEHICLE_CRASH
;
553 NewsType newstype
= NT_ACCIDENT
;
555 if (v
->owner
!= _local_company
) {
556 newstype
= NT_ACCIDENT_OTHER
;
559 AddTileNewsItem(newsitem
, newstype
, v
->tile
);
561 ModifyStationRatingAround(v
->tile
, v
->owner
, -160, 22);
562 if (_settings_client
.sound
.disaster
) SndPlayVehicleFx(SND_12_EXPLOSION
, v
);
565 static bool RoadVehCheckTrainCrash(RoadVehicle
*v
)
567 for (RoadVehicle
*u
= v
; u
!= nullptr; u
= u
->Next()) {
568 if (u
->state
== RVSB_WORMHOLE
) continue;
570 TileIndex tile
= u
->tile
;
572 if (!IsLevelCrossingTile(tile
)) continue;
574 if (HasVehicleOnPosXY(v
->x_pos
, v
->y_pos
, u
, EnumCheckRoadVehCrashTrain
)) {
583 TileIndex
RoadVehicle::GetOrderStationLocation(StationID station
)
585 if (station
== this->last_station_visited
) this->last_station_visited
= INVALID_STATION
;
587 const Station
*st
= Station::Get(station
);
588 if (!CanVehicleUseStation(this, st
)) {
589 /* There is no stop left at the station, so don't even TRY to go there */
590 this->IncrementRealOrderIndex();
597 static void StartRoadVehSound(const RoadVehicle
*v
)
599 if (!PlayVehicleSound(v
, VSE_START
)) {
600 SoundID s
= RoadVehInfo(v
->engine_type
)->sfx
;
601 if (s
== SND_19_DEPARTURE_OLD_RV_1
&& (v
->tick_counter
& 3) == 0) {
602 s
= SND_1A_DEPARTURE_OLD_RV_2
;
604 SndPlayVehicleFx(s
, v
);
608 struct RoadVehFindData
{
617 static Vehicle
*EnumCheckRoadVehClose(Vehicle
*v
, void *data
)
619 static const int8_t dist_x
[] = { -4, -8, -4, -1, 4, 8, 4, 1 };
620 static const int8_t dist_y
[] = { -4, -1, 4, 8, 4, 1, -4, -8 };
622 RoadVehFindData
*rvf
= (RoadVehFindData
*)data
;
624 short x_diff
= v
->x_pos
- rvf
->x
;
625 short y_diff
= v
->y_pos
- rvf
->y
;
627 if (v
->type
== VEH_ROAD
&&
629 abs(v
->z_pos
- rvf
->veh
->z_pos
) < 6 &&
630 v
->direction
== rvf
->dir
&&
631 rvf
->veh
->First() != v
->First() &&
632 (dist_x
[v
->direction
] >= 0 || (x_diff
> dist_x
[v
->direction
] && x_diff
<= 0)) &&
633 (dist_x
[v
->direction
] <= 0 || (x_diff
< dist_x
[v
->direction
] && x_diff
>= 0)) &&
634 (dist_y
[v
->direction
] >= 0 || (y_diff
> dist_y
[v
->direction
] && y_diff
<= 0)) &&
635 (dist_y
[v
->direction
] <= 0 || (y_diff
< dist_y
[v
->direction
] && y_diff
>= 0))) {
636 uint diff
= abs(x_diff
) + abs(y_diff
);
638 if (diff
< rvf
->best_diff
|| (diff
== rvf
->best_diff
&& v
->index
< rvf
->best
->index
)) {
640 rvf
->best_diff
= diff
;
647 static RoadVehicle
*RoadVehFindCloseTo(RoadVehicle
*v
, int x
, int y
, Direction dir
, bool update_blocked_ctr
= true)
650 RoadVehicle
*front
= v
->First();
652 if (front
->reverse_ctr
!= 0) return nullptr;
658 rvf
.best_diff
= UINT_MAX
;
660 if (front
->state
== RVSB_WORMHOLE
) {
661 FindVehicleOnPos(v
->tile
, &rvf
, EnumCheckRoadVehClose
);
662 FindVehicleOnPos(GetOtherTunnelBridgeEnd(v
->tile
), &rvf
, EnumCheckRoadVehClose
);
664 FindVehicleOnPosXY(x
, y
, &rvf
, EnumCheckRoadVehClose
);
667 /* This code protects a roadvehicle from being blocked for ever
668 * If more than 1480 / 74 days a road vehicle is blocked, it will
669 * drive just through it. The ultimate backup-code of TTD.
670 * It can be disabled. */
671 if (rvf
.best_diff
== UINT_MAX
) {
672 front
->blocked_ctr
= 0;
676 if (update_blocked_ctr
&& ++front
->blocked_ctr
> 1480) return nullptr;
678 return RoadVehicle::From(rvf
.best
);
682 * A road vehicle arrives at a station. If it is the first time, create a news item.
683 * @param v Road vehicle that arrived.
684 * @param st Station where the road vehicle arrived.
686 static void RoadVehArrivesAt(const RoadVehicle
*v
, Station
*st
)
689 /* Check if station was ever visited before */
690 if (!(st
->had_vehicle_of_type
& HVOT_BUS
)) {
691 st
->had_vehicle_of_type
|= HVOT_BUS
;
692 SetDParam(0, st
->index
);
694 RoadTypeIsRoad(v
->roadtype
) ? STR_NEWS_FIRST_BUS_ARRIVAL
: STR_NEWS_FIRST_PASSENGER_TRAM_ARRIVAL
,
695 (v
->owner
== _local_company
) ? NT_ARRIVAL_COMPANY
: NT_ARRIVAL_OTHER
,
699 AI::NewEvent(v
->owner
, new ScriptEventStationFirstVehicle(st
->index
, v
->index
));
700 Game::NewEvent(new ScriptEventStationFirstVehicle(st
->index
, v
->index
));
703 /* Check if station was ever visited before */
704 if (!(st
->had_vehicle_of_type
& HVOT_TRUCK
)) {
705 st
->had_vehicle_of_type
|= HVOT_TRUCK
;
706 SetDParam(0, st
->index
);
708 RoadTypeIsRoad(v
->roadtype
) ? STR_NEWS_FIRST_TRUCK_ARRIVAL
: STR_NEWS_FIRST_CARGO_TRAM_ARRIVAL
,
709 (v
->owner
== _local_company
) ? NT_ARRIVAL_COMPANY
: NT_ARRIVAL_OTHER
,
713 AI::NewEvent(v
->owner
, new ScriptEventStationFirstVehicle(st
->index
, v
->index
));
714 Game::NewEvent(new ScriptEventStationFirstVehicle(st
->index
, v
->index
));
720 * This function looks at the vehicle and updates its speed (cur_speed
721 * and subspeed) variables. Furthermore, it returns the distance that
722 * the vehicle can drive this tick. #Vehicle::GetAdvanceDistance() determines
723 * the distance to drive before moving a step on the map.
724 * @return distance to drive.
726 int RoadVehicle::UpdateSpeed()
728 switch (_settings_game
.vehicle
.roadveh_acceleration_model
) {
729 default: NOT_REACHED();
731 return this->DoUpdateSpeed(this->overtaking
!= 0 ? 512 : 256, 0, this->GetCurrentMaxSpeed());
734 return this->DoUpdateSpeed(this->GetAcceleration() + (this->overtaking
!= 0 ? 256 : 0), this->GetAccelerationStatus() == AS_BRAKE
? 0 : 4, this->GetCurrentMaxSpeed());
738 static Direction
RoadVehGetNewDirection(const RoadVehicle
*v
, int x
, int y
)
740 static const Direction _roadveh_new_dir
[] = {
741 DIR_N
, DIR_NW
, DIR_W
, INVALID_DIR
,
742 DIR_NE
, DIR_N
, DIR_SW
, INVALID_DIR
,
743 DIR_E
, DIR_SE
, DIR_S
746 x
= x
- v
->x_pos
+ 1;
747 y
= y
- v
->y_pos
+ 1;
749 if ((uint
)x
> 2 || (uint
)y
> 2) return v
->direction
;
750 return _roadveh_new_dir
[y
* 4 + x
];
753 static Direction
RoadVehGetSlidingDirection(const RoadVehicle
*v
, int x
, int y
)
755 Direction new_dir
= RoadVehGetNewDirection(v
, x
, y
);
756 Direction old_dir
= v
->direction
;
759 if (new_dir
== old_dir
) return old_dir
;
760 delta
= (DirDifference(new_dir
, old_dir
) > DIRDIFF_REVERSE
? DIRDIFF_45LEFT
: DIRDIFF_45RIGHT
);
761 return ChangeDir(old_dir
, delta
);
764 struct OvertakeData
{
765 const RoadVehicle
*u
;
766 const RoadVehicle
*v
;
771 static Vehicle
*EnumFindVehBlockingOvertake(Vehicle
*v
, void *data
)
773 const OvertakeData
*od
= (OvertakeData
*)data
;
775 return (v
->type
== VEH_ROAD
&& v
->First() == v
&& v
!= od
->u
&& v
!= od
->v
) ? v
: nullptr;
779 * Check if overtaking is possible on a piece of track
781 * @param od Information about the tile and the involved vehicles
782 * @return true if we have to abort overtaking
784 static bool CheckRoadBlockedForOvertaking(OvertakeData
*od
)
786 if (!HasTileAnyRoadType(od
->tile
, od
->v
->compatible_roadtypes
)) return true;
787 TrackStatus ts
= GetTileTrackStatus(od
->tile
, TRANSPORT_ROAD
, GetRoadTramType(od
->v
->roadtype
));
788 TrackdirBits trackdirbits
= TrackStatusToTrackdirBits(ts
);
789 TrackdirBits red_signals
= TrackStatusToRedSignals(ts
); // barred level crossing
790 TrackBits trackbits
= TrackdirBitsToTrackBits(trackdirbits
);
792 /* Track does not continue along overtaking direction || track has junction || levelcrossing is barred */
793 if (!HasBit(trackdirbits
, od
->trackdir
) || (trackbits
& ~TRACK_BIT_CROSS
) || (red_signals
!= TRACKDIR_BIT_NONE
)) return true;
795 /* Are there more vehicles on the tile except the two vehicles involved in overtaking */
796 return HasVehicleOnPos(od
->tile
, od
, EnumFindVehBlockingOvertake
);
799 static void RoadVehCheckOvertake(RoadVehicle
*v
, RoadVehicle
*u
)
806 /* Trams can't overtake other trams */
807 if (RoadTypeIsTram(v
->roadtype
)) return;
809 /* Don't overtake in stations */
810 if (IsTileType(v
->tile
, MP_STATION
) || IsTileType(u
->tile
, MP_STATION
)) return;
812 /* For now, articulated road vehicles can't overtake anything. */
813 if (v
->HasArticulatedPart()) return;
815 /* Vehicles are not driving in same direction || direction is not a diagonal direction */
816 if (v
->direction
!= u
->direction
|| !(v
->direction
& 1)) return;
818 /* Check if vehicle is in a road stop, depot, tunnel or bridge or not on a straight road */
819 if (v
->state
>= RVSB_IN_ROAD_STOP
|| !IsStraightRoadTrackdir((Trackdir
)(v
->state
& RVSB_TRACKDIR_MASK
))) return;
821 /* Can't overtake a vehicle that is moving faster than us. If the vehicle in front is
822 * accelerating, take the maximum speed for the comparison, else the current speed.
823 * Original acceleration always accelerates, so always use the maximum speed. */
824 int u_speed
= (_settings_game
.vehicle
.roadveh_acceleration_model
== AM_ORIGINAL
|| u
->GetAcceleration() > 0) ? u
->GetCurrentMaxSpeed() : u
->cur_speed
;
825 if (u_speed
>= v
->GetCurrentMaxSpeed() &&
826 !(u
->vehstatus
& VS_STOPPED
) &&
831 od
.trackdir
= DiagDirToDiagTrackdir(DirToDiagDir(v
->direction
));
833 /* Are the current and the next tile suitable for overtaking?
834 * - Does the track continue along od.trackdir
836 * - No barred levelcrossing
837 * - No other vehicles in the way
840 if (CheckRoadBlockedForOvertaking(&od
)) return;
842 od
.tile
= v
->tile
+ TileOffsByDiagDir(DirToDiagDir(v
->direction
));
843 if (CheckRoadBlockedForOvertaking(&od
)) return;
845 /* When the vehicle in front of us is stopped we may only take
846 * half the time to pass it than when the vehicle is moving. */
847 v
->overtaking_ctr
= (od
.u
->cur_speed
== 0 || (od
.u
->vehstatus
& VS_STOPPED
)) ? RV_OVERTAKE_TIMEOUT
/ 2 : 0;
848 v
->overtaking
= RVSB_DRIVE_SIDE
;
851 static void RoadZPosAffectSpeed(RoadVehicle
*v
, int old_z
)
853 if (old_z
== v
->z_pos
|| _settings_game
.vehicle
.roadveh_acceleration_model
!= AM_ORIGINAL
) return;
855 if (old_z
< v
->z_pos
) {
856 v
->cur_speed
= v
->cur_speed
* 232 / 256; // slow down by ~10%
858 uint16_t spd
= v
->cur_speed
+ 2;
859 if (spd
<= v
->gcache
.cached_max_track_speed
) v
->cur_speed
= spd
;
863 static int PickRandomBit(uint bits
)
866 uint num
= RandomRange(CountBits(bits
));
868 for (i
= 0; !(bits
& 1) || (int)--num
>= 0; bits
>>= 1, i
++) {}
873 * Returns direction to for a road vehicle to take or
874 * INVALID_TRACKDIR if the direction is currently blocked
875 * @param v the Vehicle to do the pathfinding for
876 * @param tile the where to start the pathfinding
877 * @param enterdir the direction the vehicle enters the tile from
878 * @return the Trackdir to take
880 static Trackdir
RoadFindPathToDest(RoadVehicle
*v
, TileIndex tile
, DiagDirection enterdir
)
882 #define return_track(x) { best_track = (Trackdir)x; goto found_best_track; }
886 bool path_found
= true;
888 TrackStatus ts
= GetTileTrackStatus(tile
, TRANSPORT_ROAD
, GetRoadTramType(v
->roadtype
));
889 TrackdirBits red_signals
= TrackStatusToRedSignals(ts
); // crossing
890 TrackdirBits trackdirs
= TrackStatusToTrackdirBits(ts
);
892 if (IsTileType(tile
, MP_ROAD
)) {
893 if (IsRoadDepot(tile
) && (!IsTileOwner(tile
, v
->owner
) || GetRoadDepotDirection(tile
) == enterdir
)) {
894 /* Road depot owned by another company or with the wrong orientation */
895 trackdirs
= TRACKDIR_BIT_NONE
;
897 } else if (IsTileType(tile
, MP_STATION
) && IsBayRoadStopTile(tile
)) {
898 /* Standard road stop (drive-through stops are treated as normal road) */
900 if (!IsTileOwner(tile
, v
->owner
) || GetBayRoadStopDir(tile
) == enterdir
|| v
->HasArticulatedPart()) {
901 /* different station owner or wrong orientation or the vehicle has articulated parts */
902 trackdirs
= TRACKDIR_BIT_NONE
;
905 RoadStopType rstype
= v
->IsBus() ? ROADSTOP_BUS
: ROADSTOP_TRUCK
;
907 if (GetRoadStopType(tile
) != rstype
) {
908 /* Wrong station type */
909 trackdirs
= TRACKDIR_BIT_NONE
;
911 /* Proper station type, check if there is free loading bay */
912 if (!_settings_game
.pf
.roadveh_queue
&& IsBayRoadStopTile(tile
) &&
913 !RoadStop::GetByTile(tile
, rstype
)->HasFreeBay()) {
914 /* Station is full and RV queuing is off */
915 trackdirs
= TRACKDIR_BIT_NONE
;
920 /* The above lookups should be moved to GetTileTrackStatus in the
921 * future, but that requires more changes to the pathfinder and other
922 * stuff, probably even more arguments to GTTS.
925 /* Remove tracks unreachable from the enter dir */
926 trackdirs
&= DiagdirReachesTrackdirs(enterdir
);
927 if (trackdirs
== TRACKDIR_BIT_NONE
) {
928 /* If vehicle expected a path, it no longer exists, so invalidate it. */
929 if (!v
->path
.empty()) v
->path
.clear();
930 /* No reachable tracks, so we'll reverse */
931 return_track(_road_reverse_table
[enterdir
]);
934 if (v
->reverse_ctr
!= 0) {
936 if (RoadTypeIsTram(v
->roadtype
)) {
937 /* Trams may only reverse on a tile if it contains at least the straight
938 * trackbits or when it is a valid turning tile (i.e. one roadbit) */
939 RoadBits rb
= GetAnyRoadBits(tile
, RTT_TRAM
);
940 RoadBits straight
= AxisToRoadBits(DiagDirToAxis(enterdir
));
941 reverse
= ((rb
& straight
) == straight
) ||
942 (rb
== DiagDirToRoadBits(enterdir
));
946 if (v
->tile
!= tile
) {
947 return_track(_road_reverse_table
[enterdir
]);
952 desttile
= v
->dest_tile
;
954 /* We've got no destination, pick a random track */
955 return_track(PickRandomBit(trackdirs
));
958 /* Only one track to choose between? */
959 if (KillFirstBit(trackdirs
) == TRACKDIR_BIT_NONE
) {
960 if (!v
->path
.empty() && v
->path
.tile
.front() == tile
) {
961 /* Vehicle expected a choice here, invalidate its path. */
964 return_track(FindFirstBit(trackdirs
));
967 /* Attempt to follow cached path. */
968 if (!v
->path
.empty()) {
969 if (v
->path
.tile
.front() != tile
) {
970 /* Vehicle didn't expect a choice here, invalidate its path. */
973 Trackdir trackdir
= v
->path
.td
.front();
975 if (HasBit(trackdirs
, trackdir
)) {
976 v
->path
.td
.pop_front();
977 v
->path
.tile
.pop_front();
978 return_track(trackdir
);
981 /* Vehicle expected a choice which is no longer available. */
986 best_track
= YapfRoadVehicleChooseTrack(v
, tile
, enterdir
, trackdirs
, path_found
, v
->path
);
988 v
->HandlePathfindingResult(path_found
);
992 if (HasBit(red_signals
, best_track
)) return INVALID_TRACKDIR
;
997 struct RoadDriveEntry
{
1001 #include "table/roadveh_movement.h"
1003 bool RoadVehLeaveDepot(RoadVehicle
*v
, bool first
)
1005 /* Don't leave unless v and following wagons are in the depot. */
1006 for (const RoadVehicle
*u
= v
; u
!= nullptr; u
= u
->Next()) {
1007 if (u
->state
!= RVSB_IN_DEPOT
|| u
->tile
!= v
->tile
) return false;
1010 DiagDirection dir
= GetRoadDepotDirection(v
->tile
);
1011 v
->direction
= DiagDirToDir(dir
);
1013 Trackdir tdir
= DiagDirToDiagTrackdir(dir
);
1014 const RoadDriveEntry
*rdp
= _road_drive_data
[GetRoadTramType(v
->roadtype
)][(_settings_game
.vehicle
.road_side
<< RVS_DRIVE_SIDE
) + tdir
];
1016 int x
= TileX(v
->tile
) * TILE_SIZE
+ (rdp
[RVC_DEPOT_START_FRAME
].x
& 0xF);
1017 int y
= TileY(v
->tile
) * TILE_SIZE
+ (rdp
[RVC_DEPOT_START_FRAME
].y
& 0xF);
1020 /* We are leaving a depot, but have to go to the exact same one; re-enter */
1021 if (v
->current_order
.IsType(OT_GOTO_DEPOT
) && v
->tile
== v
->dest_tile
) {
1022 VehicleEnterDepot(v
);
1026 if (RoadVehFindCloseTo(v
, x
, y
, v
->direction
, false) != nullptr) return true;
1028 VehicleServiceInDepot(v
);
1029 v
->LeaveUnbunchingDepot();
1031 StartRoadVehSound(v
);
1033 /* Vehicle is about to leave a depot */
1037 v
->vehstatus
&= ~VS_HIDDEN
;
1039 v
->frame
= RVC_DEPOT_START_FRAME
;
1043 v
->UpdatePosition();
1044 v
->UpdateInclination(true, true);
1046 InvalidateWindowData(WC_VEHICLE_DEPOT
, v
->tile
);
1051 static Trackdir
FollowPreviousRoadVehicle(const RoadVehicle
*v
, const RoadVehicle
*prev
, TileIndex tile
, DiagDirection entry_dir
, bool already_reversed
)
1053 if (prev
->tile
== v
->tile
&& !already_reversed
) {
1054 /* If the previous vehicle is on the same tile as this vehicle is
1055 * then it must have reversed. */
1056 return _road_reverse_table
[entry_dir
];
1059 uint8_t prev_state
= prev
->state
;
1062 if (prev_state
== RVSB_WORMHOLE
|| prev_state
== RVSB_IN_DEPOT
) {
1063 DiagDirection diag_dir
= INVALID_DIAGDIR
;
1065 if (IsTileType(tile
, MP_TUNNELBRIDGE
)) {
1066 diag_dir
= GetTunnelBridgeDirection(tile
);
1067 } else if (IsRoadDepotTile(tile
)) {
1068 diag_dir
= ReverseDiagDir(GetRoadDepotDirection(tile
));
1071 if (diag_dir
== INVALID_DIAGDIR
) return INVALID_TRACKDIR
;
1072 dir
= DiagDirToDiagTrackdir(diag_dir
);
1074 if (already_reversed
&& prev
->tile
!= tile
) {
1076 * The vehicle has reversed, but did not go straight back.
1077 * It immediately turn onto another tile. This means that
1078 * the roadstate of the previous vehicle cannot be used
1079 * as the direction we have to go with this vehicle.
1081 * Next table is build in the following way:
1082 * - first row for when the vehicle in front went to the northern or
1083 * western tile, second for southern and eastern.
1084 * - columns represent the entry direction.
1085 * - cell values are determined by the Trackdir one has to take from
1086 * the entry dir (column) to the tile in north or south by only
1087 * going over the trackdirs used for turning 90 degrees, i.e.
1088 * TRACKDIR_{UPPER,RIGHT,LOWER,LEFT}_{N,E,S,W}.
1090 static const Trackdir reversed_turn_lookup
[2][DIAGDIR_END
] = {
1091 { TRACKDIR_UPPER_W
, TRACKDIR_RIGHT_N
, TRACKDIR_LEFT_N
, TRACKDIR_UPPER_E
},
1092 { TRACKDIR_RIGHT_S
, TRACKDIR_LOWER_W
, TRACKDIR_LOWER_E
, TRACKDIR_LEFT_S
}};
1093 dir
= reversed_turn_lookup
[prev
->tile
< tile
? 0 : 1][ReverseDiagDir(entry_dir
)];
1094 } else if (HasBit(prev_state
, RVS_IN_DT_ROAD_STOP
)) {
1095 dir
= (Trackdir
)(prev_state
& RVSB_ROAD_STOP_TRACKDIR_MASK
);
1096 } else if (prev_state
< TRACKDIR_END
) {
1097 dir
= (Trackdir
)prev_state
;
1099 return INVALID_TRACKDIR
;
1103 /* Do some sanity checking. */
1104 static const RoadBits required_roadbits
[] = {
1105 ROAD_X
, ROAD_Y
, ROAD_NW
| ROAD_NE
, ROAD_SW
| ROAD_SE
,
1106 ROAD_NW
| ROAD_SW
, ROAD_NE
| ROAD_SE
, ROAD_X
, ROAD_Y
1108 RoadBits required
= required_roadbits
[dir
& 0x07];
1110 if ((required
& GetAnyRoadBits(tile
, GetRoadTramType(v
->roadtype
), true)) == ROAD_NONE
) {
1111 dir
= INVALID_TRACKDIR
;
1118 * Can a tram track build without destruction on the given tile?
1119 * @param c the company that would be building the tram tracks
1120 * @param t the tile to build on.
1121 * @param rt the tram type to build.
1122 * @param r the road bits needed.
1123 * @return true when a track track can be build on 't'
1125 static bool CanBuildTramTrackOnTile(CompanyID c
, TileIndex t
, RoadType rt
, RoadBits r
)
1127 /* The 'current' company is not necessarily the owner of the vehicle. */
1128 Backup
<CompanyID
> cur_company(_current_company
, c
);
1130 CommandCost ret
= Command
<CMD_BUILD_ROAD
>::Do(DC_NO_WATER
, t
, r
, rt
, DRD_NONE
, 0);
1132 cur_company
.Restore();
1133 return ret
.Succeeded();
1136 bool IndividualRoadVehicleController(RoadVehicle
*v
, const RoadVehicle
*prev
)
1138 if (v
->overtaking
!= 0) {
1139 if (IsTileType(v
->tile
, MP_STATION
)) {
1140 /* Force us to be not overtaking! */
1142 } else if (++v
->overtaking_ctr
>= RV_OVERTAKE_TIMEOUT
) {
1143 /* If overtaking just aborts at a random moment, we can have a out-of-bound problem,
1144 * if the vehicle started a corner. To protect that, only allow an abort of
1145 * overtake if we are on straight roads */
1146 if (v
->state
< RVSB_IN_ROAD_STOP
&& IsStraightRoadTrackdir((Trackdir
)v
->state
)) {
1152 /* If this vehicle is in a depot and we've reached this point it must be
1153 * one of the articulated parts. It will stay in the depot until activated
1154 * by the previous vehicle in the chain when it gets to the right place. */
1155 if (v
->IsInDepot()) return true;
1157 if (v
->state
== RVSB_WORMHOLE
) {
1158 /* Vehicle is entering a depot or is on a bridge or in a tunnel */
1159 GetNewVehiclePosResult gp
= GetNewVehiclePos(v
);
1161 if (v
->IsFrontEngine()) {
1162 const Vehicle
*u
= RoadVehFindCloseTo(v
, gp
.x
, gp
.y
, v
->direction
);
1164 v
->cur_speed
= u
->First()->cur_speed
;
1169 if (IsTileType(gp
.new_tile
, MP_TUNNELBRIDGE
) && HasBit(VehicleEnterTile(v
, gp
.new_tile
, gp
.x
, gp
.y
), VETS_ENTERED_WORMHOLE
)) {
1170 /* Vehicle has just entered a bridge or tunnel */
1173 v
->UpdatePosition();
1174 v
->UpdateInclination(true, true);
1180 v
->UpdatePosition();
1181 if ((v
->vehstatus
& VS_HIDDEN
) == 0) v
->Vehicle::UpdateViewport(true);
1185 /* Get move position data for next frame.
1186 * For a drive-through road stop use 'straight road' move data.
1187 * In this case v->state is masked to give the road stop entry direction. */
1188 RoadDriveEntry rd
= _road_drive_data
[GetRoadTramType(v
->roadtype
)][(
1189 (HasBit(v
->state
, RVS_IN_DT_ROAD_STOP
) ? v
->state
& RVSB_ROAD_STOP_TRACKDIR_MASK
: v
->state
) +
1190 (_settings_game
.vehicle
.road_side
<< RVS_DRIVE_SIDE
)) ^ v
->overtaking
][v
->frame
+ 1];
1192 if (rd
.x
& RDE_NEXT_TILE
) {
1193 TileIndex tile
= v
->tile
+ TileOffsByDiagDir((DiagDirection
)(rd
.x
& 3));
1196 if (v
->IsFrontEngine()) {
1197 /* If this is the front engine, look for the right path. */
1198 if (HasTileAnyRoadType(tile
, v
->compatible_roadtypes
)) {
1199 dir
= RoadFindPathToDest(v
, tile
, (DiagDirection
)(rd
.x
& 3));
1201 dir
= _road_reverse_table
[(DiagDirection
)(rd
.x
& 3)];
1204 dir
= FollowPreviousRoadVehicle(v
, prev
, tile
, (DiagDirection
)(rd
.x
& 3), false);
1207 if (dir
== INVALID_TRACKDIR
) {
1208 if (!v
->IsFrontEngine()) FatalError("Disconnecting road vehicle.");
1214 uint start_frame
= RVC_DEFAULT_START_FRAME
;
1215 if (IsReversingRoadTrackdir(dir
)) {
1216 /* When turning around we can't be overtaking. */
1219 /* Turning around */
1220 if (RoadTypeIsTram(v
->roadtype
)) {
1221 /* Determine the road bits the tram needs to be able to turn around
1222 * using the 'big' corner loop. */
1225 default: NOT_REACHED();
1226 case TRACKDIR_RVREV_NE
: needed
= ROAD_SW
; break;
1227 case TRACKDIR_RVREV_SE
: needed
= ROAD_NW
; break;
1228 case TRACKDIR_RVREV_SW
: needed
= ROAD_NE
; break;
1229 case TRACKDIR_RVREV_NW
: needed
= ROAD_SE
; break;
1231 if ((v
->Previous() != nullptr && v
->Previous()->tile
== tile
) ||
1232 (v
->IsFrontEngine() && IsNormalRoadTile(tile
) && !HasRoadWorks(tile
) &&
1233 HasTileAnyRoadType(tile
, v
->compatible_roadtypes
) &&
1234 (needed
& GetRoadBits(tile
, RTT_TRAM
)) != ROAD_NONE
)) {
1236 * Taking the 'big' corner for trams only happens when:
1237 * - The previous vehicle in this (articulated) tram chain is
1238 * already on the 'next' tile, we just follow them regardless of
1239 * anything. When it is NOT on the 'next' tile, the tram started
1240 * doing a reversing turn when the piece of tram track on the next
1241 * tile did not exist yet. Do not use the big tram loop as that is
1242 * going to cause the tram to split up.
1243 * - Or the front of the tram can drive over the next tile.
1245 } else if (!v
->IsFrontEngine() || !CanBuildTramTrackOnTile(v
->owner
, tile
, v
->roadtype
, needed
) || ((~needed
& GetAnyRoadBits(v
->tile
, RTT_TRAM
, false)) == ROAD_NONE
)) {
1247 * Taking the 'small' corner for trams only happens when:
1248 * - We are not the from vehicle of an articulated tram.
1249 * - Or when the company cannot build on the next tile.
1251 * The 'small' corner means that the vehicle is on the end of a
1252 * tram track and needs to start turning there. To do this properly
1253 * the tram needs to start at an offset in the tram turning 'code'
1254 * for 'big' corners. It furthermore does not go to the next tile,
1255 * so that needs to be fixed too.
1258 start_frame
= RVC_TURN_AROUND_START_FRAME_SHORT_TRAM
;
1260 /* The company can build on the next tile, so wait till they do. */
1264 } else if (IsNormalRoadTile(v
->tile
) && GetDisallowedRoadDirections(v
->tile
) != DRD_NONE
) {
1272 /* Get position data for first frame on the new tile */
1273 const RoadDriveEntry
*rdp
= _road_drive_data
[GetRoadTramType(v
->roadtype
)][(dir
+ (_settings_game
.vehicle
.road_side
<< RVS_DRIVE_SIDE
)) ^ v
->overtaking
];
1275 int x
= TileX(tile
) * TILE_SIZE
+ rdp
[start_frame
].x
;
1276 int y
= TileY(tile
) * TILE_SIZE
+ rdp
[start_frame
].y
;
1278 Direction new_dir
= RoadVehGetSlidingDirection(v
, x
, y
);
1279 if (v
->IsFrontEngine()) {
1280 const Vehicle
*u
= RoadVehFindCloseTo(v
, x
, y
, new_dir
);
1282 v
->cur_speed
= u
->First()->cur_speed
;
1283 /* We might be blocked, prevent pathfinding rerun as we already know where we are heading to. */
1284 v
->path
.tile
.push_front(tile
);
1285 v
->path
.td
.push_front(dir
);
1290 uint32_t r
= VehicleEnterTile(v
, tile
, x
, y
);
1291 if (HasBit(r
, VETS_CANNOT_ENTER
)) {
1292 if (!IsTileType(tile
, MP_TUNNELBRIDGE
)) {
1296 /* Try an about turn to re-enter the previous tile */
1297 dir
= _road_reverse_table
[rd
.x
& 3];
1301 if (IsInsideMM(v
->state
, RVSB_IN_ROAD_STOP
, RVSB_IN_DT_ROAD_STOP_END
) && IsTileType(v
->tile
, MP_STATION
)) {
1302 if (IsReversingRoadTrackdir(dir
) && IsInsideMM(v
->state
, RVSB_IN_ROAD_STOP
, RVSB_IN_ROAD_STOP_END
)) {
1303 /* New direction is trying to turn vehicle around.
1304 * We can't turn at the exit of a road stop so wait.*/
1309 /* If we are a drive through road stop and the next tile is of
1310 * the same road stop and the next tile isn't this one (i.e. we
1311 * are not reversing), then keep the reservation and state.
1312 * This way we will not be shortly unregister from the road
1313 * stop. It also makes it possible to load when on the edge of
1314 * two road stops; otherwise you could get vehicles that should
1315 * be loading but are not actually loading. */
1316 if (IsDriveThroughStopTile(v
->tile
) &&
1317 RoadStop::IsDriveThroughRoadStopContinuation(v
->tile
, tile
) &&
1319 /* So, keep 'our' state */
1320 dir
= (Trackdir
)v
->state
;
1321 } else if (IsStationRoadStop(v
->tile
)) {
1322 /* We're not continuing our drive through road stop, so leave. */
1323 RoadStop::GetByTile(v
->tile
, GetRoadStopType(v
->tile
))->Leave(v
);
1327 if (!HasBit(r
, VETS_ENTERED_WORMHOLE
)) {
1328 TileIndex old_tile
= v
->tile
;
1331 v
->state
= (uint8_t)dir
;
1332 v
->frame
= start_frame
;
1333 RoadTramType rtt
= GetRoadTramType(v
->roadtype
);
1334 if (GetRoadType(old_tile
, rtt
) != GetRoadType(tile
, rtt
)) {
1335 if (v
->IsFrontEngine()) {
1336 RoadVehUpdateCache(v
);
1338 v
->First()->CargoChanged();
1341 if (new_dir
!= v
->direction
) {
1342 v
->direction
= new_dir
;
1343 if (_settings_game
.vehicle
.roadveh_acceleration_model
== AM_ORIGINAL
) v
->cur_speed
-= v
->cur_speed
>> 2;
1347 v
->UpdatePosition();
1348 RoadZPosAffectSpeed(v
, v
->UpdateInclination(true, true));
1352 if (rd
.x
& RDE_TURNED
) {
1353 /* Vehicle has finished turning around, it will now head back onto the same tile */
1355 uint turn_around_start_frame
= RVC_TURN_AROUND_START_FRAME
;
1357 if (RoadTypeIsTram(v
->roadtype
) && !IsRoadDepotTile(v
->tile
) && HasExactlyOneBit(GetAnyRoadBits(v
->tile
, RTT_TRAM
, true))) {
1359 * The tram is turning around with one tram 'roadbit'. This means that
1360 * it is using the 'big' corner 'drive data'. However, to support the
1361 * trams to take a small corner, there is a 'turned' marker in the middle
1362 * of the turning 'drive data'. When the tram took the long corner, we
1363 * will still use the 'big' corner drive data, but we advance it one
1364 * frame. We furthermore set the driving direction so the turning is
1365 * going to be properly shown.
1367 turn_around_start_frame
= RVC_START_FRAME_AFTER_LONG_TRAM
;
1368 switch (rd
.x
& 0x3) {
1369 default: NOT_REACHED();
1370 case DIAGDIR_NW
: dir
= TRACKDIR_RVREV_SE
; break;
1371 case DIAGDIR_NE
: dir
= TRACKDIR_RVREV_SW
; break;
1372 case DIAGDIR_SE
: dir
= TRACKDIR_RVREV_NW
; break;
1373 case DIAGDIR_SW
: dir
= TRACKDIR_RVREV_NE
; break;
1376 if (v
->IsFrontEngine()) {
1377 /* If this is the front engine, look for the right path. */
1378 dir
= RoadFindPathToDest(v
, v
->tile
, (DiagDirection
)(rd
.x
& 3));
1380 dir
= FollowPreviousRoadVehicle(v
, prev
, v
->tile
, (DiagDirection
)(rd
.x
& 3), true);
1384 if (dir
== INVALID_TRACKDIR
) {
1389 const RoadDriveEntry
*rdp
= _road_drive_data
[GetRoadTramType(v
->roadtype
)][(_settings_game
.vehicle
.road_side
<< RVS_DRIVE_SIDE
) + dir
];
1391 int x
= TileX(v
->tile
) * TILE_SIZE
+ rdp
[turn_around_start_frame
].x
;
1392 int y
= TileY(v
->tile
) * TILE_SIZE
+ rdp
[turn_around_start_frame
].y
;
1394 Direction new_dir
= RoadVehGetSlidingDirection(v
, x
, y
);
1395 if (v
->IsFrontEngine()) {
1396 const Vehicle
*u
= RoadVehFindCloseTo(v
, x
, y
, new_dir
);
1398 v
->cur_speed
= u
->First()->cur_speed
;
1399 /* We might be blocked, prevent pathfinding rerun as we already know where we are heading to. */
1400 v
->path
.tile
.push_front(v
->tile
);
1401 v
->path
.td
.push_front(dir
);
1406 uint32_t r
= VehicleEnterTile(v
, v
->tile
, x
, y
);
1407 if (HasBit(r
, VETS_CANNOT_ENTER
)) {
1413 v
->frame
= turn_around_start_frame
;
1415 if (new_dir
!= v
->direction
) {
1416 v
->direction
= new_dir
;
1417 if (_settings_game
.vehicle
.roadveh_acceleration_model
== AM_ORIGINAL
) v
->cur_speed
-= v
->cur_speed
>> 2;
1422 v
->UpdatePosition();
1423 RoadZPosAffectSpeed(v
, v
->UpdateInclination(true, true));
1427 /* This vehicle is not in a wormhole and it hasn't entered a new tile. If
1428 * it's on a depot tile, check if it's time to activate the next vehicle in
1430 if (v
->Next() != nullptr && IsRoadDepotTile(v
->tile
)) {
1431 if (v
->frame
== v
->gcache
.cached_veh_length
+ RVC_DEPOT_START_FRAME
) {
1432 RoadVehLeaveDepot(v
->Next(), false);
1436 /* Calculate new position for the vehicle */
1437 int x
= (v
->x_pos
& ~15) + (rd
.x
& 15);
1438 int y
= (v
->y_pos
& ~15) + (rd
.y
& 15);
1440 Direction new_dir
= RoadVehGetSlidingDirection(v
, x
, y
);
1442 if (v
->IsFrontEngine() && !IsInsideMM(v
->state
, RVSB_IN_ROAD_STOP
, RVSB_IN_ROAD_STOP_END
)) {
1443 /* Vehicle is not in a road stop.
1444 * Check for another vehicle to overtake */
1445 RoadVehicle
*u
= RoadVehFindCloseTo(v
, x
, y
, new_dir
);
1449 /* There is a vehicle in front overtake it if possible */
1450 if (v
->overtaking
== 0) RoadVehCheckOvertake(v
, u
);
1451 if (v
->overtaking
== 0) v
->cur_speed
= u
->cur_speed
;
1453 /* In case an RV is stopped in a road stop, why not try to load? */
1454 if (v
->cur_speed
== 0 && IsInsideMM(v
->state
, RVSB_IN_DT_ROAD_STOP
, RVSB_IN_DT_ROAD_STOP_END
) &&
1455 v
->current_order
.ShouldStopAtStation(v
, GetStationIndex(v
->tile
)) &&
1456 v
->owner
== GetTileOwner(v
->tile
) && !v
->current_order
.IsType(OT_LEAVESTATION
) &&
1457 GetRoadStopType(v
->tile
) == (v
->IsBus() ? ROADSTOP_BUS
: ROADSTOP_TRUCK
)) {
1458 Station
*st
= Station::GetByTile(v
->tile
);
1459 v
->last_station_visited
= st
->index
;
1460 RoadVehArrivesAt(v
, st
);
1467 Direction old_dir
= v
->direction
;
1468 if (new_dir
!= old_dir
) {
1469 v
->direction
= new_dir
;
1470 if (_settings_game
.vehicle
.roadveh_acceleration_model
== AM_ORIGINAL
) v
->cur_speed
-= v
->cur_speed
>> 2;
1472 /* Delay the vehicle in curves by making it require one additional frame per turning direction (two in total).
1473 * A vehicle has to spend at least 9 frames on a tile, so the following articulated part can follow.
1474 * (The following part may only be one tile behind, and the front part is moved before the following ones.)
1475 * The short (inner) curve has 8 frames, this elongates it to 10. */
1476 v
->UpdateViewport(true, true);
1480 /* If the vehicle is in a normal road stop and the frame equals the stop frame OR
1481 * if the vehicle is in a drive-through road stop and this is the destination station
1482 * and it's the correct type of stop (bus or truck) and the frame equals the stop frame...
1483 * (the station test and stop type test ensure that other vehicles, using the road stop as
1484 * a through route, do not stop) */
1485 if (v
->IsFrontEngine() && ((IsInsideMM(v
->state
, RVSB_IN_ROAD_STOP
, RVSB_IN_ROAD_STOP_END
) &&
1486 _road_stop_stop_frame
[v
->state
- RVSB_IN_ROAD_STOP
+ (_settings_game
.vehicle
.road_side
<< RVS_DRIVE_SIDE
)] == v
->frame
) ||
1487 (IsInsideMM(v
->state
, RVSB_IN_DT_ROAD_STOP
, RVSB_IN_DT_ROAD_STOP_END
) &&
1488 v
->current_order
.ShouldStopAtStation(v
, GetStationIndex(v
->tile
)) &&
1489 v
->owner
== GetTileOwner(v
->tile
) &&
1490 GetRoadStopType(v
->tile
) == (v
->IsBus() ? ROADSTOP_BUS
: ROADSTOP_TRUCK
) &&
1491 v
->frame
== RVC_DRIVE_THROUGH_STOP_FRAME
))) {
1493 RoadStop
*rs
= RoadStop::GetByTile(v
->tile
, GetRoadStopType(v
->tile
));
1494 Station
*st
= Station::GetByTile(v
->tile
);
1496 /* Vehicle is at the stop position (at a bay) in a road stop.
1497 * Note, if vehicle is loading/unloading it has already been handled,
1498 * so if we get here the vehicle has just arrived or is just ready to leave. */
1499 if (!HasBit(v
->state
, RVS_ENTERED_STOP
)) {
1500 /* Vehicle has arrived at a bay in a road stop */
1502 if (IsDriveThroughStopTile(v
->tile
)) {
1503 TileIndex next_tile
= TileAddByDir(v
->tile
, v
->direction
);
1505 /* Check if next inline bay is free and has compatible road. */
1506 if (RoadStop::IsDriveThroughRoadStopContinuation(v
->tile
, next_tile
) && HasTileAnyRoadType(next_tile
, v
->compatible_roadtypes
)) {
1510 v
->UpdatePosition();
1511 RoadZPosAffectSpeed(v
, v
->UpdateInclination(true, false));
1516 rs
->SetEntranceBusy(false);
1517 SetBit(v
->state
, RVS_ENTERED_STOP
);
1519 v
->last_station_visited
= st
->index
;
1521 if (IsDriveThroughStopTile(v
->tile
) || (v
->current_order
.IsType(OT_GOTO_STATION
) && v
->current_order
.GetDestination() == st
->index
)) {
1522 RoadVehArrivesAt(v
, st
);
1527 /* Vehicle is ready to leave a bay in a road stop */
1528 if (rs
->IsEntranceBusy()) {
1529 /* Road stop entrance is busy, so wait as there is nowhere else to go */
1533 if (v
->current_order
.IsType(OT_LEAVESTATION
)) v
->current_order
.Free();
1536 if (IsBayRoadStopTile(v
->tile
)) rs
->SetEntranceBusy(true);
1538 StartRoadVehSound(v
);
1539 SetWindowWidgetDirty(WC_VEHICLE_VIEW
, v
->index
, WID_VV_START_STOP
);
1542 /* Check tile position conditions - i.e. stop position in depot,
1543 * entry onto bridge or into tunnel */
1544 uint32_t r
= VehicleEnterTile(v
, v
->tile
, x
, y
);
1545 if (HasBit(r
, VETS_CANNOT_ENTER
)) {
1550 if (v
->current_order
.IsType(OT_LEAVESTATION
) && IsDriveThroughStopTile(v
->tile
)) {
1551 v
->current_order
.Free();
1554 /* Move to next frame unless vehicle arrived at a stop position
1555 * in a depot or entered a tunnel/bridge */
1556 if (!HasBit(r
, VETS_ENTERED_WORMHOLE
)) v
->frame
++;
1559 v
->UpdatePosition();
1560 RoadZPosAffectSpeed(v
, v
->UpdateInclination(false, true));
1564 static bool RoadVehController(RoadVehicle
*v
)
1566 /* decrease counters */
1567 v
->current_order_time
++;
1568 if (v
->reverse_ctr
!= 0) v
->reverse_ctr
--;
1570 /* handle crashed */
1571 if (v
->vehstatus
& VS_CRASHED
|| RoadVehCheckTrainCrash(v
)) {
1572 return RoadVehIsCrashed(v
);
1575 /* road vehicle has broken down? */
1576 if (v
->HandleBreakdown()) return true;
1577 if (v
->vehstatus
& VS_STOPPED
) {
1585 if (v
->current_order
.IsType(OT_LOADING
)) return true;
1587 if (v
->IsInDepot()) {
1588 /* Check if we should wait here for unbunching. */
1589 if (v
->IsWaitingForUnbunching()) return true;
1590 if (RoadVehLeaveDepot(v
, true)) return true;
1593 v
->ShowVisualEffect();
1595 /* Check how far the vehicle needs to proceed */
1596 int j
= v
->UpdateSpeed();
1598 int adv_spd
= v
->GetAdvanceDistance();
1599 bool blocked
= false;
1600 while (j
>= adv_spd
) {
1604 for (RoadVehicle
*prev
= nullptr; u
!= nullptr; prev
= u
, u
= u
->Next()) {
1605 if (!IndividualRoadVehicleController(u
, prev
)) {
1612 /* Determine distance to next map position */
1613 adv_spd
= v
->GetAdvanceDistance();
1615 /* Test for a collision, but only if another movement will occur. */
1616 if (j
>= adv_spd
&& RoadVehCheckTrainCrash(v
)) break;
1621 for (RoadVehicle
*u
= v
; u
!= nullptr; u
= u
->Next()) {
1622 if ((u
->vehstatus
& VS_HIDDEN
) != 0) continue;
1624 u
->UpdateViewport(false, false);
1627 /* If movement is blocked, set 'progress' to its maximum, so the roadvehicle does
1628 * not accelerate again before it can actually move. I.e. make sure it tries to advance again
1629 * on next tick to discover whether it is still blocked. */
1630 if (v
->progress
== 0) v
->progress
= blocked
? adv_spd
- 1 : j
;
1635 Money
RoadVehicle::GetRunningCost() const
1637 const Engine
*e
= this->GetEngine();
1638 if (e
->u
.road
.running_cost_class
== INVALID_PRICE
) return 0;
1640 uint cost_factor
= GetVehicleProperty(this, PROP_ROADVEH_RUNNING_COST_FACTOR
, e
->u
.road
.running_cost
);
1641 if (cost_factor
== 0) return 0;
1643 return GetPrice(e
->u
.road
.running_cost_class
, cost_factor
, e
->GetGRF());
1646 bool RoadVehicle::Tick()
1648 PerformanceAccumulator
framerate(PFE_GL_ROADVEHS
);
1650 this->tick_counter
++;
1652 if (this->IsFrontEngine()) {
1653 if (!(this->vehstatus
& VS_STOPPED
)) this->running_ticks
++;
1654 return RoadVehController(this);
1660 void RoadVehicle::SetDestTile(TileIndex tile
)
1662 if (tile
== this->dest_tile
) return;
1664 this->dest_tile
= tile
;
1667 static void CheckIfRoadVehNeedsService(RoadVehicle
*v
)
1669 /* If we already got a slot at a stop, use that FIRST, and go to a depot later */
1670 if (Company::Get(v
->owner
)->settings
.vehicle
.servint_roadveh
== 0 || !v
->NeedsAutomaticServicing()) return;
1671 if (v
->IsChainInDepot()) {
1672 VehicleServiceInDepot(v
);
1676 uint max_penalty
= _settings_game
.pf
.yapf
.maximum_go_to_depot_penalty
;
1678 FindDepotData rfdd
= FindClosestRoadDepot(v
, max_penalty
);
1679 /* Only go to the depot if it is not too far out of our way. */
1680 if (rfdd
.best_length
== UINT_MAX
|| rfdd
.best_length
> max_penalty
) {
1681 if (v
->current_order
.IsType(OT_GOTO_DEPOT
)) {
1682 /* If we were already heading for a depot but it has
1683 * suddenly moved farther away, we continue our normal
1685 v
->current_order
.MakeDummy();
1686 SetWindowWidgetDirty(WC_VEHICLE_VIEW
, v
->index
, WID_VV_START_STOP
);
1691 DepotID depot
= GetDepotIndex(rfdd
.tile
);
1693 if (v
->current_order
.IsType(OT_GOTO_DEPOT
) &&
1694 v
->current_order
.GetNonStopType() & ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS
&&
1699 SetBit(v
->gv_flags
, GVF_SUPPRESS_IMPLICIT_ORDERS
);
1700 v
->current_order
.MakeGoToDepot(depot
, ODTFB_SERVICE
);
1701 v
->SetDestTile(rfdd
.tile
);
1702 SetWindowWidgetDirty(WC_VEHICLE_VIEW
, v
->index
, WID_VV_START_STOP
);
1705 /** Calandar day handler */
1706 void RoadVehicle::OnNewCalendarDay()
1708 if (!this->IsFrontEngine()) return;
1712 /** Economy day handler. */
1713 void RoadVehicle::OnNewEconomyDay()
1715 if (!this->IsFrontEngine()) return;
1716 EconomyAgeVehicle(this);
1718 if ((++this->day_counter
& 7) == 0) DecreaseVehicleValue(this);
1719 if (this->blocked_ctr
== 0) CheckVehicleBreakdown(this);
1721 CheckIfRoadVehNeedsService(this);
1725 if (this->running_ticks
== 0) return;
1727 CommandCost
cost(EXPENSES_ROADVEH_RUN
, this->GetRunningCost() * this->running_ticks
/ (CalendarTime::DAYS_IN_YEAR
* Ticks::DAY_TICKS
));
1729 this->profit_this_year
-= cost
.GetCost();
1730 this->running_ticks
= 0;
1732 SubtractMoneyFromCompanyFract(this->owner
, cost
);
1734 SetWindowDirty(WC_VEHICLE_DETAILS
, this->index
);
1735 SetWindowClassesDirty(WC_ROADVEH_LIST
);
1738 Trackdir
RoadVehicle::GetVehicleTrackdir() const
1740 if (this->vehstatus
& VS_CRASHED
) return INVALID_TRACKDIR
;
1742 if (this->IsInDepot()) {
1743 /* We'll assume the road vehicle is facing outwards */
1744 return DiagDirToDiagTrackdir(GetRoadDepotDirection(this->tile
));
1747 if (IsBayRoadStopTile(this->tile
)) {
1748 /* We'll assume the road vehicle is facing outwards */
1749 return DiagDirToDiagTrackdir(GetBayRoadStopDir(this->tile
)); // Road vehicle in a station
1752 /* Drive through road stops / wormholes (tunnels) */
1753 if (this->state
> RVSB_TRACKDIR_MASK
) return DiagDirToDiagTrackdir(DirToDiagDir(this->direction
));
1755 /* If vehicle's state is a valid track direction (vehicle is not turning around) return it,
1756 * otherwise transform it into a valid track direction */
1757 return (Trackdir
)((IsReversingRoadTrackdir((Trackdir
)this->state
)) ? (this->state
- 6) : this->state
);
1760 uint16_t RoadVehicle::GetMaxWeight() const
1762 uint16_t weight
= CargoSpec::Get(this->cargo_type
)->WeightOfNUnits(this->GetEngine()->DetermineCapacity(this));
1764 /* Vehicle weight is not added for articulated parts. */
1765 if (!this->IsArticulatedPart()) {
1766 /* Road vehicle weight is in units of 1/4 t. */
1767 weight
+= GetVehicleProperty(this, PROP_ROADVEH_WEIGHT
, RoadVehInfo(this->engine_type
)->weight
) / 4;