OpenTTD Source 20261112-master-gbcbec5e63f
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 <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
9
10#include "stdafx.h"
11#include "bridge.h"
12#include "roadveh.h"
13#include "command_func.h"
14#include "error_func.h"
15#include "news_func.h"
16#include "station_base.h"
17#include "station_func.h"
18#include "company_func.h"
20#include "newgrf_sound.h"
22#include "strings_func.h"
23#include "tunnelbridge_map.h"
24#include "script/api/script_event_types.hpp"
27#include "vehicle_func.h"
28#include "sound_func.h"
29#include "ai/ai.hpp"
30#include "game/game.hpp"
31#include "depot_map.h"
32#include "effectvehicle_func.h"
33#include "roadstop_base.h"
34#include "core/random_func.hpp"
35#include "company_base.h"
36#include "core/backup_type.hpp"
37#include "newgrf.h"
38#include "zoom_func.h"
39#include "framerate_type.h"
40#include "roadveh_cmd.h"
41#include "road_cmd.h"
42#include "newgrf_roadstop.h"
43
44#include "table/strings.h"
45
46#include "safeguards.h"
47
48static const uint16_t _roadveh_images[] = {
49 0xCD4, 0xCDC, 0xCE4, 0xCEC, 0xCF4, 0xCFC, 0xD0C, 0xD14,
50 0xD24, 0xD1C, 0xD2C, 0xD04, 0xD1C, 0xD24, 0xD6C, 0xD74,
51 0xD7C, 0xC14, 0xC1C, 0xC24, 0xC2C, 0xC34, 0xC3C, 0xC4C,
52 0xC54, 0xC64, 0xC5C, 0xC6C, 0xC44, 0xC5C, 0xC64, 0xCAC,
53 0xCB4, 0xCBC, 0xD94, 0xD9C, 0xDA4, 0xDAC, 0xDB4, 0xDBC,
54 0xDCC, 0xDD4, 0xDE4, 0xDDC, 0xDEC, 0xDC4, 0xDDC, 0xDE4,
55 0xE2C, 0xE34, 0xE3C, 0xC14, 0xC1C, 0xC2C, 0xC3C, 0xC4C,
56 0xC5C, 0xC64, 0xC6C, 0xC74, 0xC84, 0xC94, 0xCA4
57};
58
59static const uint16_t _roadveh_full_adder[] = {
60 0, 88, 0, 0, 0, 0, 48, 48,
61 48, 48, 0, 0, 64, 64, 0, 16,
62 16, 0, 88, 0, 0, 0, 0, 48,
63 48, 48, 48, 0, 0, 64, 64, 0,
64 16, 16, 0, 88, 0, 0, 0, 0,
65 48, 48, 48, 48, 0, 0, 64, 64,
66 0, 16, 16, 0, 8, 8, 8, 8,
67 0, 0, 0, 8, 8, 8, 8
68};
69static_assert(lengthof(_roadveh_images) == lengthof(_roadveh_full_adder));
70
72template <>
73bool IsValidImageIndex<VehicleType::Road>(uint8_t image_index)
74{
75 return image_index < lengthof(_roadveh_images);
76}
77
82
88{
89 assert(this->IsFrontEngine());
91}
92
99{
100 int reference_width = ROADVEHINFO_DEFAULT_VEHICLE_WIDTH;
101
102 if (offset != nullptr) {
103 offset->x = ScaleSpriteTrad(reference_width) / 2;
104 offset->y = 0;
105 }
106 return ScaleSpriteTrad(this->gcache.cached_veh_length * reference_width / VEHICLE_LENGTH);
107}
108
109static void GetRoadVehIcon(EngineID engine, EngineImageType image_type, VehicleSpriteSeq *result)
110{
111 const Engine *e = Engine::Get(engine);
112 uint8_t spritenum = e->VehInfo<RoadVehicleInfo>().image_index;
113
114 if (IsCustomVehicleSpriteNum(spritenum)) {
115 GetCustomVehicleIcon(engine, Direction::W, image_type, result);
116 if (result->IsValid()) return;
117
118 spritenum = e->original_image_index;
119 }
120
121 assert(IsValidImageIndex<VehicleType::Road>(spritenum));
122 result->Set(to_underlying(Direction::W) + _roadveh_images[spritenum]);
123}
124
126{
127 uint8_t spritenum = this->spritenum;
128
129 if (IsCustomVehicleSpriteNum(spritenum)) {
131 GetCustomVehicleSprite(this, direction, image_type, result);
132 if (result->IsValid()) return;
133
135 }
136
138 SpriteID sprite = to_underlying(direction) + _roadveh_images[spritenum];
139
140 if (this->cargo.StoredCount() >= this->cargo_cap / 2U) sprite += _roadveh_full_adder[spritenum];
141
142 result->Set(sprite);
143}
144
155void DrawRoadVehEngine(int left, int right, int preferred_x, int y, EngineID engine, PaletteID pal, EngineImageType image_type)
156{
158 GetRoadVehIcon(engine, image_type, &seq);
159
160 Rect rect;
161 seq.GetBounds(&rect);
162 preferred_x = Clamp(preferred_x,
163 left - UnScaleGUI(rect.left),
164 right - UnScaleGUI(rect.right));
165
166 seq.Draw(preferred_x, y, pal, pal == PALETTE_CRASH);
167}
168
178void GetRoadVehSpriteSize(EngineID engine, uint &width, uint &height, int &xoffs, int &yoffs, EngineImageType image_type)
179{
181 GetRoadVehIcon(engine, image_type, &seq);
182
183 Rect rect;
184 seq.GetBounds(&rect);
185
186 width = UnScaleGUI(rect.Width());
187 height = UnScaleGUI(rect.Height());
188 xoffs = UnScaleGUI(rect.left);
189 yoffs = UnScaleGUI(rect.top);
190}
191
197static uint GetRoadVehLength(const RoadVehicle *v)
198{
199 const Engine *e = v->GetEngine();
200 uint length = VEHICLE_LENGTH;
201
202 uint16_t veh_len = CALLBACK_FAILED;
203 if (e->GetGRF() != nullptr && e->GetGRF()->grf_version >= 8) {
204 /* Use callback 36 */
205 veh_len = GetVehicleProperty(v, PROP_ROADVEH_SHORTEN_FACTOR, CALLBACK_FAILED);
206 if (veh_len != CALLBACK_FAILED && veh_len >= VEHICLE_LENGTH) ErrorUnknownCallbackResult(e->GetGRFID(), CBID_VEHICLE_LENGTH, veh_len);
207 } else {
208 /* Use callback 11 */
209 veh_len = GetVehicleCallback(CBID_VEHICLE_LENGTH, 0, 0, v->engine_type, v);
210 }
211 if (veh_len == CALLBACK_FAILED) veh_len = e->VehInfo<RoadVehicleInfo>().shorten_factor;
212 if (veh_len != 0) {
213 length -= Clamp(veh_len, 0, VEHICLE_LENGTH - 1);
214 }
215
216 return length;
217}
218
225void RoadVehUpdateCache(RoadVehicle *v, bool same_length)
226{
227 assert(v->type == VehicleType::Road);
228 assert(v->IsFrontEngine());
229
231
233
234 for (RoadVehicle *u = v; u != nullptr; u = u->Next()) {
235 /* Check the v->first cache. */
236 assert(u->First() == v);
237
238 /* Update the 'first engine' */
239 u->gcache.first_engine = (v == u) ? EngineID::Invalid() : v->engine_type;
240
241 /* Update the length of the vehicle. */
242 uint veh_len = GetRoadVehLength(u);
243 /* Verify length hasn't changed. */
244 if (same_length && veh_len != u->gcache.cached_veh_length) VehicleLengthChanged(u);
245
246 u->gcache.cached_veh_length = veh_len;
247 v->gcache.cached_total_length += u->gcache.cached_veh_length;
248
249 /* Update visual effect */
250 u->UpdateVisualEffect();
251
252 /* Update cargo aging period. */
253 u->vcache.cached_cargo_age_period = GetVehicleProperty(u, PROP_ROADVEH_CARGO_AGE_PERIOD, EngInfo(u->engine_type)->cargo_age_period);
254 }
255
256 uint max_speed = GetVehicleProperty(v, PROP_ROADVEH_SPEED, 0);
257 v->vcache.cached_max_speed = (max_speed != 0) ? max_speed * 4 : RoadVehInfo(v->engine_type)->max_speed;
258}
259
269{
270 /* Check that the vehicle can drive on the road in question */
271 RoadType rt = e->VehInfo<RoadVehicleInfo>().roadtype;
272 const RoadTypeInfo *rti = GetRoadTypeInfo(rt);
273 if (!HasTileAnyRoadType(tile, rti->powered_roadtypes)) return CommandCost(STR_ERROR_DEPOT_WRONG_DEPOT_TYPE);
274
275 if (flags.Test(DoCommandFlag::Execute)) {
276 const RoadVehicleInfo *rvi = &e->VehInfo<RoadVehicleInfo>();
277
279 *ret = v;
281 v->owner = _current_company;
282
283 v->tile = tile;
284 int x = TileX(tile) * TILE_SIZE + TILE_SIZE / 2;
285 int y = TileY(tile) * TILE_SIZE + TILE_SIZE / 2;
286 v->x_pos = x;
287 v->y_pos = y;
288 v->z_pos = GetSlopePixelZ(x, y, true);
289
290 v->state = RVSB_IN_DEPOT;
292
293 v->spritenum = rvi->image_index;
294 v->cargo_type = e->GetDefaultCargoType();
295 assert(IsValidCargoType(v->cargo_type));
296 v->cargo_cap = rvi->capacity;
297 v->refit_cap = 0;
298
299 v->last_station_visited = StationID::Invalid();
300 v->last_loading_station = StationID::Invalid();
301 v->engine_type = e->index;
302 v->gcache.first_engine = EngineID::Invalid(); // needs to be set before first callback
303
304 v->reliability = e->reliability;
305 v->reliability_spd_dec = e->reliability_spd_dec;
306 v->max_age = e->GetLifeLengthInDays();
307
308 v->SetServiceInterval(Company::Get(v->owner)->settings.vehicle.servint_roadveh);
309
310 v->date_of_last_service = TimerGameEconomy::date;
311 v->date_of_last_service_newgrf = TimerGameCalendar::date;
312 v->build_year = TimerGameCalendar::year;
313
314 v->sprite_cache.sprite_seq.Set(SPR_IMG_QUERY);
315 v->random_bits = Random();
316 v->SetFrontEngine();
317
318 v->roadtype = rt;
319 v->compatible_roadtypes = rti->powered_roadtypes;
320 v->gcache.cached_veh_length = VEHICLE_LENGTH;
321
323 v->SetServiceIntervalIsPercent(Company::Get(_current_company)->settings.vehicle.servint_ispercent);
324
326 v->InvalidateNewGRFCacheOfChain();
327
328 /* Call various callbacks after the whole consist has been constructed */
329 for (RoadVehicle *u = v; u != nullptr; u = u->Next()) {
330 u->cargo_cap = u->GetEngine()->DetermineCapacity(u);
331 u->refit_cap = 0;
332 v->InvalidateNewGRFCache();
333 u->InvalidateNewGRFCache();
334 }
336 /* Initialize cached values for realistic acceleration. */
337 if (_settings_game.vehicle.roadveh_acceleration_model != AccelerationModel::Original) v->CargoChanged();
338
339 v->UpdatePosition();
340
342 }
343
344 return CommandCost();
345}
346
347static FindDepotData FindClosestRoadDepot(const RoadVehicle *v, int max_distance)
348{
349 if (IsRoadDepotTile(v->tile)) return FindDepotData(v->tile, 0);
350
351 return YapfRoadVehicleFindNearestDepot(v, max_distance);
352}
353
355{
356 FindDepotData rfdd = FindClosestRoadDepot(this, 0);
357 if (rfdd.best_length == UINT_MAX) return ClosestDepot();
358
359 return ClosestDepot(rfdd.tile, GetDepotIndex(rfdd.tile));
360}
361
369{
371 if (v == nullptr) return CMD_ERROR;
372
373 if (!v->IsPrimaryVehicle()) return CMD_ERROR;
374
376 if (ret.Failed()) return ret;
377
378 if (v->vehstatus.Any({VehState::Stopped, VehState::Crashed}) ||
379 v->breakdown_ctr != 0 ||
380 v->overtaking != 0 ||
381 v->state == RVSB_WORMHOLE ||
382 v->IsInDepot() ||
383 v->current_order.IsType(OT_LOADING)) {
384 return CMD_ERROR;
385 }
386
388
390
391 if (flags.Test(DoCommandFlag::Execute)) {
392 v->reverse_ctr = 180;
393
394 /* Unbunching data is no longer valid. */
396 }
397
398 return CommandCost();
399}
400
401
403{
404 for (RoadVehicle *v = this; v != nullptr; v = v->Next()) {
405 v->colourmap = PAL_NONE;
406 v->UpdateViewport(true, false);
407 }
408 RoadVehUpdateCache(this, true);
409 this->CargoChanged();
410}
411
413{
414 /* Set common defaults. */
415 this->bounds = {{-1, -1, 0}, {3, 3, 6}, {}};
416
417 if (!IsDiagonalDirection(this->direction)) {
418 static const DiagDirectionIndexArray<Point> _sign_table{{{
419 /* x, y */
420 {-1, -1}, // Direction::N
421 {-1, 1}, // Direction::E
422 { 1, 1}, // Direction::S
423 { 1, -1}, // Direction::W
424 }}};
425
426 int half_shorten = (VEHICLE_LENGTH - this->gcache.cached_veh_length) / 2;
427
428 /* For all straight directions, move the bound box to the centre of the vehicle, but keep the size. */
429 this->bounds.offset.x -= half_shorten * _sign_table[DirToDiagDir(this->direction)].x;
430 this->bounds.offset.y -= half_shorten * _sign_table[DirToDiagDir(this->direction)].y;
431 } else {
432 /* Unlike trains, road vehicles do not have their offsets moved to the centre. */
433 switch (this->direction) {
434 /* Shorten southern corner of the bounding box according the vehicle length. */
435 case Direction::NE:
436 this->bounds.origin.x = -3;
437 this->bounds.extent.x = this->gcache.cached_veh_length;
438 this->bounds.offset.x = 1;
439 break;
440
441 case Direction::NW:
442 this->bounds.origin.y = -3;
443 this->bounds.extent.y = this->gcache.cached_veh_length;
444 this->bounds.offset.y = 1;
445 break;
446
447 /* Move northern corner of the bounding box down according to vehicle length. */
448 case Direction::SW:
449 this->bounds.origin.x = -3 + (VEHICLE_LENGTH - this->gcache.cached_veh_length);
450 this->bounds.extent.x = this->gcache.cached_veh_length;
451 this->bounds.offset.x = 1 - (VEHICLE_LENGTH - this->gcache.cached_veh_length);
452 break;
453
454 case Direction::SE:
455 this->bounds.origin.y = -3 + (VEHICLE_LENGTH - this->gcache.cached_veh_length);
456 this->bounds.extent.y = this->gcache.cached_veh_length;
457 this->bounds.offset.y = 1 - (VEHICLE_LENGTH - this->gcache.cached_veh_length);
458 break;
459
460 default:
461 NOT_REACHED();
462 }
463 }
464}
465
471{
472 int max_speed = this->gcache.cached_max_track_speed;
473
474 /* Limit speed to 50% while reversing, 75% in curves. */
475 for (const RoadVehicle *u = this; u != nullptr; u = u->Next()) {
476 if (_settings_game.vehicle.roadveh_acceleration_model == AccelerationModel::Realistic) {
477 if (this->state <= RVSB_TRACKDIR_MASK && IsReversingRoadTrackdir(static_cast<Trackdir>(this->state))) {
478 max_speed = this->gcache.cached_max_track_speed / 2;
479 break;
480 } else if (!IsDiagonalDirection(u->direction)) {
481 max_speed = this->gcache.cached_max_track_speed * 3 / 4;
482 }
483 }
484
485 /* Vehicle is on the middle part of a bridge. */
486 if (u->state == RVSB_WORMHOLE && !u->vehstatus.Test(VehState::Hidden)) {
487 max_speed = std::min(max_speed, GetBridgeSpec(GetBridgeType(u->tile))->speed * 2);
488 }
489 }
490
491 return std::min(max_speed, this->current_order.GetMaxSpeed() * 2);
492}
493
499{
500 RoadVehicle *first = v->First();
501 Vehicle *u = v;
502 for (; v->Next() != nullptr; v = v->Next()) u = v;
503 u->SetNext(nullptr);
504 v->last_station_visited = first->last_station_visited; // for PreDestructor
505
506 /* Only leave the road stop when we're really gone. */
507 if (IsInsideMM(v->state, RVSB_IN_ROAD_STOP, RVSB_IN_ROAD_STOP_END)) RoadStop::GetByTile(v->tile, GetRoadStopType(v->tile))->Leave(v);
508
509 delete v;
510}
511
512static void RoadVehSetRandomDirection(RoadVehicle *v)
513{
514 static const DirDiff delta[] = {
516 };
517
518 do {
519 uint32_t r = Random();
520
521 v->direction = ChangeDir(v->direction, delta[r & 3]);
522 v->UpdateViewport(true, true);
523 } while ((v = v->Next()) != nullptr);
524}
525
532{
533 v->crashed_ctr++;
534 if (v->crashed_ctr == 2) {
536 } else if (v->crashed_ctr <= 45) {
537 if ((v->tick_counter & 7) == 0) RoadVehSetRandomDirection(v);
538 } else if (v->crashed_ctr >= 2220 && !(v->tick_counter & 0x1F)) {
539 bool ret = v->Next() != nullptr;
541 return ret;
542 }
543
544 return true;
545}
546
547uint RoadVehicle::Crash(bool flooded)
548{
549 uint victims = this->GroundVehicleBase::Crash(flooded);
550 if (this->IsFrontEngine()) {
551 victims += 1; // driver
552
553 /* If we're in a drive through road stop we ought to leave it */
554 if (IsInsideMM(this->state, RVSB_IN_DT_ROAD_STOP, RVSB_IN_DT_ROAD_STOP_END)) {
555 RoadStop::GetByTile(this->tile, GetRoadStopType(this->tile))->Leave(this);
556 }
557 }
558 this->crashed_ctr = flooded ? 2000 : 1; // max 2220, disappear pretty fast when flooded
559 return victims;
560}
561
562static void RoadVehCrash(RoadVehicle *v)
563{
564 uint victims = v->Crash();
565
566 AI::NewEvent(v->owner, new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_RV_LEVEL_CROSSING, victims, v->owner));
567 Game::NewEvent(new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_RV_LEVEL_CROSSING, victims, v->owner));
568
569 EncodedString headline = (victims == 1)
570 ? GetEncodedString(STR_NEWS_ROAD_VEHICLE_CRASH_DRIVER)
571 : GetEncodedString(STR_NEWS_ROAD_VEHICLE_CRASH, victims);
573
574 AddTileNewsItem(std::move(headline), newstype, v->tile);
575
576 ModifyStationRatingAround(v->tile, v->owner, -160, 22);
577 if (_settings_client.sound.disaster) SndPlayVehicleFx(SND_12_EXPLOSION, v);
578}
579
580static bool RoadVehCheckTrainCrash(RoadVehicle *v)
581{
582 for (RoadVehicle *u = v; u != nullptr; u = u->Next()) {
583 if (u->state == RVSB_WORMHOLE) continue;
584
585 TileIndex tile = u->tile;
586
587 if (!IsLevelCrossingTile(tile)) continue;
588
589 if (HasVehicleNearTileXY(v->x_pos, v->y_pos, 4, [&u](const Vehicle *t) {
590 return t->type == VehicleType::Train && abs(t->z_pos - u->z_pos) <= 6;
591 })) {
592 RoadVehCrash(v);
593 return true;
594 }
595 }
596
597 return false;
598}
599
601{
602 if (station == this->last_station_visited) this->last_station_visited = StationID::Invalid();
603
604 const Station *st = Station::Get(station);
605 if (!CanVehicleUseStation(this, st)) {
606 /* There is no stop left at the station, so don't even TRY to go there */
608 return TileIndex{};
609 }
610
611 return st->xy;
612}
613
614static void StartRoadVehSound(const RoadVehicle *v)
615{
617 SoundID s = RoadVehInfo(v->engine_type)->sfx;
618 if (s == SND_19_DEPARTURE_OLD_RV_1 && (v->tick_counter & 3) == 0) {
620 }
621 SndPlayVehicleFx(s, v);
622 }
623}
624
626 int x;
627 int y;
628 const Vehicle *veh;
629 Vehicle *best;
630 uint best_diff;
631 Direction dir;
632};
633
634static void FindClosestBlockingRoadVeh(Vehicle *v, RoadVehFindData *rvf)
635{
636 static constexpr DirectionIndexArray<int8_t> dist_x{-4, -8, -4, -1, 4, 8, 4, 1};
637 static constexpr DirectionIndexArray<int8_t> dist_y{-4, -1, 4, 8, 4, 1, -4, -8};
638
639 int x_diff = v->x_pos - rvf->x;
640 int y_diff = v->y_pos - rvf->y;
641
642 /* Not a close Road vehicle when it's not a road vehicle, in the depot, or ourself. */
643 if (v->type != VehicleType::Road || v->IsInDepot() || rvf->veh->First() == v->First()) return;
644
645 /* Not close when at a different height or when going in a different direction. */
646 if (abs(v->z_pos - rvf->veh->z_pos) >= 6 || v->direction != rvf->dir) return;
647
648 /* We 'return' the closest vehicle, in distance and then VehicleID as tie-breaker. */
649 uint diff = abs(x_diff) + abs(y_diff);
650 if (diff > rvf->best_diff || (diff == rvf->best_diff && v->index > rvf->best->index)) return;
651
652 auto IsCloseOnAxis = [](int dist, int diff) {
653 if (dist < 0) return diff > dist && diff <= 0;
654 return diff < dist && diff >= 0;
655 };
656
657 if (IsCloseOnAxis(dist_x[v->direction], x_diff) && IsCloseOnAxis(dist_y[v->direction], y_diff)) {
658 rvf->best = v;
659 rvf->best_diff = diff;
660 }
661}
662
663static RoadVehicle *RoadVehFindCloseTo(RoadVehicle *v, int x, int y, Direction dir, bool update_blocked_ctr = true)
664{
665 RoadVehFindData rvf;
666 RoadVehicle *front = v->First();
667
668 if (front->reverse_ctr != 0) return nullptr;
669
670 rvf.x = x;
671 rvf.y = y;
672 rvf.dir = dir;
673 rvf.veh = v;
674 rvf.best_diff = UINT_MAX;
675
676 if (front->state == RVSB_WORMHOLE) {
677 for (Vehicle *u : VehiclesOnTile(v->tile)) {
678 FindClosestBlockingRoadVeh(u, &rvf);
679 }
681 FindClosestBlockingRoadVeh(u, &rvf);
682 }
683 } else {
684 for (Vehicle *u : VehiclesNearTileXY(x, y, 8)) {
685 FindClosestBlockingRoadVeh(u, &rvf);
686 }
687 }
688
689 /* This code protects a roadvehicle from being blocked for ever
690 * If more than 1480 / 74 days a road vehicle is blocked, it will
691 * drive just through it. The ultimate backup-code of TTD.
692 * It can be disabled. */
693 if (rvf.best_diff == UINT_MAX) {
694 front->blocked_ctr = 0;
695 return nullptr;
696 }
697
698 if (update_blocked_ctr && ++front->blocked_ctr > 1480) return nullptr;
699
700 return RoadVehicle::From(rvf.best);
701}
702
708static void RoadVehArrivesAt(const RoadVehicle *v, Station *st)
709{
710 if (v->IsBus()) {
711 /* Check if station was ever visited before */
712 if (!st->had_vehicle_of_type.Test(StationVehicleType::Bus)) {
713 st->had_vehicle_of_type.Set(StationVehicleType::Bus);
715 GetEncodedString(RoadTypeIsRoad(v->roadtype) ? STR_NEWS_FIRST_BUS_ARRIVAL : STR_NEWS_FIRST_PASSENGER_TRAM_ARRIVAL, st->index),
717 v->index,
718 st->index
719 );
720 AI::NewEvent(v->owner, new ScriptEventStationFirstVehicle(st->index, v->index));
721 Game::NewEvent(new ScriptEventStationFirstVehicle(st->index, v->index));
722 }
723 } else {
724 /* Check if station was ever visited before */
725 if (!st->had_vehicle_of_type.Test(StationVehicleType::Truck)) {
726 st->had_vehicle_of_type.Set(StationVehicleType::Truck);
728 GetEncodedString(RoadTypeIsRoad(v->roadtype) ? STR_NEWS_FIRST_TRUCK_ARRIVAL : STR_NEWS_FIRST_CARGO_TRAM_ARRIVAL, st->index),
730 v->index,
731 st->index
732 );
733 AI::NewEvent(v->owner, new ScriptEventStationFirstVehicle(st->index, v->index));
734 Game::NewEvent(new ScriptEventStationFirstVehicle(st->index, v->index));
735 }
736 }
737}
738
747{
748 switch (_settings_game.vehicle.roadveh_acceleration_model) {
749 default: NOT_REACHED();
751 return this->DoUpdateSpeed(this->overtaking != 0 ? 512 : 256, 0, this->GetCurrentMaxSpeed());
752
754 return this->DoUpdateSpeed(this->GetAcceleration() + (this->overtaking != 0 ? 256 : 0), this->GetAccelerationStatus() == AS_BRAKE ? 0 : 4, this->GetCurrentMaxSpeed());
755 }
756}
757
758static Direction RoadVehGetNewDirection(const RoadVehicle *v, int x, int y)
759{
760 static const Direction _roadveh_new_dir[] = {
764 };
765
766 x = x - v->x_pos + 1;
767 y = y - v->y_pos + 1;
768
769 if ((uint)x > 2 || (uint)y > 2) return v->direction;
770 return _roadveh_new_dir[y * 4 + x];
771}
772
773static Direction RoadVehGetSlidingDirection(const RoadVehicle *v, int x, int y)
774{
775 Direction new_dir = RoadVehGetNewDirection(v, x, y);
776 Direction old_dir = v->direction;
777
778 if (new_dir == old_dir) return old_dir;
779 DirDiff dirdiff = DirDifference(new_dir, old_dir);
780 return ChangeDir(old_dir, LimitDirDiff(dirdiff));
781}
782
784 const RoadVehicle *u;
785 const RoadVehicle *v;
786 TileIndex tile;
787 Trackdir trackdir;
788};
789
797{
798 if (!HasTileAnyRoadType(od->tile, od->v->compatible_roadtypes)) return true;
799 TrackStatus ts = GetTileTrackStatus(od->tile, TransportType::Road, GetRoadTramType(od->v->roadtype));
801 Tile next_tile = od->tile + TileOffsByDiagDir(DirToDiagDir(od->v->direction));
802
803 /* Track does not continue along overtaking direction. */
804 if (!ts.trackdirs.Test(od->trackdir)) return true;
805
806 /* Don't overtake across junction or barred level crossing, unless next tile is one-way. */
807 if ((trackbits.Any({Track::Upper, Track::Lower, Track::Left, Track::Right}) || ts.signals.Any()) && !IsOneWayRoadTile(next_tile)) return true;
808
809 /* Are there more vehicles on the tile except the two vehicles involved in overtaking */
810 return HasVehicleOnTile(od->tile, [&](const Vehicle *v) {
811 return v->type == VehicleType::Road && v->First() == v && v != od->u && v != od->v;
812 });
813}
814
815static void RoadVehCheckOvertake(RoadVehicle *v, RoadVehicle *u)
816{
817 OvertakeData od;
818
819 od.v = v;
820 od.u = u;
821
822 /* Trams can't overtake other trams */
823 if (RoadTypeIsTram(v->roadtype)) return;
824
825 /* Don't overtake in stations */
827
828 /* For now, articulated road vehicles can't overtake anything. */
829 if (v->HasArticulatedPart()) return;
830
831 /* Vehicles are not driving in same direction || direction is not a diagonal direction */
832 if (v->direction != u->direction || !IsDiagonalDirection(v->direction)) return;
833
834 /* Check if vehicle is in a road stop, depot, tunnel or bridge or not on a straight road */
835 if (v->state >= RVSB_IN_ROAD_STOP || !IsStraightRoadTrackdir(static_cast<Trackdir>(v->state & RVSB_TRACKDIR_MASK))) return;
836
837 /* Can't overtake a vehicle that is moving faster than us. If the vehicle in front is
838 * accelerating, take the maximum speed for the comparison, else the current speed.
839 * Original acceleration always accelerates, so always use the maximum speed. */
840 int u_speed = (_settings_game.vehicle.roadveh_acceleration_model == AccelerationModel::Original || u->GetAcceleration() > 0) ? u->GetCurrentMaxSpeed() : u->cur_speed;
841 if (u_speed >= v->GetCurrentMaxSpeed() &&
843 u->cur_speed != 0) {
844 return;
845 }
846
848
849 /* Are the current and the next tile suitable for overtaking?
850 * - Does the track continue along od.trackdir
851 * - No junctions
852 * - No barred levelcrossing
853 * - No other vehicles in the way
854 */
855 od.tile = v->tile;
856 if (CheckRoadBlockedForOvertaking(&od)) return;
857
858 od.tile = v->tile + TileOffsByDiagDir(DirToDiagDir(v->direction));
859 if (CheckRoadBlockedForOvertaking(&od)) return;
860
861 /* When the vehicle in front of us is stopped we may only take
862 * half the time to pass it than when the vehicle is moving. */
863 v->overtaking_ctr = (od.u->cur_speed == 0 || od.u->vehstatus.Test(VehState::Stopped)) ? RV_OVERTAKE_TIMEOUT / 2 : 0;
865}
866
867static void RoadZPosAffectSpeed(RoadVehicle *v, int old_z)
868{
869 if (old_z == v->z_pos || _settings_game.vehicle.roadveh_acceleration_model != AccelerationModel::Original) return;
870
871 if (old_z < v->z_pos) {
872 v->cur_speed = v->cur_speed * 232 / 256; // slow down by ~10%
873 } else {
874 uint16_t spd = v->cur_speed + 2;
875 if (spd <= v->gcache.cached_max_track_speed) v->cur_speed = spd;
876 }
877}
878
888{
889 bool path_found = true;
890
891 TrackStatus ts = GetTileTrackStatus(tile, TransportType::Road, GetRoadTramType(v->roadtype));
892
893 /* Replaces the given trackdir with Trackdir::Invalid when there is red signal for that trackdir. */
894 auto FilterRedSignal = [&ts](Trackdir trackdir) {
895 if (ts.signals.Test(trackdir)) return Trackdir::Invalid;
896 return trackdir;
897 };
898
899 if (IsTileType(tile, TileType::Road)) {
900 if (IsRoadDepot(tile) && (!IsTileOwner(tile, v->owner) || GetRoadDepotDirection(tile) == enterdir)) {
901 /* Road depot owned by another company or with the wrong orientation */
902 ts.trackdirs.Reset();
903 }
904 } else if (IsTileType(tile, TileType::Station) && IsBayRoadStopTile(tile)) {
905 /* Standard road stop (drive-through stops are treated as normal road) */
906
907 if (!IsTileOwner(tile, v->owner) || GetBayRoadStopDir(tile) == enterdir || v->HasArticulatedPart()) {
908 /* different station owner or wrong orientation or the vehicle has articulated parts */
909 ts.trackdirs.Reset();
910 } else {
911 /* Our station */
913
914 if (GetRoadStopType(tile) != rstype) {
915 /* Wrong station type */
916 ts.trackdirs.Reset();
917 } else {
918 /* Proper station type, check if there is free loading bay */
919 if (!_settings_game.pf.roadveh_queue && IsBayRoadStopTile(tile) &&
920 !RoadStop::GetByTile(tile, rstype)->HasFreeBay()) {
921 /* Station is full and RV queuing is off */
922 ts.trackdirs.Reset();
923 }
924 }
925 }
926 }
927 /* The above lookups should be moved to GetTileTrackStatus in the
928 * future, but that requires more changes to the pathfinder and other
929 * stuff, probably even more arguments to GTTS.
930 */
931
932 /* Remove tracks unreachable from the enter dir */
933 ts.trackdirs &= DiagdirReachesTrackdirs(enterdir);
934 if (ts.trackdirs.None()) {
935 /* If vehicle expected a path, it no longer exists, so invalidate it. */
936 if (!v->path.empty()) v->path.clear();
937 /* No reachable tracks, so we'll reverse */
938 return FilterRedSignal(_road_reverse_table[enterdir]);
939 }
940
941 if (v->reverse_ctr != 0) {
942 bool reverse = true;
943 if (RoadTypeIsTram(v->roadtype)) {
944 /* Trams may only reverse on a tile if it contains at least the straight
945 * trackbits or when it is a valid turning tile (i.e. one roadbit) */
947 RoadBits straight = AxisToRoadBits(DiagDirToAxis(enterdir));
948 reverse = rb.All(straight) ||
949 rb == DiagDirToRoadBits(enterdir);
950 }
951 if (reverse) {
952 v->reverse_ctr = 0;
953 if (v->tile != tile) {
954 return FilterRedSignal(_road_reverse_table[enterdir]);
955 }
956 }
957 }
958
959 if (v->dest_tile == INVALID_TILE) {
960 /* We've got no destination, pick a random track */
961 return FilterRedSignal(ts.trackdirs.GetNthSetBit(RandomRange(ts.trackdirs.Count())).value());
962 }
963
964 /* Only one track to choose between? */
965 if (ts.trackdirs.Count() == 1) {
966 if (!v->path.empty() && v->path.back().tile == tile) {
967 /* Vehicle expected a choice here, invalidate its path. */
968 v->path.clear();
969 }
970 return FilterRedSignal(ts.trackdirs.GetNthSetBit(0).value());
971 }
972
973 /* Attempt to follow cached path. */
974 if (!v->path.empty()) {
975 if (v->path.back().tile != tile) {
976 /* Vehicle didn't expect a choice here, invalidate its path. */
977 v->path.clear();
978 } else {
979 Trackdir trackdir = v->path.back().trackdir;
980
981 if (ts.trackdirs.Test(trackdir)) {
982 v->path.pop_back();
983 return FilterRedSignal(trackdir);
984 }
985
986 /* Vehicle expected a choice which is no longer available. */
987 v->path.clear();
988 }
989 }
990
991 Trackdir best_track = YapfRoadVehicleChooseTrack(v, tile, enterdir, ts.trackdirs, path_found, v->path);
992
993 v->HandlePathfindingResult(path_found);
994
995 return FilterRedSignal(best_track);
996}
997
999 uint8_t x, y;
1000};
1001
1002#include "table/roadveh_movement.h"
1003
1004bool RoadVehLeaveDepot(RoadVehicle *v, bool first)
1005{
1006 /* Don't leave unless v and following wagons are in the depot. */
1007 for (const RoadVehicle *u = v; u != nullptr; u = u->Next()) {
1008 if (u->state != RVSB_IN_DEPOT || u->tile != v->tile) return false;
1009 }
1010
1012 v->direction = DiagDirToDir(dir);
1013
1014 Trackdir tdir = DiagDirToDiagTrackdir(dir);
1015 const RoadDriveEntry *rdp = _road_drive_data[GetRoadTramType(v->roadtype)][(to_underlying(_settings_game.vehicle.road_side) << RVS_DRIVE_SIDE) + to_underlying(tdir)];
1016
1017 int x = TileX(v->tile) * TILE_SIZE + (rdp[RVC_DEPOT_START_FRAME].x & 0xF);
1018 int y = TileY(v->tile) * TILE_SIZE + (rdp[RVC_DEPOT_START_FRAME].y & 0xF);
1019
1020 if (first) {
1021 /* We are leaving a depot, but have to go to the exact same one; re-enter */
1022 if (v->current_order.IsType(OT_GOTO_DEPOT) && v->tile == v->dest_tile) {
1024 return true;
1025 }
1026
1027 if (RoadVehFindCloseTo(v, x, y, v->direction, false) != nullptr) return true;
1028
1031
1032 StartRoadVehSound(v);
1033
1034 /* Vehicle is about to leave a depot */
1035 v->cur_speed = 0;
1036 }
1037
1039 v->state = to_underlying(tdir);
1040 v->frame = RVC_DEPOT_START_FRAME;
1041
1042 v->x_pos = x;
1043 v->y_pos = y;
1044 v->UpdatePosition();
1045 v->UpdateInclination(true, true);
1046
1047 InvalidateWindowData(WindowClass::VehicleDepot, v->tile);
1048
1049 return true;
1050}
1051
1052static Trackdir FollowPreviousRoadVehicle(const RoadVehicle *v, const RoadVehicle *prev, TileIndex tile, DiagDirection entry_dir, bool already_reversed)
1053{
1054 if (prev->tile == v->tile && !already_reversed) {
1055 /* If the previous vehicle is on the same tile as this vehicle is
1056 * then it must have reversed. */
1057 return _road_reverse_table[entry_dir];
1058 }
1059
1060 uint8_t prev_state = prev->state;
1061 Trackdir dir;
1062
1063 if (prev_state == RVSB_WORMHOLE || prev_state == RVSB_IN_DEPOT) {
1065
1067 diag_dir = GetTunnelBridgeDirection(tile);
1068 } else if (IsRoadDepotTile(tile)) {
1069 diag_dir = ReverseDiagDir(GetRoadDepotDirection(tile));
1070 }
1071
1072 if (diag_dir == DiagDirection::Invalid) return Trackdir::Invalid;
1073 dir = DiagDirToDiagTrackdir(diag_dir);
1074 } else {
1075 if (already_reversed && (prev->tile != tile || (static_cast<Trackdir>(prev_state) < Trackdir::End && IsReversingRoadTrackdir(static_cast<Trackdir>(prev_state))))) {
1076 /*
1077 * The vehicle has reversed, but did not go straight back.
1078 * It immediately turn onto another tile. This means that
1079 * the roadstate of the previous vehicle cannot be used
1080 * as the direction we have to go with this vehicle.
1081 *
1082 * Next table is build in the following way:
1083 * - first row for when the vehicle in front went to the northern or
1084 * western tile, second for southern and eastern.
1085 * - columns represent the entry direction.
1086 * - cell values are determined by the Trackdir one has to take from
1087 * the entry dir (column) to the tile in north or south by only
1088 * going over the trackdirs used for turning 90 degrees, i.e.
1089 * TRACKDIR_{UPPER,RIGHT,LOWER,LEFT}_{N,E,S,W}.
1090 */
1091 bool north;
1092 if (prev->tile != tile) {
1093 north = prev->tile < tile;
1094 } else {
1095 north = static_cast<Trackdir>(prev_state) == Trackdir::RvRev_NW || static_cast<Trackdir>(prev_state) == Trackdir::RvRev_NE;
1096 }
1097 static const DiagDirectionIndexArray<Trackdir> reversed_turn_lookup[2] = {
1100 dir = reversed_turn_lookup[north ? 0 : 1][ReverseDiagDir(entry_dir)];
1101 } else if (HasBit(prev_state, RVS_IN_DT_ROAD_STOP)) {
1102 dir = static_cast<Trackdir>(prev_state & RVSB_ROAD_STOP_TRACKDIR_MASK);
1103 } else if (static_cast<Trackdir>(prev_state) < Trackdir::End) {
1104 dir = static_cast<Trackdir>(prev_state);
1105 } else {
1106 return Trackdir::Invalid;
1107 }
1108 }
1109
1110 /* Do some sanity checking. */
1111 static const RoadBits required_roadbits[] = {
1112 ROAD_X,
1113 ROAD_Y,
1118 ROAD_X,
1119 ROAD_Y,
1120 };
1121 RoadBits required = required_roadbits[to_underlying(dir) & 0x07];
1122
1123 if (!required.Any(GetAnyRoadBits(tile, GetRoadTramType(v->roadtype), true))) {
1124 dir = Trackdir::Invalid;
1125 }
1126
1127 return dir;
1128}
1129
1138static bool CanBuildTramTrackOnTile(CompanyID c, TileIndex t, RoadType rt, RoadBits r)
1139{
1140 /* The 'current' company is not necessarily the owner of the vehicle. */
1141 AutoRestoreBackup cur_company(_current_company, c);
1142 return Command<Commands::BuildRoad>::Do(DoCommandFlag::NoWater, t, r, rt, {}, TownID::Invalid()).Succeeded();
1143}
1144
1145bool IndividualRoadVehicleController(RoadVehicle *v, const RoadVehicle *prev)
1146{
1147 if (v->overtaking != 0) {
1149 /* Force us to be not overtaking! */
1150 v->overtaking = 0;
1151 } else if (++v->overtaking_ctr >= RV_OVERTAKE_TIMEOUT) {
1152 /* If overtaking just aborts at a random moment, we can have a out-of-bound problem,
1153 * if the vehicle started a corner. To protect that, only allow an abort of
1154 * overtake if we are on straight roads */
1155 if (v->state < RVSB_IN_ROAD_STOP && IsStraightRoadTrackdir(static_cast<Trackdir>(v->state))) {
1156 v->overtaking = 0;
1157 }
1158 }
1159 }
1160
1161 /* If this vehicle is in a depot and we've reached this point it must be
1162 * one of the articulated parts. It will stay in the depot until activated
1163 * by the previous vehicle in the chain when it gets to the right place. */
1164 if (v->IsInDepot()) return true;
1165
1166 if (v->state == RVSB_WORMHOLE) {
1167 /* Vehicle is entering a depot or is on a bridge or in a tunnel */
1169
1170 if (v->IsFrontEngine()) {
1171 const Vehicle *u = RoadVehFindCloseTo(v, gp.x, gp.y, v->direction);
1172 if (u != nullptr) {
1173 v->cur_speed = u->First()->cur_speed;
1174 return false;
1175 }
1176 }
1177
1179 /* Vehicle has just entered a bridge or tunnel */
1180 v->x_pos = gp.x;
1181 v->y_pos = gp.y;
1182 v->UpdatePosition();
1183 v->UpdateInclination(true, true);
1184 return true;
1185 }
1186
1187 v->x_pos = gp.x;
1188 v->y_pos = gp.y;
1189 v->UpdatePosition();
1190 if (!v->vehstatus.Test(VehState::Hidden)) v->Vehicle::UpdateViewport(true);
1191 return true;
1192 }
1193
1194 /* Get move position data for next frame.
1195 * For a drive-through road stop use 'straight road' move data.
1196 * In this case v->state is masked to give the road stop entry direction. */
1197 RoadDriveEntry rd = _road_drive_data[GetRoadTramType(v->roadtype)][(
1199 (to_underlying(_settings_game.vehicle.road_side) << RVS_DRIVE_SIDE)) ^ v->overtaking][v->frame + 1];
1200
1201 if (rd.x & RDE_NEXT_TILE) {
1202 DiagDirection diagdir = static_cast<DiagDirection>(rd.x & 3);
1203 TileIndex tile = v->tile + TileOffsByDiagDir(diagdir);
1204 Trackdir dir;
1205
1206 if (v->IsFrontEngine()) {
1207 /* If this is the front engine, look for the right path. */
1209 dir = RoadFindPathToDest(v, tile, diagdir);
1210 } else {
1211 dir = _road_reverse_table[diagdir];
1212 }
1213 } else {
1214 dir = FollowPreviousRoadVehicle(v, prev, tile, diagdir, false);
1215 }
1216
1217 if (dir == Trackdir::Invalid) {
1218 if (!v->IsFrontEngine()) FatalError("Disconnecting road vehicle.");
1219 v->cur_speed = 0;
1220 return false;
1221 }
1222
1223again:
1224 uint start_frame = RVC_DEFAULT_START_FRAME;
1225 if (IsReversingRoadTrackdir(dir)) {
1226 /* When turning around we can't be overtaking. */
1227 v->overtaking = 0;
1228
1229 /* Turning around */
1230 if (RoadTypeIsTram(v->roadtype)) {
1231 /* Determine the road bits the tram needs to be able to turn around
1232 * using the 'big' corner loop. */
1233 RoadBit needed;
1234 switch (dir) {
1235 default: NOT_REACHED();
1236 case Trackdir::RvRev_NE: needed = RoadBit::SW; break;
1237 case Trackdir::RvRev_SE: needed = RoadBit::NW; break;
1238 case Trackdir::RvRev_SW: needed = RoadBit::NE; break;
1239 case Trackdir::RvRev_NW: needed = RoadBit::SE; break;
1240 }
1241 if ((v->Previous() != nullptr && v->Previous()->tile == tile) ||
1242 (v->IsFrontEngine() && IsNormalRoadTile(tile) && !HasRoadWorks(tile) &&
1244 GetRoadBits(tile, RoadTramType::Tram).Test(needed))) {
1245 /*
1246 * Taking the 'big' corner for trams only happens when:
1247 * - The previous vehicle in this (articulated) tram chain is
1248 * already on the 'next' tile, we just follow them regardless of
1249 * anything. When it is NOT on the 'next' tile, the tram started
1250 * doing a reversing turn when the piece of tram track on the next
1251 * tile did not exist yet. Do not use the big tram loop as that is
1252 * going to cause the tram to split up.
1253 * - Or the front of the tram can drive over the next tile.
1254 */
1255 } else if (!v->IsFrontEngine() || !CanBuildTramTrackOnTile(v->owner, tile, v->roadtype, needed) || GetAnyRoadBits(v->tile, RoadTramType::Tram, false).Reset(needed).Any()) {
1256 /*
1257 * Taking the 'small' corner for trams only happens when:
1258 * - We are not the from vehicle of an articulated tram.
1259 * - Or when the company cannot build on the next tile.
1260 *
1261 * The 'small' corner means that the vehicle is on the end of a
1262 * tram track and needs to start turning there. To do this properly
1263 * the tram needs to start at an offset in the tram turning 'code'
1264 * for 'big' corners. It furthermore does not go to the next tile,
1265 * so that needs to be fixed too.
1266 */
1267 tile = v->tile;
1268 start_frame = RVC_TURN_AROUND_START_FRAME_SHORT_TRAM;
1269 } else {
1270 /* The company can build on the next tile, so wait till they do. */
1271 v->cur_speed = 0;
1272 return false;
1273 }
1274 } else if (IsNormalRoadTile(v->tile) && GetDisallowedRoadDirections(v->tile).Any()) {
1275 v->cur_speed = 0;
1276 return false;
1277 } else {
1278 tile = v->tile;
1279 }
1280 }
1281
1282 /* Get position data for first frame on the new tile */
1283 const RoadDriveEntry *rdp = _road_drive_data[GetRoadTramType(v->roadtype)][(to_underlying(dir) + (to_underlying(_settings_game.vehicle.road_side) << RVS_DRIVE_SIDE)) ^ v->overtaking];
1284
1285 int x = TileX(tile) * TILE_SIZE + rdp[start_frame].x;
1286 int y = TileY(tile) * TILE_SIZE + rdp[start_frame].y;
1287
1288 Direction new_dir = RoadVehGetSlidingDirection(v, x, y);
1289 if (v->IsFrontEngine()) {
1290 const Vehicle *u = RoadVehFindCloseTo(v, x, y, new_dir);
1291 if (u != nullptr) {
1292 v->cur_speed = u->First()->cur_speed;
1293 /* We might be blocked, prevent pathfinding rerun as we already know where we are heading to. */
1294 v->path.emplace_back(dir, tile);
1295 return false;
1296 }
1297 }
1298
1299 auto vets = VehicleEnterTile(v, tile, x, y);
1300 if (vets.Test(VehicleEnterTileState::CannotEnter)) {
1301 if (!IsTileType(tile, TileType::TunnelBridge)) {
1302 v->cur_speed = 0;
1303 return false;
1304 }
1305 /* Try an about turn to re-enter the previous tile */
1306 dir = _road_reverse_table[static_cast<DiagDirection>(rd.x & 3)];
1307 goto again;
1308 }
1309
1310 if (IsInsideMM(v->state, RVSB_IN_ROAD_STOP, RVSB_IN_DT_ROAD_STOP_END) && IsTileType(v->tile, TileType::Station)) {
1311 if (IsReversingRoadTrackdir(dir) && IsInsideMM(v->state, RVSB_IN_ROAD_STOP, RVSB_IN_ROAD_STOP_END)) {
1312 /* New direction is trying to turn vehicle around.
1313 * We can't turn at the exit of a road stop so wait.*/
1314 v->cur_speed = 0;
1315 return false;
1316 }
1317
1318 /* If we are a drive through road stop and the next tile is of
1319 * the same road stop and the next tile isn't this one (i.e. we
1320 * are not reversing), then keep the reservation and state.
1321 * This way we will not be shortly unregister from the road
1322 * stop. It also makes it possible to load when on the edge of
1323 * two road stops; otherwise you could get vehicles that should
1324 * be loading but are not actually loading. */
1325 if (IsDriveThroughStopTile(v->tile) &&
1327 v->tile != tile) {
1328 /* So, keep 'our' state */
1329 dir = static_cast<Trackdir>(v->state);
1330 } else if (IsStationRoadStop(v->tile)) {
1331 /* We're not continuing our drive through road stop, so leave. */
1333 }
1334 }
1335
1337 TileIndex old_tile = v->tile;
1338
1339 v->tile = tile;
1340 v->state = (uint8_t)dir;
1341 v->frame = start_frame;
1342 RoadTramType rtt = GetRoadTramType(v->roadtype);
1343 if (GetRoadType(old_tile, rtt) != GetRoadType(tile, rtt)) {
1344 if (v->IsFrontEngine()) {
1346 }
1347 v->First()->CargoChanged();
1348 }
1349 }
1350 if (new_dir != v->direction) {
1351 v->direction = new_dir;
1352 if (_settings_game.vehicle.roadveh_acceleration_model == AccelerationModel::Original) v->cur_speed -= v->cur_speed >> 2;
1353 }
1354 v->x_pos = x;
1355 v->y_pos = y;
1356 v->UpdatePosition();
1357 RoadZPosAffectSpeed(v, v->UpdateInclination(true, true));
1358 return true;
1359 }
1360
1361 if (rd.x & RDE_TURNED) {
1362 /* Vehicle has finished turning around, it will now head back onto the same tile */
1363 Trackdir dir;
1364 uint turn_around_start_frame = RVC_TURN_AROUND_START_FRAME;
1365
1366 if (RoadTypeIsTram(v->roadtype) && !IsRoadDepotTile(v->tile) && GetAnyRoadBits(v->tile, RoadTramType::Tram, true).Count() == 1) {
1367 /*
1368 * The tram is turning around with one tram 'roadbit'. This means that
1369 * it is using the 'big' corner 'drive data'. However, to support the
1370 * trams to take a small corner, there is a 'turned' marker in the middle
1371 * of the turning 'drive data'. When the tram took the long corner, we
1372 * will still use the 'big' corner drive data, but we advance it one
1373 * frame. We furthermore set the driving direction so the turning is
1374 * going to be properly shown.
1375 */
1376 turn_around_start_frame = RVC_START_FRAME_AFTER_LONG_TRAM;
1377 switch (static_cast<DiagDirection>(rd.x & 0x3)) {
1378 default: NOT_REACHED();
1379 case DiagDirection::NW: dir = Trackdir::RvRev_SE; break;
1380 case DiagDirection::NE: dir = Trackdir::RvRev_SW; break;
1381 case DiagDirection::SE: dir = Trackdir::RvRev_NW; break;
1382 case DiagDirection::SW: dir = Trackdir::RvRev_NE; break;
1383 }
1384 } else {
1385 if (v->IsFrontEngine()) {
1386 /* If this is the front engine, look for the right path. */
1387 dir = RoadFindPathToDest(v, v->tile, (DiagDirection)(rd.x & 3));
1388 } else {
1389 dir = FollowPreviousRoadVehicle(v, prev, v->tile, (DiagDirection)(rd.x & 3), true);
1390 }
1391 }
1392
1393 if (dir == Trackdir::Invalid) {
1394 v->cur_speed = 0;
1395 return false;
1396 }
1397
1398 const RoadDriveEntry *rdp = _road_drive_data[GetRoadTramType(v->roadtype)][(to_underlying(_settings_game.vehicle.road_side) << RVS_DRIVE_SIDE) + to_underlying(dir)];
1399
1400 int x = TileX(v->tile) * TILE_SIZE + rdp[turn_around_start_frame].x;
1401 int y = TileY(v->tile) * TILE_SIZE + rdp[turn_around_start_frame].y;
1402
1403 Direction new_dir = RoadVehGetSlidingDirection(v, x, y);
1404 if (v->IsFrontEngine()) {
1405 const Vehicle *u = RoadVehFindCloseTo(v, x, y, new_dir);
1406 if (u != nullptr) {
1407 v->cur_speed = u->First()->cur_speed;
1408 /* We might be blocked, prevent pathfinding rerun as we already know where we are heading to. */
1409 v->path.emplace_back(dir, v->tile);
1410 return false;
1411 }
1412 }
1413
1414 auto vets = VehicleEnterTile(v, v->tile, x, y);
1415 if (vets.Test(VehicleEnterTileState::CannotEnter)) {
1416 v->cur_speed = 0;
1417 return false;
1418 }
1419
1420 v->state = to_underlying(dir);
1421 v->frame = turn_around_start_frame;
1422
1423 if (new_dir != v->direction) {
1424 v->direction = new_dir;
1425 if (_settings_game.vehicle.roadveh_acceleration_model == AccelerationModel::Original) v->cur_speed -= v->cur_speed >> 2;
1426 }
1427
1428 v->x_pos = x;
1429 v->y_pos = y;
1430 v->UpdatePosition();
1431 RoadZPosAffectSpeed(v, v->UpdateInclination(true, true));
1432 return true;
1433 }
1434
1435 /* This vehicle is not in a wormhole and it hasn't entered a new tile. If
1436 * it's on a depot tile, check if it's time to activate the next vehicle in
1437 * the chain yet. */
1438 if (v->Next() != nullptr && IsRoadDepotTile(v->tile)) {
1439 if (v->frame == v->gcache.cached_veh_length + RVC_DEPOT_START_FRAME) {
1440 RoadVehLeaveDepot(v->Next(), false);
1441 }
1442 }
1443
1444 /* Calculate new position for the vehicle */
1445 int x = (v->x_pos & ~15) + (rd.x & 15);
1446 int y = (v->y_pos & ~15) + (rd.y & 15);
1447
1448 Direction new_dir = RoadVehGetSlidingDirection(v, x, y);
1449
1450 if (v->IsFrontEngine() && !IsInsideMM(v->state, RVSB_IN_ROAD_STOP, RVSB_IN_ROAD_STOP_END)) {
1451 /* Vehicle is not in a road stop.
1452 * Check for another vehicle to overtake */
1453 RoadVehicle *u = RoadVehFindCloseTo(v, x, y, new_dir);
1454
1455 if (u != nullptr) {
1456 u = u->First();
1457 /* There is a vehicle in front overtake it if possible */
1458 if (v->overtaking == 0) RoadVehCheckOvertake(v, u);
1459 if (v->overtaking == 0) v->cur_speed = u->cur_speed;
1460
1461 /* In case an RV is stopped in a road stop, why not try to load? */
1462 if (v->cur_speed == 0 && IsInsideMM(v->state, RVSB_IN_DT_ROAD_STOP, RVSB_IN_DT_ROAD_STOP_END) &&
1464 v->owner == GetTileOwner(v->tile) && !v->current_order.IsType(OT_LEAVESTATION) &&
1467 v->last_station_visited = st->index;
1468 RoadVehArrivesAt(v, st);
1469 v->BeginLoading();
1471 TriggerRoadStopAnimation(st, v->tile, StationAnimationTrigger::VehicleArrives);
1472 }
1473 return false;
1474 }
1475 }
1476
1477 Direction old_dir = v->direction;
1478 if (new_dir != old_dir) {
1479 v->direction = new_dir;
1480 if (_settings_game.vehicle.roadveh_acceleration_model == AccelerationModel::Original) v->cur_speed -= v->cur_speed >> 2;
1481
1482 /* Delay the vehicle in curves by making it require one additional frame per turning direction (two in total).
1483 * A vehicle has to spend at least 9 frames on a tile, so the following articulated part can follow.
1484 * (The following part may only be one tile behind, and the front part is moved before the following ones.)
1485 * The short (inner) curve has 8 frames, this elongates it to 10. */
1486 v->UpdateViewport(true, true);
1487 return true;
1488 }
1489
1490 /* If the vehicle is in a normal road stop and the frame equals the stop frame OR
1491 * if the vehicle is in a drive-through road stop and this is the destination station
1492 * and it's the correct type of stop (bus or truck) and the frame equals the stop frame...
1493 * (the station test and stop type test ensure that other vehicles, using the road stop as
1494 * a through route, do not stop) */
1495 if (v->IsFrontEngine() && ((IsInsideMM(v->state, RVSB_IN_ROAD_STOP, RVSB_IN_ROAD_STOP_END) &&
1496 _road_stop_stop_frame[v->state - RVSB_IN_ROAD_STOP + (to_underlying(_settings_game.vehicle.road_side) << RVS_DRIVE_SIDE)] == v->frame) ||
1497 (IsInsideMM(v->state, RVSB_IN_DT_ROAD_STOP, RVSB_IN_DT_ROAD_STOP_END) &&
1499 v->owner == GetTileOwner(v->tile) &&
1501 v->frame == RVC_DRIVE_THROUGH_STOP_FRAME))) {
1502
1505
1506 /* Vehicle is at the stop position (at a bay) in a road stop.
1507 * Note, if vehicle is loading/unloading it has already been handled,
1508 * so if we get here the vehicle has just arrived or is just ready to leave. */
1509 if (!HasBit(v->state, RVS_ENTERED_STOP)) {
1510 /* Vehicle has arrived at a bay in a road stop */
1511
1512 if (IsDriveThroughStopTile(v->tile)) {
1513 TileIndex next_tile = TileAddByDir(v->tile, v->direction);
1514
1515 /* Check if next inline bay is free and has compatible road. */
1517 v->frame++;
1518 v->x_pos = x;
1519 v->y_pos = y;
1520 v->UpdatePosition();
1521 RoadZPosAffectSpeed(v, v->UpdateInclination(true, false));
1522 return true;
1523 }
1524 }
1525
1526 rs->SetEntranceBusy(false);
1528
1529 v->last_station_visited = st->index;
1530
1531 if (IsDriveThroughStopTile(v->tile) || (v->current_order.IsType(OT_GOTO_STATION) && v->current_order.GetDestination() == st->index)) {
1532 RoadVehArrivesAt(v, st);
1533 v->BeginLoading();
1535 TriggerRoadStopAnimation(st, v->tile, StationAnimationTrigger::VehicleArrives);
1536 return false;
1537 }
1538 } else {
1539 /* Vehicle is ready to leave a bay in a road stop */
1540 if (rs->IsEntranceBusy()) {
1541 /* Road stop entrance is busy, so wait as there is nowhere else to go */
1542 v->cur_speed = 0;
1543 return false;
1544 }
1545 if (v->current_order.IsType(OT_LEAVESTATION)) v->current_order.Free();
1546 }
1547
1548 if (IsBayRoadStopTile(v->tile)) rs->SetEntranceBusy(true);
1549
1550 StartRoadVehSound(v);
1551 SetWindowWidgetDirty(WindowClass::VehicleView, v->index, WID_VV_START_STOP);
1552 }
1553
1554 /* Check tile position conditions - i.e. stop position in depot,
1555 * entry onto bridge or into tunnel */
1556 auto vets = VehicleEnterTile(v, v->tile, x, y);
1557 if (vets.Test(VehicleEnterTileState::CannotEnter)) {
1558 v->cur_speed = 0;
1559 return false;
1560 }
1561
1562 if (v->current_order.IsType(OT_LEAVESTATION) && IsDriveThroughStopTile(v->tile)) {
1563 v->current_order.Free();
1564 }
1565
1566 /* Move to next frame unless vehicle arrived at a stop position
1567 * in a depot or entered a tunnel/bridge */
1568 if (!vets.Test(VehicleEnterTileState::EnteredWormhole)) v->frame++;
1569 v->x_pos = x;
1570 v->y_pos = y;
1571 v->UpdatePosition();
1572 RoadZPosAffectSpeed(v, v->UpdateInclination(false, true));
1573 return true;
1574}
1575
1576static bool RoadVehController(RoadVehicle *v)
1577{
1578 /* decrease counters */
1579 v->current_order_time++;
1580 if (v->reverse_ctr != 0) v->reverse_ctr--;
1581
1582 /* handle crashed */
1583 if (v->vehstatus.Test(VehState::Crashed) || RoadVehCheckTrainCrash(v)) {
1584 return RoadVehIsCrashed(v);
1585 }
1586
1587 /* road vehicle has broken down? */
1588 if (v->HandleBreakdown()) return true;
1590 v->SetLastSpeed();
1591 return true;
1592 }
1593
1594 ProcessOrders(v);
1595 v->HandleLoading();
1596
1597 if (v->current_order.IsType(OT_LOADING)) return true;
1598
1599 if (v->IsInDepot()) {
1600 /* Check if we should wait here for unbunching. */
1601 if (v->IsWaitingForUnbunching()) return true;
1602 if (RoadVehLeaveDepot(v, true)) return true;
1603 }
1604
1605 v->ShowVisualEffect();
1606
1607 /* Check how far the vehicle needs to proceed */
1608 int j = v->UpdateSpeed();
1609
1610 int adv_spd = v->GetAdvanceDistance();
1611 bool blocked = false;
1612 while (j >= adv_spd) {
1613 j -= adv_spd;
1614
1615 RoadVehicle *u = v;
1616 for (RoadVehicle *prev = nullptr; u != nullptr; prev = u, u = u->Next()) {
1617 if (!IndividualRoadVehicleController(u, prev)) {
1618 blocked = true;
1619 break;
1620 }
1621 }
1622 if (blocked) break;
1623
1624 /* Determine distance to next map position */
1625 adv_spd = v->GetAdvanceDistance();
1626
1627 /* Test for a collision, but only if another movement will occur. */
1628 if (j >= adv_spd && RoadVehCheckTrainCrash(v)) break;
1629 }
1630
1631 v->SetLastSpeed();
1632
1633 for (RoadVehicle *u = v; u != nullptr; u = u->Next()) {
1634 if (u->vehstatus.Test(VehState::Hidden)) continue;
1635
1636 u->UpdateViewport(false, false);
1637 }
1638
1639 /* If movement is blocked, set 'progress' to its maximum, so the roadvehicle does
1640 * not accelerate again before it can actually move. I.e. make sure it tries to advance again
1641 * on next tick to discover whether it is still blocked. */
1642 if (v->progress == 0) v->progress = blocked ? adv_spd - 1 : j;
1643
1644 return true;
1645}
1646
1648{
1649 const Engine *e = this->GetEngine();
1650 if (e->VehInfo<RoadVehicleInfo>().running_cost_class == Price::Invalid) return 0;
1651
1652 uint cost_factor = GetVehicleProperty(this, PROP_ROADVEH_RUNNING_COST_FACTOR, e->VehInfo<RoadVehicleInfo>().running_cost);
1653 if (cost_factor == 0) return 0;
1654
1655 return GetPrice(e->VehInfo<RoadVehicleInfo>().running_cost_class, cost_factor, e->GetGRF());
1656}
1657
1659{
1661
1662 this->tick_counter++;
1663
1664 if (this->IsFrontEngine()) {
1665 if (!this->vehstatus.Test(VehState::Stopped)) this->running_ticks++;
1666 return RoadVehController(this);
1667 }
1668
1669 return true;
1670}
1671
1673{
1674 if (tile == this->dest_tile) return;
1675 this->path.clear();
1676 this->dest_tile = tile;
1677}
1678
1679static void CheckIfRoadVehNeedsService(RoadVehicle *v)
1680{
1681 /* If we already got a slot at a stop, use that FIRST, and go to a depot later */
1682 if (Company::Get(v->owner)->settings.vehicle.servint_roadveh == 0 || !v->NeedsAutomaticServicing()) return;
1683 if (v->IsChainInDepot()) {
1685 return;
1686 }
1687
1688 uint max_penalty = _settings_game.pf.yapf.maximum_go_to_depot_penalty;
1689
1690 FindDepotData rfdd = FindClosestRoadDepot(v, max_penalty);
1691 /* Only go to the depot if it is not too far out of our way. */
1692 if (rfdd.best_length == UINT_MAX || rfdd.best_length > max_penalty) {
1693 if (v->current_order.IsType(OT_GOTO_DEPOT)) {
1694 /* If we were already heading for a depot but it has
1695 * suddenly moved farther away, we continue our normal
1696 * schedule? */
1698 SetWindowWidgetDirty(WindowClass::VehicleView, v->index, WID_VV_START_STOP);
1699 }
1700 return;
1701 }
1702
1703 DepotID depot = GetDepotIndex(rfdd.tile);
1704
1705 if (v->current_order.IsType(OT_GOTO_DEPOT) &&
1707 !Chance16(1, 20)) {
1708 return;
1709 }
1710
1713 v->SetDestTile(rfdd.tile);
1714 SetWindowWidgetDirty(WindowClass::VehicleView, v->index, WID_VV_START_STOP);
1715}
1716
1719{
1720 if (!this->IsFrontEngine()) return;
1721 AgeVehicle(this);
1722}
1723
1726{
1727 if (!this->IsFrontEngine()) return;
1728 EconomyAgeVehicle(this);
1729
1730 if ((++this->day_counter & 7) == 0) DecreaseVehicleValue(this);
1731 if (this->blocked_ctr == 0) CheckVehicleBreakdown(this);
1732
1733 CheckIfRoadVehNeedsService(this);
1734
1735 CheckOrders(this);
1736
1737 if (this->running_ticks == 0) return;
1738
1740
1741 this->profit_this_year -= cost.GetCost();
1742 this->running_ticks = 0;
1743
1745
1746 SetWindowDirty(WindowClass::VehicleDetails, this->index);
1747 SetWindowClassesDirty(WindowClass::RoadVehicleList);
1748}
1749
1751{
1752 if (this->vehstatus.Test(VehState::Crashed)) return Trackdir::Invalid;
1753
1754 if (this->IsInDepot()) {
1755 /* We'll assume the road vehicle is facing outwards */
1756 return DiagDirToDiagTrackdir(GetRoadDepotDirection(this->tile));
1757 }
1758
1759 if (IsBayRoadStopTile(this->tile)) {
1760 /* We'll assume the road vehicle is facing outwards */
1761 return DiagDirToDiagTrackdir(GetBayRoadStopDir(this->tile)); // Road vehicle in a station
1762 }
1763
1764 /* Drive through road stops / wormholes (tunnels) */
1766
1767 /* If vehicle's state is a valid track direction (vehicle is not turning around) return it,
1768 * otherwise transform it into a valid track direction */
1769 return static_cast<Trackdir>(IsReversingRoadTrackdir(static_cast<Trackdir>(this->state)) ? (this->state - 6) : this->state);
1770}
1771
1773{
1774 uint16_t weight = CargoSpec::Get(this->cargo_type)->WeightOfNUnits(this->GetEngine()->DetermineCapacity(this));
1775
1776 /* Vehicle weight is not added for articulated parts. */
1777 if (!this->IsArticulatedPart()) {
1778 /* Road vehicle weight is in units of 1/4 t. */
1779 weight += GetVehicleProperty(this, PROP_ROADVEH_WEIGHT, RoadVehInfo(this->engine_type)->weight) / 4;
1780 }
1781
1782 return weight;
1783}
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).
constexpr T SetBit(T &x, const uint8_t y)
Set a bit in a variable.
constexpr bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
Header file for bridges.
const BridgeSpec * GetBridgeSpec(BridgeType i)
Get the specification of a bridge type.
Definition bridge.h:63
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:112
@ Passengers
Passengers.
Definition cargotype.h:50
bool IsCargoInClass(CargoType cargo, CargoClasses cc)
Does a given cargo have any cargo class from cc.
Definition cargotype.h:288
static void NewEvent(CompanyID company, ScriptEvent *event)
Queue a new event for an AI.
Definition ai_core.cpp:231
uint Count() const
Count the number of set bits.
constexpr bool All(const Timpl &other) const
Test if all of the values are set.
constexpr bool Test(Tvalue_type value) const
Test if the value-th bit is set.
constexpr bool None() const
Test if none of the values are 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.
std::optional< Tvalue_type > GetNthSetBit(uint n) const
Get the value of the Nth set bit.
Common return value for all commands.
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.
uint16_t reliability_spd_dec
Speed of reliability decay between services (per day).
Definition engine_base.h:52
const GRFFile * GetGRF() const
Retrieve the NewGRF the engine is tied to.
GrfID GetGRFID() const
Retrieve the GRF ID of the NewGRF the engine is tied to.
Definition engine.cpp:185
EngineFlags flags
Flags of the engine.
Definition engine_base.h:59
uint8_t original_image_index
Original vehicle image index, thus the image index of the overridden vehicle.
Definition engine_base.h:63
TimerGameCalendar::Date GetLifeLengthInDays() const
Returns the vehicle's (not model's!) life length in days.
Definition engine.cpp:471
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:51
static void NewEvent(class ScriptEvent *event)
Queue a new event for the game script.
RAII class for measuring multi-step elements of performance.
static constexpr TimerGameTick::Ticks DAY_TICKS
1 day is 74 ticks; TimerGameCalendar::date_fract used to be uint16_t and incremented by 885.
Wrapper class to abstract away the way the tiles are stored.
Definition map_func.h:25
static Date date
Current date in days (day counter).
static Year year
Current year, starting at 0.
static Date date
Current date in days (day counter).
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.
@ NoWater
don't allow building on water
@ Execute
execute the given command
EnumBitSet< DoCommandFlag, uint16_t > DoCommandFlags
Bitset of DoCommandFlag elements.
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:56
PoolID< uint16_t, struct DepotIDTag, 64000, 0xFFFF > DepotID
Type for the unique identifier of depots.
Definition depot_type.h:15
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.
DirDiff LimitDirDiff(DirDiff d)
Limit a direction difference to up to 45 degrees.
DiagDirection DirToDiagDir(Direction dir)
Convert a Direction to a DiagDirection.
DirDiff
Enumeration for the difference between two directions.
@ Left45
Angle of 45 degrees left.
@ Same
Both directions faces to the same direction.
@ Right45
Angle of 45 degrees right.
EnumIndexArray< T, DiagDirection, DiagDirection::End > DiagDirectionIndexArray
Array with DiagDirection as index.
Direction
Defines the 8 directions on the map.
@ Invalid
Flag for an invalid direction.
@ SW
Southwest.
@ NW
Northwest.
@ NE
Northeast.
@ SE
Southeast.
EnumIndexArray< T, Direction, Direction::End > DirectionIndexArray
Array with Direction as index.
DiagDirection
Enumeration for diagonal directions.
@ Invalid
Flag for an invalid DiagDirection.
@ SW
Southwest.
@ NW
Northwest.
@ NE
Northeast, upper right on your monitor.
@ SE
Southeast.
Money GetPrice(Price index, uint cost_factor, const GRFFile *grf_file, int shift)
Determine a certain price.
Definition economy.cpp:941
@ RoadVehRun
Running costs road vehicles.
@ Invalid
Invalid base price.
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.
PoolID< uint16_t, struct EngineIDTag, 64000, 0xFFFF > EngineID
Unique identification number of an engine.
Definition engine_type.h:25
@ ExclusivePreview
This vehicle is in the exclusive preview stage, either being used or being offered to a company.
constexpr std::underlying_type_t< enum_type > to_underlying(enum_type e)
Implementation of std::to_underlying (from C++23).
Definition enum_type.hpp:21
Error reporting related functions.
fluid_settings_t * settings
FluidSynth settings handle.
Types for recording game performance data.
@ GameLoopRoadVehicles
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.
TrackStatus GetTileTrackStatus(TileIndex tile, TransportType mode, RoadTramType 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.
#define Rect
Macro that prevents name conflicts between included headers.
#define Point
Macro that prevents name conflicts between included headers.
TileIndex TileAddByDir(TileIndex tile, Direction dir)
Adds a Direction to a tile.
Definition map_func.h:603
static uint TileY(TileIndex tile)
Get the Y component of a tile.
Definition map_func.h:429
static uint TileX(TileIndex tile)
Get the X component of a tile.
Definition map_func.h:419
TileIndexDiff TileOffsByDiagDir(DiagDirection dir)
Convert a DiagDirection to a TileIndexDiff.
Definition map_func.h:574
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(GrfID 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.
void TriggerRoadStopRandomisation(BaseStation *st, TileIndex tile, StationRandomTrigger trigger, CargoType cargo_type)
Trigger road stop randomisation.
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.
@ 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:32
NewsType
Type of news.
Definition news_type.h:30
@ ArrivalCompany
First vehicle arrived for company.
Definition news_type.h:31
@ AccidentOther
An accident or disaster has occurred.
Definition news_type.h:34
@ ArrivalOther
First vehicle arrived for competitor.
Definition news_type.h:32
@ Accident
An accident or disaster has occurred.
Definition news_type.h:33
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.
@ NonStop
The vehicle will not stop at any stations it passes except the destination, aka non-stop.
Definition order_type.h:88
@ Service
This depot order is because of the servicing limit.
Definition order_type.h:109
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:217
Road related functions.
RoadBits AxisToRoadBits(Axis a)
Create the road-part which belongs to the given Axis.
Definition road_func.h:93
RoadBits DiagDirToRoadBits(DiagDirection d)
Create the road-part which belongs to the given DiagDirection.
Definition road_func.h:78
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
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
static bool IsRoadDepotTile(Tile t)
Return whether a tile is a road depot tile.
Definition road_map.h:100
bool HasTileAnyRoadType(Tile t, RoadTypes rts)
Check if a tile has one of the specified road types.
Definition road_map.h:232
DisallowedRoadDirections GetDisallowedRoadDirections(Tile t)
Gets the disallowed directions.
Definition road_map.h:311
DiagDirection GetRoadDepotDirection(Tile t)
Get the direction of the exit of a road depot.
Definition road_map.h:576
static bool IsRoadDepot(Tile t)
Return whether a tile is a road depot.
Definition road_map.h:90
bool IsOneWayRoadTile(Tile t)
Check if a tile is a one-way road tile.
Definition road_map.h:334
RoadType GetRoadType(Tile t, RoadTramType rtt)
Get the road type for the given RoadTramType.
Definition road_map.h:175
static bool IsNormalRoadTile(Tile t)
Return whether a tile is a normal road tile.
Definition road_map.h:58
bool HasRoadWorks(Tile t)
Check if a tile has road works.
Definition road_map.h:519
static constexpr RoadBits ROAD_X
Full road along the x-axis (south-west + north-east).
Definition road_type.h:67
EnumBitSet< RoadBit, uint8_t > RoadBits
Bitset of RoadBit elements.
Definition road_type.h:65
RoadBit
Enumeration for the road parts on a tile.
Definition road_type.h:57
@ SW
South-west part.
Definition road_type.h:59
@ NW
North-west part.
Definition road_type.h:58
@ NE
North-east part.
Definition road_type.h:61
@ SE
South-east part.
Definition road_type.h:60
static constexpr RoadBits ROAD_Y
Full road along the y-axis (north-west + south-east).
Definition road_type.h:68
RoadType
The different roadtypes we support.
Definition road_type.h:24
RoadTramType
The different types of road type.
Definition road_type.h:38
@ Tram
Tram type.
Definition road_type.h:40
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:63
static const uint RVC_DRIVE_THROUGH_STOP_FRAME
Stop frame for a vehicle in a drive-through stop.
Definition roadveh.h:82
static const uint8_t RV_OVERTAKE_TIMEOUT
The number of ticks a vehicle has for overtaking.
Definition roadveh.h:86
void RoadVehUpdateCache(RoadVehicle *v, bool same_length=false)
Update the cache of a road vehicle.
static const uint RDE_NEXT_TILE
We should enter the next tile.
Definition roadveh.h:62
bool IsValidImageIndex< VehicleType::Road >(uint8_t image_index)
Helper to check whether an image index is valid for a particular vehicle.
static constexpr DiagDirectionIndexArray< Trackdir > _road_reverse_table
Track direction to use when reversing for each diagonal direction.
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 Trackdir::Invalid if the direction is currently bl...
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.
static const EnumIndexArray< const RoadDriveEntry *const *, RoadTramType, RoadTramType::End > _road_drive_data
Road drive data for all RoadTramTypes.
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
static const PaletteID PALETTE_CRASH
Recolour sprite greying of crashed vehicles.
Definition sprites.h:1794
static const SpriteID SPR_IMG_QUERY
Definition sprites.h:1275
Base classes/functions for stations.
void ModifyStationRatingAround(TileIndex tile, Owner owner, int amount, uint radius)
Forcibly modify station ratings near a given tile.
Functions related to 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:26
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:54
RoadStopType
Types of RoadStops.
@ Bus
A standard stop for buses.
@ Truck
A standard stop for trucks.
@ VehicleArrives
Trigger platform when train arrives.
@ VehicleArrives
Trigger platform when train arrives.
@ Bus
Station has seen a bus.
@ Truck
Station has seen a truck.
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:261
EncodedString GetEncodedString(StringID str)
Encode a string with no parameters into an encoded string.
Definition strings.cpp:89
Functions related to OTTD's strings.
Class to backup a specific variable and restore it upon destruction of this object to prevent stack v...
TimerGameTick::Ticks current_order_time
How many ticks have passed since this order started.
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:41
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo type.
Definition cargotype.h:140
uint64_t WeightOfNUnits(uint32_t n) const
Calculate the weight of n units of cargo.
Definition cargotype.h:153
Structure to return information about the closest depot location, and whether it could be found.
T y
Y coordinate.
T x
X coordinate.
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.
uint8_t grf_version
GRF version (See https://newgrf-specs.tt-wiki.net/wiki/Version_numbers#GRF_version).
Definition newgrf.h:129
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
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...
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.
GroundVehicleFlags gv_flags
uint Crash(bool flooded) override
Common code executed for crashed ground vehicles.
uint DoUpdateSpeed(uint accel, int min_speed, int max_speed)
void SetLastSpeed()
Update the GUI variant of the current speed of the vehicle.
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...
void MakeGoToDepot(DestinationID destination, OrderDepotTypeFlags order, OrderNonStopFlags non_stop_type=OrderNonStopFlag::NonStop, OrderDepotActionFlags action={}, CargoType cargo=CARGO_NO_REFIT)
Makes this order a Go To Depot order.
Definition order_cmd.cpp:74
OrderNonStopFlags GetNonStopType() const
At which stations must we stop?
Definition order_base.h:157
static T * Create(Targs &&... args)
static Engine * Get(auto index)
static Vehicle * GetIfValid(auto index)
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:203
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:292
static RoadStop * GetByTile(TileIndex tile, RoadStopType type)
Find a roadstop at given tile.
Definition roadstop.cpp:253
Information about a road vehicle.
Buses, trucks and trams belong to this class.
Definition roadveh.h:105
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:107
void SetDestTile(TileIndex tile) override
Set the destination of this vehicle.
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:128
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:117
AccelStatus GetAccelerationStatus() const
Checks the current acceleration status of this vehicle.
Definition roadveh.h:229
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:112
bool IsBus() const
Check whether a roadvehicle is a bus.
uint8_t overtaking_ctr
The length of the current overtake attempt.
Definition roadveh.h:111
void OnNewCalendarDay() override
Calender day handler.
bool IsInDepot() const override
Check whether the vehicle is in the depot.
Definition roadveh.h:134
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:106
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:115
uint8_t overtaking
Set to RVSB_DRIVE_SIDE when overtaking, otherwise 0.
Definition roadveh.h:110
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.
static Station * Get(auto index)
T * Next() const
Get next vehicle in the chain.
T * Previous() const
Get previous vehicle in the chain.
static RoadVehicle * From(Vehicle *v)
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.
Track status of a tile.
Definition track_type.h:105
TrackdirBits signals
Red signals on the tile.
Definition track_type.h:107
TrackdirBits trackdirs
Trackdirs present on the tile.
Definition track_type.h:106
uint16_t cached_max_speed
Maximum speed of the consist (minimum of the max speed of all vehicles in the consist).
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:125
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:153
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:750
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 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:2454
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.
VehStates vehstatus
Status.
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:2534
CargoType cargo_type
type of cargo this vehicle is carrying
Vehicle * First() const
Get the first vehicle of this vehicle chain.
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:794
int32_t y_pos
y coordinate.
int32_t x_pos
x coordinate.
VehicleCache vcache
Cache of often used vehicle values.
SpriteBounds bounds
Bounding box of vehicle.
void BeginLoading()
Prepare everything to begin the loading when arriving at a station.
Definition vehicle.cpp:2229
uint8_t spritenum
currently displayed sprite index 0xfd == custom sprite, 0xfe == custom second head sprite 0xff == res...
uint16_t cur_speed
current speed
bool IsFrontEngine() const
Check if the vehicle is a front engine.
bool IsWaitingForUnbunching() const
Check whether a vehicle inside a depot is waiting for unbunching.
Definition vehicle.cpp:2581
void SetNext(Vehicle *next)
Set the next vehicle of this vehicle.
Definition vehicle.cpp:2988
bool HandleBreakdown()
Handle all of the aspects of a vehicle breakdown This includes adding smoke and sounds,...
Definition vehicle.cpp:1376
uint8_t progress
The percentage (if divided by 256) this vehicle already crossed the tile unit.
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:1701
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:2836
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:294
uint8_t running_ticks
Number of ticks this vehicle was not stopped this day.
@ CannotEnter
The vehicle cannot enter the tile.
Definition tile_cmd.h:27
@ EnteredWormhole
The vehicle either entered a bridge, tunnel or depot tile (this includes the last tile of the bridge/...
Definition tile_cmd.h:26
VehicleEnterTileStates VehicleEnterTile(Vehicle *v, TileIndex tile, int x, int y)
Call the tile callback function for a vehicle entering a tile.
Definition vehicle.cpp:1865
static bool IsTileType(Tile tile, TileType type)
Checks if a tile is a given tiletype.
Definition tile_map.h:150
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
StrongType::Typedef< uint32_t, struct TileIndexTag, StrongType::Compare, StrongType::Integer, StrongType::Compatible< int32_t >, StrongType::Compatible< int64_t > > TileIndex
The index/ID of a Tile.
Definition tile_type.h:92
constexpr TileIndex INVALID_TILE
The very nice invalid tile marker.
Definition tile_type.h:100
static constexpr uint TILE_SIZE
Tile size in world coordinates.
Definition tile_type.h:15
@ TunnelBridge
Tunnel entry/exit and bridge heads.
Definition tile_type.h:58
@ Station
A tile of a station or airport.
Definition tile_type.h:54
@ Road
A tile with road and/or tram tracks.
Definition tile_type.h:51
Definition of the game-calendar-timer.
Definition of the game-economy-timer.
bool IsReversingRoadTrackdir(Trackdir dir)
Checks whether the trackdir means that we are reversing.
Definition track_func.h:568
TrackdirBits DiagdirReachesTrackdirs(DiagDirection diagdir)
Returns all trackdirs that can be reached when entering a tile from a given (diagonal) direction.
Definition track_func.h:450
bool IsStraightRoadTrackdir(Trackdir dir)
Checks whether the given trackdir is a straight road.
Definition track_func.h:579
Trackdir DiagDirToDiagTrackdir(DiagDirection diagdir)
Maps a (4-way) direction to the diagonal trackdir that runs in that direction.
Definition track_func.h:432
TrackBits TrackdirBitsToTrackBits(TrackdirBits bits)
Discards all directional information from a TrackdirBits value.
Definition track_func.h:281
EnumBitSet< Track, uint8_t > TrackBits
Bitset of Track elements.
Definition track_type.h:43
Trackdir
Enumeration for tracks and directions.
Definition track_type.h:63
@ Right_N
Right track and direction to north.
Definition track_type.h:77
@ Right_S
Right track and direction to south.
Definition track_type.h:69
@ Left_S
Left track and direction to south.
Definition track_type.h:68
@ Lower_E
Lower track and direction to east.
Definition track_type.h:67
@ Invalid
Flag for an invalid trackdir.
Definition track_type.h:82
@ RvRev_NW
(Road vehicle) reverse direction north-west
Definition track_type.h:79
@ Upper_W
Upper track and direction to west.
Definition track_type.h:74
@ End
End marker.
Definition track_type.h:81
@ RvRev_NE
(Road vehicle) reverse direction north-east
Definition track_type.h:70
@ Upper_E
Upper track and direction to east.
Definition track_type.h:66
@ RvRev_SW
(Road vehicle) reverse direction south-west
Definition track_type.h:78
@ Left_N
Left track and direction to north.
Definition track_type.h:76
@ Lower_W
Lower track and direction to west.
Definition track_type.h:75
@ RvRev_SE
(Road vehicle) reverse direction south-east
Definition track_type.h:71
@ 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:1564
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:365
void VehicleServiceInDepot(Vehicle *v)
Service a vehicle and all subsequent vehicles in the consist.
Definition vehicle.cpp:189
void CheckVehicleBreakdown(Vehicle *v)
Periodic check for a vehicle to maybe break down.
Definition vehicle.cpp:1320
GetNewVehiclePosResult GetNewVehiclePos(const Vehicle *v)
Get position information of a vehicle when moving one pixel in the direction it is facing.
Definition vehicle.cpp:1804
void DecreaseVehicleValue(Vehicle *v)
Decrease the value of a vehicle.
Definition vehicle.cpp:1299
void EconomyAgeVehicle(Vehicle *v)
Update economy age of a vehicle.
Definition vehicle.cpp:1442
bool CanVehicleUseStation(EngineID engine_type, const Station *st)
Can this station be used by the given engine type?
Definition vehicle.cpp:3115
void AgeVehicle(Vehicle *v)
Update age of a vehicle.
Definition vehicle.cpp:1454
@ 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...
bool IsValidImageIndex(uint8_t image_index)
Helper to check whether an image index is valid for a particular vehicle.
@ 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.
PoolID< uint32_t, struct VehicleIDTag, 0xFF000, 0xFFFFF > VehicleID
The type all our vehicle IDs have.
@ Road
Road vehicle type.
@ Original
Original acceleration model.
@ Realistic
"Realistic" acceleration model.
@ SuppressImplicitOrders
Disable insertion and removal of automatic orders until the vehicle completes the real order.
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:3285
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:3377
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:3271
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting).
Definition window.cpp:3255
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