OpenTTD Source 20250528-master-g3aca5d62a8
roadveh_cmd.cpp
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6 */
7
10#include "stdafx.h"
11#include "roadveh.h"
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"
18#include "newgrf_sound.h"
20#include "strings_func.h"
21#include "tunnelbridge_map.h"
24#include "vehicle_func.h"
25#include "sound_func.h"
26#include "ai/ai.hpp"
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"
35#include "newgrf.h"
36#include "zoom_func.h"
37#include "framerate_type.h"
38#include "roadveh_cmd.h"
39#include "road_cmd.h"
40#include "newgrf_roadstop.h"
41
42#include "table/strings.h"
43
44#include "safeguards.h"
45
46static const uint16_t _roadveh_images[] = {
47 0xCD4, 0xCDC, 0xCE4, 0xCEC, 0xCF4, 0xCFC, 0xD0C, 0xD14,
48 0xD24, 0xD1C, 0xD2C, 0xD04, 0xD1C, 0xD24, 0xD6C, 0xD74,
49 0xD7C, 0xC14, 0xC1C, 0xC24, 0xC2C, 0xC34, 0xC3C, 0xC4C,
50 0xC54, 0xC64, 0xC5C, 0xC6C, 0xC44, 0xC5C, 0xC64, 0xCAC,
51 0xCB4, 0xCBC, 0xD94, 0xD9C, 0xDA4, 0xDAC, 0xDB4, 0xDBC,
52 0xDCC, 0xDD4, 0xDE4, 0xDDC, 0xDEC, 0xDC4, 0xDDC, 0xDE4,
53 0xE2C, 0xE34, 0xE3C, 0xC14, 0xC1C, 0xC2C, 0xC3C, 0xC4C,
54 0xC5C, 0xC64, 0xC6C, 0xC74, 0xC84, 0xC94, 0xCA4
55};
56
57static const uint16_t _roadveh_full_adder[] = {
58 0, 88, 0, 0, 0, 0, 48, 48,
59 48, 48, 0, 0, 64, 64, 0, 16,
60 16, 0, 88, 0, 0, 0, 0, 48,
61 48, 48, 48, 0, 0, 64, 64, 0,
62 16, 16, 0, 88, 0, 0, 0, 0,
63 48, 48, 48, 48, 0, 0, 64, 64,
64 0, 16, 16, 0, 8, 8, 8, 8,
65 0, 0, 0, 8, 8, 8, 8
66};
67static_assert(lengthof(_roadveh_images) == lengthof(_roadveh_full_adder));
68
69template <>
70bool IsValidImageIndex<VEH_ROAD>(uint8_t image_index)
71{
72 return image_index < lengthof(_roadveh_images);
73}
74
75static const Trackdir _road_reverse_table[DIAGDIR_END] = {
77};
78
84{
85 assert(this->IsFrontEngine());
87}
88
95{
96 int reference_width = ROADVEHINFO_DEFAULT_VEHICLE_WIDTH;
97
98 if (offset != nullptr) {
99 offset->x = ScaleSpriteTrad(reference_width) / 2;
100 offset->y = 0;
101 }
102 return ScaleSpriteTrad(this->gcache.cached_veh_length * reference_width / VEHICLE_LENGTH);
103}
104
105static void GetRoadVehIcon(EngineID engine, EngineImageType image_type, VehicleSpriteSeq *result)
106{
107 const Engine *e = Engine::Get(engine);
108 uint8_t spritenum = e->u.road.image_index;
109
110 if (IsCustomVehicleSpriteNum(spritenum)) {
111 GetCustomVehicleIcon(engine, DIR_W, image_type, result);
112 if (result->IsValid()) return;
113
114 spritenum = e->original_image_index;
115 }
116
117 assert(IsValidImageIndex<VEH_ROAD>(spritenum));
118 result->Set(DIR_W + _roadveh_images[spritenum]);
119}
120
121void RoadVehicle::GetImage(Direction direction, EngineImageType image_type, VehicleSpriteSeq *result) const
122{
123 uint8_t spritenum = this->spritenum;
124
125 if (IsCustomVehicleSpriteNum(spritenum)) {
127 GetCustomVehicleSprite(this, direction, image_type, result);
128 if (result->IsValid()) return;
129
131 }
132
133 assert(IsValidImageIndex<VEH_ROAD>(spritenum));
134 SpriteID sprite = direction + _roadveh_images[spritenum];
135
136 if (this->cargo.StoredCount() >= this->cargo_cap / 2U) sprite += _roadveh_full_adder[spritenum];
137
138 result->Set(sprite);
139}
140
150void DrawRoadVehEngine(int left, int right, int preferred_x, int y, EngineID engine, PaletteID pal, EngineImageType image_type)
151{
153 GetRoadVehIcon(engine, image_type, &seq);
154
155 Rect rect;
156 seq.GetBounds(&rect);
157 preferred_x = Clamp(preferred_x,
158 left - UnScaleGUI(rect.left),
159 right - UnScaleGUI(rect.right));
160
161 seq.Draw(preferred_x, y, pal, pal == PALETTE_CRASH);
162}
163
173void GetRoadVehSpriteSize(EngineID engine, uint &width, uint &height, int &xoffs, int &yoffs, EngineImageType image_type)
174{
176 GetRoadVehIcon(engine, image_type, &seq);
177
178 Rect rect;
179 seq.GetBounds(&rect);
180
181 width = UnScaleGUI(rect.Width());
182 height = UnScaleGUI(rect.Height());
183 xoffs = UnScaleGUI(rect.left);
184 yoffs = UnScaleGUI(rect.top);
185}
186
192static uint GetRoadVehLength(const RoadVehicle *v)
193{
194 const Engine *e = v->GetEngine();
195 uint length = VEHICLE_LENGTH;
196
197 uint16_t veh_len = CALLBACK_FAILED;
198 if (e->GetGRF() != nullptr && e->GetGRF()->grf_version >= 8) {
199 /* Use callback 36 */
200 veh_len = GetVehicleProperty(v, PROP_ROADVEH_SHORTEN_FACTOR, CALLBACK_FAILED);
201 if (veh_len != CALLBACK_FAILED && veh_len >= VEHICLE_LENGTH) ErrorUnknownCallbackResult(e->GetGRFID(), CBID_VEHICLE_LENGTH, veh_len);
202 } else {
203 /* Use callback 11 */
204 veh_len = GetVehicleCallback(CBID_VEHICLE_LENGTH, 0, 0, v->engine_type, v);
205 }
206 if (veh_len == CALLBACK_FAILED) veh_len = e->u.road.shorten_factor;
207 if (veh_len != 0) {
208 length -= Clamp(veh_len, 0, VEHICLE_LENGTH - 1);
209 }
210
211 return length;
212}
213
220void RoadVehUpdateCache(RoadVehicle *v, bool same_length)
221{
222 assert(v->type == VEH_ROAD);
223 assert(v->IsFrontEngine());
224
226
228
229 for (RoadVehicle *u = v; u != nullptr; u = u->Next()) {
230 /* Check the v->first cache. */
231 assert(u->First() == v);
232
233 /* Update the 'first engine' */
234 u->gcache.first_engine = (v == u) ? EngineID::Invalid() : v->engine_type;
235
236 /* Update the length of the vehicle. */
237 uint veh_len = GetRoadVehLength(u);
238 /* Verify length hasn't changed. */
239 if (same_length && veh_len != u->gcache.cached_veh_length) VehicleLengthChanged(u);
240
241 u->gcache.cached_veh_length = veh_len;
242 v->gcache.cached_total_length += u->gcache.cached_veh_length;
243
244 /* Update visual effect */
245 u->UpdateVisualEffect();
246
247 /* Update cargo aging period. */
248 u->vcache.cached_cargo_age_period = GetVehicleProperty(u, PROP_ROADVEH_CARGO_AGE_PERIOD, EngInfo(u->engine_type)->cargo_age_period);
249 }
250
251 uint max_speed = GetVehicleProperty(v, PROP_ROADVEH_SPEED, 0);
252 v->vcache.cached_max_speed = (max_speed != 0) ? max_speed * 4 : RoadVehInfo(v->engine_type)->max_speed;
253}
254
264{
265 /* Check that the vehicle can drive on the road in question */
266 RoadType rt = e->u.road.roadtype;
267 const RoadTypeInfo *rti = GetRoadTypeInfo(rt);
268 if (!HasTileAnyRoadType(tile, rti->powered_roadtypes)) return CommandCost(STR_ERROR_DEPOT_WRONG_DEPOT_TYPE);
269
270 if (flags.Test(DoCommandFlag::Execute)) {
271 const RoadVehicleInfo *rvi = &e->u.road;
272
273 RoadVehicle *v = new RoadVehicle();
274 *ret = v;
277
278 v->tile = tile;
279 int x = TileX(tile) * TILE_SIZE + TILE_SIZE / 2;
280 int y = TileY(tile) * TILE_SIZE + TILE_SIZE / 2;
281 v->x_pos = x;
282 v->y_pos = y;
283 v->z_pos = GetSlopePixelZ(x, y, true);
284
285 v->state = RVSB_IN_DEPOT;
287
288 v->spritenum = rvi->image_index;
290 assert(IsValidCargoType(v->cargo_type));
291 v->cargo_cap = rvi->capacity;
292 v->refit_cap = 0;
293
294 v->last_station_visited = StationID::Invalid();
295 v->last_loading_station = StationID::Invalid();
296 v->engine_type = e->index;
297 v->gcache.first_engine = EngineID::Invalid(); // needs to be set before first callback
298
299 v->reliability = e->reliability;
302
303 v->SetServiceInterval(Company::Get(v->owner)->settings.vehicle.servint_roadveh);
304
308
309 v->sprite_cache.sprite_seq.Set(SPR_IMG_QUERY);
310 v->random_bits = Random();
311 v->SetFrontEngine();
312
313 v->roadtype = rt;
316
318 v->SetServiceIntervalIsPercent(Company::Get(_current_company)->settings.vehicle.servint_ispercent);
319
322
323 /* Call various callbacks after the whole consist has been constructed */
324 for (RoadVehicle *u = v; u != nullptr; u = u->Next()) {
325 u->cargo_cap = u->GetEngine()->DetermineCapacity(u);
326 u->refit_cap = 0;
328 u->InvalidateNewGRFCache();
329 }
331 /* Initialize cached values for realistic acceleration. */
333
334 v->UpdatePosition();
335
337 }
338
339 return CommandCost();
340}
341
342static FindDepotData FindClosestRoadDepot(const RoadVehicle *v, int max_distance)
343{
344 if (IsRoadDepotTile(v->tile)) return FindDepotData(v->tile, 0);
345
346 return YapfRoadVehicleFindNearestDepot(v, max_distance);
347}
348
350{
351 FindDepotData rfdd = FindClosestRoadDepot(this, 0);
352 if (rfdd.best_length == UINT_MAX) return ClosestDepot();
353
354 return ClosestDepot(rfdd.tile, GetDepotIndex(rfdd.tile));
355}
356
364{
366 if (v == nullptr) return CMD_ERROR;
367
368 if (!v->IsPrimaryVehicle()) return CMD_ERROR;
369
371 if (ret.Failed()) return ret;
372
373 if (v->vehstatus.Any({VehState::Stopped, VehState::Crashed}) ||
374 v->breakdown_ctr != 0 ||
375 v->overtaking != 0 ||
376 v->state == RVSB_WORMHOLE ||
377 v->IsInDepot() ||
378 v->current_order.IsType(OT_LOADING)) {
379 return CMD_ERROR;
380 }
381
383
385
386 if (flags.Test(DoCommandFlag::Execute)) {
387 v->reverse_ctr = 180;
388
389 /* Unbunching data is no longer valid. */
391 }
392
393 return CommandCost();
394}
395
396
398{
399 for (RoadVehicle *v = this; v != nullptr; v = v->Next()) {
400 v->colourmap = PAL_NONE;
401 v->UpdateViewport(true, false);
402 }
403 this->CargoChanged();
404}
405
407{
408 static const int8_t _delta_xy_table[8][10] = {
409 /* 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 */
410 {3, 3, -1, -1, 0, 0, -1, -1, -1, -1}, // N
411 {3, 7, -1, -3, 0, -1, 0, -1, 0, 0}, // NE
412 {3, 3, -1, -1, 0, 0, 1, -1, 1, -1}, // E
413 {7, 3, -3, -1, -1, 0, 0, 0, 1, 0}, // SE
414 {3, 3, -1, -1, 0, 0, 1, 1, 1, 1}, // S
415 {3, 7, -1, -3, 0, -1, 0, 0, 0, 1}, // SW
416 {3, 3, -1, -1, 0, 0, -1, 1, -1, 1}, // W
417 {7, 3, -3, -1, -1, 0, -1, 0, 0, 0}, // NW
418 };
419
420 int shorten = VEHICLE_LENGTH - this->gcache.cached_veh_length;
421 if (!IsDiagonalDirection(this->direction)) shorten >>= 1;
422
423 const int8_t *bb = _delta_xy_table[this->direction];
424 this->x_bb_offs = bb[5] + bb[9] * shorten;
425 this->y_bb_offs = bb[4] + bb[8] * shorten;;
426 this->x_offs = bb[3];
427 this->y_offs = bb[2];
428 this->x_extent = bb[1] + bb[7] * shorten;
429 this->y_extent = bb[0] + bb[6] * shorten;
430 this->z_extent = 6;
431}
432
438{
439 int max_speed = this->gcache.cached_max_track_speed;
440
441 /* Limit speed to 50% while reversing, 75% in curves. */
442 for (const RoadVehicle *u = this; u != nullptr; u = u->Next()) {
445 max_speed = this->gcache.cached_max_track_speed / 2;
446 break;
447 } else if ((u->direction & 1) == 0) {
448 max_speed = this->gcache.cached_max_track_speed * 3 / 4;
449 }
450 }
451
452 /* Vehicle is on the middle part of a bridge. */
453 if (u->state == RVSB_WORMHOLE && !u->vehstatus.Test(VehState::Hidden)) {
454 max_speed = std::min(max_speed, GetBridgeSpec(GetBridgeType(u->tile))->speed * 2);
455 }
456 }
457
458 return std::min(max_speed, this->current_order.GetMaxSpeed() * 2);
459}
460
466{
467 RoadVehicle *first = v->First();
468 Vehicle *u = v;
469 for (; v->Next() != nullptr; v = v->Next()) u = v;
470 u->SetNext(nullptr);
471 v->last_station_visited = first->last_station_visited; // for PreDestructor
472
473 /* Only leave the road stop when we're really gone. */
474 if (IsInsideMM(v->state, RVSB_IN_ROAD_STOP, RVSB_IN_ROAD_STOP_END)) RoadStop::GetByTile(v->tile, GetRoadStopType(v->tile))->Leave(v);
475
476 delete v;
477}
478
479static void RoadVehSetRandomDirection(RoadVehicle *v)
480{
481 static const DirDiff delta[] = {
483 };
484
485 do {
486 uint32_t r = Random();
487
488 v->direction = ChangeDir(v->direction, delta[r & 3]);
489 v->UpdateViewport(true, true);
490 } while ((v = v->Next()) != nullptr);
491}
492
499{
500 v->crashed_ctr++;
501 if (v->crashed_ctr == 2) {
503 } else if (v->crashed_ctr <= 45) {
504 if ((v->tick_counter & 7) == 0) RoadVehSetRandomDirection(v);
505 } else if (v->crashed_ctr >= 2220 && !(v->tick_counter & 0x1F)) {
506 bool ret = v->Next() != nullptr;
508 return ret;
509 }
510
511 return true;
512}
513
514uint RoadVehicle::Crash(bool flooded)
515{
516 uint victims = this->GroundVehicleBase::Crash(flooded);
517 if (this->IsFrontEngine()) {
518 victims += 1; // driver
519
520 /* If we're in a drive through road stop we ought to leave it */
521 if (IsInsideMM(this->state, RVSB_IN_DT_ROAD_STOP, RVSB_IN_DT_ROAD_STOP_END)) {
522 RoadStop::GetByTile(this->tile, GetRoadStopType(this->tile))->Leave(this);
523 }
524 }
525 this->crashed_ctr = flooded ? 2000 : 1; // max 2220, disappear pretty fast when flooded
526 return victims;
527}
528
529static void RoadVehCrash(RoadVehicle *v)
530{
531 uint victims = v->Crash();
532
533 AI::NewEvent(v->owner, new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_RV_LEVEL_CROSSING, victims, v->owner));
534 Game::NewEvent(new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_RV_LEVEL_CROSSING, victims, v->owner));
535
536 EncodedString headline = (victims == 1)
537 ? GetEncodedString(STR_NEWS_ROAD_VEHICLE_CRASH_DRIVER)
538 : GetEncodedString(STR_NEWS_ROAD_VEHICLE_CRASH, victims);
540
541 AddTileNewsItem(std::move(headline), newstype, v->tile);
542
543 ModifyStationRatingAround(v->tile, v->owner, -160, 22);
544 if (_settings_client.sound.disaster) SndPlayVehicleFx(SND_12_EXPLOSION, v);
545}
546
547static bool RoadVehCheckTrainCrash(RoadVehicle *v)
548{
549 for (RoadVehicle *u = v; u != nullptr; u = u->Next()) {
550 if (u->state == RVSB_WORMHOLE) continue;
551
552 TileIndex tile = u->tile;
553
554 if (!IsLevelCrossingTile(tile)) continue;
555
556 if (HasVehicleNearTileXY(v->x_pos, v->y_pos, 4, [&u](const Vehicle *t) {
557 return t->type == VEH_TRAIN && abs(t->z_pos - u->z_pos) <= 6;
558 })) {
559 RoadVehCrash(v);
560 return true;
561 }
562 }
563
564 return false;
565}
566
568{
569 if (station == this->last_station_visited) this->last_station_visited = StationID::Invalid();
570
571 const Station *st = Station::Get(station);
572 if (!CanVehicleUseStation(this, st)) {
573 /* There is no stop left at the station, so don't even TRY to go there */
575 return TileIndex{};
576 }
577
578 return st->xy;
579}
580
581static void StartRoadVehSound(const RoadVehicle *v)
582{
583 if (!PlayVehicleSound(v, VSE_START)) {
584 SoundID s = RoadVehInfo(v->engine_type)->sfx;
585 if (s == SND_19_DEPARTURE_OLD_RV_1 && (v->tick_counter & 3) == 0) {
587 }
588 SndPlayVehicleFx(s, v);
589 }
590}
591
593 int x;
594 int y;
595 const Vehicle *veh;
596 Vehicle *best;
597 uint best_diff;
598 Direction dir;
599};
600
601static void FindClosestBlockingRoadVeh(Vehicle *v, RoadVehFindData *rvf)
602{
603 static const int8_t dist_x[] = { -4, -8, -4, -1, 4, 8, 4, 1 };
604 static const int8_t dist_y[] = { -4, -1, 4, 8, 4, 1, -4, -8 };
605
606 int x_diff = v->x_pos - rvf->x;
607 int y_diff = v->y_pos - rvf->y;
608
609 /* Not a close Road vehicle when it's not a road vehicle, in the depot, or ourself. */
610 if (v->type != VEH_ROAD || v->IsInDepot() || rvf->veh->First() == v->First()) return;
611
612 /* Not close when at a different height or when going in a different direction. */
613 if (abs(v->z_pos - rvf->veh->z_pos) >= 6 || v->direction != rvf->dir) return;
614
615 /* We 'return' the closest vehicle, in distance and then VehicleID as tie-breaker. */
616 uint diff = abs(x_diff) + abs(y_diff);
617 if (diff > rvf->best_diff || (diff == rvf->best_diff && v->index > rvf->best->index)) return;
618
619 auto IsCloseOnAxis = [](int dist, int diff) {
620 if (dist < 0) return diff > dist && diff <= 0;
621 return diff < dist && diff >= 0;
622 };
623
624 if (IsCloseOnAxis(dist_x[v->direction], x_diff) && IsCloseOnAxis(dist_y[v->direction], y_diff)) {
625 rvf->best = v;
626 rvf->best_diff = diff;
627 }
628}
629
630static RoadVehicle *RoadVehFindCloseTo(RoadVehicle *v, int x, int y, Direction dir, bool update_blocked_ctr = true)
631{
632 RoadVehFindData rvf;
633 RoadVehicle *front = v->First();
634
635 if (front->reverse_ctr != 0) return nullptr;
636
637 rvf.x = x;
638 rvf.y = y;
639 rvf.dir = dir;
640 rvf.veh = v;
641 rvf.best_diff = UINT_MAX;
642
643 if (front->state == RVSB_WORMHOLE) {
644 for (Vehicle *u : VehiclesOnTile(v->tile)) {
645 FindClosestBlockingRoadVeh(u, &rvf);
646 }
647 for (Vehicle *u : VehiclesOnTile(GetOtherTunnelBridgeEnd(v->tile))) {
648 FindClosestBlockingRoadVeh(u, &rvf);
649 }
650 } else {
651 for (Vehicle *u : VehiclesNearTileXY(x, y, 8)) {
652 FindClosestBlockingRoadVeh(u, &rvf);
653 }
654 }
655
656 /* This code protects a roadvehicle from being blocked for ever
657 * If more than 1480 / 74 days a road vehicle is blocked, it will
658 * drive just through it. The ultimate backup-code of TTD.
659 * It can be disabled. */
660 if (rvf.best_diff == UINT_MAX) {
661 front->blocked_ctr = 0;
662 return nullptr;
663 }
664
665 if (update_blocked_ctr && ++front->blocked_ctr > 1480) return nullptr;
666
667 return RoadVehicle::From(rvf.best);
668}
669
675static void RoadVehArrivesAt(const RoadVehicle *v, Station *st)
676{
677 if (v->IsBus()) {
678 /* Check if station was ever visited before */
679 if (!(st->had_vehicle_of_type & HVOT_BUS)) {
680 st->had_vehicle_of_type |= HVOT_BUS;
682 GetEncodedString(RoadTypeIsRoad(v->roadtype) ? STR_NEWS_FIRST_BUS_ARRIVAL : STR_NEWS_FIRST_PASSENGER_TRAM_ARRIVAL, st->index),
684 v->index,
685 st->index
686 );
687 AI::NewEvent(v->owner, new ScriptEventStationFirstVehicle(st->index, v->index));
688 Game::NewEvent(new ScriptEventStationFirstVehicle(st->index, v->index));
689 }
690 } else {
691 /* Check if station was ever visited before */
692 if (!(st->had_vehicle_of_type & HVOT_TRUCK)) {
693 st->had_vehicle_of_type |= HVOT_TRUCK;
695 GetEncodedString(RoadTypeIsRoad(v->roadtype) ? STR_NEWS_FIRST_TRUCK_ARRIVAL : STR_NEWS_FIRST_CARGO_TRAM_ARRIVAL, st->index),
697 v->index,
698 st->index
699 );
700 AI::NewEvent(v->owner, new ScriptEventStationFirstVehicle(st->index, v->index));
701 Game::NewEvent(new ScriptEventStationFirstVehicle(st->index, v->index));
702 }
703 }
704}
705
714{
716 default: NOT_REACHED();
717 case AM_ORIGINAL:
718 return this->DoUpdateSpeed(this->overtaking != 0 ? 512 : 256, 0, this->GetCurrentMaxSpeed());
719
720 case AM_REALISTIC:
721 return this->DoUpdateSpeed(this->GetAcceleration() + (this->overtaking != 0 ? 256 : 0), this->GetAccelerationStatus() == AS_BRAKE ? 0 : 4, this->GetCurrentMaxSpeed());
722 }
723}
724
725static Direction RoadVehGetNewDirection(const RoadVehicle *v, int x, int y)
726{
727 static const Direction _roadveh_new_dir[] = {
731 };
732
733 x = x - v->x_pos + 1;
734 y = y - v->y_pos + 1;
735
736 if ((uint)x > 2 || (uint)y > 2) return v->direction;
737 return _roadveh_new_dir[y * 4 + x];
738}
739
740static Direction RoadVehGetSlidingDirection(const RoadVehicle *v, int x, int y)
741{
742 Direction new_dir = RoadVehGetNewDirection(v, x, y);
743 Direction old_dir = v->direction;
744 DirDiff delta;
745
746 if (new_dir == old_dir) return old_dir;
747 delta = (DirDifference(new_dir, old_dir) > DIRDIFF_REVERSE ? DIRDIFF_45LEFT : DIRDIFF_45RIGHT);
748 return ChangeDir(old_dir, delta);
749}
750
752 const RoadVehicle *u;
753 const RoadVehicle *v;
754 TileIndex tile;
755 Trackdir trackdir;
756};
757
765{
766 if (!HasTileAnyRoadType(od->tile, od->v->compatible_roadtypes)) return true;
767 TrackStatus ts = GetTileTrackStatus(od->tile, TRANSPORT_ROAD, GetRoadTramType(od->v->roadtype));
768 TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts);
769 TrackdirBits red_signals = TrackStatusToRedSignals(ts); // barred level crossing
770 TrackBits trackbits = TrackdirBitsToTrackBits(trackdirbits);
771
772 /* Track does not continue along overtaking direction || track has junction || levelcrossing is barred */
773 if (!HasBit(trackdirbits, od->trackdir) || (trackbits & ~TRACK_BIT_CROSS) || (red_signals != TRACKDIR_BIT_NONE)) return true;
774
775 /* Are there more vehicles on the tile except the two vehicles involved in overtaking */
776 return HasVehicleOnTile(od->tile, [&](const Vehicle *v) {
777 return v->type == VEH_ROAD && v->First() == v && v != od->u && v != od->v;
778 });
779}
780
781static void RoadVehCheckOvertake(RoadVehicle *v, RoadVehicle *u)
782{
783 OvertakeData od;
784
785 od.v = v;
786 od.u = u;
787
788 /* Trams can't overtake other trams */
789 if (RoadTypeIsTram(v->roadtype)) return;
790
791 /* Don't overtake in stations */
792 if (IsTileType(v->tile, MP_STATION) || IsTileType(u->tile, MP_STATION)) return;
793
794 /* For now, articulated road vehicles can't overtake anything. */
795 if (v->HasArticulatedPart()) return;
796
797 /* Vehicles are not driving in same direction || direction is not a diagonal direction */
798 if (v->direction != u->direction || !(v->direction & 1)) return;
799
800 /* Check if vehicle is in a road stop, depot, tunnel or bridge or not on a straight road */
802
803 /* Can't overtake a vehicle that is moving faster than us. If the vehicle in front is
804 * accelerating, take the maximum speed for the comparison, else the current speed.
805 * Original acceleration always accelerates, so always use the maximum speed. */
806 int u_speed = (_settings_game.vehicle.roadveh_acceleration_model == AM_ORIGINAL || u->GetAcceleration() > 0) ? u->GetCurrentMaxSpeed() : u->cur_speed;
807 if (u_speed >= v->GetCurrentMaxSpeed() &&
809 u->cur_speed != 0) {
810 return;
811 }
812
814
815 /* Are the current and the next tile suitable for overtaking?
816 * - Does the track continue along od.trackdir
817 * - No junctions
818 * - No barred levelcrossing
819 * - No other vehicles in the way
820 */
821 od.tile = v->tile;
822 if (CheckRoadBlockedForOvertaking(&od)) return;
823
824 od.tile = v->tile + TileOffsByDiagDir(DirToDiagDir(v->direction));
825 if (CheckRoadBlockedForOvertaking(&od)) return;
826
827 /* When the vehicle in front of us is stopped we may only take
828 * half the time to pass it than when the vehicle is moving. */
829 v->overtaking_ctr = (od.u->cur_speed == 0 || od.u->vehstatus.Test(VehState::Stopped)) ? RV_OVERTAKE_TIMEOUT / 2 : 0;
831}
832
833static void RoadZPosAffectSpeed(RoadVehicle *v, int old_z)
834{
835 if (old_z == v->z_pos || _settings_game.vehicle.roadveh_acceleration_model != AM_ORIGINAL) return;
836
837 if (old_z < v->z_pos) {
838 v->cur_speed = v->cur_speed * 232 / 256; // slow down by ~10%
839 } else {
840 uint16_t spd = v->cur_speed + 2;
841 if (spd <= v->gcache.cached_max_track_speed) v->cur_speed = spd;
842 }
843}
844
845static int PickRandomBit(uint bits)
846{
847 uint i;
848 uint num = RandomRange(CountBits(bits));
849
850 for (i = 0; !(bits & 1) || (int)--num >= 0; bits >>= 1, i++) {}
851 return i;
852}
853
863{
864#define return_track(x) { best_track = (Trackdir)x; goto found_best_track; }
865
866 TileIndex desttile;
867 Trackdir best_track;
868 bool path_found = true;
869
870 TrackStatus ts = GetTileTrackStatus(tile, TRANSPORT_ROAD, GetRoadTramType(v->roadtype));
871 TrackdirBits red_signals = TrackStatusToRedSignals(ts); // crossing
873
874 if (IsTileType(tile, MP_ROAD)) {
875 if (IsRoadDepot(tile) && (!IsTileOwner(tile, v->owner) || GetRoadDepotDirection(tile) == enterdir)) {
876 /* Road depot owned by another company or with the wrong orientation */
877 trackdirs = TRACKDIR_BIT_NONE;
878 }
879 } else if (IsTileType(tile, MP_STATION) && IsBayRoadStopTile(tile)) {
880 /* Standard road stop (drive-through stops are treated as normal road) */
881
882 if (!IsTileOwner(tile, v->owner) || GetBayRoadStopDir(tile) == enterdir || v->HasArticulatedPart()) {
883 /* different station owner or wrong orientation or the vehicle has articulated parts */
884 trackdirs = TRACKDIR_BIT_NONE;
885 } else {
886 /* Our station */
888
889 if (GetRoadStopType(tile) != rstype) {
890 /* Wrong station type */
891 trackdirs = TRACKDIR_BIT_NONE;
892 } else {
893 /* Proper station type, check if there is free loading bay */
895 !RoadStop::GetByTile(tile, rstype)->HasFreeBay()) {
896 /* Station is full and RV queuing is off */
897 trackdirs = TRACKDIR_BIT_NONE;
898 }
899 }
900 }
901 }
902 /* The above lookups should be moved to GetTileTrackStatus in the
903 * future, but that requires more changes to the pathfinder and other
904 * stuff, probably even more arguments to GTTS.
905 */
906
907 /* Remove tracks unreachable from the enter dir */
908 trackdirs &= DiagdirReachesTrackdirs(enterdir);
909 if (trackdirs == TRACKDIR_BIT_NONE) {
910 /* If vehicle expected a path, it no longer exists, so invalidate it. */
911 if (!v->path.empty()) v->path.clear();
912 /* No reachable tracks, so we'll reverse */
913 return_track(_road_reverse_table[enterdir]);
914 }
915
916 if (v->reverse_ctr != 0) {
917 bool reverse = true;
918 if (RoadTypeIsTram(v->roadtype)) {
919 /* Trams may only reverse on a tile if it contains at least the straight
920 * trackbits or when it is a valid turning tile (i.e. one roadbit) */
921 RoadBits rb = GetAnyRoadBits(tile, RTT_TRAM);
922 RoadBits straight = AxisToRoadBits(DiagDirToAxis(enterdir));
923 reverse = ((rb & straight) == straight) ||
924 (rb == DiagDirToRoadBits(enterdir));
925 }
926 if (reverse) {
927 v->reverse_ctr = 0;
928 if (v->tile != tile) {
929 return_track(_road_reverse_table[enterdir]);
930 }
931 }
932 }
933
934 desttile = v->dest_tile;
935 if (desttile == 0) {
936 /* We've got no destination, pick a random track */
937 return_track(PickRandomBit(trackdirs));
938 }
939
940 /* Only one track to choose between? */
941 if (KillFirstBit(trackdirs) == TRACKDIR_BIT_NONE) {
942 if (!v->path.empty() && v->path.back().tile == tile) {
943 /* Vehicle expected a choice here, invalidate its path. */
944 v->path.clear();
945 }
946 return_track(FindFirstBit(trackdirs));
947 }
948
949 /* Attempt to follow cached path. */
950 if (!v->path.empty()) {
951 if (v->path.back().tile != tile) {
952 /* Vehicle didn't expect a choice here, invalidate its path. */
953 v->path.clear();
954 } else {
955 Trackdir trackdir = v->path.back().trackdir;
956
957 if (HasBit(trackdirs, trackdir)) {
958 v->path.pop_back();
959 return_track(trackdir);
960 }
961
962 /* Vehicle expected a choice which is no longer available. */
963 v->path.clear();
964 }
965 }
966
967 best_track = YapfRoadVehicleChooseTrack(v, tile, enterdir, trackdirs, path_found, v->path);
968
969 v->HandlePathfindingResult(path_found);
970
971found_best_track:;
972
973 if (HasBit(red_signals, best_track)) return INVALID_TRACKDIR;
974
975 return best_track;
976}
977
979 uint8_t x, y;
980};
981
983
984bool RoadVehLeaveDepot(RoadVehicle *v, bool first)
985{
986 /* Don't leave unless v and following wagons are in the depot. */
987 for (const RoadVehicle *u = v; u != nullptr; u = u->Next()) {
988 if (u->state != RVSB_IN_DEPOT || u->tile != v->tile) return false;
989 }
990
992 v->direction = DiagDirToDir(dir);
993
995 const RoadDriveEntry *rdp = _road_drive_data[GetRoadTramType(v->roadtype)][(_settings_game.vehicle.road_side << RVS_DRIVE_SIDE) + tdir];
996
997 int x = TileX(v->tile) * TILE_SIZE + (rdp[RVC_DEPOT_START_FRAME].x & 0xF);
998 int y = TileY(v->tile) * TILE_SIZE + (rdp[RVC_DEPOT_START_FRAME].y & 0xF);
999
1000 if (first) {
1001 /* We are leaving a depot, but have to go to the exact same one; re-enter */
1002 if (v->current_order.IsType(OT_GOTO_DEPOT) && v->tile == v->dest_tile) {
1004 return true;
1005 }
1006
1007 if (RoadVehFindCloseTo(v, x, y, v->direction, false) != nullptr) return true;
1008
1011
1012 StartRoadVehSound(v);
1013
1014 /* Vehicle is about to leave a depot */
1015 v->cur_speed = 0;
1016 }
1017
1019 v->state = tdir;
1020 v->frame = RVC_DEPOT_START_FRAME;
1021
1022 v->x_pos = x;
1023 v->y_pos = y;
1024 v->UpdatePosition();
1025 v->UpdateInclination(true, true);
1026
1028
1029 return true;
1030}
1031
1032static Trackdir FollowPreviousRoadVehicle(const RoadVehicle *v, const RoadVehicle *prev, TileIndex tile, DiagDirection entry_dir, bool already_reversed)
1033{
1034 if (prev->tile == v->tile && !already_reversed) {
1035 /* If the previous vehicle is on the same tile as this vehicle is
1036 * then it must have reversed. */
1037 return _road_reverse_table[entry_dir];
1038 }
1039
1040 uint8_t prev_state = prev->state;
1041 Trackdir dir;
1042
1043 if (prev_state == RVSB_WORMHOLE || prev_state == RVSB_IN_DEPOT) {
1044 DiagDirection diag_dir = INVALID_DIAGDIR;
1045
1046 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
1047 diag_dir = GetTunnelBridgeDirection(tile);
1048 } else if (IsRoadDepotTile(tile)) {
1049 diag_dir = ReverseDiagDir(GetRoadDepotDirection(tile));
1050 }
1051
1052 if (diag_dir == INVALID_DIAGDIR) return INVALID_TRACKDIR;
1053 dir = DiagDirToDiagTrackdir(diag_dir);
1054 } else {
1055 if (already_reversed && prev->tile != tile) {
1056 /*
1057 * The vehicle has reversed, but did not go straight back.
1058 * It immediately turn onto another tile. This means that
1059 * the roadstate of the previous vehicle cannot be used
1060 * as the direction we have to go with this vehicle.
1061 *
1062 * Next table is build in the following way:
1063 * - first row for when the vehicle in front went to the northern or
1064 * western tile, second for southern and eastern.
1065 * - columns represent the entry direction.
1066 * - cell values are determined by the Trackdir one has to take from
1067 * the entry dir (column) to the tile in north or south by only
1068 * going over the trackdirs used for turning 90 degrees, i.e.
1069 * TRACKDIR_{UPPER,RIGHT,LOWER,LEFT}_{N,E,S,W}.
1070 */
1071 static const Trackdir reversed_turn_lookup[2][DIAGDIR_END] = {
1074 dir = reversed_turn_lookup[prev->tile < tile ? 0 : 1][ReverseDiagDir(entry_dir)];
1075 } else if (HasBit(prev_state, RVS_IN_DT_ROAD_STOP)) {
1076 dir = (Trackdir)(prev_state & RVSB_ROAD_STOP_TRACKDIR_MASK);
1077 } else if (prev_state < TRACKDIR_END) {
1078 dir = (Trackdir)prev_state;
1079 } else {
1080 return INVALID_TRACKDIR;
1081 }
1082 }
1083
1084 /* Do some sanity checking. */
1085 static const RoadBits required_roadbits[] = {
1088 };
1089 RoadBits required = required_roadbits[dir & 0x07];
1090
1091 if ((required & GetAnyRoadBits(tile, GetRoadTramType(v->roadtype), true)) == ROAD_NONE) {
1092 dir = INVALID_TRACKDIR;
1093 }
1094
1095 return dir;
1096}
1097
1107{
1108 /* The 'current' company is not necessarily the owner of the vehicle. */
1109 Backup<CompanyID> cur_company(_current_company, c);
1110
1111 CommandCost ret = Command<CMD_BUILD_ROAD>::Do(DoCommandFlag::NoWater, t, r, rt, DRD_NONE, TownID::Invalid());
1112
1113 cur_company.Restore();
1114 return ret.Succeeded();
1115}
1116
1117bool IndividualRoadVehicleController(RoadVehicle *v, const RoadVehicle *prev)
1118{
1119 if (v->overtaking != 0) {
1120 if (IsTileType(v->tile, MP_STATION)) {
1121 /* Force us to be not overtaking! */
1122 v->overtaking = 0;
1123 } else if (++v->overtaking_ctr >= RV_OVERTAKE_TIMEOUT) {
1124 /* If overtaking just aborts at a random moment, we can have a out-of-bound problem,
1125 * if the vehicle started a corner. To protect that, only allow an abort of
1126 * overtake if we are on straight roads */
1128 v->overtaking = 0;
1129 }
1130 }
1131 }
1132
1133 /* If this vehicle is in a depot and we've reached this point it must be
1134 * one of the articulated parts. It will stay in the depot until activated
1135 * by the previous vehicle in the chain when it gets to the right place. */
1136 if (v->IsInDepot()) return true;
1137
1138 if (v->state == RVSB_WORMHOLE) {
1139 /* Vehicle is entering a depot or is on a bridge or in a tunnel */
1141
1142 if (v->IsFrontEngine()) {
1143 const Vehicle *u = RoadVehFindCloseTo(v, gp.x, gp.y, v->direction);
1144 if (u != nullptr) {
1145 v->cur_speed = u->First()->cur_speed;
1146 return false;
1147 }
1148 }
1149
1151 /* Vehicle has just entered a bridge or tunnel */
1152 v->x_pos = gp.x;
1153 v->y_pos = gp.y;
1154 v->UpdatePosition();
1155 v->UpdateInclination(true, true);
1156 return true;
1157 }
1158
1159 v->x_pos = gp.x;
1160 v->y_pos = gp.y;
1161 v->UpdatePosition();
1162 if (!v->vehstatus.Test(VehState::Hidden)) v->Vehicle::UpdateViewport(true);
1163 return true;
1164 }
1165
1166 /* Get move position data for next frame.
1167 * For a drive-through road stop use 'straight road' move data.
1168 * In this case v->state is masked to give the road stop entry direction. */
1169 RoadDriveEntry rd = _road_drive_data[GetRoadTramType(v->roadtype)][(
1171 (_settings_game.vehicle.road_side << RVS_DRIVE_SIDE)) ^ v->overtaking][v->frame + 1];
1172
1173 if (rd.x & RDE_NEXT_TILE) {
1174 TileIndex tile = v->tile + TileOffsByDiagDir((DiagDirection)(rd.x & 3));
1175 Trackdir dir;
1176
1177 if (v->IsFrontEngine()) {
1178 /* If this is the front engine, look for the right path. */
1180 dir = RoadFindPathToDest(v, tile, (DiagDirection)(rd.x & 3));
1181 } else {
1182 dir = _road_reverse_table[(DiagDirection)(rd.x & 3)];
1183 }
1184 } else {
1185 dir = FollowPreviousRoadVehicle(v, prev, tile, (DiagDirection)(rd.x & 3), false);
1186 }
1187
1188 if (dir == INVALID_TRACKDIR) {
1189 if (!v->IsFrontEngine()) FatalError("Disconnecting road vehicle.");
1190 v->cur_speed = 0;
1191 return false;
1192 }
1193
1194again:
1195 uint start_frame = RVC_DEFAULT_START_FRAME;
1196 if (IsReversingRoadTrackdir(dir)) {
1197 /* When turning around we can't be overtaking. */
1198 v->overtaking = 0;
1199
1200 /* Turning around */
1201 if (RoadTypeIsTram(v->roadtype)) {
1202 /* Determine the road bits the tram needs to be able to turn around
1203 * using the 'big' corner loop. */
1204 RoadBits needed;
1205 switch (dir) {
1206 default: NOT_REACHED();
1207 case TRACKDIR_RVREV_NE: needed = ROAD_SW; break;
1208 case TRACKDIR_RVREV_SE: needed = ROAD_NW; break;
1209 case TRACKDIR_RVREV_SW: needed = ROAD_NE; break;
1210 case TRACKDIR_RVREV_NW: needed = ROAD_SE; break;
1211 }
1212 if ((v->Previous() != nullptr && v->Previous()->tile == tile) ||
1213 (v->IsFrontEngine() && IsNormalRoadTile(tile) && !HasRoadWorks(tile) &&
1215 (needed & GetRoadBits(tile, RTT_TRAM)) != ROAD_NONE)) {
1216 /*
1217 * Taking the 'big' corner for trams only happens when:
1218 * - The previous vehicle in this (articulated) tram chain is
1219 * already on the 'next' tile, we just follow them regardless of
1220 * anything. When it is NOT on the 'next' tile, the tram started
1221 * doing a reversing turn when the piece of tram track on the next
1222 * tile did not exist yet. Do not use the big tram loop as that is
1223 * going to cause the tram to split up.
1224 * - Or the front of the tram can drive over the next tile.
1225 */
1226 } else if (!v->IsFrontEngine() || !CanBuildTramTrackOnTile(v->owner, tile, v->roadtype, needed) || ((~needed & GetAnyRoadBits(v->tile, RTT_TRAM, false)) == ROAD_NONE)) {
1227 /*
1228 * Taking the 'small' corner for trams only happens when:
1229 * - We are not the from vehicle of an articulated tram.
1230 * - Or when the company cannot build on the next tile.
1231 *
1232 * The 'small' corner means that the vehicle is on the end of a
1233 * tram track and needs to start turning there. To do this properly
1234 * the tram needs to start at an offset in the tram turning 'code'
1235 * for 'big' corners. It furthermore does not go to the next tile,
1236 * so that needs to be fixed too.
1237 */
1238 tile = v->tile;
1239 start_frame = RVC_TURN_AROUND_START_FRAME_SHORT_TRAM;
1240 } else {
1241 /* The company can build on the next tile, so wait till they do. */
1242 v->cur_speed = 0;
1243 return false;
1244 }
1246 v->cur_speed = 0;
1247 return false;
1248 } else {
1249 tile = v->tile;
1250 }
1251 }
1252
1253 /* Get position data for first frame on the new tile */
1254 const RoadDriveEntry *rdp = _road_drive_data[GetRoadTramType(v->roadtype)][(dir + (_settings_game.vehicle.road_side << RVS_DRIVE_SIDE)) ^ v->overtaking];
1255
1256 int x = TileX(tile) * TILE_SIZE + rdp[start_frame].x;
1257 int y = TileY(tile) * TILE_SIZE + rdp[start_frame].y;
1258
1259 Direction new_dir = RoadVehGetSlidingDirection(v, x, y);
1260 if (v->IsFrontEngine()) {
1261 const Vehicle *u = RoadVehFindCloseTo(v, x, y, new_dir);
1262 if (u != nullptr) {
1263 v->cur_speed = u->First()->cur_speed;
1264 /* We might be blocked, prevent pathfinding rerun as we already know where we are heading to. */
1265 v->path.emplace_back(dir, tile);
1266 return false;
1267 }
1268 }
1269
1270 auto vets = VehicleEnterTile(v, tile, x, y);
1271 if (vets.Test(VehicleEnterTileState::CannotEnter)) {
1272 if (!IsTileType(tile, MP_TUNNELBRIDGE)) {
1273 v->cur_speed = 0;
1274 return false;
1275 }
1276 /* Try an about turn to re-enter the previous tile */
1277 dir = _road_reverse_table[rd.x & 3];
1278 goto again;
1279 }
1280
1281 if (IsInsideMM(v->state, RVSB_IN_ROAD_STOP, RVSB_IN_DT_ROAD_STOP_END) && IsTileType(v->tile, MP_STATION)) {
1282 if (IsReversingRoadTrackdir(dir) && IsInsideMM(v->state, RVSB_IN_ROAD_STOP, RVSB_IN_ROAD_STOP_END)) {
1283 /* New direction is trying to turn vehicle around.
1284 * We can't turn at the exit of a road stop so wait.*/
1285 v->cur_speed = 0;
1286 return false;
1287 }
1288
1289 /* If we are a drive through road stop and the next tile is of
1290 * the same road stop and the next tile isn't this one (i.e. we
1291 * are not reversing), then keep the reservation and state.
1292 * This way we will not be shortly unregister from the road
1293 * stop. It also makes it possible to load when on the edge of
1294 * two road stops; otherwise you could get vehicles that should
1295 * be loading but are not actually loading. */
1296 if (IsDriveThroughStopTile(v->tile) &&
1298 v->tile != tile) {
1299 /* So, keep 'our' state */
1300 dir = (Trackdir)v->state;
1301 } else if (IsStationRoadStop(v->tile)) {
1302 /* We're not continuing our drive through road stop, so leave. */
1304 }
1305 }
1306
1308 TileIndex old_tile = v->tile;
1309
1310 v->tile = tile;
1311 v->state = (uint8_t)dir;
1312 v->frame = start_frame;
1313 RoadTramType rtt = GetRoadTramType(v->roadtype);
1314 if (GetRoadType(old_tile, rtt) != GetRoadType(tile, rtt)) {
1315 if (v->IsFrontEngine()) {
1317 }
1318 v->First()->CargoChanged();
1319 }
1320 }
1321 if (new_dir != v->direction) {
1322 v->direction = new_dir;
1323 if (_settings_game.vehicle.roadveh_acceleration_model == AM_ORIGINAL) v->cur_speed -= v->cur_speed >> 2;
1324 }
1325 v->x_pos = x;
1326 v->y_pos = y;
1327 v->UpdatePosition();
1328 RoadZPosAffectSpeed(v, v->UpdateInclination(true, true));
1329 return true;
1330 }
1331
1332 if (rd.x & RDE_TURNED) {
1333 /* Vehicle has finished turning around, it will now head back onto the same tile */
1334 Trackdir dir;
1335 uint turn_around_start_frame = RVC_TURN_AROUND_START_FRAME;
1336
1337 if (RoadTypeIsTram(v->roadtype) && !IsRoadDepotTile(v->tile) && HasExactlyOneBit(GetAnyRoadBits(v->tile, RTT_TRAM, true))) {
1338 /*
1339 * The tram is turning around with one tram 'roadbit'. This means that
1340 * it is using the 'big' corner 'drive data'. However, to support the
1341 * trams to take a small corner, there is a 'turned' marker in the middle
1342 * of the turning 'drive data'. When the tram took the long corner, we
1343 * will still use the 'big' corner drive data, but we advance it one
1344 * frame. We furthermore set the driving direction so the turning is
1345 * going to be properly shown.
1346 */
1347 turn_around_start_frame = RVC_START_FRAME_AFTER_LONG_TRAM;
1348 switch (rd.x & 0x3) {
1349 default: NOT_REACHED();
1350 case DIAGDIR_NW: dir = TRACKDIR_RVREV_SE; break;
1351 case DIAGDIR_NE: dir = TRACKDIR_RVREV_SW; break;
1352 case DIAGDIR_SE: dir = TRACKDIR_RVREV_NW; break;
1353 case DIAGDIR_SW: dir = TRACKDIR_RVREV_NE; break;
1354 }
1355 } else {
1356 if (v->IsFrontEngine()) {
1357 /* If this is the front engine, look for the right path. */
1358 dir = RoadFindPathToDest(v, v->tile, (DiagDirection)(rd.x & 3));
1359 } else {
1360 dir = FollowPreviousRoadVehicle(v, prev, v->tile, (DiagDirection)(rd.x & 3), true);
1361 }
1362 }
1363
1364 if (dir == INVALID_TRACKDIR) {
1365 v->cur_speed = 0;
1366 return false;
1367 }
1368
1369 const RoadDriveEntry *rdp = _road_drive_data[GetRoadTramType(v->roadtype)][(_settings_game.vehicle.road_side << RVS_DRIVE_SIDE) + dir];
1370
1371 int x = TileX(v->tile) * TILE_SIZE + rdp[turn_around_start_frame].x;
1372 int y = TileY(v->tile) * TILE_SIZE + rdp[turn_around_start_frame].y;
1373
1374 Direction new_dir = RoadVehGetSlidingDirection(v, x, y);
1375 if (v->IsFrontEngine()) {
1376 const Vehicle *u = RoadVehFindCloseTo(v, x, y, new_dir);
1377 if (u != nullptr) {
1378 v->cur_speed = u->First()->cur_speed;
1379 /* We might be blocked, prevent pathfinding rerun as we already know where we are heading to. */
1380 v->path.emplace_back(dir, v->tile);
1381 return false;
1382 }
1383 }
1384
1385 auto vets = VehicleEnterTile(v, v->tile, x, y);
1386 if (vets.Test(VehicleEnterTileState::CannotEnter)) {
1387 v->cur_speed = 0;
1388 return false;
1389 }
1390
1391 v->state = dir;
1392 v->frame = turn_around_start_frame;
1393
1394 if (new_dir != v->direction) {
1395 v->direction = new_dir;
1396 if (_settings_game.vehicle.roadveh_acceleration_model == AM_ORIGINAL) v->cur_speed -= v->cur_speed >> 2;
1397 }
1398
1399 v->x_pos = x;
1400 v->y_pos = y;
1401 v->UpdatePosition();
1402 RoadZPosAffectSpeed(v, v->UpdateInclination(true, true));
1403 return true;
1404 }
1405
1406 /* This vehicle is not in a wormhole and it hasn't entered a new tile. If
1407 * it's on a depot tile, check if it's time to activate the next vehicle in
1408 * the chain yet. */
1409 if (v->Next() != nullptr && IsRoadDepotTile(v->tile)) {
1410 if (v->frame == v->gcache.cached_veh_length + RVC_DEPOT_START_FRAME) {
1411 RoadVehLeaveDepot(v->Next(), false);
1412 }
1413 }
1414
1415 /* Calculate new position for the vehicle */
1416 int x = (v->x_pos & ~15) + (rd.x & 15);
1417 int y = (v->y_pos & ~15) + (rd.y & 15);
1418
1419 Direction new_dir = RoadVehGetSlidingDirection(v, x, y);
1420
1421 if (v->IsFrontEngine() && !IsInsideMM(v->state, RVSB_IN_ROAD_STOP, RVSB_IN_ROAD_STOP_END)) {
1422 /* Vehicle is not in a road stop.
1423 * Check for another vehicle to overtake */
1424 RoadVehicle *u = RoadVehFindCloseTo(v, x, y, new_dir);
1425
1426 if (u != nullptr) {
1427 u = u->First();
1428 /* There is a vehicle in front overtake it if possible */
1429 if (v->overtaking == 0) RoadVehCheckOvertake(v, u);
1430 if (v->overtaking == 0) v->cur_speed = u->cur_speed;
1431
1432 /* In case an RV is stopped in a road stop, why not try to load? */
1433 if (v->cur_speed == 0 && IsInsideMM(v->state, RVSB_IN_DT_ROAD_STOP, RVSB_IN_DT_ROAD_STOP_END) &&
1435 v->owner == GetTileOwner(v->tile) && !v->current_order.IsType(OT_LEAVESTATION) &&
1436 GetRoadStopType(v->tile) == (v->IsBus() ? RoadStopType::Bus : RoadStopType::Truck)) {
1438 v->last_station_visited = st->index;
1439 RoadVehArrivesAt(v, st);
1440 v->BeginLoading();
1441 TriggerRoadStopRandomisation(st, v->tile, StationRandomTrigger::VehicleArrives);
1442 TriggerRoadStopAnimation(st, v->tile, StationAnimationTrigger::VehicleArrives);
1443 }
1444 return false;
1445 }
1446 }
1447
1448 Direction old_dir = v->direction;
1449 if (new_dir != old_dir) {
1450 v->direction = new_dir;
1451 if (_settings_game.vehicle.roadveh_acceleration_model == AM_ORIGINAL) v->cur_speed -= v->cur_speed >> 2;
1452
1453 /* Delay the vehicle in curves by making it require one additional frame per turning direction (two in total).
1454 * A vehicle has to spend at least 9 frames on a tile, so the following articulated part can follow.
1455 * (The following part may only be one tile behind, and the front part is moved before the following ones.)
1456 * The short (inner) curve has 8 frames, this elongates it to 10. */
1457 v->UpdateViewport(true, true);
1458 return true;
1459 }
1460
1461 /* If the vehicle is in a normal road stop and the frame equals the stop frame OR
1462 * if the vehicle is in a drive-through road stop and this is the destination station
1463 * and it's the correct type of stop (bus or truck) and the frame equals the stop frame...
1464 * (the station test and stop type test ensure that other vehicles, using the road stop as
1465 * a through route, do not stop) */
1466 if (v->IsFrontEngine() && ((IsInsideMM(v->state, RVSB_IN_ROAD_STOP, RVSB_IN_ROAD_STOP_END) &&
1468 (IsInsideMM(v->state, RVSB_IN_DT_ROAD_STOP, RVSB_IN_DT_ROAD_STOP_END) &&
1470 v->owner == GetTileOwner(v->tile) &&
1471 GetRoadStopType(v->tile) == (v->IsBus() ? RoadStopType::Bus : RoadStopType::Truck) &&
1472 v->frame == RVC_DRIVE_THROUGH_STOP_FRAME))) {
1473
1476
1477 /* Vehicle is at the stop position (at a bay) in a road stop.
1478 * Note, if vehicle is loading/unloading it has already been handled,
1479 * so if we get here the vehicle has just arrived or is just ready to leave. */
1480 if (!HasBit(v->state, RVS_ENTERED_STOP)) {
1481 /* Vehicle has arrived at a bay in a road stop */
1482
1483 if (IsDriveThroughStopTile(v->tile)) {
1484 TileIndex next_tile = TileAddByDir(v->tile, v->direction);
1485
1486 /* Check if next inline bay is free and has compatible road. */
1488 v->frame++;
1489 v->x_pos = x;
1490 v->y_pos = y;
1491 v->UpdatePosition();
1492 RoadZPosAffectSpeed(v, v->UpdateInclination(true, false));
1493 return true;
1494 }
1495 }
1496
1497 rs->SetEntranceBusy(false);
1499
1500 v->last_station_visited = st->index;
1501
1502 if (IsDriveThroughStopTile(v->tile) || (v->current_order.IsType(OT_GOTO_STATION) && v->current_order.GetDestination() == st->index)) {
1503 RoadVehArrivesAt(v, st);
1504 v->BeginLoading();
1505 TriggerRoadStopRandomisation(st, v->tile, StationRandomTrigger::VehicleArrives);
1506 TriggerRoadStopAnimation(st, v->tile, StationAnimationTrigger::VehicleArrives);
1507 return false;
1508 }
1509 } else {
1510 /* Vehicle is ready to leave a bay in a road stop */
1511 if (rs->IsEntranceBusy()) {
1512 /* Road stop entrance is busy, so wait as there is nowhere else to go */
1513 v->cur_speed = 0;
1514 return false;
1515 }
1516 if (v->current_order.IsType(OT_LEAVESTATION)) v->current_order.Free();
1517 }
1518
1519 if (IsBayRoadStopTile(v->tile)) rs->SetEntranceBusy(true);
1520
1521 StartRoadVehSound(v);
1523 }
1524
1525 /* Check tile position conditions - i.e. stop position in depot,
1526 * entry onto bridge or into tunnel */
1527 auto vets = VehicleEnterTile(v, v->tile, x, y);
1528 if (vets.Test(VehicleEnterTileState::CannotEnter)) {
1529 v->cur_speed = 0;
1530 return false;
1531 }
1532
1533 if (v->current_order.IsType(OT_LEAVESTATION) && IsDriveThroughStopTile(v->tile)) {
1534 v->current_order.Free();
1535 }
1536
1537 /* Move to next frame unless vehicle arrived at a stop position
1538 * in a depot or entered a tunnel/bridge */
1539 if (!vets.Test(VehicleEnterTileState::EnteredWormhole)) v->frame++;
1540 v->x_pos = x;
1541 v->y_pos = y;
1542 v->UpdatePosition();
1543 RoadZPosAffectSpeed(v, v->UpdateInclination(false, true));
1544 return true;
1545}
1546
1547static bool RoadVehController(RoadVehicle *v)
1548{
1549 /* decrease counters */
1550 v->current_order_time++;
1551 if (v->reverse_ctr != 0) v->reverse_ctr--;
1552
1553 /* handle crashed */
1554 if (v->vehstatus.Test(VehState::Crashed) || RoadVehCheckTrainCrash(v)) {
1555 return RoadVehIsCrashed(v);
1556 }
1557
1558 /* road vehicle has broken down? */
1559 if (v->HandleBreakdown()) return true;
1561 v->SetLastSpeed();
1562 return true;
1563 }
1564
1565 ProcessOrders(v);
1566 v->HandleLoading();
1567
1568 if (v->current_order.IsType(OT_LOADING)) return true;
1569
1570 if (v->IsInDepot()) {
1571 /* Check if we should wait here for unbunching. */
1572 if (v->IsWaitingForUnbunching()) return true;
1573 if (RoadVehLeaveDepot(v, true)) return true;
1574 }
1575
1576 v->ShowVisualEffect();
1577
1578 /* Check how far the vehicle needs to proceed */
1579 int j = v->UpdateSpeed();
1580
1581 int adv_spd = v->GetAdvanceDistance();
1582 bool blocked = false;
1583 while (j >= adv_spd) {
1584 j -= adv_spd;
1585
1586 RoadVehicle *u = v;
1587 for (RoadVehicle *prev = nullptr; u != nullptr; prev = u, u = u->Next()) {
1588 if (!IndividualRoadVehicleController(u, prev)) {
1589 blocked = true;
1590 break;
1591 }
1592 }
1593 if (blocked) break;
1594
1595 /* Determine distance to next map position */
1596 adv_spd = v->GetAdvanceDistance();
1597
1598 /* Test for a collision, but only if another movement will occur. */
1599 if (j >= adv_spd && RoadVehCheckTrainCrash(v)) break;
1600 }
1601
1602 v->SetLastSpeed();
1603
1604 for (RoadVehicle *u = v; u != nullptr; u = u->Next()) {
1605 if (u->vehstatus.Test(VehState::Hidden)) continue;
1606
1607 u->UpdateViewport(false, false);
1608 }
1609
1610 /* If movement is blocked, set 'progress' to its maximum, so the roadvehicle does
1611 * not accelerate again before it can actually move. I.e. make sure it tries to advance again
1612 * on next tick to discover whether it is still blocked. */
1613 if (v->progress == 0) v->progress = blocked ? adv_spd - 1 : j;
1614
1615 return true;
1616}
1617
1619{
1620 const Engine *e = this->GetEngine();
1621 if (e->u.road.running_cost_class == INVALID_PRICE) return 0;
1622
1623 uint cost_factor = GetVehicleProperty(this, PROP_ROADVEH_RUNNING_COST_FACTOR, e->u.road.running_cost);
1624 if (cost_factor == 0) return 0;
1625
1626 return GetPrice(e->u.road.running_cost_class, cost_factor, e->GetGRF());
1627}
1628
1630{
1632
1633 this->tick_counter++;
1634
1635 if (this->IsFrontEngine()) {
1636 if (!this->vehstatus.Test(VehState::Stopped)) this->running_ticks++;
1637 return RoadVehController(this);
1638 }
1639
1640 return true;
1641}
1642
1643void RoadVehicle::SetDestTile(TileIndex tile)
1644{
1645 if (tile == this->dest_tile) return;
1646 this->path.clear();
1647 this->dest_tile = tile;
1648}
1649
1650static void CheckIfRoadVehNeedsService(RoadVehicle *v)
1651{
1652 /* If we already got a slot at a stop, use that FIRST, and go to a depot later */
1653 if (Company::Get(v->owner)->settings.vehicle.servint_roadveh == 0 || !v->NeedsAutomaticServicing()) return;
1654 if (v->IsChainInDepot()) {
1656 return;
1657 }
1658
1660
1661 FindDepotData rfdd = FindClosestRoadDepot(v, max_penalty);
1662 /* Only go to the depot if it is not too far out of our way. */
1663 if (rfdd.best_length == UINT_MAX || rfdd.best_length > max_penalty) {
1664 if (v->current_order.IsType(OT_GOTO_DEPOT)) {
1665 /* If we were already heading for a depot but it has
1666 * suddenly moved farther away, we continue our normal
1667 * schedule? */
1670 }
1671 return;
1672 }
1673
1674 DepotID depot = GetDepotIndex(rfdd.tile);
1675
1676 if (v->current_order.IsType(OT_GOTO_DEPOT) &&
1678 !Chance16(1, 20)) {
1679 return;
1680 }
1681
1684 v->SetDestTile(rfdd.tile);
1686}
1687
1690{
1691 if (!this->IsFrontEngine()) return;
1692 AgeVehicle(this);
1693}
1694
1697{
1698 if (!this->IsFrontEngine()) return;
1699 EconomyAgeVehicle(this);
1700
1701 if ((++this->day_counter & 7) == 0) DecreaseVehicleValue(this);
1702 if (this->blocked_ctr == 0) CheckVehicleBreakdown(this);
1703
1704 CheckIfRoadVehNeedsService(this);
1705
1706 CheckOrders(this);
1707
1708 if (this->running_ticks == 0) return;
1709
1711
1712 this->profit_this_year -= cost.GetCost();
1713 this->running_ticks = 0;
1714
1716
1719}
1720
1722{
1724
1725 if (this->IsInDepot()) {
1726 /* We'll assume the road vehicle is facing outwards */
1727 return DiagDirToDiagTrackdir(GetRoadDepotDirection(this->tile));
1728 }
1729
1730 if (IsBayRoadStopTile(this->tile)) {
1731 /* We'll assume the road vehicle is facing outwards */
1732 return DiagDirToDiagTrackdir(GetBayRoadStopDir(this->tile)); // Road vehicle in a station
1733 }
1734
1735 /* Drive through road stops / wormholes (tunnels) */
1737
1738 /* If vehicle's state is a valid track direction (vehicle is not turning around) return it,
1739 * otherwise transform it into a valid track direction */
1740 return (Trackdir)((IsReversingRoadTrackdir((Trackdir)this->state)) ? (this->state - 6) : this->state);
1741}
1742
1744{
1745 uint16_t weight = CargoSpec::Get(this->cargo_type)->WeightOfNUnits(this->GetEngine()->DetermineCapacity(this));
1746
1747 /* Vehicle weight is not added for articulated parts. */
1748 if (!this->IsArticulatedPart()) {
1749 /* Road vehicle weight is in units of 1/4 t. */
1750 weight += GetVehicleProperty(this, PROP_ROADVEH_WEIGHT, RoadVehInfo(this->engine_type)->weight) / 4;
1751 }
1752
1753 return weight;
1754}
Base functions for all AIs.
void AddArticulatedParts(Vehicle *first)
Add the remaining articulated parts to the given vehicle.
void CheckConsistencyOfArticulatedVehicle(const Vehicle *v)
Checks whether the specs of freshly build articulated vehicles are consistent with the information sp...
Functions related to articulated vehicles.
Class for backupping variables and making sure they are restored later.
@ BuiltAsPrototype
Vehicle is a prototype (accepted as exclusive preview).
debug_inline constexpr bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
constexpr bool HasExactlyOneBit(T value)
Test whether value has exactly 1 bit set.
constexpr T SetBit(T &x, const uint8_t y)
Set a bit in a variable.
constexpr uint8_t FindFirstBit(T x)
Search the first set bit in a value.
constexpr uint CountBits(T value)
Counts the number of set bits in a variable.
constexpr T KillFirstBit(T value)
Clear the first bit in an integer.
const BridgeSpec * GetBridgeSpec(BridgeType i)
Get the specification of a bridge type.
Definition bridge.h:67
BridgeType GetBridgeType(Tile t)
Determines the type of bridge on a tile.
Definition bridge_map.h:56
bool IsValidCargoType(CargoType cargo)
Test whether cargo type is not INVALID_CARGO.
Definition cargo_type.h:106
@ Passengers
Passengers.
bool IsCargoInClass(CargoType cargo, CargoClasses cc)
Does cargo c have cargo class cc?
Definition cargotype.h:236
static void NewEvent(CompanyID company, ScriptEvent *event)
Queue a new event for an AI.
Definition ai_core.cpp:235
constexpr bool Test(Tvalue_type value) const
Test if the value-th bit is set.
constexpr Timpl & Reset()
Reset all bits.
constexpr Timpl & Set()
Set all bits.
constexpr bool Any(const Timpl &other) const
Test if any of the given values are set.
Common return value for all commands.
bool Succeeded() const
Did this command succeed?
Money GetCost() const
The costs as made up to this moment.
bool Failed() const
Did this command fail?
Container for an encoded string, created by GetEncodedString.
Enum-as-bit-set wrapper.
static void NewEvent(class ScriptEvent *event)
Queue a new event for a Game Script.
RAII class for measuring multi-step elements of performance.
RoadTypes powered_roadtypes
bitmask to the OTHER roadtypes on which a vehicle of THIS roadtype generates power
Definition road.h:113
static constexpr TimerGameTick::Ticks DAY_TICKS
1 day is 74 ticks; TimerGameCalendar::date_fract used to be uint16_t and incremented by 885.
static Date date
Current date in days (day counter).
static Year year
Current year, starting at 0.
static constexpr int DAYS_IN_YEAR
days per year
static Date date
Current date in days (day counter).
uint StoredCount() const
Returns sum of cargo on board the vehicle (ie not only reserved).
Iterate over all vehicles near a given world coordinate.
Iterate over all vehicles on a tile.
Functions related to commands.
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
@ Execute
execute the given command
@ NoWater
don't allow building on water
Definition of stuff that is very close to a company, like the company struct itself.
CommandCost CheckOwnership(Owner owner, TileIndex tile)
Check whether the current owner owns something.
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
CompanyID _current_company
Company currently doing an action.
void SubtractMoneyFromCompanyFract(CompanyID company, const CommandCost &cst)
Subtract money from a company, including the money fraction.
Functions related to companies.
Map related accessors for depots.
DepotID GetDepotIndex(Tile t)
Get the index of which depot is attached to the tile.
Definition depot_map.h:53
DirDiff DirDifference(Direction d0, Direction d1)
Calculate the difference between two directions.
Direction DiagDirToDir(DiagDirection dir)
Convert a DiagDirection to a Direction.
DiagDirection ReverseDiagDir(DiagDirection d)
Returns the reverse direction of the given DiagDirection.
Direction ReverseDir(Direction d)
Return the reverse of a direction.
Direction ChangeDir(Direction d, DirDiff delta)
Change a direction by a given difference.
bool IsDiagonalDirection(Direction dir)
Checks if a given Direction is diagonal.
Axis DiagDirToAxis(DiagDirection d)
Convert a DiagDirection to the axis.
DiagDirection DirToDiagDir(Direction dir)
Convert a Direction to a DiagDirection.
DirDiff
Enumeration for the difference between two directions.
@ DIRDIFF_45LEFT
Angle of 45 degrees left.
@ DIRDIFF_REVERSE
One direction is the opposite of the other one.
@ DIRDIFF_45RIGHT
Angle of 45 degrees right.
@ DIRDIFF_SAME
Both directions faces to the same direction.
Direction
Defines the 8 directions on the map.
@ DIR_SW
Southwest.
@ DIR_NW
Northwest.
@ INVALID_DIR
Flag for an invalid direction.
@ DIR_N
North.
@ DIR_SE
Southeast.
@ DIR_S
South.
@ DIR_NE
Northeast.
@ DIR_W
West.
@ DIR_E
East.
DiagDirection
Enumeration for diagonal directions.
@ DIAGDIR_NE
Northeast, upper right on your monitor.
@ DIAGDIR_NW
Northwest.
@ DIAGDIR_SE
Southeast.
@ DIAGDIR_END
Used for iterations.
@ INVALID_DIAGDIR
Flag for an invalid DiagDirection.
@ DIAGDIR_SW
Southwest.
Money GetPrice(Price index, uint cost_factor, const GRFFile *grf_file, int shift)
Determine a certain price.
Definition economy.cpp:952
@ EXPENSES_ROADVEH_RUN
Running costs road vehicles.
EffectVehicle * CreateEffectVehicleRel(const Vehicle *v, int x, int y, int z, EffectVehicleType type)
Create an effect vehicle above a particular vehicle.
Functions related to effect vehicles.
@ EV_EXPLOSION_LARGE
Various explosions.
@ ExclusivePreview
This vehicle is in the exclusive preview stage, either being used or being offered to a company.
Error reporting related functions.
fluid_settings_t * settings
FluidSynth settings handle.
Types for recording game performance data.
@ PFE_GL_ROADVEHS
Time spend processing road vehicles.
Base functions for all Games.
uint32_t SpriteID
The number of a sprite, without mapping bits and colourtables.
Definition gfx_type.h:17
uint32_t PaletteID
The number of the palette.
Definition gfx_type.h:18
@ AS_BRAKE
We want to stop.
@ GVF_SUPPRESS_IMPLICIT_ORDERS
Disable insertion and removal of automatic orders until the vehicle completes the real order.
TrackStatus GetTileTrackStatus(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
Returns information about trackdirs and signal states.
int GetSlopePixelZ(int x, int y, bool ground_vehicle)
Return world Z coordinate of a given point of a tile.
@ Random
Randomise borders.
TileIndex TileAddByDir(TileIndex tile, Direction dir)
Adds a Direction to a tile.
Definition map_func.h:598
static debug_inline uint TileY(TileIndex tile)
Get the Y component of a tile.
Definition map_func.h:424
static debug_inline uint TileX(TileIndex tile)
Get the X component of a tile.
Definition map_func.h:414
TileIndexDiff TileOffsByDiagDir(DiagDirection dir)
Convert a DiagDirection to a TileIndexDiff.
Definition map_func.h:569
constexpr bool IsInsideMM(const size_t x, const size_t min, const size_t max) noexcept
Checks if a value is in an interval.
constexpr T abs(const T a)
Returns the absolute value of (scalar) variable.
Definition math_func.hpp:23
constexpr T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Definition math_func.hpp:79
Base for the NewGRF implementation.
@ CBID_VEHICLE_LENGTH
Vehicle length, returns the amount of 1/8's the vehicle is shorter for trains and RVs.
static const uint CALLBACK_FAILED
Different values for Callback result evaluations.
void ErrorUnknownCallbackResult(uint32_t grfid, uint16_t cbid, uint16_t cb_res)
Record that a NewGRF returned an unknown/invalid callback result.
uint16_t GetVehicleCallback(CallbackID callback, uint32_t param1, uint32_t param2, EngineID engine, const Vehicle *v, std::span< int32_t > regs100)
Evaluate a newgrf callback for vehicles.
@ PROP_ROADVEH_CARGO_AGE_PERIOD
Number of ticks before carried cargo is aged.
@ PROP_ROADVEH_WEIGHT
Weight in 1/4 t.
@ PROP_ROADVEH_RUNNING_COST_FACTOR
Yearly runningcost.
@ PROP_ROADVEH_SHORTEN_FACTOR
Shorter vehicles.
@ PROP_ROADVEH_SPEED
Max. speed: 1 unit = 1/0.8 mph = 2 km-ish/h.
NewGRF definitions and structures for road stops.
bool PlayVehicleSound(const Vehicle *v, VehicleSoundEvent event, bool force)
Checks whether a NewGRF wants to play a different vehicle sound effect.
Functions related to NewGRF provided sounds.
@ VSE_START
Vehicle starting, i.e. leaving, the station.
Functions related to news.
void AddVehicleNewsItem(EncodedString &&headline, NewsType type, VehicleID vehicle, StationID station=StationID::Invalid())
Adds a newsitem referencing a vehicle.
Definition news_func.h:30
NewsType
Type of news.
Definition news_type.h:28
@ ArrivalCompany
First vehicle arrived for company.
@ AccidentOther
An accident or disaster has occurred.
@ ArrivalOther
First vehicle arrived for competitor.
@ Accident
An accident or disaster has occurred.
bool ProcessOrders(Vehicle *v)
Handle the orders of a vehicle and determine the next place to go to if needed.
void CheckOrders(const Vehicle *v)
Check the orders of a vehicle, to see if there are invalid orders and stuff.
@ ODTFB_SERVICE
This depot order is because of the servicing limit.
Definition order_type.h:110
@ ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS
The vehicle will not stop at any stations it passes except the destination.
Definition order_type.h:89
Pseudo random number generator.
uint32_t RandomRange(uint32_t limit, const std::source_location location=std::source_location::current())
Pick a random number between 0 and limit - 1, inclusive.
bool Chance16(const uint32_t a, const uint32_t b, const std::source_location location=std::source_location::current())
Flips a coin with given probability.
const RoadTypeInfo * GetRoadTypeInfo(RoadType roadtype)
Returns a pointer to the Roadtype information for a given roadtype.
Definition road.h:230
Road related functions.
RoadBits AxisToRoadBits(Axis a)
Create the road-part which belongs to the given Axis.
Definition road_func.h:111
RoadBits DiagDirToRoadBits(DiagDirection d)
Create the road-part which belongs to the given DiagDirection.
Definition road_func.h:96
RoadBits GetAnyRoadBits(Tile tile, RoadTramType rtt, bool straight_tunnel_bridge_entrance)
Returns the RoadBits on an arbitrary tile Special behaviour:
Definition road_map.cpp:54
static debug_inline bool IsNormalRoadTile(Tile t)
Return whether a tile is a normal road tile.
Definition road_map.h:58
static debug_inline bool IsRoadDepot(Tile t)
Return whether a tile is a road depot.
Definition road_map.h:90
bool IsLevelCrossingTile(Tile t)
Return whether a tile is a level crossing tile.
Definition road_map.h:79
RoadBits GetRoadBits(Tile t, RoadTramType rtt)
Get the present road bits for a specific road type.
Definition road_map.h:112
bool HasTileAnyRoadType(Tile t, RoadTypes rts)
Check if a tile has one of the specified road types.
Definition road_map.h:206
DisallowedRoadDirections GetDisallowedRoadDirections(Tile t)
Gets the disallowed directions.
Definition road_map.h:285
DiagDirection GetRoadDepotDirection(Tile t)
Get the direction of the exit of a road depot.
Definition road_map.h:545
static debug_inline bool IsRoadDepotTile(Tile t)
Return whether a tile is a road depot tile.
Definition road_map.h:100
bool HasRoadWorks(Tile t)
Check if a tile has road works.
Definition road_map.h:493
RoadBits
Enumeration for the road parts on a tile.
Definition road_type.h:40
@ ROAD_SW
South-west part.
Definition road_type.h:43
@ ROAD_NONE
No road-part is build.
Definition road_type.h:41
@ ROAD_NE
North-east part.
Definition road_type.h:45
@ ROAD_SE
South-east part.
Definition road_type.h:44
@ ROAD_Y
Full road along the y-axis (north-west + south-east)
Definition road_type.h:47
@ ROAD_NW
North-west part.
Definition road_type.h:42
@ ROAD_X
Full road along the x-axis (south-west + north-east)
Definition road_type.h:46
RoadType
The different roadtypes we support.
Definition road_type.h:23
@ DRD_NONE
None of the directions are disallowed.
Definition road_type.h:62
Base class for roadstops.
Road vehicle states.
@ RVSB_IN_DT_ROAD_STOP
The vehicle is in a drive-through road stop.
Definition roadveh.h:51
@ RVS_ENTERED_STOP
Only set when a vehicle has entered the stop.
Definition roadveh.h:43
@ RVSB_IN_ROAD_STOP
The vehicle is in a road stop.
Definition roadveh.h:49
@ RVSB_ROAD_STOP_TRACKDIR_MASK
Only bits 0 and 3 are used to encode the trackdir for road stops.
Definition roadveh.h:57
@ RVS_IN_DT_ROAD_STOP
The vehicle is in a drive-through road stop.
Definition roadveh.h:46
@ RVSB_TRACKDIR_MASK
The mask used to extract track dirs.
Definition roadveh.h:56
@ RVSB_DRIVE_SIDE
The vehicle is at the opposite side of the road.
Definition roadveh.h:54
@ RVSB_IN_DEPOT
The vehicle is in a depot.
Definition roadveh.h:38
@ RVSB_WORMHOLE
The vehicle is in a tunnel and/or bridge.
Definition roadveh.h:39
@ RVS_DRIVE_SIDE
Only used when retrieving move data.
Definition roadveh.h:44
static const uint RDE_TURNED
We just finished turning.
Definition roadveh.h:62
static const uint8_t RV_OVERTAKE_TIMEOUT
The number of ticks a vehicle has for overtaking.
Definition roadveh.h:79
static const uint RDE_NEXT_TILE
State information about the Road Vehicle controller.
Definition roadveh.h:61
static bool RoadVehIsCrashed(RoadVehicle *v)
Road vehicle chain has crashed.
static uint GetRoadVehLength(const RoadVehicle *v)
Get length of a road vehicle.
static void RoadVehArrivesAt(const RoadVehicle *v, Station *st)
A road vehicle arrives at a station.
static bool CheckRoadBlockedForOvertaking(OvertakeData *od)
Check if overtaking is possible on a piece of track.
void RoadVehUpdateCache(RoadVehicle *v, bool same_length)
Update the cache of a road vehicle.
static bool CanBuildTramTrackOnTile(CompanyID c, TileIndex t, RoadType rt, RoadBits r)
Can a tram track build without destruction on the given tile?
void GetRoadVehSpriteSize(EngineID engine, uint &width, uint &height, int &xoffs, int &yoffs, EngineImageType image_type)
Get the size of the sprite of a road vehicle sprite heading west (used for lists).
CommandCost CmdBuildRoadVehicle(DoCommandFlags flags, TileIndex tile, const Engine *e, Vehicle **ret)
Build a road vehicle.
CommandCost CmdTurnRoadVeh(DoCommandFlags flags, VehicleID veh_id)
Turn a roadvehicle around.
void DrawRoadVehEngine(int left, int right, int preferred_x, int y, EngineID engine, PaletteID pal, EngineImageType image_type)
Draw a road vehicle engine.
static Trackdir RoadFindPathToDest(RoadVehicle *v, TileIndex tile, DiagDirection enterdir)
Returns direction to for a road vehicle to take or INVALID_TRACKDIR if the direction is currently blo...
static void DeleteLastRoadVeh(RoadVehicle *v)
Delete last vehicle of a chain road vehicles.
Command definitions related to road vehicles.
Data about how a road vehicle must drive on a tile.
const uint8_t _road_stop_stop_frame[]
Table of road stop stop frames, when to stop at a road stop.
A number of safeguards to prevent using unsafe methods.
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition settings.cpp:61
ClientSettings _settings_client
The current settings for this game.
Definition settings.cpp:60
Functions related to sound.
@ SND_19_DEPARTURE_OLD_RV_1
23 == 0x17 Station departure: truck and old bus (1) (non-toyland)
Definition sound_type.h:70
@ SND_12_EXPLOSION
16 == 0x10 Destruction, crashes, disasters, ...
Definition sound_type.h:63
@ SND_1A_DEPARTURE_OLD_RV_2
24 == 0x18 Station departure: truck and old bus (2) (random variation of SND_19_DEPARTURE_OLD_RV_1) (...
Definition sound_type.h:71
Functions to cache sprites in memory.
static const PaletteID PALETTE_CRASH
Recolour sprite greying of crashed vehicles.
Definition sprites.h:1611
Base classes/functions for stations.
bool IsBayRoadStopTile(Tile t)
Is tile t a bay (non-drive through) road stop station?
bool IsDriveThroughStopTile(Tile t)
Is tile t a drive through road stop station or waypoint?
StationID GetStationIndex(Tile t)
Get StationID from a tile.
Definition station_map.h:28
bool IsStationRoadStop(Tile t)
Is the station at t a road station?
DiagDirection GetBayRoadStopDir(Tile t)
Gets the direction the bay road stop entrance points towards.
RoadStopType GetRoadStopType(Tile t)
Get the road stop type of this tile.
Definition station_map.h:56
RoadStopType
Types of RoadStops.
@ Bus
A standard stop for buses.
@ Truck
A standard stop for trucks.
@ HVOT_TRUCK
Station has seen a truck.
@ HVOT_BUS
Station has seen a bus.
@ VehicleArrives
Trigger platform when train arrives.
@ VehicleArrives
Trigger platform when train arrives.
Definition of base types and functions in a cross-platform compatible way.
#define lengthof(array)
Return the length of an fixed size array.
Definition stdafx.h:271
EncodedString GetEncodedString(StringID str)
Encode a string with no parameters into an encoded string.
Definition strings.cpp:91
Functions related to OTTD's strings.
Class to backup a specific variable and restore it later.
void Restore()
Restore the variable.
TimerGameTick::Ticks current_order_time
How many ticks have passed since this order started.
VehicleFlags vehicle_flags
Used for gradual loading and other miscellaneous things (.
void ResetDepotUnbunching()
Resets all the data used for depot unbunching.
TileIndex xy
Base tile of the station.
static BaseStation * GetByTile(TileIndex tile)
Get the base station belonging to a specific tile.
VehicleType type
Type of vehicle.
uint16_t speed
maximum travel speed (1 unit = 1/1.6 mph = 1 km-ish/h)
Definition bridge.h:48
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo type.
Definition cargotype.h:137
SoundSettings sound
sound effect settings
Structure to return information about the closest depot location, and whether it could be found.
uint16_t cargo_age_period
Number of ticks before carried cargo is aged.
uint32_t GetGRFID() const
Retrieve the GRF ID of the NewGRF the engine is tied to.
Definition engine.cpp:157
uint16_t reliability_spd_dec
Speed of reliability decay between services (per day).
Definition engine_base.h:49
const GRFFile * GetGRF() const
Retrieve the NewGRF the engine is tied to.
EngineFlags flags
Flags of the engine.
Definition engine_base.h:56
uint8_t original_image_index
Original vehicle image index, thus the image index of the overridden vehicle.
Definition engine_base.h:60
TimerGameCalendar::Date GetLifeLengthInDays() const
Returns the vehicle's (not model's!) life length in days.
Definition engine.cpp:443
CargoType GetDefaultCargoType() const
Determines the default cargo type of an engine.
Definition engine_base.h:96
uint16_t reliability
Current reliability of the engine.
Definition engine_base.h:48
Helper container to find a depot.
uint best_length
The distance towards the depot in penalty, or UINT_MAX if not found.
TileIndex tile
The tile of the depot.
PathfinderSettings pf
settings for all pathfinders
VehicleSettings vehicle
options for vehicles
Position information of a vehicle after it moved.
TileIndex new_tile
Tile of the vehicle after moving.
int y
x and y position of the vehicle after moving
EngineID first_engine
Cached EngineID of the front vehicle. EngineID::Invalid() for the front vehicle itself.
uint16_t cached_total_length
Length of the whole vehicle (valid only for the first engine).
uint8_t cached_veh_length
Length of this vehicle in units of 1/VEHICLE_LENGTH of normal length. It is cached because this can b...
uint16_t cached_max_track_speed
Maximum consist speed (in internal units) limited by track type (valid only for the first engine).
bool IsChainInDepot() const override
Check whether the whole vehicle chain is in the depot.
int UpdateInclination(bool new_tile, bool update_delta)
Checks if the vehicle is in a slope and sets the required flags in that case.
GroundVehicleCache gcache
Cache of often calculated values.
void CargoChanged()
Recalculates the cached weight of a vehicle and its parts.
void SetFrontEngine()
Set front engine state.
uint Crash(bool flooded) override
Common code executed for crashed ground vehicles.
uint DoUpdateSpeed(uint accel, int min_speed, int max_speed)
Update the speed of the vehicle.
int GetAcceleration() const
Calculates the acceleration of the vehicle under its current conditions.
void SetLastSpeed()
Update the GUI variant of the current speed of the vehicle.
VehicleSpriteSeq sprite_seq
Vehicle appearance.
uint16_t GetMaxSpeed() const
Get the maxmimum speed in km-ish/h a vehicle is allowed to reach on the way to the destination.
Definition order_base.h:197
DestinationID GetDestination() const
Gets the destination of this order.
Definition order_base.h:99
bool IsType(OrderType type) const
Check whether this order is of the given type.
Definition order_base.h:66
void MakeDummy()
Makes this order a Dummy order.
void Free()
'Free' the order
Definition order_cmd.cpp:48
bool ShouldStopAtStation(const Vehicle *v, StationID station) const
Check whether the given vehicle should stop at the given station based on this order and the non-stop...
OrderNonStopFlags GetNonStopType() const
At which stations must we stop?
Definition order_base.h:136
void MakeGoToDepot(DestinationID destination, OrderDepotTypeFlags order, OrderNonStopFlags non_stop_type=ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS, OrderDepotActionFlags action=ODATF_SERVICE_ONLY, CargoType cargo=CARGO_NO_REFIT)
Makes this order a Go To Depot order.
Definition order_cmd.cpp:74
YAPFSettings yapf
pathfinder settings for the yet another pathfinder
bool roadveh_queue
buggy road vehicle queueing
Coordinates of a point in 2D.
static Titem * Get(auto index)
Returns Titem with given index.
Tindex index
Index of this pool item.
Specification of a rectangle with absolute coordinates of all edges.
int Width() const
Get width of Rect.
int Height() const
Get height of Rect.
A Stop for a Road Vehicle.
void SetEntranceBusy(bool busy)
Makes an entrance occupied or free.
void Leave(RoadVehicle *rv)
Leave the road stop.
Definition roadstop.cpp:205
bool IsEntranceBusy() const
Checks whether the entrance of the road stop is occupied by a vehicle.
static bool IsDriveThroughRoadStopContinuation(TileIndex rs, TileIndex next)
Checks whether the 'next' tile is still part of the road same drive through stop 'rs' in the same dir...
Definition roadstop.cpp:294
static RoadStop * GetByTile(TileIndex tile, RoadStopType type)
Find a roadstop at given tile.
Definition roadstop.cpp:255
Information about a road vehicle.
uint16_t max_speed
Maximum speed (1 unit = 1/3.2 mph = 0.5 km-ish/h)
RoadType roadtype
Road type.
uint8_t shorten_factor
length on main map for this type is 8 - shorten_factor
Buses, trucks and trams belong to this class.
Definition roadveh.h:98
uint Crash(bool flooded=false) override
Common code executed for crashed ground vehicles.
TileIndex GetOrderStationLocation(StationID station) override
Determine the location for the station where the vehicle goes to next.
void OnNewEconomyDay() override
Economy day handler.
uint8_t state
Definition roadveh.h:100
int GetDisplayImageWidth(Point *offset=nullptr) const
Get the width of a road vehicle image in the GUI.
Money GetRunningCost() const override
Gets the running cost of a vehicle.
bool IsPrimaryVehicle() const override
Whether this is the primary vehicle in the chain.
Definition roadveh.h:122
uint16_t GetMaxWeight() const override
Calculates the weight value that this vehicle will have when fully loaded with its current cargo.
RoadTypes compatible_roadtypes
NOSAVE: Roadtypes this consist is powered on.
Definition roadveh.h:110
AccelStatus GetAccelerationStatus() const
Checks the current acceleration status of this vehicle.
Definition roadveh.h:223
void UpdateDeltaXY() override
Updates the x and y offsets and the size of the sprite used for this vehicle.
uint16_t crashed_ctr
Animation counter when the vehicle has crashed.
Definition roadveh.h:105
bool IsBus() const
Check whether a roadvehicle is a bus.
uint8_t overtaking_ctr
The length of the current overtake attempt.
Definition roadveh.h:104
void OnNewCalendarDay() override
Calandar day handler.
bool IsInDepot() const override
Check whether the vehicle is in the depot.
Definition roadveh.h:128
void GetImage(Direction direction, EngineImageType image_type, VehicleSpriteSeq *result) const override
Gets the sprite to show for the given direction.
RoadVehPathCache path
Cached path.
Definition roadveh.h:99
Trackdir GetVehicleTrackdir() const override
Returns the Trackdir on which the vehicle is currently located.
int GetCurrentMaxSpeed() const override
Calculates the maximum speed of the vehicle under its current conditions.
RoadType roadtype
NOSAVE: Roadtype of this vehicle.
Definition roadveh.h:108
uint8_t overtaking
Set to RVSB_DRIVE_SIDE when overtaking, otherwise 0.
Definition roadveh.h:103
int UpdateSpeed()
This function looks at the vehicle and updates its speed (cur_speed and subspeed) variables.
bool Tick() override
Calls the tick handler of the vehicle.
ClosestDepot FindClosestDepot() override
Find the closest depot for this vehicle and tell us the location, DestinationID and whether we should...
void MarkDirty() override
Marks the vehicles to be redrawn and updates cached variables.
bool disaster
Play disaster and accident sounds.
static Station * Get(auto index)
Gets station with given index.
T * Next() const
Get next vehicle in the chain.
T * Previous() const
Get previous vehicle in the chain.
static T * From(Vehicle *v)
Converts a Vehicle to SpecializedVehicle with type checking.
static T * GetIfValid(auto index)
Returns vehicle if the index is a valid index for this vehicle type.
T * First() const
Get the first vehicle in the chain.
void UpdateViewport(bool force_update, bool update_delta)
Update vehicle sprite- and position caches.
Station data structure.
uint16_t cached_max_speed
Maximum speed of the consist (minimum of the max speed of all vehicles in the consist).
uint8_t roadveh_acceleration_model
realistic acceleration for road vehicles
uint8_t road_side
the side of the road vehicles drive on
Sprite sequence for a vehicle part.
bool IsValid() const
Check whether the sequence contains any sprites.
void GetBounds(Rect *bounds) const
Determine shared bounds of all sprites.
Definition vehicle.cpp:114
void Set(SpriteID sprite)
Assign a single sprite to the sequence.
void Draw(int x, int y, PaletteID default_pal, bool force_pal) const
Draw the sprite sequence.
Definition vehicle.cpp:142
Vehicle data structure.
EngineID engine_type
The type of engine used for this vehicle.
int32_t z_pos
z coordinate.
Direction direction
facing
const Engine * GetEngine() const
Retrieves the engine of the vehicle.
Definition vehicle.cpp:718
void IncrementRealOrderIndex()
Advanced cur_real_order_index to the next real order, keeps care of the wrap-around and invalidates t...
VehicleCargoList cargo
The cargo this vehicle is carrying.
uint8_t x_extent
x-extent of vehicle bounding box
TimerGameEconomy::Date date_of_last_service
Last economy date the vehicle had a service at a depot.
uint16_t cargo_cap
total capacity
StationID last_loading_station
Last station the vehicle has stopped at and could possibly leave from with any cargo loaded.
uint16_t random_bits
Bits used for randomized variational spritegroups.
uint8_t day_counter
Increased by one for each day.
void HandleLoading(bool mode=false)
Handle the loading of the vehicle; when not it skips through dummy orders and does nothing in all oth...
Definition vehicle.cpp:2396
Money profit_this_year
Profit this year << 8, low 8 bits are fract.
bool HasArticulatedPart() const
Check if an engine has an articulated part.
SpriteID colourmap
NOSAVE: cached colour mapping.
uint8_t breakdown_ctr
Counter for managing breakdown events.
uint GetAdvanceDistance()
Determines the vehicle "progress" needed for moving a step.
uint8_t z_extent
z-extent of vehicle bounding box
VehStates vehstatus
Status.
TimerGameCalendar::Date date_of_last_service_newgrf
Last calendar date the vehicle had a service at a depot, unchanged by the date cheat to protect again...
bool IsArticulatedPart() const
Check if the vehicle is an articulated part of an engine.
void LeaveUnbunchingDepot()
Leave an unbunching depot and calculate the next departure time for shared order vehicles.
Definition vehicle.cpp:2475
int8_t y_offs
y offset for vehicle sprite
CargoType cargo_type
type of cargo this vehicle is carrying
debug_inline bool IsFrontEngine() const
Check if the vehicle is a front engine.
Vehicle * First() const
Get the first vehicle of this vehicle chain.
int8_t x_bb_offs
x offset of vehicle bounding box
Order current_order
The current order (+ status, like: loading)
void HandlePathfindingResult(bool path_found)
Handle the pathfinding result, especially the lost status.
Definition vehicle.cpp:762
int8_t x_offs
x offset for vehicle sprite
int32_t y_pos
y coordinate.
int32_t x_pos
x coordinate.
uint8_t y_extent
y-extent of vehicle bounding box
uint16_t refit_cap
Capacity left over from before last refit.
void InvalidateNewGRFCache()
Invalidates cached NewGRF variables.
VehicleCache vcache
Cache of often used vehicle values.
int8_t y_bb_offs
y offset of vehicle bounding box
void BeginLoading()
Prepare everything to begin the loading when arriving at a station.
Definition vehicle.cpp:2172
uint8_t spritenum
currently displayed sprite index 0xfd == custom sprite, 0xfe == custom second head sprite 0xff == res...
uint16_t cur_speed
current speed
bool IsWaitingForUnbunching() const
Check whether a vehicle inside a depot is waiting for unbunching.
Definition vehicle.cpp:2522
void SetNext(Vehicle *next)
Set the next vehicle of this vehicle.
Definition vehicle.cpp:2900
TimerGameCalendar::Date max_age
Maximum age.
MutableSpriteCache sprite_cache
Cache of sprites and values related to recalculating them, see MutableSpriteCache.
uint16_t reliability
Reliability.
bool HandleBreakdown()
Handle all of the aspects of a vehicle breakdown This includes adding smoke and sounds,...
Definition vehicle.cpp:1333
uint8_t progress
The percentage (if divided by 256) this vehicle already crossed the tile unit.
uint16_t reliability_spd_dec
Reliability decrease speed.
uint8_t tick_counter
Increased by one for each tick.
virtual bool IsInDepot() const
Check whether the vehicle is in the depot.
TileIndex tile
Current tile index.
TileIndex dest_tile
Heading for this tile.
void UpdatePosition()
Update the position of the vehicle.
Definition vehicle.cpp:1663
StationID last_station_visited
The last station we stopped at.
void InvalidateNewGRFCacheOfChain()
Invalidates cached NewGRF variables of all vehicles in the chain (after the current vehicle)
void ShowVisualEffect() const
Draw visual effects (smoke and/or sparks) for a vehicle chain.
Definition vehicle.cpp:2750
TimerGameCalendar::Year build_year
Year the vehicle has been built.
Owner owner
Which company owns the vehicle?
bool NeedsAutomaticServicing() const
Checks if the current order should be interrupted for a service-in-depot order.
Definition vehicle.cpp:283
uint8_t running_ticks
Number of ticks this vehicle was not stopped this day.
uint32_t maximum_go_to_depot_penalty
What is the maximum penalty that may be endured for going to a depot.
@ CannotEnter
The vehicle cannot enter the tile.
@ EnteredWormhole
The vehicle either entered a bridge, tunnel or depot tile (this includes the last tile of the bridge/...
VehicleEnterTileStates VehicleEnterTile(Vehicle *v, TileIndex tile, int x, int y)
Call the tile callback function for a vehicle entering a tile.
Definition vehicle.cpp:1808
bool IsTileOwner(Tile tile, Owner owner)
Checks if a tile belongs to the given owner.
Definition tile_map.h:214
Owner GetTileOwner(Tile tile)
Returns the owner of a tile.
Definition tile_map.h:178
static debug_inline bool IsTileType(Tile tile, TileType type)
Checks if a tile is a given tiletype.
Definition tile_map.h:150
static const uint TILE_SIZE
Tile size in world coordinates.
Definition tile_type.h:15
@ MP_ROAD
A tile with road (or tram tracks)
Definition tile_type.h:50
@ MP_STATION
A tile of a station.
Definition tile_type.h:53
@ MP_TUNNELBRIDGE
Tunnel entry/exit and bridge heads.
Definition tile_type.h:57
Definition of the game-calendar-timer.
Definition of the game-economy-timer.
TrackdirBits TrackStatusToTrackdirBits(TrackStatus ts)
Returns the present-trackdir-information of a TrackStatus.
Definition track_func.h:352
bool IsReversingRoadTrackdir(Trackdir dir)
Checks whether the trackdir means that we are reversing.
Definition track_func.h:673
TrackdirBits DiagdirReachesTrackdirs(DiagDirection diagdir)
Returns all trackdirs that can be reached when entering a tile from a given (diagonal) direction.
Definition track_func.h:555
bool IsStraightRoadTrackdir(Trackdir dir)
Checks whether the given trackdir is a straight road.
Definition track_func.h:684
Trackdir DiagDirToDiagTrackdir(DiagDirection diagdir)
Maps a (4-way) direction to the diagonal trackdir that runs in that direction.
Definition track_func.h:537
TrackdirBits TrackStatusToRedSignals(TrackStatus ts)
Returns the red-signal-information of a TrackStatus.
Definition track_func.h:376
TrackBits TrackdirBitsToTrackBits(TrackdirBits bits)
Discards all directional information from a TrackdirBits value.
Definition track_func.h:308
TrackBits
Allow incrementing of Track variables.
Definition track_type.h:35
@ TRACK_BIT_CROSS
X-Y-axis cross.
Definition track_type.h:43
Trackdir
Enumeration for tracks and directions.
Definition track_type.h:66
@ TRACKDIR_RVREV_NE
(Road vehicle) reverse direction north-east
Definition track_type.h:74
@ TRACKDIR_LOWER_E
Lower track and direction to east.
Definition track_type.h:71
@ TRACKDIR_RIGHT_N
Right track and direction to north.
Definition track_type.h:81
@ INVALID_TRACKDIR
Flag for an invalid trackdir.
Definition track_type.h:85
@ TRACKDIR_UPPER_E
Upper track and direction to east.
Definition track_type.h:70
@ TRACKDIR_LEFT_S
Left track and direction to south.
Definition track_type.h:72
@ TRACKDIR_UPPER_W
Upper track and direction to west.
Definition track_type.h:78
@ TRACKDIR_RVREV_SE
(Road vehicle) reverse direction south-east
Definition track_type.h:75
@ TRACKDIR_LOWER_W
Lower track and direction to west.
Definition track_type.h:79
@ TRACKDIR_END
Used for iterations.
Definition track_type.h:84
@ TRACKDIR_RIGHT_S
Right track and direction to south.
Definition track_type.h:73
@ TRACKDIR_RVREV_NW
(Road vehicle) reverse direction north-west
Definition track_type.h:83
@ TRACKDIR_RVREV_SW
(Road vehicle) reverse direction south-west
Definition track_type.h:82
@ TRACKDIR_LEFT_N
Left track and direction to north.
Definition track_type.h:80
TrackdirBits
Allow incrementing of Trackdir variables.
Definition track_type.h:97
@ TRACKDIR_BIT_NONE
No track build.
Definition track_type.h:98
@ TRANSPORT_ROAD
Transport by road vehicle.
Functions that have tunnels and bridges in common.
DiagDirection GetTunnelBridgeDirection(Tile t)
Get the direction pointing to the other end.
TileIndex GetOtherTunnelBridgeEnd(Tile t)
Determines type of the wormhole and returns its other end.
void VehicleEnterDepot(Vehicle *v)
Vehicle entirely entered the depot, update its status, orders, vehicle windows, service it,...
Definition vehicle.cpp:1521
void VehicleLengthChanged(const Vehicle *u)
Logs a bug in GRF and shows a warning message if this is for the first time this happened.
Definition vehicle.cpp:354
void VehicleServiceInDepot(Vehicle *v)
Service a vehicle and all subsequent vehicles in the consist.
Definition vehicle.cpp:178
GetNewVehiclePosResult GetNewVehiclePos(const Vehicle *v)
Get position information of a vehicle when moving one pixel in the direction it is facing.
Definition vehicle.cpp:1754
void DecreaseVehicleValue(Vehicle *v)
Decrease the value of a vehicle.
Definition vehicle.cpp:1271
void EconomyAgeVehicle(Vehicle *v)
Update economy age of a vehicle.
Definition vehicle.cpp:1399
bool CanVehicleUseStation(EngineID engine_type, const Station *st)
Can this station be used by the given engine type?
Definition vehicle.cpp:3019
void AgeVehicle(Vehicle *v)
Update age of a vehicle.
Definition vehicle.cpp:1411
@ Crashed
Vehicle is crashed.
@ Hidden
Vehicle is not visible.
@ DefaultPalette
Use default vehicle palette.
@ Stopped
Vehicle is stopped by the player.
Functions related to vehicles.
bool HasVehicleNearTileXY(int32_t x, int32_t y, uint max_dist, UnaryPred &&predicate)
Loop over vehicles near a given world coordinate, and check whether a predicate is true for any of th...
@ CUSTOM_VEHICLE_SPRITENUM_REVERSED
Vehicle sprite from NewGRF with reverse driving direction (from articulation callback)
bool HasVehicleOnTile(TileIndex tile, UnaryPred &&predicate)
Loop over vehicles on a tile, and check whether a predicate is true for any of them.
EngineImageType
Visualisation contexts of vehicles and engines.
@ VEH_ROAD
Road vehicle type.
static const uint VEHICLE_LENGTH
The length of a vehicle in tile units.
@ WID_VV_START_STOP
Start or stop this vehicle, and show information about the current state.
void SetWindowClassesDirty(WindowClass cls)
Mark all windows of a particular class as dirty (in need of repainting)
Definition window.cpp:3173
void InvalidateWindowData(WindowClass cls, WindowNumber number, int data, bool gui_scope)
Mark window data of the window of a given class and specific window number as invalid (in need of re-...
Definition window.cpp:3265
void SetWindowWidgetDirty(WindowClass cls, WindowNumber number, WidgetID widget_index)
Mark a particular widget in a particular window as dirty (in need of repainting)
Definition window.cpp:3160
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
Definition window.cpp:3147
@ WC_ROADVEH_LIST
Road vehicle list; Window numbers:
@ WC_VEHICLE_DEPOT
Depot view; Window numbers:
@ WC_VEHICLE_DETAILS
Vehicle details; Window numbers:
@ WC_VEHICLE_VIEW
Vehicle view; Window numbers:
Entry point for OpenTTD to YAPF.
Trackdir YapfRoadVehicleChooseTrack(const RoadVehicle *v, TileIndex tile, DiagDirection enterdir, TrackdirBits trackdirs, bool &path_found, RoadVehPathCache &path_cache)
Finds the best path for given road vehicle using YAPF.
FindDepotData YapfRoadVehicleFindNearestDepot(const RoadVehicle *v, int max_penalty)
Used when user sends road vehicle to the nearest depot or if road vehicle needs servicing using YAPF.
Functions related to zooming.
int ScaleSpriteTrad(int value)
Scale traditional pixel dimensions to GUI zoom level, for drawing sprites.
Definition zoom_func.h:107
int UnScaleGUI(int value)
Short-hand to apply GUI zoom level.
Definition zoom_func.h:77