Fix some daylength issues, possible division by zero in main menu.
[openttd-joker.git] / src / roadveh_cmd.cpp
blobc2c4418590c9b24d66e984da9d2819fa83bb5888
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8 */
10 /** @file roadveh_cmd.cpp Handling of road vehicles. */
12 #include "stdafx.h"
13 #include "roadveh.h"
14 #include "command_func.h"
15 #include "news_func.h"
16 #include "pathfinder/npf/npf_func.h"
17 #include "station_base.h"
18 #include "company_func.h"
19 #include "articulated_vehicles.h"
20 #include "newgrf_sound.h"
21 #include "pathfinder/yapf/yapf.h"
22 #include "strings_func.h"
23 #include "tunnelbridge_map.h"
24 #include "date_func.h"
25 #include "vehicle_func.h"
26 #include "sound_func.h"
27 #include "ai/ai.hpp"
28 #include "game/game.hpp"
29 #include "depot_map.h"
30 #include "effectvehicle_func.h"
31 #include "roadstop_base.h"
32 #include "spritecache.h"
33 #include "core/random_func.hpp"
34 #include "company_base.h"
35 #include "core/backup_type.hpp"
36 #include "newgrf.h"
37 #include "zoom_func.h"
39 #include "table/strings.h"
41 #include "safeguards.h"
43 static const uint16 _roadveh_images[] = {
44 0xCD4, 0xCDC, 0xCE4, 0xCEC, 0xCF4, 0xCFC, 0xD0C, 0xD14,
45 0xD24, 0xD1C, 0xD2C, 0xD04, 0xD1C, 0xD24, 0xD6C, 0xD74,
46 0xD7C, 0xC14, 0xC1C, 0xC24, 0xC2C, 0xC34, 0xC3C, 0xC4C,
47 0xC54, 0xC64, 0xC5C, 0xC6C, 0xC44, 0xC5C, 0xC64, 0xCAC,
48 0xCB4, 0xCBC, 0xD94, 0xD9C, 0xDA4, 0xDAC, 0xDB4, 0xDBC,
49 0xDCC, 0xDD4, 0xDE4, 0xDDC, 0xDEC, 0xDC4, 0xDDC, 0xDE4,
50 0xE2C, 0xE34, 0xE3C, 0xC14, 0xC1C, 0xC2C, 0xC3C, 0xC4C,
51 0xC5C, 0xC64, 0xC6C, 0xC74, 0xC84, 0xC94, 0xCA4
54 static const uint16 _roadveh_full_adder[] = {
55 0, 88, 0, 0, 0, 0, 48, 48,
56 48, 48, 0, 0, 64, 64, 0, 16,
57 16, 0, 88, 0, 0, 0, 0, 48,
58 48, 48, 48, 0, 0, 64, 64, 0,
59 16, 16, 0, 88, 0, 0, 0, 0,
60 48, 48, 48, 48, 0, 0, 64, 64,
61 0, 16, 16, 0, 8, 8, 8, 8,
62 0, 0, 0, 8, 8, 8, 8
64 assert_compile(lengthof(_roadveh_images) == lengthof(_roadveh_full_adder));
66 template <>
67 bool IsValidImageIndex<VEH_ROAD>(uint8 image_index)
69 return image_index < lengthof(_roadveh_images);
72 static const Trackdir _road_reverse_table[DIAGDIR_END] = {
73 TRACKDIR_RVREV_NE, TRACKDIR_RVREV_SE, TRACKDIR_RVREV_SW, TRACKDIR_RVREV_NW
76 /**
77 * Check whether a roadvehicle is a bus
78 * @return true if bus
80 bool RoadVehicle::IsBus() const
82 assert(this->IsFrontEngine());
83 return IsCargoInClass(this->cargo_type, CC_PASSENGERS);
86 /**
87 * Get the width of a road vehicle image in the GUI.
88 * @param offset Additional offset for positioning the sprite; set to NULL if not needed
89 * @return Width in pixels
91 int RoadVehicle::GetDisplayImageWidth(Point *offset) const
93 int reference_width = ROADVEHINFO_DEFAULT_VEHICLE_WIDTH;
95 if (offset != NULL) {
96 offset->x = ScaleGUITrad(reference_width) / 2;
97 offset->y = 0;
99 return ScaleGUITrad(this->gcache.cached_veh_length * reference_width / VEHICLE_LENGTH);
102 static void GetRoadVehIcon(EngineID engine, EngineImageType image_type, VehicleSpriteSeq *result)
104 const Engine *e = Engine::Get(engine);
105 uint8 spritenum = e->u.road.image_index;
107 if (is_custom_sprite(spritenum)) {
108 GetCustomVehicleIcon(engine, DIR_W, image_type, result);
109 if (result->IsValid()) return;
111 spritenum = e->original_image_index;
114 assert(IsValidImageIndex<VEH_ROAD>(spritenum));
115 result->Set(DIR_W + _roadveh_images[spritenum]);
118 void RoadVehicle::GetImage(Direction direction, EngineImageType image_type, VehicleSpriteSeq *result) const
120 uint8 spritenum = this->spritenum;
122 if (is_custom_sprite(spritenum)) {
123 GetCustomVehicleSprite(this, (Direction)(direction + 4 * IS_CUSTOM_SECONDHEAD_SPRITE(spritenum)), image_type, result);
124 if (result->IsValid()) return;
126 spritenum = this->GetEngine()->original_image_index;
129 assert(IsValidImageIndex<VEH_ROAD>(spritenum));
130 SpriteID sprite = direction + _roadveh_images[spritenum];
132 if (this->cargo.StoredCount() >= this->cargo_cap / 2U) sprite += _roadveh_full_adder[spritenum];
134 result->Set(sprite);
138 * Draw a road vehicle engine.
139 * @param left Left edge to draw within.
140 * @param right Right edge to draw within.
141 * @param preferred_x Preferred position of the engine.
142 * @param y Vertical position of the engine.
143 * @param engine Engine to draw
144 * @param pal Palette to use.
146 void DrawRoadVehEngine(int left, int right, int preferred_x, int y, EngineID engine, PaletteID pal, EngineImageType image_type)
148 VehicleSpriteSeq seq;
149 GetRoadVehIcon(engine, image_type, &seq);
151 Rect16 rect = seq.GetBounds();
152 preferred_x = Clamp(preferred_x,
153 left - UnScaleGUI(rect.left),
154 right - UnScaleGUI(rect.right));
156 seq.Draw(preferred_x, y, pal, pal == PALETTE_CRASH);
160 * Get the size of the sprite of a road vehicle sprite heading west (used for lists).
161 * @param engine The engine to get the sprite from.
162 * @param[out] width The width of the sprite.
163 * @param[out] height The height of the sprite.
164 * @param[out] xoffs Number of pixels to shift the sprite to the right.
165 * @param[out] yoffs Number of pixels to shift the sprite downwards.
166 * @param image_type Context the sprite is used in.
168 void GetRoadVehSpriteSize(EngineID engine, uint &width, uint &height, int &xoffs, int &yoffs, EngineImageType image_type)
170 VehicleSpriteSeq seq;
171 GetRoadVehIcon(engine, image_type, &seq);
173 Rect16 rect = seq.GetBounds();
175 width = UnScaleGUI(rect.right - rect.left + 1);
176 height = UnScaleGUI(rect.bottom - rect.top + 1);
177 xoffs = UnScaleGUI(rect.left);
178 yoffs = UnScaleGUI(rect.top);
182 * Get length of a road vehicle.
183 * @param v Road vehicle to query length.
184 * @return Length of the given road vehicle.
186 static uint GetRoadVehLength(const RoadVehicle *v)
188 const Engine *e = v->GetEngine();
189 uint length = VEHICLE_LENGTH;
191 uint16 veh_len = CALLBACK_FAILED;
192 if (e->GetGRF() != NULL && e->GetGRF()->grf_version >= 8) {
193 /* Use callback 36 */
194 veh_len = GetVehicleProperty(v, PROP_ROADVEH_SHORTEN_FACTOR, CALLBACK_FAILED);
195 if (veh_len != CALLBACK_FAILED && veh_len >= VEHICLE_LENGTH) ErrorUnknownCallbackResult(e->GetGRFID(), CBID_VEHICLE_LENGTH, veh_len);
196 } else {
197 /* Use callback 11 */
198 veh_len = GetVehicleCallback(CBID_VEHICLE_LENGTH, 0, 0, v->engine_type, v);
200 if (veh_len == CALLBACK_FAILED) veh_len = e->u.road.shorten_factor;
201 if (veh_len != 0) {
202 length -= Clamp(veh_len, 0, VEHICLE_LENGTH - 1);
205 return length;
209 * Update the cache of a road vehicle.
210 * @param v Road vehicle needing an update of its cache.
211 * @param same_length should length of vehicles stay the same?
212 * @pre \a v must be first road vehicle.
214 void RoadVehUpdateCache(RoadVehicle *v, bool same_length)
216 assert(v->type == VEH_ROAD);
217 assert(v->IsFrontEngine());
219 v->InvalidateNewGRFCacheOfChain();
221 v->gcache.cached_total_length = 0;
223 for (RoadVehicle *u = v; u != NULL; u = u->Next()) {
224 /* Check the v->first cache. */
225 assert(u->First() == v);
227 /* Update the 'first engine' */
228 u->gcache.first_engine = (v == u) ? INVALID_ENGINE : v->engine_type;
230 /* Update the length of the vehicle. */
231 uint veh_len = GetRoadVehLength(u);
232 /* Verify length hasn't changed. */
233 if (same_length && veh_len != u->gcache.cached_veh_length) VehicleLengthChanged(u);
235 u->gcache.cached_veh_length = veh_len;
236 v->gcache.cached_total_length += u->gcache.cached_veh_length;
238 /* Update visual effect */
239 u->UpdateVisualEffect();
241 /* Update cargo aging period. */
242 u->vcache.cached_cargo_age_period = GetVehicleProperty(u, PROP_ROADVEH_CARGO_AGE_PERIOD, EngInfo(u->engine_type)->cargo_age_period);
245 uint max_speed = GetVehicleProperty(v, PROP_ROADVEH_SPEED, 0);
246 v->vcache.cached_max_speed = (max_speed != 0) ? max_speed * 4 : RoadVehInfo(v->engine_type)->max_speed;
250 * Build a road vehicle.
251 * @param tile tile of the depot where road vehicle is built.
252 * @param flags type of operation.
253 * @param e the engine to build.
254 * @param data unused.
255 * @param ret[out] the vehicle that has been built.
256 * @return the cost of this operation or an error.
258 CommandCost CmdBuildRoadVehicle(TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **ret)
260 if (HasTileRoadType(tile, ROADTYPE_TRAM) != HasBit(e->info.misc_flags, EF_ROAD_TRAM)) return_cmd_error(STR_ERROR_DEPOT_WRONG_DEPOT_TYPE);
262 if (flags & DC_EXEC) {
263 const RoadVehicleInfo *rvi = &e->u.road;
265 RoadVehicle *v = new RoadVehicle();
266 *ret = v;
267 v->direction = DiagDirToDir(GetRoadDepotDirection(tile));
268 v->owner = _current_company;
270 v->tile = tile;
271 int x = TileX(tile) * TILE_SIZE + TILE_SIZE / 2;
272 int y = TileY(tile) * TILE_SIZE + TILE_SIZE / 2;
273 v->x_pos = x;
274 v->y_pos = y;
275 v->z_pos = GetSlopePixelZ(x, y);
277 v->state = RVSB_IN_DEPOT;
278 v->vehstatus = VS_HIDDEN | VS_STOPPED | VS_DEFPAL;
280 v->spritenum = rvi->image_index;
281 v->cargo_type = e->GetDefaultCargoType();
282 v->cargo_cap = rvi->capacity;
283 v->refit_cap = 0;
285 v->last_station_visited = INVALID_STATION;
286 v->last_loading_station = INVALID_STATION;
287 v->engine_type = e->index;
288 v->gcache.first_engine = INVALID_ENGINE; // needs to be set before first callback
290 v->reliability = e->reliability;
291 v->reliability_spd_dec = e->reliability_spd_dec;
292 v->max_age = e->GetLifeLengthInDays();
293 _new_vehicle_id = v->index;
295 v->SetServiceInterval(Company::Get(v->owner)->settings.vehicle.servint_roadveh);
297 v->date_of_last_service = _date;
298 v->build_year = _cur_year;
300 v->sprite_seq.Set(SPR_IMG_QUERY);
301 v->random_bits = VehicleRandomBits();
302 v->SetFrontEngine();
304 v->roadtype = HasBit(e->info.misc_flags, EF_ROAD_TRAM) ? ROADTYPE_TRAM : ROADTYPE_ROAD;
305 v->compatible_roadtypes = RoadTypeToRoadTypes(v->roadtype);
306 v->gcache.cached_veh_length = VEHICLE_LENGTH;
308 if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) SetBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE);
309 v->SetServiceIntervalIsPercent(Company::Get(_current_company)->settings.vehicle.servint_ispercent);
311 AddArticulatedParts(v);
312 v->InvalidateNewGRFCacheOfChain();
314 /* Call various callbacks after the whole consist has been constructed */
315 for (RoadVehicle *u = v; u != NULL; u = u->Next()) {
316 u->cargo_cap = u->GetEngine()->DetermineCapacity(u);
317 u->refit_cap = 0;
318 v->InvalidateNewGRFCache();
319 u->InvalidateNewGRFCache();
321 RoadVehUpdateCache(v);
322 /* Initialize cached values for realistic acceleration. */
323 if (_settings_game.vehicle.roadveh_acceleration_model != AM_ORIGINAL) v->CargoChanged();
325 v->UpdatePosition();
327 CheckConsistencyOfArticulatedVehicle(v);
330 return CommandCost();
333 static FindDepotData FindClosestRoadDepot(const RoadVehicle *v, int max_distance)
335 if (IsRoadDepotTile(v->tile)) return FindDepotData(v->tile, 0);
337 switch (_settings_game.pf.pathfinder_for_roadvehs) {
338 case VPF_NPF: return NPFRoadVehicleFindNearestDepot(v, max_distance);
339 case VPF_YAPF: return YapfRoadVehicleFindNearestDepot(v, max_distance);
341 default: NOT_REACHED();
345 bool RoadVehicle::FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
347 FindDepotData rfdd = FindClosestRoadDepot(this, 0);
348 if (rfdd.best_length == UINT_MAX) return false;
350 if (location != NULL) *location = rfdd.tile;
351 if (destination != NULL) *destination = GetDepotIndex(rfdd.tile);
353 return true;
357 * Turn a roadvehicle around.
358 * @param tile unused
359 * @param flags operation to perform
360 * @param p1 vehicle ID to turn
361 * @param p2 unused
362 * @param text unused
363 * @return the cost of this operation or an error
365 CommandCost CmdTurnRoadVeh(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
367 RoadVehicle *v = RoadVehicle::GetIfValid(p1);
368 if (v == NULL) return CMD_ERROR;
370 if (!v->IsPrimaryVehicle()) return CMD_ERROR;
372 CommandCost ret = CheckOwnership(v->owner);
373 if (ret.Failed()) return ret;
375 if ((v->vehstatus & VS_STOPPED) ||
376 (v->vehstatus & VS_CRASHED) ||
377 v->breakdown_ctr != 0 ||
378 v->overtaking != 0 ||
379 v->state == RVSB_WORMHOLE ||
380 v->IsInDepot() ||
381 v->current_order.IsType(OT_LOADING)) {
382 return CMD_ERROR;
385 if (IsNormalRoadTile(v->tile) && GetDisallowedRoadDirections(v->tile) != DRD_NONE) return CMD_ERROR;
387 if (IsTileType(v->tile, MP_TUNNELBRIDGE) && DirToDiagDir(v->direction) == GetTunnelBridgeDirection(v->tile)) return CMD_ERROR;
389 if (flags & DC_EXEC) v->reverse_ctr = 180;
391 return CommandCost();
395 void RoadVehicle::MarkDirty()
397 for (RoadVehicle *v = this; v != NULL; v = v->Next()) {
398 v->colourmap = PAL_NONE;
399 v->UpdateViewport(true, false);
401 this->CargoChanged();
404 void RoadVehicle::UpdateDeltaXY(Direction direction)
406 static const int8 _delta_xy_table[8][10] = {
407 /* 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 */
408 {3, 3, -1, -1, 0, 0, -1, -1, -1, -1}, // N
409 {3, 7, -1, -3, 0, -1, 0, -1, 0, 0}, // NE
410 {3, 3, -1, -1, 0, 0, 1, -1, 1, -1}, // E
411 {7, 3, -3, -1, -1, 0, 0, 0, 1, 0}, // SE
412 {3, 3, -1, -1, 0, 0, 1, 1, 1, 1}, // S
413 {3, 7, -1, -3, 0, -1, 0, 0, 0, 1}, // SW
414 {3, 3, -1, -1, 0, 0, -1, 1, -1, 1}, // W
415 {7, 3, -3, -1, -1, 0, -1, 0, 0, 0}, // NW
418 int shorten = VEHICLE_LENGTH - this->gcache.cached_veh_length;
419 if (!IsDiagonalDirection(direction)) shorten >>= 1;
421 const int8 *bb = _delta_xy_table[direction];
422 this->x_bb_offs = bb[5] + bb[9] * shorten;
423 this->y_bb_offs = bb[4] + bb[8] * shorten;;
424 this->x_offs = bb[3];
425 this->y_offs = bb[2];
426 this->x_extent = bb[1] + bb[7] * shorten;
427 this->y_extent = bb[0] + bb[6] * shorten;
428 this->z_extent = 6;
432 * Calculates the maximum speed of the vehicle under its current conditions.
433 * @return Maximum speed of the vehicle.
435 inline int RoadVehicle::GetCurrentMaxSpeed() const
437 int max_speed = this->vcache.cached_max_speed;
439 /* Limit speed to 50% while reversing, 75% in curves. */
440 for (const RoadVehicle *u = this; u != NULL; u = u->Next()) {
441 if (_settings_game.vehicle.roadveh_acceleration_model == AM_REALISTIC) {
442 if (this->state <= RVSB_TRACKDIR_MASK && IsReversingRoadTrackdir((Trackdir)this->state)) {
443 max_speed = this->vcache.cached_max_speed / 2;
444 break;
445 } else if ((u->direction & 1) == 0) {
446 max_speed = this->vcache.cached_max_speed * 3 / 4;
450 /* Vehicle is on the middle part of a bridge. */
451 if (u->state == RVSB_WORMHOLE && !(u->vehstatus & VS_HIDDEN)) {
452 max_speed = min(max_speed, GetBridgeSpec(GetBridgeType(u->tile))->speed * 2);
456 return min(max_speed, this->current_order.GetMaxSpeed() * 2);
460 * Delete last vehicle of a chain road vehicles.
461 * @param v First roadvehicle.
463 static void DeleteLastRoadVeh(RoadVehicle *v)
465 RoadVehicle *first = v->First();
466 Vehicle *u = v;
467 for (; v->Next() != NULL; v = v->Next()) u = v;
468 u->SetNext(NULL);
469 v->last_station_visited = first->last_station_visited; // for PreDestructor
471 /* Only leave the road stop when we're really gone. */
472 if (IsInsideMM(v->state, RVSB_IN_ROAD_STOP, RVSB_IN_ROAD_STOP_END)) RoadStop::GetByTile(v->tile, GetRoadStopType(v->tile))->Leave(v);
474 delete v;
477 static void RoadVehSetRandomDirection(RoadVehicle *v)
479 static const DirDiff delta[] = {
480 DIRDIFF_45LEFT, DIRDIFF_SAME, DIRDIFF_SAME, DIRDIFF_45RIGHT
483 do {
484 uint32 r = Random();
486 v->direction = ChangeDir(v->direction, delta[r & 3]);
487 v->UpdateViewport(true, true);
488 } while ((v = v->Next()) != NULL);
492 * Road vehicle chain has crashed.
493 * @param v First roadvehicle.
494 * @return whether the chain still exists.
496 static bool RoadVehIsCrashed(RoadVehicle *v)
498 v->crashed_ctr++;
499 if (v->crashed_ctr == 2) {
500 CreateEffectVehicleRel(v, 4, 4, 8, EV_EXPLOSION_LARGE);
501 } else if (v->crashed_ctr <= 45) {
502 if ((v->tick_counter & 7) == 0) RoadVehSetRandomDirection(v);
503 } else if (v->crashed_ctr >= 2220 && !(v->tick_counter & 0x1F)) {
504 bool ret = v->Next() != NULL;
505 DeleteLastRoadVeh(v);
506 return ret;
509 return true;
513 * Check routine whether a road and a train vehicle have collided.
514 * @param v %Train vehicle to test.
515 * @param data Road vehicle to test.
516 * @return %Train vehicle if the vehicles collided, else \c NULL.
518 static Vehicle *EnumCheckRoadVehCrashTrain(Vehicle *v, void *data)
520 const Vehicle *u = (Vehicle*)data;
522 return (v->type == VEH_TRAIN &&
523 abs(v->z_pos - u->z_pos) <= 6 &&
524 abs(v->x_pos - u->x_pos) <= 4 &&
525 abs(v->y_pos - u->y_pos) <= 4) ? v : NULL;
528 uint RoadVehicle::Crash(bool flooded)
530 uint pass = this->GroundVehicleBase::Crash(flooded);
531 if (this->IsFrontEngine()) {
532 pass += 1; // driver
534 /* If we're in a drive through road stop we ought to leave it */
535 if (IsInsideMM(this->state, RVSB_IN_DT_ROAD_STOP, RVSB_IN_DT_ROAD_STOP_END)) {
536 RoadStop::GetByTile(this->tile, GetRoadStopType(this->tile))->Leave(this);
539 this->crashed_ctr = flooded ? 2000 : 1; // max 2220, disappear pretty fast when flooded
540 return pass;
543 static void RoadVehCrash(RoadVehicle *v)
545 uint pass = v->Crash();
547 AI::NewEvent(v->owner, new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_RV_LEVEL_CROSSING));
548 Game::NewEvent(new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_RV_LEVEL_CROSSING));
550 SetDParam(0, pass);
551 AddVehicleNewsItem(
552 (pass == 1) ?
553 STR_NEWS_ROAD_VEHICLE_CRASH_DRIVER : STR_NEWS_ROAD_VEHICLE_CRASH,
554 NT_ACCIDENT,
555 v->index
558 ModifyStationRatingAround(v->tile, v->owner, -160, 22);
559 if (_settings_client.sound.disaster) SndPlayVehicleFx(SND_12_EXPLOSION, v);
562 static bool RoadVehCheckTrainCrash(RoadVehicle *v)
564 //for (RoadVehicle *u = v; u != NULL; u = u->Next()) {
565 // if (u->state == RVSB_WORMHOLE) continue;
567 // TileIndex tile = u->tile;
569 // if (!IsLevelCrossingTile(tile)) continue;
571 // if (HasVehicleOnPosXY(v->x_pos, v->y_pos, u, EnumCheckRoadVehCrashTrain)) {
572 // RoadVehCrash(v);
573 // return true;
574 // }
577 return false;
580 TileIndex RoadVehicle::GetOrderStationLocation(StationID station)
582 if (station == this->last_station_visited) this->last_station_visited = INVALID_STATION;
584 const Station *st = Station::Get(station);
585 if (!CanVehicleUseStation(this, st)) {
586 /* There is no stop left at the station, so don't even TRY to go there */
587 this->IncrementRealOrderIndex();
588 return 0;
591 return st->xy;
594 static void StartRoadVehSound(const RoadVehicle *v)
596 if (!PlayVehicleSound(v, VSE_START)) {
597 SoundID s = RoadVehInfo(v->engine_type)->sfx;
598 if (s == SND_19_BUS_START_PULL_AWAY && (v->tick_counter & 3) == 0) {
599 s = SND_1A_BUS_START_PULL_AWAY_WITH_HORN;
601 SndPlayVehicleFx(s, v);
605 struct RoadVehFindData {
606 int x;
607 int y;
608 const Vehicle *veh;
609 Vehicle *best;
610 uint best_diff;
611 Direction dir;
614 static Vehicle *EnumCheckRoadVehClose(Vehicle *v, void *data)
616 static const int8 dist_x[] = { -4, -8, -4, -1, 4, 8, 4, 1 };
617 static const int8 dist_y[] = { -4, -1, 4, 8, 4, 1, -4, -8 };
619 RoadVehFindData *rvf = (RoadVehFindData*)data;
621 short x_diff = v->x_pos - rvf->x;
622 short y_diff = v->y_pos - rvf->y;
624 if (v->type == VEH_ROAD &&
625 !v->IsInDepot() &&
626 abs(v->z_pos - rvf->veh->z_pos) < 6 &&
627 v->direction == rvf->dir &&
628 rvf->veh->First() != v->First() &&
629 (dist_x[v->direction] >= 0 || (x_diff > dist_x[v->direction] && x_diff <= 0)) &&
630 (dist_x[v->direction] <= 0 || (x_diff < dist_x[v->direction] && x_diff >= 0)) &&
631 (dist_y[v->direction] >= 0 || (y_diff > dist_y[v->direction] && y_diff <= 0)) &&
632 (dist_y[v->direction] <= 0 || (y_diff < dist_y[v->direction] && y_diff >= 0))) {
633 uint diff = abs(x_diff) + abs(y_diff);
635 if (diff < rvf->best_diff || (diff == rvf->best_diff && v->index < rvf->best->index)) {
636 rvf->best = v;
637 rvf->best_diff = diff;
641 return NULL;
644 static RoadVehicle *RoadVehFindCloseTo(RoadVehicle *v, int x, int y, Direction dir, bool update_blocked_ctr = true)
646 RoadVehFindData rvf;
647 RoadVehicle *front = v->First();
649 if (front->reverse_ctr != 0) return NULL;
651 rvf.x = x;
652 rvf.y = y;
653 rvf.dir = dir;
654 rvf.veh = v;
655 rvf.best_diff = UINT_MAX;
657 if (front->state == RVSB_WORMHOLE) {
658 FindVehicleOnPos(v->tile, &rvf, EnumCheckRoadVehClose);
659 FindVehicleOnPos(GetOtherTunnelBridgeEnd(v->tile), &rvf, EnumCheckRoadVehClose);
660 } else {
661 FindVehicleOnPosXY(x, y, &rvf, EnumCheckRoadVehClose);
664 /* This code protects a roadvehicle from being blocked for ever
665 * If more than 1480 / 74 days a road vehicle is blocked, it will
666 * drive just through it. The ultimate backup-code of TTD.
667 * It can be disabled. */
668 if (rvf.best_diff == UINT_MAX) {
669 front->blocked_ctr = 0;
670 return NULL;
673 if (update_blocked_ctr && ++front->blocked_ctr > 1480) return NULL;
675 return RoadVehicle::From(rvf.best);
679 * A road vehicle arrives at a station. If it is the first time, create a news item.
680 * @param v Road vehicle that arrived.
681 * @param st Station where the road vehicle arrived.
683 static void RoadVehArrivesAt(const RoadVehicle *v, Station *st)
685 if (v->IsBus()) {
686 /* Check if station was ever visited before */
687 if (!(st->had_vehicle_of_type & HVOT_BUS)) {
688 st->had_vehicle_of_type |= HVOT_BUS;
689 SetDParam(0, st->index);
690 AddVehicleNewsItem(
691 v->roadtype == ROADTYPE_ROAD ? STR_NEWS_FIRST_BUS_ARRIVAL : STR_NEWS_FIRST_PASSENGER_TRAM_ARRIVAL,
692 (v->owner == _local_company) ? NT_ARRIVAL_COMPANY : NT_ARRIVAL_OTHER,
693 v->index,
694 st->index
696 AI::NewEvent(v->owner, new ScriptEventStationFirstVehicle(st->index, v->index));
697 Game::NewEvent(new ScriptEventStationFirstVehicle(st->index, v->index));
699 } else {
700 /* Check if station was ever visited before */
701 if (!(st->had_vehicle_of_type & HVOT_TRUCK)) {
702 st->had_vehicle_of_type |= HVOT_TRUCK;
703 SetDParam(0, st->index);
704 AddVehicleNewsItem(
705 v->roadtype == ROADTYPE_ROAD ? STR_NEWS_FIRST_TRUCK_ARRIVAL : STR_NEWS_FIRST_CARGO_TRAM_ARRIVAL,
706 (v->owner == _local_company) ? NT_ARRIVAL_COMPANY : NT_ARRIVAL_OTHER,
707 v->index,
708 st->index
710 AI::NewEvent(v->owner, new ScriptEventStationFirstVehicle(st->index, v->index));
711 Game::NewEvent(new ScriptEventStationFirstVehicle(st->index, v->index));
717 * This function looks at the vehicle and updates its speed (cur_speed
718 * and subspeed) variables. Furthermore, it returns the distance that
719 * the vehicle can drive this tick. #Vehicle::GetAdvanceDistance() determines
720 * the distance to drive before moving a step on the map.
721 * @return distance to drive.
723 int RoadVehicle::UpdateSpeed()
725 switch (_settings_game.vehicle.roadveh_acceleration_model) {
726 default: NOT_REACHED();
727 case AM_ORIGINAL:
728 return this->DoUpdateSpeed(this->overtaking != 0 ? 512 : 256, 0, this->GetCurrentMaxSpeed());
730 case AM_REALISTIC:
731 return this->DoUpdateSpeed(this->GetAcceleration() + (this->overtaking != 0 ? 256 : 0), this->GetAccelerationStatus() == AS_BRAKE ? 0 : 4, this->GetCurrentMaxSpeed());
735 static Direction RoadVehGetNewDirection(const RoadVehicle *v, int x, int y)
737 static const Direction _roadveh_new_dir[] = {
738 DIR_N , DIR_NW, DIR_W , INVALID_DIR,
739 DIR_NE, DIR_N , DIR_SW, INVALID_DIR,
740 DIR_E , DIR_SE, DIR_S
743 x = x - v->x_pos + 1;
744 y = y - v->y_pos + 1;
746 if ((uint)x > 2 || (uint)y > 2) return v->direction;
747 return _roadveh_new_dir[y * 4 + x];
750 static Direction RoadVehGetSlidingDirection(const RoadVehicle *v, int x, int y)
752 Direction new_dir = RoadVehGetNewDirection(v, x, y);
753 Direction old_dir = v->direction;
754 DirDiff delta;
756 if (new_dir == old_dir) return old_dir;
757 delta = (DirDifference(new_dir, old_dir) > DIRDIFF_REVERSE ? DIRDIFF_45LEFT : DIRDIFF_45RIGHT);
758 return ChangeDir(old_dir, delta);
761 struct OvertakeData {
762 const RoadVehicle *u;
763 const RoadVehicle *v;
764 TileIndex tile;
765 Trackdir trackdir;
768 static Vehicle *EnumFindVehBlockingOvertake(Vehicle *v, void *data)
770 const OvertakeData *od = (OvertakeData*)data;
772 return (v->type == VEH_ROAD && v->First() == v && v != od->u && v != od->v) ? v : NULL;
775 static Vehicle *EnumFindVehPreventingOvertake(Vehicle *v, void *data)
777 const OvertakeData *od = (OvertakeData*)data;
779 Vehicle* blocking_v = EnumFindVehBlockingOvertake(v, data);
781 if (blocking_v == NULL)
782 return NULL;
784 if (blocking_v->type != VEH_ROAD)
785 return blocking_v;
787 RoadVehicle* blocking_road_v = RoadVehicle::From(blocking_v);
789 bool is_overtaking = (blocking_road_v->overtaking != 0);
790 bool is_driving_in_same_direction = (od->v->direction == blocking_road_v->direction);
791 bool has_lower_max_speed = (od->v->vcache.cached_max_speed > blocking_road_v->vcache.cached_max_speed);
792 bool has_been_stopped = (blocking_road_v->vehstatus & VS_STOPPED) != 0;
793 bool is_at_zero_speed = (blocking_road_v->cur_speed == 0);
794 bool is_straight_road_trackdir = IsStraightRoadTrackdir((Trackdir)(blocking_road_v->state & RVSB_TRACKDIR_MASK));
795 bool is_in_road_stop_or_station = (blocking_road_v->state >= RVSB_IN_ROAD_STOP) || IsTileType(blocking_road_v->tile, MP_STATION);
797 bool is_preventing = !is_driving_in_same_direction ||
798 is_overtaking ||
799 (!has_lower_max_speed && !(has_been_stopped || is_at_zero_speed)) ||
800 !is_straight_road_trackdir ||
801 is_in_road_stop_or_station;
803 return is_preventing ? blocking_v : NULL;
807 * Check if overtaking is possible on a piece of track
809 * @param od Information about the tile and the involved vehicles
810 * @return true if we have to abort overtaking
812 static bool CheckRoadBlockedForOvertaking(OvertakeData *od)
814 TrackStatus ts = GetTileTrackStatus(od->tile, TRANSPORT_ROAD, od->v->compatible_roadtypes);
815 TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts);
816 TrackdirBits red_signals = TrackStatusToRedSignals(ts); // barred level crossing
817 TrackBits trackbits = TrackdirBitsToTrackBits(trackdirbits);
819 /* Track does not continue along overtaking direction || track has junction || level crossing is barred */
820 bool track_does_continue = HasBit(trackdirbits, od->trackdir);
821 bool track_has_junction = (trackbits & ~TRACK_BIT_CROSS) != 0;
822 bool level_crossing_is_barred = (red_signals != TRACKDIR_BIT_NONE);
824 if (!track_does_continue || track_has_junction || level_crossing_is_barred) return true;
826 return HasVehicleOnPos(od->tile, od, EnumFindVehPreventingOvertake);
829 static void RoadVehCheckOvertake(RoadVehicle *v, RoadVehicle *u)
831 OvertakeData od;
833 od.v = v;
834 od.u = u;
836 bool has_lower_max_speed = (v->vcache.cached_max_speed > u->vcache.cached_max_speed);
837 bool has_been_stopped = (u->vehstatus & VS_STOPPED) != 0;
838 bool is_at_zero_speed = (u->cur_speed == 0);
840 if (!has_been_stopped && !is_at_zero_speed && !has_lower_max_speed) {
841 return;
844 /* Trams can't overtake other trams */
845 if (v->roadtype == ROADTYPE_TRAM) return;
847 /* Don't overtake in stations */
848 if (IsTileType(v->tile, MP_STATION) || IsTileType(u->tile, MP_STATION)) return;
850 /* For now, articulated road vehicles can't overtake anything. */
851 if (v->HasArticulatedPart()) return;
853 /* Vehicles are not driving in same direction || direction is not a diagonal direction */
854 bool driving_in_same_direction = (v->direction == u->direction);
855 bool diagonal_direction = (v->direction & 1);
857 if (!driving_in_same_direction || !diagonal_direction) return;
859 /* Check if vehicle is in a road stop, depot, tunnel or bridge or not on a straight road */
860 bool is_straight_road_trackdir = IsStraightRoadTrackdir((Trackdir)(v->state & RVSB_TRACKDIR_MASK));
862 if (v->state >= RVSB_IN_ROAD_STOP || !is_straight_road_trackdir) return;
864 /* Can't overtake a vehicle that is moving faster than us. If the vehicle in front is
865 * accelerating, take the maximum speed for the comparison, else the current speed.
866 * Original acceleration always accelerates, so always use the maximum speed. */
867 int u_speed = (_settings_game.vehicle.roadveh_acceleration_model == AM_ORIGINAL || u->GetAcceleration() > 0) ? u->GetCurrentMaxSpeed() : u->cur_speed;
868 if (u_speed >= v->GetCurrentMaxSpeed() &&
869 !(u->vehstatus & VS_STOPPED) &&
870 u->cur_speed != 0) {
871 return;
874 od.trackdir = DiagDirToDiagTrackdir(DirToDiagDir(v->direction));
876 /* Are the current and the next tile suitable for overtaking?
877 * - Does the track continue along od.trackdir
878 * - No junctions
879 * - No barred level crossing
880 * - No other vehicles in the way
882 od.tile = u->tile;
883 if (CheckRoadBlockedForOvertaking(&od)) return;
885 od.tile = u->tile + TileOffsByDiagDir(DirToDiagDir(u->direction));
886 if (CheckRoadBlockedForOvertaking(&od)) return;
888 /* When the vehicle in front of us is stopped we may only take
889 * half the time to pass it than when the vehicle is moving. */
890 v->overtaking_ctr = ((od.u->cur_speed == 0) || (od.u->vehstatus & VS_STOPPED)) ?
891 (RV_OVERTAKE_TIMEOUT / 2) :
893 v->overtaking = RVSB_DRIVE_SIDE;
896 static void RoadZPosAffectSpeed(RoadVehicle *v, int old_z)
898 if (old_z == v->z_pos || _settings_game.vehicle.roadveh_acceleration_model != AM_ORIGINAL) return;
900 if (old_z < v->z_pos) {
901 v->cur_speed = v->cur_speed * 232 / 256; // slow down by ~10%
902 } else {
903 uint16 spd = v->cur_speed + 2;
904 if (spd <= v->vcache.cached_max_speed) v->cur_speed = spd;
908 static int PickRandomBit(uint bits)
910 uint i;
911 uint num = RandomRange(CountBits(bits));
913 for (i = 0; !(bits & 1) || (int)--num >= 0; bits >>= 1, i++) {}
914 return i;
918 * Returns direction to for a road vehicle to take or
919 * INVALID_TRACKDIR if the direction is currently blocked
920 * @param v the Vehicle to do the pathfinding for
921 * @param tile the where to start the pathfinding
922 * @param enterdir the direction the vehicle enters the tile from
923 * @return the Trackdir to take
925 static Trackdir RoadFindPathToDest(RoadVehicle *v, TileIndex tile, DiagDirection enterdir)
927 #define return_track(x) { best_track = (Trackdir)x; goto found_best_track; }
929 TileIndex desttile;
930 Trackdir best_track;
931 bool path_found = true;
933 TrackStatus ts = GetTileTrackStatus(tile, TRANSPORT_ROAD, v->compatible_roadtypes);
934 TrackdirBits red_signals = TrackStatusToRedSignals(ts); // crossing
935 TrackdirBits trackdirs = TrackStatusToTrackdirBits(ts);
937 if (IsTileType(tile, MP_ROAD)) {
938 if (IsRoadDepot(tile) && (!IsTileOwner(tile, v->owner) || GetRoadDepotDirection(tile) == enterdir || (GetRoadTypes(tile) & v->compatible_roadtypes) == 0)) {
939 /* Road depot owned by another company or with the wrong orientation */
940 trackdirs = TRACKDIR_BIT_NONE;
942 } else if (IsTileType(tile, MP_STATION) && IsStandardRoadStopTile(tile)) {
943 /* Standard road stop (drive-through stops are treated as normal road) */
945 if (!IsTileOwner(tile, v->owner) || GetRoadStopDir(tile) == enterdir || v->HasArticulatedPart()) {
946 /* different station owner or wrong orientation or the vehicle has articulated parts */
947 trackdirs = TRACKDIR_BIT_NONE;
948 } else {
949 /* Our station */
950 RoadStopType rstype = v->IsBus() ? ROADSTOP_BUS : ROADSTOP_TRUCK;
952 if (GetRoadStopType(tile) != rstype) {
953 /* Wrong station type */
954 trackdirs = TRACKDIR_BIT_NONE;
955 } else {
956 /* Proper station type, check if there is free loading bay */
957 if (!_settings_game.pf.roadveh_queue && IsStandardRoadStopTile(tile) &&
958 !RoadStop::GetByTile(tile, rstype)->HasFreeBay()) {
959 /* Station is full and RV queuing is off */
960 trackdirs = TRACKDIR_BIT_NONE;
965 /* The above lookups should be moved to GetTileTrackStatus in the
966 * future, but that requires more changes to the pathfinder and other
967 * stuff, probably even more arguments to GTTS.
970 /* Remove tracks unreachable from the enter dir */
971 trackdirs &= DiagdirReachesTrackdirs(enterdir);
972 if (trackdirs == TRACKDIR_BIT_NONE) {
973 /* No reachable tracks, so we'll reverse */
974 return_track(_road_reverse_table[enterdir]);
977 if (v->reverse_ctr != 0) {
978 bool reverse = true;
979 if (v->roadtype == ROADTYPE_TRAM) {
980 /* Trams may only reverse on a tile if it contains at least the straight
981 * trackbits or when it is a valid turning tile (i.e. one roadbit) */
982 RoadBits rb = GetAnyRoadBits(tile, ROADTYPE_TRAM);
983 RoadBits straight = AxisToRoadBits(DiagDirToAxis(enterdir));
984 reverse = ((rb & straight) == straight) ||
985 (rb == DiagDirToRoadBits(enterdir));
987 if (reverse) {
988 v->reverse_ctr = 0;
989 if (v->tile != tile) {
990 return_track(_road_reverse_table[enterdir]);
995 desttile = v->dest_tile;
996 if (desttile == 0) {
997 /* We've got no destination, pick a random track */
998 return_track(PickRandomBit(trackdirs));
1001 /* Only one track to choose between? */
1002 if (KillFirstBit(trackdirs) == TRACKDIR_BIT_NONE) {
1003 return_track(FindFirstBit2x64(trackdirs));
1006 switch (_settings_game.pf.pathfinder_for_roadvehs) {
1007 case VPF_NPF: best_track = NPFRoadVehicleChooseTrack(v, tile, enterdir, trackdirs, path_found); break;
1008 case VPF_YAPF: best_track = YapfRoadVehicleChooseTrack(v, tile, enterdir, trackdirs, path_found); break;
1010 default: NOT_REACHED();
1012 v->HandlePathfindingResult(path_found);
1014 found_best_track:;
1016 if (HasBit(red_signals, best_track)) return INVALID_TRACKDIR;
1018 return best_track;
1021 struct RoadDriveEntry {
1022 byte x, y;
1025 #include "table/roadveh_movement.h"
1027 static bool RoadVehLeaveDepot(RoadVehicle *v, bool first)
1029 /* Don't leave unless v and following wagons are in the depot. */
1030 for (const RoadVehicle *u = v; u != NULL; u = u->Next()) {
1031 if (u->state != RVSB_IN_DEPOT || u->tile != v->tile) return false;
1034 DiagDirection dir = GetRoadDepotDirection(v->tile);
1035 v->direction = DiagDirToDir(dir);
1037 Trackdir tdir = DiagDirToDiagTrackdir(dir);
1038 const RoadDriveEntry *rdp = _road_drive_data[v->roadtype][(_settings_game.vehicle.road_side << RVS_DRIVE_SIDE) + tdir];
1040 int x = TileX(v->tile) * TILE_SIZE + (rdp[RVC_DEPOT_START_FRAME].x & 0xF);
1041 int y = TileY(v->tile) * TILE_SIZE + (rdp[RVC_DEPOT_START_FRAME].y & 0xF);
1043 if (first) {
1044 /* We are leaving a depot, but have to go to the exact same one; re-enter */
1045 if (v->current_order.IsType(OT_GOTO_DEPOT) && v->tile == v->dest_tile) {
1046 VehicleEnterDepot(v);
1047 return true;
1050 if (RoadVehFindCloseTo(v, x, y, v->direction, false) != NULL) return true;
1052 VehicleServiceInDepot(v);
1054 StartRoadVehSound(v);
1056 /* Vehicle is about to leave a depot */
1057 v->cur_speed = 0;
1060 v->vehstatus &= ~VS_HIDDEN;
1061 v->state = tdir;
1062 v->frame = RVC_DEPOT_START_FRAME;
1064 v->x_pos = x;
1065 v->y_pos = y;
1066 v->UpdatePosition();
1067 v->UpdateInclination(true, true);
1069 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
1071 return true;
1074 static Trackdir FollowPreviousRoadVehicle(const RoadVehicle *v, const RoadVehicle *prev, TileIndex tile, DiagDirection entry_dir, bool already_reversed)
1076 if (prev->tile == v->tile && !already_reversed) {
1077 /* If the previous vehicle is on the same tile as this vehicle is
1078 * then it must have reversed. */
1079 return _road_reverse_table[entry_dir];
1082 byte prev_state = prev->state;
1083 Trackdir dir;
1085 if (prev_state == RVSB_WORMHOLE || prev_state == RVSB_IN_DEPOT) {
1086 DiagDirection diag_dir = INVALID_DIAGDIR;
1088 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
1089 diag_dir = GetTunnelBridgeDirection(tile);
1090 } else if (IsRoadDepotTile(tile)) {
1091 diag_dir = ReverseDiagDir(GetRoadDepotDirection(tile));
1094 if (diag_dir == INVALID_DIAGDIR) return INVALID_TRACKDIR;
1095 dir = DiagDirToDiagTrackdir(diag_dir);
1096 } else {
1097 if (already_reversed && prev->tile != tile) {
1099 * The vehicle has reversed, but did not go straight back.
1100 * It immediately turn onto another tile. This means that
1101 * the roadstate of the previous vehicle cannot be used
1102 * as the direction we have to go with this vehicle.
1104 * Next table is build in the following way:
1105 * - first row for when the vehicle in front went to the northern or
1106 * western tile, second for southern and eastern.
1107 * - columns represent the entry direction.
1108 * - cell values are determined by the Trackdir one has to take from
1109 * the entry dir (column) to the tile in north or south by only
1110 * going over the trackdirs used for turning 90 degrees, i.e.
1111 * TRACKDIR_{UPPER,RIGHT,LOWER,LEFT}_{N,E,S,W}.
1113 static const Trackdir reversed_turn_lookup[2][DIAGDIR_END] = {
1114 { TRACKDIR_UPPER_W, TRACKDIR_RIGHT_N, TRACKDIR_LEFT_N, TRACKDIR_UPPER_E },
1115 { TRACKDIR_RIGHT_S, TRACKDIR_LOWER_W, TRACKDIR_LOWER_E, TRACKDIR_LEFT_S }};
1116 dir = reversed_turn_lookup[prev->tile < tile ? 0 : 1][ReverseDiagDir(entry_dir)];
1117 } else if (HasBit(prev_state, RVS_IN_DT_ROAD_STOP)) {
1118 dir = (Trackdir)(prev_state & RVSB_ROAD_STOP_TRACKDIR_MASK);
1119 } else if (prev_state < TRACKDIR_END) {
1120 dir = (Trackdir)prev_state;
1121 } else {
1122 return INVALID_TRACKDIR;
1126 /* Do some sanity checking. */
1127 static const RoadBits required_roadbits[] = {
1128 ROAD_X, ROAD_Y, ROAD_NW | ROAD_NE, ROAD_SW | ROAD_SE,
1129 ROAD_NW | ROAD_SW, ROAD_NE | ROAD_SE, ROAD_X, ROAD_Y
1131 RoadBits required = required_roadbits[dir & 0x07];
1133 if ((required & GetAnyRoadBits(tile, v->roadtype, false)) == ROAD_NONE) {
1134 dir = INVALID_TRACKDIR;
1137 return dir;
1141 * Can a tram track build without destruction on the given tile?
1142 * @param c the company that would be building the tram tracks
1143 * @param t the tile to build on.
1144 * @param r the road bits needed.
1145 * @return true when a track track can be build on 't'
1147 static bool CanBuildTramTrackOnTile(CompanyID c, TileIndex t, RoadBits r)
1149 /* The 'current' company is not necessarily the owner of the vehicle. */
1150 Backup<CompanyByte> cur_company(_current_company, c, FILE_LINE);
1152 CommandCost ret = DoCommand(t, ROADTYPE_TRAM << 4 | r, 0, DC_NO_WATER, CMD_BUILD_ROAD);
1154 cur_company.Restore();
1155 return ret.Succeeded();
1158 bool IndividualRoadVehicleController(RoadVehicle *v, const RoadVehicle *prev)
1160 if (v->overtaking != 0) {
1161 if (IsTileType(v->tile, MP_STATION)) {
1162 /* Force us to be not overtaking! */
1163 v->overtaking = 0;
1164 } else if (++v->overtaking_ctr >= RV_OVERTAKE_TIMEOUT) {
1165 /* If overtaking just aborts at a random moment, we can have a out-of-bound problem,
1166 * if the vehicle started a corner. To protect that, only allow an abort of
1167 * overtake if we are on straight roads */
1168 if (v->state < RVSB_IN_ROAD_STOP && IsStraightRoadTrackdir((Trackdir)v->state)) {
1169 v->overtaking = 0;
1174 /* If this vehicle is in a depot and we've reached this point it must be
1175 * one of the articulated parts. It will stay in the depot until activated
1176 * by the previous vehicle in the chain when it gets to the right place. */
1177 if (v->IsInDepot()) return true;
1179 bool no_advance_tile = false;
1181 if (v->state == RVSB_WORMHOLE) {
1182 /* Vehicle is entering a depot or is on a bridge or in a tunnel */
1183 GetNewVehiclePosResult gp = GetNewVehiclePos(v);
1185 if (v->IsFrontEngine()) {
1186 const Vehicle *u = RoadVehFindCloseTo(v, gp.x, gp.y, v->direction);
1187 if (u != NULL) {
1188 v->cur_speed = u->First()->cur_speed;
1189 return false;
1193 if (IsTileType(gp.new_tile, MP_TUNNELBRIDGE) && HasBit(VehicleEnterTile(v, gp.new_tile, gp.x, gp.y), VETS_ENTERED_WORMHOLE)) {
1195 if (IsRoadCustomBridgeHeadTile(gp.new_tile)) {
1196 v->frame = 15;
1197 no_advance_tile = true;
1198 } else {
1199 /* Vehicle has just entered a bridge or tunnel */
1200 v->x_pos = gp.x;
1201 v->y_pos = gp.y;
1202 v->UpdatePosition();
1203 v->UpdateInclination(true, true);
1204 return true;
1206 } else {
1207 v->x_pos = gp.x;
1208 v->y_pos = gp.y;
1209 v->UpdatePosition();
1210 RoadZPosAffectSpeed(v, v->UpdateInclination(false, false, true));
1211 if (v->IsDrawn()) v->Vehicle::UpdateViewport(true);
1212 return true;
1216 /* Get move position data for next frame.
1217 * For a drive-through road stop use 'straight road' move data.
1218 * In this case v->state is masked to give the road stop entry direction. */
1219 RoadDriveEntry rd = _road_drive_data[v->roadtype][(
1220 (HasBit(v->state, RVS_IN_DT_ROAD_STOP) ? v->state & RVSB_ROAD_STOP_TRACKDIR_MASK : v->state) +
1221 (_settings_game.vehicle.road_side << RVS_DRIVE_SIDE)) ^ v->overtaking][v->frame + 1];
1223 if (rd.x & RDE_NEXT_TILE) {
1224 TileIndex tile = v->tile;
1225 if (!no_advance_tile) tile += TileOffsByDiagDir((DiagDirection)(rd.x & 3));
1226 Trackdir dir;
1228 if (v->IsFrontEngine()) {
1229 /* If this is the front engine, look for the right path. */
1230 dir = RoadFindPathToDest(v, tile, (DiagDirection)(rd.x & 3));
1231 } else if (no_advance_tile) {
1232 /* Follow previous vehicle out of custom bridge wormhole */
1233 dir = (Trackdir) prev->state;
1234 } else {
1235 dir = FollowPreviousRoadVehicle(v, prev, tile, (DiagDirection)(rd.x & 3), false);
1238 if (dir == INVALID_TRACKDIR) {
1239 if (!v->IsFrontEngine()) error("Disconnecting road vehicle.");
1240 v->cur_speed = 0;
1241 return false;
1244 again:
1245 uint start_frame = RVC_DEFAULT_START_FRAME;
1246 if (IsReversingRoadTrackdir(dir)) {
1247 /* When turning around we can't be overtaking. */
1248 v->overtaking = 0;
1250 if (no_advance_tile) {
1251 DEBUG(misc, 0, "Road vehicle attempted to turn around on a single road piece bridge head");
1254 /* Turning around */
1255 if (v->roadtype == ROADTYPE_TRAM) {
1256 /* Determine the road bits the tram needs to be able to turn around
1257 * using the 'big' corner loop. */
1258 RoadBits needed;
1259 switch (dir) {
1260 default: NOT_REACHED();
1261 case TRACKDIR_RVREV_NE: needed = ROAD_SW; break;
1262 case TRACKDIR_RVREV_SE: needed = ROAD_NW; break;
1263 case TRACKDIR_RVREV_SW: needed = ROAD_NE; break;
1264 case TRACKDIR_RVREV_NW: needed = ROAD_SE; break;
1266 auto tile_turn_ok = [&]() -> bool {
1267 if (IsNormalRoadTile(tile)) {
1268 return !HasRoadWorks(tile) && (needed & GetRoadBits(tile, ROADTYPE_TRAM)) != ROAD_NONE;
1269 } else if (IsRoadCustomBridgeHeadTile(tile)) {
1270 return (needed & GetCustomBridgeHeadRoadBits(tile, ROADTYPE_TRAM)) != ROAD_NONE;
1271 } else {
1272 return false;
1275 if ((v->Previous() != NULL && v->Previous()->tile == tile) || (v->IsFrontEngine() && tile_turn_ok())) {
1277 * Taking the 'big' corner for trams only happens when:
1278 * - The previous vehicle in this (articulated) tram chain is
1279 * already on the 'next' tile, we just follow them regardless of
1280 * anything. When it is NOT on the 'next' tile, the tram started
1281 * doing a reversing turn when the piece of tram track on the next
1282 * tile did not exist yet. Do not use the big tram loop as that is
1283 * going to cause the tram to split up.
1284 * - Or the front of the tram can drive over the next tile.
1286 } else if (!v->IsFrontEngine() || !CanBuildTramTrackOnTile(v->owner, tile, needed) || ((~needed & GetAnyRoadBits(v->tile, ROADTYPE_TRAM, false)) == ROAD_NONE)) {
1288 * Taking the 'small' corner for trams only happens when:
1289 * - We are not the from vehicle of an articulated tram.
1290 * - Or when the company cannot build on the next tile.
1292 * The 'small' corner means that the vehicle is on the end of a
1293 * tram track and needs to start turning there. To do this properly
1294 * the tram needs to start at an offset in the tram turning 'code'
1295 * for 'big' corners. It furthermore does not go to the next tile,
1296 * so that needs to be fixed too.
1298 tile = v->tile;
1299 start_frame = RVC_TURN_AROUND_START_FRAME_SHORT_TRAM;
1300 } else {
1301 /* The company can build on the next tile, so wait till (s)he does. */
1302 v->cur_speed = 0;
1303 return false;
1305 } else if (IsNormalRoadTile(v->tile) && GetDisallowedRoadDirections(v->tile) != DRD_NONE) {
1306 v->cur_speed = 0;
1307 return false;
1308 } else {
1309 tile = v->tile;
1313 /* Get position data for first frame on the new tile */
1314 const RoadDriveEntry *rdp = _road_drive_data[v->roadtype][(dir + (_settings_game.vehicle.road_side << RVS_DRIVE_SIDE)) ^ v->overtaking];
1316 int x = TileX(tile) * TILE_SIZE + rdp[start_frame].x;
1317 int y = TileY(tile) * TILE_SIZE + rdp[start_frame].y;
1319 Direction new_dir = RoadVehGetSlidingDirection(v, x, y);
1320 if (v->IsFrontEngine()) {
1321 Vehicle *u = RoadVehFindCloseTo(v, x, y, new_dir);
1322 if (u != NULL) {
1323 v->cur_speed = u->First()->cur_speed;
1324 return false;
1328 uint32 r = VehicleEnterTile(v, tile, x, y);
1329 if (HasBit(r, VETS_CANNOT_ENTER)) {
1330 if (!IsTileType(tile, MP_TUNNELBRIDGE)) {
1331 v->cur_speed = 0;
1332 return false;
1334 /* Try an about turn to re-enter the previous tile */
1335 dir = _road_reverse_table[rd.x & 3];
1336 goto again;
1339 if (IsInsideMM(v->state, RVSB_IN_ROAD_STOP, RVSB_IN_DT_ROAD_STOP_END) && IsTileType(v->tile, MP_STATION)) {
1340 if (IsReversingRoadTrackdir(dir) && IsInsideMM(v->state, RVSB_IN_ROAD_STOP, RVSB_IN_ROAD_STOP_END)) {
1341 /* New direction is trying to turn vehicle around.
1342 * We can't turn at the exit of a road stop so wait.*/
1343 v->cur_speed = 0;
1344 return false;
1347 /* If we are a drive through road stop and the next tile is of
1348 * the same road stop and the next tile isn't this one (i.e. we
1349 * are not reversing), then keep the reservation and state.
1350 * This way we will not be shortly unregister from the road
1351 * stop. It also makes it possible to load when on the edge of
1352 * two road stops; otherwise you could get vehicles that should
1353 * be loading but are not actually loading. */
1354 if (IsDriveThroughStopTile(v->tile) &&
1355 RoadStop::IsDriveThroughRoadStopContinuation(v->tile, tile) &&
1356 v->tile != tile) {
1357 /* So, keep 'our' state */
1358 dir = (Trackdir)v->state;
1359 } else if (IsRoadStop(v->tile)) {
1360 /* We're not continuing our drive through road stop, so leave. */
1361 RoadStop::GetByTile(v->tile, GetRoadStopType(v->tile))->Leave(v);
1365 if (!HasBit(r, VETS_ENTERED_WORMHOLE)) {
1366 v->tile = tile;
1367 v->state = (byte)dir;
1368 v->frame = start_frame;
1370 if (new_dir != v->direction) {
1371 v->direction = new_dir;
1372 if (_settings_game.vehicle.roadveh_acceleration_model == AM_ORIGINAL) v->cur_speed -= v->cur_speed >> 2;
1374 v->x_pos = x;
1375 v->y_pos = y;
1376 v->UpdatePosition();
1377 RoadZPosAffectSpeed(v, v->UpdateInclination(true, true));
1378 return true;
1381 if (rd.x & RDE_TURNED) {
1382 /* Vehicle has finished turning around, it will now head back onto the same tile */
1383 Trackdir dir;
1384 uint turn_around_start_frame = RVC_TURN_AROUND_START_FRAME;
1386 if (v->roadtype == ROADTYPE_TRAM && !IsRoadDepotTile(v->tile) && HasExactlyOneBit(GetAnyRoadBits(v->tile, ROADTYPE_TRAM, false))) {
1388 * The tram is turning around with one tram 'roadbit'. This means that
1389 * it is using the 'big' corner 'drive data'. However, to support the
1390 * trams to take a small corner, there is a 'turned' marker in the middle
1391 * of the turning 'drive data'. When the tram took the long corner, we
1392 * will still use the 'big' corner drive data, but we advance it one
1393 * frame. We furthermore set the driving direction so the turning is
1394 * going to be properly shown.
1396 turn_around_start_frame = RVC_START_FRAME_AFTER_LONG_TRAM;
1397 switch (rd.x & 0x3) {
1398 default: NOT_REACHED();
1399 case DIAGDIR_NW: dir = TRACKDIR_RVREV_SE; break;
1400 case DIAGDIR_NE: dir = TRACKDIR_RVREV_SW; break;
1401 case DIAGDIR_SE: dir = TRACKDIR_RVREV_NW; break;
1402 case DIAGDIR_SW: dir = TRACKDIR_RVREV_NE; break;
1404 } else {
1405 if (v->IsFrontEngine()) {
1406 /* If this is the front engine, look for the right path. */
1407 dir = RoadFindPathToDest(v, v->tile, (DiagDirection)(rd.x & 3));
1408 } else {
1409 dir = FollowPreviousRoadVehicle(v, prev, v->tile, (DiagDirection)(rd.x & 3), true);
1413 if (dir == INVALID_TRACKDIR) {
1414 v->cur_speed = 0;
1415 return false;
1418 const RoadDriveEntry *rdp = _road_drive_data[v->roadtype][(_settings_game.vehicle.road_side << RVS_DRIVE_SIDE) + dir];
1420 int x = TileX(v->tile) * TILE_SIZE + rdp[turn_around_start_frame].x;
1421 int y = TileY(v->tile) * TILE_SIZE + rdp[turn_around_start_frame].y;
1423 Direction new_dir = RoadVehGetSlidingDirection(v, x, y);
1424 if (v->IsFrontEngine() && RoadVehFindCloseTo(v, x, y, new_dir) != NULL) return false;
1426 uint32 r = VehicleEnterTile(v, v->tile, x, y);
1427 if (HasBit(r, VETS_CANNOT_ENTER)) {
1428 v->cur_speed = 0;
1429 return false;
1432 v->state = dir;
1433 v->frame = turn_around_start_frame;
1435 if (new_dir != v->direction) {
1436 v->direction = new_dir;
1437 if (_settings_game.vehicle.roadveh_acceleration_model == AM_ORIGINAL) v->cur_speed -= v->cur_speed >> 2;
1440 v->x_pos = x;
1441 v->y_pos = y;
1442 v->UpdatePosition();
1443 RoadZPosAffectSpeed(v, v->UpdateInclination(true, true));
1444 return true;
1447 /* This vehicle is not in a wormhole and it hasn't entered a new tile. If
1448 * it's on a depot tile, check if it's time to activate the next vehicle in
1449 * the chain yet. */
1450 if (v->Next() != NULL && IsRoadDepotTile(v->tile)) {
1451 if (v->frame == v->gcache.cached_veh_length + RVC_DEPOT_START_FRAME) {
1452 RoadVehLeaveDepot(v->Next(), false);
1456 /* Calculate new position for the vehicle */
1457 int x = (v->x_pos & ~15) + (rd.x & 15);
1458 int y = (v->y_pos & ~15) + (rd.y & 15);
1460 Direction new_dir = RoadVehGetSlidingDirection(v, x, y);
1462 if (v->IsFrontEngine() && !IsInsideMM(v->state, RVSB_IN_ROAD_STOP, RVSB_IN_ROAD_STOP_END)) {
1463 /* Vehicle is not in a road stop.
1464 * Check for another vehicle to overtake */
1465 RoadVehicle *u = RoadVehFindCloseTo(v, x, y, new_dir);
1467 if (u != NULL) {
1468 u = u->First();
1469 /* There is a vehicle in front overtake it if possible */
1470 if (v->overtaking == 0) RoadVehCheckOvertake(v, u);
1471 if (v->overtaking == 0) v->cur_speed = u->cur_speed;
1473 /* In case an RV is stopped in a road stop, why not try to load? */
1474 if (v->cur_speed == 0 && IsInsideMM(v->state, RVSB_IN_DT_ROAD_STOP, RVSB_IN_DT_ROAD_STOP_END) &&
1475 v->current_order.ShouldStopAtStation(v, GetStationIndex(v->tile)) &&
1476 v->owner == GetTileOwner(v->tile) && !v->current_order.IsType(OT_LEAVESTATION) &&
1477 GetRoadStopType(v->tile) == (v->IsBus() ? ROADSTOP_BUS : ROADSTOP_TRUCK)) {
1478 Station *st = Station::GetByTile(v->tile);
1479 v->last_station_visited = st->index;
1480 RoadVehArrivesAt(v, st);
1481 v->BeginLoading();
1483 return false;
1487 Direction old_dir = v->direction;
1488 if (new_dir != old_dir) {
1489 v->direction = new_dir;
1490 if (_settings_game.vehicle.roadveh_acceleration_model == AM_ORIGINAL) v->cur_speed -= v->cur_speed >> 2;
1492 /* Delay the vehicle in curves by making it require one additional frame per turning direction (two in total).
1493 * A vehicle has to spend at least 9 frames on a tile, so the following articulated part can follow.
1494 * (The following part may only be one tile behind, and the front part is moved before the following ones.)
1495 * The short (inner) curve has 8 frames, this elongates it to 10. */
1496 v->UpdateInclination(false, true);
1497 return true;
1500 /* If the vehicle is in a normal road stop and the frame equals the stop frame OR
1501 * if the vehicle is in a drive-through road stop and this is the destination station
1502 * and it's the correct type of stop (bus or truck) and the frame equals the stop frame...
1503 * (the station test and stop type test ensure that other vehicles, using the road stop as
1504 * a through route, do not stop) */
1505 if (v->IsFrontEngine() && ((IsInsideMM(v->state, RVSB_IN_ROAD_STOP, RVSB_IN_ROAD_STOP_END) &&
1506 _road_stop_stop_frame[v->state - RVSB_IN_ROAD_STOP + (_settings_game.vehicle.road_side << RVS_DRIVE_SIDE)] == v->frame) ||
1507 (IsInsideMM(v->state, RVSB_IN_DT_ROAD_STOP, RVSB_IN_DT_ROAD_STOP_END) &&
1508 v->current_order.ShouldStopAtStation(v, GetStationIndex(v->tile)) &&
1509 v->owner == GetTileOwner(v->tile) &&
1510 GetRoadStopType(v->tile) == (v->IsBus() ? ROADSTOP_BUS : ROADSTOP_TRUCK) &&
1511 v->frame == RVC_DRIVE_THROUGH_STOP_FRAME))) {
1513 RoadStop *rs = RoadStop::GetByTile(v->tile, GetRoadStopType(v->tile));
1514 Station *st = Station::GetByTile(v->tile);
1516 /* Vehicle is at the stop position (at a bay) in a road stop.
1517 * Note, if vehicle is loading/unloading it has already been handled,
1518 * so if we get here the vehicle has just arrived or is just ready to leave. */
1519 if (!HasBit(v->state, RVS_ENTERED_STOP)) {
1520 /* Vehicle has arrived at a bay in a road stop */
1522 if (IsDriveThroughStopTile(v->tile)) {
1523 TileIndex next_tile = TILE_ADD(v->tile, TileOffsByDir(v->direction));
1525 /* Check if next inline bay is free and has compatible road. */
1526 if (RoadStop::IsDriveThroughRoadStopContinuation(v->tile, next_tile) && (GetRoadTypes(next_tile) & v->compatible_roadtypes) != 0) {
1527 v->frame++;
1528 v->x_pos = x;
1529 v->y_pos = y;
1530 v->UpdatePosition();
1531 RoadZPosAffectSpeed(v, v->UpdateInclination(true, false));
1532 return true;
1536 rs->SetEntranceBusy(false);
1537 SetBit(v->state, RVS_ENTERED_STOP);
1539 v->last_station_visited = st->index;
1541 if (IsDriveThroughStopTile(v->tile) || (v->current_order.IsType(OT_GOTO_STATION) && v->current_order.GetDestination() == st->index)) {
1542 RoadVehArrivesAt(v, st);
1543 v->BeginLoading();
1544 return false;
1546 } else {
1547 /* Vehicle is ready to leave a bay in a road stop */
1548 if (rs->IsEntranceBusy()) {
1549 /* Road stop entrance is busy, so wait as there is nowhere else to go */
1550 v->cur_speed = 0;
1551 return false;
1553 if (v->current_order.IsType(OT_LEAVESTATION)) v->current_order.Free();
1556 if (IsStandardRoadStopTile(v->tile)) rs->SetEntranceBusy(true);
1558 StartRoadVehSound(v);
1559 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
1562 /* Check tile position conditions - i.e. stop position in depot,
1563 * entry onto bridge or into tunnel */
1564 uint32 r = VehicleEnterTile(v, v->tile, x, y);
1565 if (HasBit(r, VETS_CANNOT_ENTER)) {
1566 v->cur_speed = 0;
1567 return false;
1570 if (v->current_order.IsType(OT_LEAVESTATION) && IsDriveThroughStopTile(v->tile)) {
1571 v->current_order.Free();
1574 /* Move to next frame unless vehicle arrived at a stop position
1575 * in a depot or entered a tunnel/bridge */
1576 if (!HasBit(r, VETS_ENTERED_WORMHOLE)) v->frame++;
1577 v->x_pos = x;
1578 v->y_pos = y;
1579 v->UpdatePosition();
1580 RoadZPosAffectSpeed(v, v->UpdateInclination(false, true, v->state == RVSB_WORMHOLE));
1581 return true;
1584 static bool RoadVehController(RoadVehicle *v)
1586 /* decrease counters */
1587 v->current_order_time++;
1588 if (v->reverse_ctr != 0) v->reverse_ctr--;
1590 /* handle crashed */
1591 if (v->vehstatus & VS_CRASHED || RoadVehCheckTrainCrash(v)) {
1592 return RoadVehIsCrashed(v);
1595 /* road vehicle has broken down? */
1596 if (v->HandleBreakdown()) return true;
1597 if (v->vehstatus & VS_STOPPED) return true;
1599 ProcessOrders(v);
1600 v->HandleLoading();
1602 if (v->current_order.IsType(OT_LOADING)) return true;
1603 v->HandleWaiting(false);
1604 if (v->current_order.IsType(OT_WAITING)) return true;
1606 if (v->IsInDepot() && RoadVehLeaveDepot(v, true)) return true;
1608 v->ShowVisualEffect();
1610 /* Check how far the vehicle needs to proceed */
1611 int j = v->UpdateSpeed();
1613 int adv_spd = v->GetAdvanceDistance();
1614 bool blocked = false;
1615 while (j >= adv_spd) {
1616 j -= adv_spd;
1618 RoadVehicle *u = v;
1619 for (RoadVehicle *prev = NULL; u != NULL; prev = u, u = u->Next()) {
1620 if (!IndividualRoadVehicleController(u, prev)) {
1621 blocked = true;
1622 break;
1625 if (blocked) break;
1627 /* Determine distance to next map position */
1628 adv_spd = v->GetAdvanceDistance();
1630 /* Test for a collision, but only if another movement will occur. */
1631 if (j >= adv_spd && RoadVehCheckTrainCrash(v)) break;
1634 v->SetLastSpeed();
1636 for (RoadVehicle *u = v; u != NULL; u = u->Next()) {
1637 if (!(u->IsDrawn())) continue;
1639 u->UpdateViewport(false, false);
1642 /* If movement is blocked, set 'progress' to its maximum, so the roadvehicle does
1643 * not accelerate again before it can actually move. I.e. make sure it tries to advance again
1644 * on next tick to discover whether it is still blocked. */
1645 if (v->progress == 0) v->progress = blocked ? adv_spd - 1 : j;
1647 return true;
1650 Money RoadVehicle::GetRunningCost() const
1652 const Engine *e = this->GetEngine();
1653 if (e->u.road.running_cost_class == INVALID_PRICE) return 0;
1655 uint cost_factor = GetVehicleProperty(this, PROP_ROADVEH_RUNNING_COST_FACTOR, e->u.road.running_cost);
1656 if (cost_factor == 0) return 0;
1658 return GetPrice(e->u.road.running_cost_class, cost_factor, e->GetGRF());
1661 bool RoadVehicle::Tick()
1663 this->tick_counter++;
1665 if (this->IsFrontEngine()) {
1666 if (!((this->vehstatus & VS_STOPPED) || this->IsChainInDepot())) this->running_ticks++;
1667 return RoadVehController(this);
1670 return true;
1673 static void CheckIfRoadVehNeedsService(RoadVehicle *v)
1675 /* If we already got a slot at a stop, use that FIRST, and go to a depot later */
1676 if (Company::Get(v->owner)->settings.vehicle.servint_roadveh == 0 || !v->NeedsAutomaticServicing()) return;
1677 if (v->IsChainInDepot()) {
1678 VehicleServiceInDepot(v);
1679 return;
1682 uint max_penalty;
1683 switch (_settings_game.pf.pathfinder_for_roadvehs) {
1684 case VPF_NPF: max_penalty = _settings_game.pf.npf.maximum_go_to_depot_penalty; break;
1685 case VPF_YAPF: max_penalty = _settings_game.pf.yapf.maximum_go_to_depot_penalty; break;
1686 default: NOT_REACHED();
1689 FindDepotData rfdd = FindClosestRoadDepot(v, max_penalty);
1690 /* Only go to the depot if it is not too far out of our way. */
1691 if (rfdd.best_length == UINT_MAX || rfdd.best_length > max_penalty) {
1692 if (v->current_order.IsType(OT_GOTO_DEPOT)) {
1693 /* If we were already heading for a depot but it has
1694 * suddenly moved farther away, we continue our normal
1695 * schedule? */
1696 v->current_order.MakeDummy();
1697 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
1699 return;
1702 DepotID depot = GetDepotIndex(rfdd.tile);
1704 if (v->current_order.IsType(OT_GOTO_DEPOT) &&
1705 v->current_order.GetNonStopType() & ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS &&
1706 !Chance16(1, 20)) {
1707 return;
1710 SetBit(v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS);
1711 v->current_order.MakeGoToDepot(depot, ODTFB_SERVICE);
1712 v->dest_tile = rfdd.tile;
1713 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
1716 void RoadVehicle::OnNewDay()
1718 AgeVehicle(this);
1720 if (!this->IsFrontEngine()) return;
1722 if ((++this->day_counter & 7) == 0) DecreaseVehicleValue(this);
1723 if (this->blocked_ctr == 0) CheckVehicleBreakdown(this);
1725 CheckIfRoadVehNeedsService(this);
1727 CheckOrders(this);
1729 if (this->running_ticks == 0) return;
1731 CommandCost cost(EXPENSES_ROADVEH_RUN, this->GetRunningCost() * this->running_ticks / (DAYS_IN_YEAR * DAY_TICKS));
1733 this->profit_this_year -= cost.GetCost();
1734 this->running_ticks = 0;
1736 SubtractMoneyFromCompanyFract(this->owner, cost);
1738 SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
1739 SetWindowClassesDirty(WC_ROADVEH_LIST);
1742 Trackdir RoadVehicle::GetVehicleTrackdir() const
1744 if (this->vehstatus & VS_CRASHED) return INVALID_TRACKDIR;
1746 if (this->IsInDepot()) {
1747 /* We'll assume the road vehicle is facing outwards */
1748 return DiagDirToDiagTrackdir(GetRoadDepotDirection(this->tile));
1751 if (IsStandardRoadStopTile(this->tile)) {
1752 /* We'll assume the road vehicle is facing outwards */
1753 return DiagDirToDiagTrackdir(GetRoadStopDir(this->tile)); // Road vehicle in a station
1756 /* Drive through road stops / wormholes (tunnels) */
1757 if (this->state > RVSB_TRACKDIR_MASK) return DiagDirToDiagTrackdir(DirToDiagDir(this->direction));
1759 /* If vehicle's state is a valid track direction (vehicle is not turning around) return it,
1760 * otherwise transform it into a valid track direction */
1761 return (Trackdir)((IsReversingRoadTrackdir((Trackdir)this->state)) ? (this->state - 6) : this->state);