41 #include "table/strings.h"
45 static const uint16_t _roadveh_images[] = {
46 0xCD4, 0xCDC, 0xCE4, 0xCEC, 0xCF4, 0xCFC, 0xD0C, 0xD14,
47 0xD24, 0xD1C, 0xD2C, 0xD04, 0xD1C, 0xD24, 0xD6C, 0xD74,
48 0xD7C, 0xC14, 0xC1C, 0xC24, 0xC2C, 0xC34, 0xC3C, 0xC4C,
49 0xC54, 0xC64, 0xC5C, 0xC6C, 0xC44, 0xC5C, 0xC64, 0xCAC,
50 0xCB4, 0xCBC, 0xD94, 0xD9C, 0xDA4, 0xDAC, 0xDB4, 0xDBC,
51 0xDCC, 0xDD4, 0xDE4, 0xDDC, 0xDEC, 0xDC4, 0xDDC, 0xDE4,
52 0xE2C, 0xE34, 0xE3C, 0xC14, 0xC1C, 0xC2C, 0xC3C, 0xC4C,
53 0xC5C, 0xC64, 0xC6C, 0xC74, 0xC84, 0xC94, 0xCA4
56 static const uint16_t _roadveh_full_adder[] = {
57 0, 88, 0, 0, 0, 0, 48, 48,
58 48, 48, 0, 0, 64, 64, 0, 16,
59 16, 0, 88, 0, 0, 0, 0, 48,
60 48, 48, 48, 0, 0, 64, 64, 0,
61 16, 16, 0, 88, 0, 0, 0, 0,
62 48, 48, 48, 48, 0, 0, 64, 64,
63 0, 16, 16, 0, 8, 8, 8, 8,
69 bool IsValidImageIndex<VEH_ROAD>(uint8_t image_index)
71 return image_index <
lengthof(_roadveh_images);
95 int reference_width = ROADVEHINFO_DEFAULT_VEHICLE_WIDTH;
97 if (offset !=
nullptr) {
107 uint8_t spritenum = e->u.road.image_index;
109 if (is_custom_sprite(spritenum)) {
110 GetCustomVehicleIcon(engine,
DIR_W, image_type, result);
111 if (result->IsValid())
return;
116 assert(IsValidImageIndex<VEH_ROAD>(spritenum));
117 result->Set(
DIR_W + _roadveh_images[spritenum]);
126 if (result->IsValid())
return;
131 assert(IsValidImageIndex<VEH_ROAD>(
spritenum));
151 GetRoadVehIcon(engine, image_type, &seq);
155 preferred_x =
Clamp(preferred_x,
174 GetRoadVehIcon(engine, image_type, &seq);
196 if (e->
GetGRF() !=
nullptr && e->
GetGRF()->grf_version >= 8) {
229 assert(u->First() == v);
239 u->gcache.cached_veh_length = veh_len;
243 u->UpdateVisualEffect();
323 u->cargo_cap = u->GetEngine()->DetermineCapacity(u);
326 u->InvalidateNewGRFCache();
369 if (ret.
Failed())
return ret;
386 v->reverse_ctr = 180;
407 static const int8_t _delta_xy_table[8][10] = {
409 {3, 3, -1, -1, 0, 0, -1, -1, -1, -1},
410 {3, 7, -1, -3, 0, -1, 0, -1, 0, 0},
411 {3, 3, -1, -1, 0, 0, 1, -1, 1, -1},
412 {7, 3, -3, -1, -1, 0, 0, 0, 1, 0},
413 {3, 3, -1, -1, 0, 0, 1, 1, 1, 1},
414 {3, 7, -1, -3, 0, -1, 0, 0, 0, 1},
415 {3, 3, -1, -1, 0, 0, -1, 1, -1, 1},
416 {7, 3, -3, -1, -1, 0, -1, 0, 0, 0},
422 const int8_t *bb = _delta_xy_table[this->
direction];
423 this->
x_bb_offs = bb[5] + bb[9] * shorten;
424 this->
y_bb_offs = bb[4] + bb[8] * shorten;;
427 this->
x_extent = bb[1] + bb[7] * shorten;
428 this->
y_extent = bb[0] + bb[6] * shorten;
446 }
else if ((u->direction & 1) == 0) {
468 for (; v->
Next() !=
nullptr; v = v->
Next()) u = v;
478 static void RoadVehSetRandomDirection(
RoadVehicle *v)
480 static const DirDiff delta[] = {
485 uint32_t r = Random();
489 }
while ((v = v->
Next()) !=
nullptr);
503 if ((v->
tick_counter & 7) == 0) RoadVehSetRandomDirection(v);
505 bool ret = v->
Next() !=
nullptr;
546 uint victims = v->
Crash();
548 AI::NewEvent(v->
owner,
new ScriptEventVehicleCrashed(v->
index, v->
tile, ScriptEventVehicleCrashed::CRASH_RV_LEVEL_CROSSING, victims));
549 Game::NewEvent(
new ScriptEventVehicleCrashed(v->
index, v->
tile, ScriptEventVehicleCrashed::CRASH_RV_LEVEL_CROSSING, victims));
552 StringID newsitem = (victims == 1) ? STR_NEWS_ROAD_VEHICLE_CRASH_DRIVER : STR_NEWS_ROAD_VEHICLE_CRASH;
559 AddTileNewsItem(newsitem, newstype, v->
tile);
561 ModifyStationRatingAround(v->
tile, v->
owner, -160, 22);
583 TileIndex RoadVehicle::GetOrderStationLocation(StationID station)
597 static void StartRoadVehSound(
const RoadVehicle *v)
604 SndPlayVehicleFx(s, v);
619 static const int8_t dist_x[] = { -4, -8, -4, -1, 4, 8, 4, 1 };
620 static const int8_t dist_y[] = { -4, -1, 4, 8, 4, 1, -4, -8 };
624 short x_diff = v->
x_pos - rvf->x;
625 short y_diff = v->
y_pos - rvf->y;
636 uint diff =
abs(x_diff) +
abs(y_diff);
638 if (diff < rvf->best_diff || (diff == rvf->best_diff && v->
index < rvf->best->
index)) {
640 rvf->best_diff = diff;
652 if (front->reverse_ctr != 0)
return nullptr;
658 rvf.best_diff = UINT_MAX;
671 if (rvf.best_diff == UINT_MAX) {
672 front->blocked_ctr = 0;
676 if (update_blocked_ctr && ++front->blocked_ctr > 1480)
return nullptr;
690 if (!(st->had_vehicle_of_type &
HVOT_BUS)) {
691 st->had_vehicle_of_type |=
HVOT_BUS;
694 RoadTypeIsRoad(v->
roadtype) ? STR_NEWS_FIRST_BUS_ARRIVAL : STR_NEWS_FIRST_PASSENGER_TRAM_ARRIVAL,
704 if (!(st->had_vehicle_of_type &
HVOT_TRUCK)) {
708 RoadTypeIsRoad(v->
roadtype) ? STR_NEWS_FIRST_TRUCK_ARRIVAL : STR_NEWS_FIRST_CARGO_TRAM_ARRIVAL,
729 default: NOT_REACHED();
740 static const Direction _roadveh_new_dir[] = {
746 x = x - v->
x_pos + 1;
747 y = y - v->
y_pos + 1;
749 if ((uint)x > 2 || (uint)y > 2)
return v->
direction;
750 return _roadveh_new_dir[y * 4 + x];
755 Direction new_dir = RoadVehGetNewDirection(v, x, y);
759 if (new_dir == old_dir)
return old_dir;
771 static Vehicle *EnumFindVehBlockingOvertake(
Vehicle *v,
void *data)
775 return (v->
type ==
VEH_ROAD && v->
First() == v && v != od->u && v != od->v) ? v :
nullptr;
807 if (RoadTypeIsTram(v->
roadtype))
return;
851 static void RoadZPosAffectSpeed(
RoadVehicle *v,
int old_z)
855 if (old_z < v->z_pos) {
859 if (spd <= v->gcache.cached_max_track_speed) v->
cur_speed = spd;
863 static int PickRandomBit(uint bits)
868 for (i = 0; !(bits & 1) || (
int)--num >= 0; bits >>= 1, i++) {}
882 #define return_track(x) { best_track = (Trackdir)x; goto found_best_track; }
886 bool path_found =
true;
929 if (!v->
path.empty()) v->
path.clear();
931 return_track(_road_reverse_table[enterdir]);
934 if (v->reverse_ctr != 0) {
941 reverse = ((rb & straight) == straight) ||
946 if (v->
tile != tile) {
947 return_track(_road_reverse_table[enterdir]);
955 return_track(PickRandomBit(trackdirs));
960 if (!v->
path.empty() && v->
path.tile.front() == tile) {
968 if (!v->
path.empty()) {
969 if (v->
path.tile.front() != tile) {
975 if (
HasBit(trackdirs, trackdir)) {
976 v->
path.td.pop_front();
977 v->
path.tile.pop_front();
978 return_track(trackdir);
1003 bool RoadVehLeaveDepot(
RoadVehicle *v,
bool first)
1026 if (RoadVehFindCloseTo(v, x, y, v->
direction,
false) !=
nullptr)
return true;
1031 StartRoadVehSound(v);
1039 v->frame = RVC_DEPOT_START_FRAME;
1053 if (prev->
tile == v->
tile && !already_reversed) {
1056 return _road_reverse_table[entry_dir];
1059 uint8_t prev_state = prev->
state;
1074 if (already_reversed && prev->
tile != tile) {
1104 static const RoadBits required_roadbits[] = {
1108 RoadBits required = required_roadbits[dir & 0x07];
1204 dir = FollowPreviousRoadVehicle(v, prev, tile, (
DiagDirection)(rd.x & 3),
false);
1208 if (!v->
IsFrontEngine()) FatalError(
"Disconnecting road vehicle.");
1214 uint start_frame = RVC_DEFAULT_START_FRAME;
1225 default: NOT_REACHED();
1258 start_frame = RVC_TURN_AROUND_START_FRAME_SHORT_TRAM;
1278 Direction new_dir = RoadVehGetSlidingDirection(v, x, y);
1280 const Vehicle *u = RoadVehFindCloseTo(v, x, y, new_dir);
1284 v->
path.tile.push_front(tile);
1285 v->
path.td.push_front(dir);
1297 dir = _road_reverse_table[rd.x & 3];
1331 v->
state = (uint8_t)dir;
1332 v->frame = start_frame;
1333 RoadTramType rtt = GetRoadTramType(v->
roadtype);
1334 if (GetRoadType(old_tile, rtt) != GetRoadType(tile, rtt)) {
1338 v->
First()->CargoChanged();
1355 uint turn_around_start_frame = RVC_TURN_AROUND_START_FRAME;
1367 turn_around_start_frame = RVC_START_FRAME_AFTER_LONG_TRAM;
1368 switch (rd.x & 0x3) {
1369 default: NOT_REACHED();
1380 dir = FollowPreviousRoadVehicle(v, prev, v->
tile, (
DiagDirection)(rd.x & 3),
true);
1394 Direction new_dir = RoadVehGetSlidingDirection(v, x, y);
1396 const Vehicle *u = RoadVehFindCloseTo(v, x, y, new_dir);
1401 v->
path.td.push_front(dir);
1413 v->frame = turn_around_start_frame;
1432 RoadVehLeaveDepot(v->
Next(),
false);
1437 int x = (v->
x_pos & ~15) + (rd.x & 15);
1438 int y = (v->
y_pos & ~15) + (rd.y & 15);
1440 Direction new_dir = RoadVehGetSlidingDirection(v, x, y);
1445 RoadVehicle *u = RoadVehFindCloseTo(v, x, y, new_dir);
1450 if (v->
overtaking == 0) RoadVehCheckOvertake(v, u);
1468 if (new_dir != old_dir) {
1491 v->frame == RVC_DRIVE_THROUGH_STOP_FRAME))) {
1538 StartRoadVehSound(v);
1568 if (v->reverse_ctr != 0) v->reverse_ctr--;
1590 if (RoadVehLeaveDepot(v,
true))
return true;
1599 bool blocked =
false;
1600 while (j >= adv_spd) {
1604 for (
RoadVehicle *prev =
nullptr; u !=
nullptr; prev = u, u = u->
Next()) {
1605 if (!IndividualRoadVehicleController(u, prev)) {
1616 if (j >= adv_spd && RoadVehCheckTrainCrash(v))
break;
1622 if ((u->vehstatus &
VS_HIDDEN) != 0)
continue;
1624 u->UpdateViewport(
false,
false);
1638 if (e->u.road.running_cost_class == INVALID_PRICE)
return 0;
1641 if (cost_factor == 0)
return 0;
1643 return GetPrice(e->u.road.running_cost_class, cost_factor, e->
GetGRF());
1654 return RoadVehController(
this);
1660 void RoadVehicle::SetDestTile(
TileIndex tile)
1667 static void CheckIfRoadVehNeedsService(
RoadVehicle *v)
1701 v->SetDestTile(rfdd.
tile);
1719 if (this->blocked_ctr == 0) CheckVehicleBreakdown(
this);
1721 CheckIfRoadVehNeedsService(
this);
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.
constexpr bool HasExactlyOneBit(T value)
Test whether value has exactly 1 bit set.
constexpr debug_inline bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
constexpr T SetBit(T &x, const uint8_t y)
Set a bit in a variable.
constexpr uint8_t FindFirstBit(T x)
Search the first set bit in a value.
constexpr uint CountBits(T value)
Counts the number of set bits in a variable.
constexpr T KillFirstBit(T value)
Clear the first bit in an integer.
const BridgeSpec * GetBridgeSpec(BridgeType i)
Get the specification of a bridge type.
BridgeType GetBridgeType(Tile t)
Determines the type of bridge on a tile.
bool IsValidCargoID(CargoID t)
Test whether cargo type is not INVALID_CARGO.
bool IsCargoInClass(CargoID c, CargoClass cc)
Does cargo c have cargo class cc?
@ CC_PASSENGERS
Passengers.
static void NewEvent(CompanyID company, ScriptEvent *event)
Queue a new event for an AI.
Common return value for all commands.
bool Succeeded() const
Did this command succeed?
Money GetCost() const
The costs as made up to this moment.
bool Failed() const
Did this command fail?
static void NewEvent(class ScriptEvent *event)
Queue a new event for a Game Script.
RoadTypes powered_roadtypes
bitmask to the OTHER roadtypes on which a vehicle of THIS roadtype generates power
static constexpr TimerGameTick::Ticks DAY_TICKS
1 day is 74 ticks; TimerGameCalendar::date_fract used to be uint16_t and incremented by 885.
static Date date
Current date in days (day counter).
static Year year
Current year, starting at 0.
static constexpr int DAYS_IN_YEAR
days per year
static Date date
Current date in days (day counter).
uint StoredCount() const
Returns sum of cargo on board the vehicle (ie not only reserved).
Functions related to commands.
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
#define return_cmd_error(errcode)
Returns from a function with a specific StringID as error.
DoCommandFlag
List of flags for a command.
@ DC_NO_WATER
don't allow building on water
@ DC_EXEC
execute the given command
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.
Owner
Enum for all companies/owners.
Map related accessors for depots.
DepotID GetDepotIndex(Tile t)
Get the index of which depot is attached to the tile.
uint16_t DepotID
Type for the unique identifier of depots.
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 ChangeDir(Direction d, DirDiff delta)
Change a direction by a given difference.
bool IsDiagonalDirection(Direction dir)
Checks if a given Direction is diagonal.
Axis DiagDirToAxis(DiagDirection d)
Convert a DiagDirection to the axis.
DiagDirection DirToDiagDir(Direction dir)
Convert a Direction to a DiagDirection.
Direction
Defines the 8 directions on the map.
@ INVALID_DIR
Flag for an invalid direction.
DiagDirection
Enumeration for diagonal directions.
@ DIAGDIR_NE
Northeast, upper right on your monitor.
@ DIAGDIR_END
Used for iterations.
@ INVALID_DIAGDIR
Flag for an invalid DiagDirection.
DirDiff
Allow incrementing of Direction variables.
@ DIRDIFF_45LEFT
Angle of 45 degrees left.
@ DIRDIFF_REVERSE
One direction is the opposite of the other one.
@ DIRDIFF_45RIGHT
Angle of 45 degrees right.
@ DIRDIFF_SAME
Both directions faces to the same direction.
Money GetPrice(Price index, uint cost_factor, const GRFFile *grf_file, int shift)
Determine a certain price.
@ EXPENSES_ROADVEH_RUN
Running costs road vehicles.
EffectVehicle * CreateEffectVehicleRel(const Vehicle *v, int x, int y, int z, EffectVehicleType type)
Create an effect vehicle above a particular vehicle.
Functions related to effect vehicles.
@ EV_EXPLOSION_LARGE
Various explosions.
static const EngineID INVALID_ENGINE
Constant denoting an invalid engine.
uint16_t EngineID
Unique identification number of an engine.
@ ENGINE_EXCLUSIVE_PREVIEW
This vehicle is in the exclusive preview stage, either being used or being offered to a company.
Error reporting related functions.
fluid_settings_t * settings
FluidSynth settings handle.
Types for recording game performance data.
@ PFE_GL_ROADVEHS
Time spend processing road vehicles.
Base functions for all Games.
uint32_t SpriteID
The number of a sprite, without mapping bits and colourtables.
uint32_t PaletteID
The number of the palette.
@ AS_BRAKE
We want to stop.
@ GVF_SUPPRESS_IMPLICIT_ORDERS
Disable insertion and removal of automatic orders until the vehicle completes the real order.
TrackStatus GetTileTrackStatus(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
Returns information about trackdirs and signal states.
int GetSlopePixelZ(int x, int y, bool ground_vehicle)
Return world Z coordinate of a given point of a tile.
TileIndex TileAddByDir(TileIndex tile, Direction dir)
Adds a Direction to a tile.
static debug_inline uint TileY(TileIndex tile)
Get the Y component of a tile.
static debug_inline uint TileX(TileIndex tile)
Get the X component of a tile.
TileIndexDiff TileOffsByDiagDir(DiagDirection dir)
Convert a DiagDirection to a TileIndexDiff.
constexpr T abs(const T a)
Returns the absolute value of (scalar) variable.
constexpr T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
constexpr bool IsInsideMM(const T x, const size_t min, const size_t max) noexcept
Checks if a value is in an interval.
Base for the NewGRF implementation.
@ CBID_VEHICLE_LENGTH
Vehicle length, returns the amount of 1/8's the vehicle is shorter for trains and RVs.
static const uint CALLBACK_FAILED
Different values for Callback result evaluations.
void ErrorUnknownCallbackResult(uint32_t grfid, uint16_t cbid, uint16_t cb_res)
Record that a NewGRF returned an unknown/invalid callback result.
uint16_t GetVehicleCallback(CallbackID callback, uint32_t param1, uint32_t param2, EngineID engine, const Vehicle *v)
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.
bool PlayVehicleSound(const Vehicle *v, VehicleSoundEvent event, bool force)
Checks whether a NewGRF wants to play a different vehicle sound effect.
Functions related to NewGRF provided sounds.
@ VSE_START
Vehicle starting, i.e. leaving, the station.
Functions related to news.
void AddVehicleNewsItem(StringID string, NewsType type, VehicleID vehicle, StationID station=INVALID_STATION)
Adds a newsitem referencing a vehicle.
@ NT_ACCIDENT_OTHER
An accident or disaster has occurred.
@ NT_ARRIVAL_COMPANY
First vehicle arrived for company.
@ NT_ARRIVAL_OTHER
First vehicle arrived for competitor.
@ NT_ACCIDENT
An accident or disaster has occurred.
bool ProcessOrders(Vehicle *v)
Handle the orders of a vehicle and determine the next place to go to if needed.
void CheckOrders(const Vehicle *v)
Check the orders of a vehicle, to see if there are invalid orders and stuff.
@ ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS
The vehicle will not stop at any stations it passes except the destination.
@ ODTFB_SERVICE
This depot order is because of the servicing limit.
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.
RoadBits AxisToRoadBits(Axis a)
Create the road-part which belongs to the given Axis.
RoadBits DiagDirToRoadBits(DiagDirection d)
Create the road-part which belongs to the given DiagDirection.
RoadBits GetAnyRoadBits(Tile tile, RoadTramType rtt, bool straight_tunnel_bridge_entrance)
Returns the RoadBits on an arbitrary tile Special behaviour:
static debug_inline bool IsNormalRoadTile(Tile t)
Return whether a tile is a normal road tile.
static debug_inline bool IsRoadDepot(Tile t)
Return whether a tile is a road depot.
bool IsLevelCrossingTile(Tile t)
Return whether a tile is a level crossing tile.
RoadBits GetRoadBits(Tile t, RoadTramType rtt)
Get the present road bits for a specific road type.
bool HasTileAnyRoadType(Tile t, RoadTypes rts)
Check if a tile has one of the specified road types.
DisallowedRoadDirections GetDisallowedRoadDirections(Tile t)
Gets the disallowed directions.
DiagDirection GetRoadDepotDirection(Tile t)
Get the direction of the exit of a road depot.
static debug_inline bool IsRoadDepotTile(Tile t)
Return whether a tile is a road depot tile.
bool HasRoadWorks(Tile t)
Check if a tile has road works.
RoadBits
Enumeration for the road parts on a tile.
@ ROAD_SW
South-west part.
@ ROAD_NONE
No road-part is build.
@ ROAD_NE
North-east part.
@ ROAD_SE
South-east part.
@ ROAD_Y
Full road along the y-axis (north-west + south-east)
@ ROAD_NW
North-west part.
@ ROAD_X
Full road along the x-axis (south-west + north-east)
RoadType
The different roadtypes we support.
@ DRD_NONE
None of the directions are disallowed.
Base class for roadstops.
static const uint RDE_TURNED
We just finished turning.
static const uint8_t RV_OVERTAKE_TIMEOUT
The number of ticks a vehicle has for overtaking.
@ RVSB_IN_DT_ROAD_STOP
The vehicle is in a drive-through road stop.
@ RVS_ENTERED_STOP
Only set when a vehicle has entered the stop.
@ RVSB_IN_ROAD_STOP
The vehicle is in a road stop.
@ RVSB_ROAD_STOP_TRACKDIR_MASK
Only bits 0 and 3 are used to encode the trackdir for road stops.
@ RVS_IN_DT_ROAD_STOP
The vehicle is in a drive-through road stop.
@ RVSB_TRACKDIR_MASK
The mask used to extract track dirs.
@ RVSB_DRIVE_SIDE
The vehicle is at the opposite side of the road.
@ RVSB_IN_DEPOT
The vehicle is in a depot.
@ RVSB_WORMHOLE
The vehicle is in a tunnel and/or bridge.
@ RVS_DRIVE_SIDE
Only used when retrieving move data.
static const uint RDE_NEXT_TILE
State information about the Road Vehicle controller.
static Vehicle * EnumCheckRoadVehCrashTrain(Vehicle *v, void *data)
Check routine whether a road and a train vehicle have collided.
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).
void DrawRoadVehEngine(int left, int right, int preferred_x, int y, EngineID engine, PaletteID pal, EngineImageType image_type)
Draw a road vehicle engine.
static Trackdir RoadFindPathToDest(RoadVehicle *v, TileIndex tile, DiagDirection enterdir)
Returns direction to for a road vehicle to take or INVALID_TRACKDIR if the direction is currently blo...
static void DeleteLastRoadVeh(RoadVehicle *v)
Delete last vehicle of a chain road vehicles.
CommandCost CmdBuildRoadVehicle(DoCommandFlag flags, TileIndex tile, const Engine *e, Vehicle **ret)
Build a road vehicle.
CommandCost CmdTurnRoadVeh(DoCommandFlag flags, VehicleID veh_id)
Turn a roadvehicle around.
Command definitions related to road vehicles.
Data about how a road vehicle must drive on a tile.
const uint8_t _road_stop_stop_frame[]
Table of road stop stop frames, when to stop at a road stop.
A number of safeguards to prevent using unsafe methods.
GameSettings _settings_game
Game settings of a running game or the scenario editor.
ClientSettings _settings_client
The current settings for this game.
Functions related to sound.
@ SND_19_DEPARTURE_OLD_RV_1
23 == 0x17 Station departure: truck and old bus (1) (non-toyland)
@ SND_12_EXPLOSION
16 == 0x10 Destruction, crashes, disasters, ...
@ SND_1A_DEPARTURE_OLD_RV_2
24 == 0x18 Station departure: truck and old bus (2) (random variation of SND_19_DEPARTURE_OLD_RV_1) (...
Functions to cache sprites in memory.
static const PaletteID PALETTE_CRASH
Recolour sprite greying of crashed vehicles.
Base classes/functions for stations.
bool IsBayRoadStopTile(Tile t)
Is tile t a bay (non-drive through) road stop station?
bool IsDriveThroughStopTile(Tile t)
Is tile t a drive through road stop station or waypoint?
StationID GetStationIndex(Tile t)
Get StationID from a tile.
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.
RoadStopType
Types of RoadStops.
@ ROADSTOP_BUS
A standard stop for buses.
@ ROADSTOP_TRUCK
A standard stop for trucks.
@ HVOT_TRUCK
Station has seen a truck.
@ HVOT_BUS
Station has seen a bus.
Definition of base types and functions in a cross-platform compatible way.
#define lengthof(array)
Return the length of an fixed size array.
void SetDParam(size_t n, uint64_t v)
Set a string parameter v at index n in the global string parameter array.
Functions related to OTTD's strings.
uint32_t StringID
Numeric value that represents a string, independent of the selected language.
Class to backup a specific variable and restore it later.
void Restore()
Restore the variable.
TimerGameTick::Ticks current_order_time
How many ticks have passed since this order started.
uint16_t vehicle_flags
Used for gradual loading and other miscellaneous things (.
void ResetDepotUnbunching()
Resets all the data used for depot unbunching.
TileIndex xy
Base tile of the station.
VehicleType type
Type of vehicle.
uint16_t speed
maximum travel speed (1 unit = 1/1.6 mph = 1 km-ish/h)
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo ID.
SoundSettings sound
sound effect settings
Structure to return information about the closest depot location, and whether it could be found.
uint16_t cargo_age_period
Number of ticks before carried cargo is aged.
CargoID GetDefaultCargoType() const
Determines the default cargo type of an engine.
uint32_t GetGRFID() const
Retrieve the GRF ID of the NewGRF the engine is tied to.
uint16_t reliability_spd_dec
Speed of reliability decay between services (per day).
uint8_t original_image_index
Original vehicle image index, thus the image index of the overridden vehicle.
const GRFFile * GetGRF() const
Retrieve the NewGRF the engine is tied to.
TimerGameCalendar::Date GetLifeLengthInDays() const
Returns the vehicle's (not model's!) life length in days.
uint16_t reliability
Current reliability of the engine.
uint8_t flags
Flags of the engine.
Helper container to find a depot.
uint best_length
The distance towards the depot in penalty, or UINT_MAX if not found.
TileIndex tile
The tile of the depot.
PathfinderSettings pf
settings for all pathfinders
VehicleSettings vehicle
options for vehicles
Position information of a vehicle after it moved.
TileIndex new_tile
Tile of the vehicle after moving.
int y
x and y position of the vehicle after moving
EngineID first_engine
Cached EngineID of the front vehicle. INVALID_ENGINE for the front vehicle itself.
uint16_t cached_total_length
Length of the whole vehicle (valid only for the first engine).
uint8_t cached_veh_length
Length of this vehicle in units of 1/VEHICLE_LENGTH of normal length. It is cached because this can b...
uint16_t cached_max_track_speed
Maximum consist speed (in internal units) limited by track type (valid only for the first engine).
bool IsChainInDepot() const override
Check whether the whole vehicle chain is in the depot.
int UpdateInclination(bool new_tile, bool update_delta)
Checks if the vehicle is in a slope and sets the required flags in that case.
GroundVehicleCache gcache
Cache of often calculated values.
void CargoChanged()
Recalculates the cached weight of a vehicle and its parts.
void SetFrontEngine()
Set front engine state.
uint Crash(bool flooded) override
Common code executed for crashed ground vehicles.
uint DoUpdateSpeed(uint accel, int min_speed, int max_speed)
Update the speed of the vehicle.
int GetAcceleration() const
Calculates the acceleration of the vehicle under its current conditions.
void SetLastSpeed()
Update the GUI variant of the current speed of the vehicle.
VehicleSpriteSeq sprite_seq
Vehicle appearance.
uint16_t GetMaxSpeed() const
Get the maxmimum speed in km-ish/h a vehicle is allowed to reach on the way to the destination.
DestinationID GetDestination() const
Gets the destination of this order.
bool IsType(OrderType type) const
Check whether this order is of the given type.
void MakeDummy()
Makes this order a Dummy order.
void MakeGoToDepot(DepotID destination, OrderDepotTypeFlags order, OrderNonStopFlags non_stop_type=ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS, OrderDepotActionFlags action=ODATF_SERVICE_ONLY, CargoID cargo=CARGO_NO_REFIT)
Makes this order a Go To Depot order.
void Free()
'Free' the order
bool ShouldStopAtStation(const Vehicle *v, StationID station) const
Check whether the given vehicle should stop at the given station based on this order and the non-stop...
OrderNonStopFlags GetNonStopType() const
At which stations must we stop?
YAPFSettings yapf
pathfinder settings for the yet another pathfinder
bool roadveh_queue
buggy road vehicle queueing
Coordinates of a point in 2D.
Tindex index
Index of this pool item.
static Titem * Get(size_t index)
Returns Titem with given index.
Specification of a rectangle with absolute coordinates of all edges.
int Width() const
Get width of Rect.
int Height() const
Get height of Rect.
A Stop for a Road Vehicle.
void SetEntranceBusy(bool busy)
Makes an entrance occupied or free.
void Leave(RoadVehicle *rv)
Leave the road stop.
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...
static RoadStop * GetByTile(TileIndex tile, RoadStopType type)
Find a roadstop at given tile.
Information about a road vehicle.
uint16_t max_speed
Maximum speed (1 unit = 1/3.2 mph = 0.5 km-ish/h)
RoadType roadtype
Road type.
uint8_t shorten_factor
length on main map for this type is 8 - shorten_factor
Buses, trucks and trams belong to this class.
uint Crash(bool flooded=false) override
Crash the (whole) vehicle chain.
void OnNewEconomyDay() override
Economy day handler.
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.
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.
AccelStatus GetAccelerationStatus() const
Checks the current acceleration status of this vehicle.
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.
bool IsBus() const
Check whether a roadvehicle is a bus.
uint8_t overtaking_ctr
The length of the current overtake attempt.
void OnNewCalendarDay() override
Calandar day handler.
bool IsInDepot() const override
Check whether the vehicle is in the depot.
RoadVehPathCache path
Cached path.
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.
uint8_t overtaking
Set to RVSB_DRIVE_SIDE when overtaking, otherwise 0.
int UpdateSpeed()
This function looks at the vehicle and updates its speed (cur_speed and subspeed) variables.
bool Tick() override
Calls the tick handler of the vehicle.
ClosestDepot FindClosestDepot() override
Find the closest depot for this vehicle and tell us the location, DestinationID and whether we should...
void MarkDirty() override
Marks the vehicles to be redrawn and updates cached variables.
bool disaster
Play disaster and accident sounds.
static Station * Get(size_t index)
Gets station with given index.
static Station * GetByTile(TileIndex tile)
Get the station belonging to a specific tile.
T * Previous() const
Get previous vehicle in the chain.
static T * From(Vehicle *v)
Converts a Vehicle to SpecializedVehicle with type checking.
T * Next() const
Get next vehicle in the chain.
void UpdateViewport(bool force_update, bool update_delta)
Update vehicle sprite- and position caches.
T * First() const
Get the first vehicle in the chain.
static T * GetIfValid(size_t index)
Returns vehicle if the index is a valid index for this vehicle type.
uint16_t cached_max_speed
Maximum speed of the consist (minimum of the max speed of all vehicles in the consist).
uint8_t roadveh_acceleration_model
realistic acceleration for road vehicles
uint8_t road_side
the side of the road vehicles drive on
Sprite sequence for a vehicle part.
void GetBounds(Rect *bounds) const
Determine shared bounds of all sprites.
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.
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.
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.
Vehicle * First() const
Get the first vehicle of this vehicle chain.
uint8_t x_extent
x-extent of vehicle bounding box
TimerGameEconomy::Date date_of_last_service
Last economy date the vehicle had a service at a depot.
uint16_t cargo_cap
total capacity
StationID last_loading_station
Last station the vehicle has stopped at and could possibly leave from with any cargo loaded.
uint16_t random_bits
Bits used for randomized variational spritegroups.
uint8_t day_counter
Increased by one for each day.
void HandleLoading(bool mode=false)
Handle the loading of the vehicle; when not it skips through dummy orders and does nothing in all oth...
Money profit_this_year
Profit this year << 8, low 8 bits are fract.
bool HasArticulatedPart() const
Check if an engine has an articulated part.
SpriteID colourmap
NOSAVE: cached colour mapping.
uint8_t breakdown_ctr
Counter for managing breakdown events.
uint GetAdvanceDistance()
Determines the vehicle "progress" needed for moving a step.
uint8_t z_extent
z-extent of vehicle bounding box
TimerGameCalendar::Date date_of_last_service_newgrf
Last calendar date the vehicle had a service at a depot, unchanged by the date cheat to protect again...
bool IsArticulatedPart() const
Check if the vehicle is an articulated part of an engine.
void LeaveUnbunchingDepot()
Leave an unbunching depot and calculate the next departure time for shared order vehicles.
int8_t y_offs
y offset for vehicle sprite
debug_inline bool IsFrontEngine() const
Check if the vehicle is a front engine.
int8_t x_bb_offs
x offset of vehicle bounding box
Order current_order
The current order (+ status, like: loading)
CargoID cargo_type
type of cargo this vehicle is carrying
void HandlePathfindingResult(bool path_found)
Handle the pathfinding result, especially the lost status.
int8_t x_offs
x offset for vehicle sprite
int32_t y_pos
y coordinate.
int32_t x_pos
x coordinate.
uint8_t y_extent
y-extent of vehicle bounding box
uint16_t refit_cap
Capacity left over from before last refit.
void InvalidateNewGRFCache()
Invalidates cached NewGRF variables.
VehicleCache vcache
Cache of often used vehicle values.
int8_t y_bb_offs
y offset of vehicle bounding box
void BeginLoading()
Prepare everything to begin the loading when arriving at a station.
uint8_t spritenum
currently displayed sprite index 0xfd == custom sprite, 0xfe == custom second head sprite 0xff == res...
uint16_t cur_speed
current speed
bool IsWaitingForUnbunching() const
Check whether a vehicle inside a depot is waiting for unbunching.
void SetNext(Vehicle *next)
Set the next vehicle of this vehicle.
TimerGameCalendar::Date max_age
Maximum age.
MutableSpriteCache sprite_cache
Cache of sprites and values related to recalculating them, see MutableSpriteCache.
uint16_t reliability
Reliability.
bool HandleBreakdown()
Handle all of the aspects of a vehicle breakdown This includes adding smoke and sounds,...
uint8_t progress
The percentage (if divided by 256) this vehicle already crossed the tile unit.
uint16_t reliability_spd_dec
Reliability decrease speed.
uint8_t tick_counter
Increased by one for each tick.
virtual bool IsInDepot() const
Check whether the vehicle is in the depot.
TileIndex tile
Current tile index.
TileIndex dest_tile
Heading for this tile.
void UpdatePosition()
Update the position of the vehicle.
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.
TimerGameCalendar::Year build_year
Year the vehicle has been built.
Owner owner
Which company owns the vehicle?
bool NeedsAutomaticServicing() const
Checks if the current order should be interrupted for a service-in-depot order.
uint8_t running_ticks
Number of ticks this vehicle was not stopped this day.
uint32_t maximum_go_to_depot_penalty
What is the maximum penalty that may be endured for going to a depot.
@ VETS_CANNOT_ENTER
The vehicle cannot enter the tile.
@ VETS_ENTERED_WORMHOLE
The vehicle either entered a bridge, tunnel or depot tile (this includes the last tile of the bridge/...
VehicleEnterTileStatus VehicleEnterTile(Vehicle *v, TileIndex tile, int x, int y)
Call the tile callback function for a vehicle entering a tile.
bool IsTileOwner(Tile tile, Owner owner)
Checks if a tile belongs to the given owner.
Owner GetTileOwner(Tile tile)
Returns the owner of a tile.
static debug_inline bool IsTileType(Tile tile, TileType type)
Checks if a tile is a given tiletype.
static const uint TILE_SIZE
Tile size in world coordinates.
@ MP_ROAD
A tile with road (or tram tracks)
@ MP_STATION
A tile of a station.
@ MP_TUNNELBRIDGE
Tunnel entry/exit and bridge heads.
Definition of the game-calendar-timer.
Definition of the game-economy-timer.
TrackdirBits TrackStatusToTrackdirBits(TrackStatus ts)
Returns the present-trackdir-information of a TrackStatus.
bool IsReversingRoadTrackdir(Trackdir dir)
Checks whether the trackdir means that we are reversing.
TrackdirBits DiagdirReachesTrackdirs(DiagDirection diagdir)
Returns all trackdirs that can be reached when entering a tile from a given (diagonal) direction.
bool IsStraightRoadTrackdir(Trackdir dir)
Checks whether the given trackdir is a straight road.
Trackdir DiagDirToDiagTrackdir(DiagDirection diagdir)
Maps a (4-way) direction to the diagonal trackdir that runs in that direction.
TrackdirBits TrackStatusToRedSignals(TrackStatus ts)
Returns the red-signal-information of a TrackStatus.
TrackBits TrackdirBitsToTrackBits(TrackdirBits bits)
Discards all directional information from a TrackdirBits value.
TrackBits
Allow incrementing of Track variables.
@ TRACK_BIT_CROSS
X-Y-axis cross.
Trackdir
Enumeration for tracks and directions.
@ TRACKDIR_RVREV_NE
(Road vehicle) reverse direction north-east
@ TRACKDIR_LOWER_E
Lower track and direction to east.
@ TRACKDIR_RIGHT_N
Right track and direction to north.
@ INVALID_TRACKDIR
Flag for an invalid trackdir.
@ TRACKDIR_UPPER_E
Upper track and direction to east.
@ TRACKDIR_LEFT_S
Left track and direction to south.
@ TRACKDIR_UPPER_W
Upper track and direction to west.
@ TRACKDIR_RVREV_SE
(Road vehicle) reverse direction south-east
@ TRACKDIR_LOWER_W
Lower track and direction to west.
@ TRACKDIR_END
Used for iterations.
@ TRACKDIR_RIGHT_S
Right track and direction to south.
@ TRACKDIR_RVREV_NW
(Road vehicle) reverse direction north-west
@ TRACKDIR_RVREV_SW
(Road vehicle) reverse direction south-west
@ TRACKDIR_LEFT_N
Left track and direction to north.
TrackdirBits
Allow incrementing of Trackdir variables.
@ TRACKDIR_BIT_NONE
No track build.
@ TRANSPORT_ROAD
Transport by road vehicle.
Functions that have tunnels and bridges in common.
DiagDirection GetTunnelBridgeDirection(Tile t)
Get the direction pointing to the other end.
TileIndex GetOtherTunnelBridgeEnd(Tile t)
Determines type of the wormhole and returns its other end.
void VehicleEnterDepot(Vehicle *v)
Vehicle entirely entered the depot, update its status, orders, vehicle windows, service it,...
bool HasVehicleOnPosXY(int x, int y, void *data, VehicleFromPosProc *proc)
Checks whether a vehicle in on a specific location.
void VehicleLengthChanged(const Vehicle *u)
Logs a bug in GRF and shows a warning message if this is for the first time this happened.
void VehicleServiceInDepot(Vehicle *v)
Service a vehicle and all subsequent vehicles in the consist.
void FindVehicleOnPosXY(int x, int y, void *data, VehicleFromPosProc *proc)
Find a vehicle from a specific location.
GetNewVehiclePosResult GetNewVehiclePos(const Vehicle *v)
Get position information of a vehicle when moving one pixel in the direction it is facing.
bool HasVehicleOnPos(TileIndex tile, void *data, VehicleFromPosProc *proc)
Checks whether a vehicle is on a specific location.
void FindVehicleOnPos(TileIndex tile, void *data, VehicleFromPosProc *proc)
Find a vehicle from a specific location.
void DecreaseVehicleValue(Vehicle *v)
Decrease the value of a vehicle.
void EconomyAgeVehicle(Vehicle *v)
Update economy age of a vehicle.
bool CanVehicleUseStation(EngineID engine_type, const Station *st)
Can this station be used by the given engine type?
void AgeVehicle(Vehicle *v)
Update age of a vehicle.
@ VF_BUILT_AS_PROTOTYPE
Vehicle is a prototype (accepted as exclusive preview).
@ VS_STOPPED
Vehicle is stopped by the player.
@ VS_HIDDEN
Vehicle is not visible.
@ VS_CRASHED
Vehicle is crashed.
@ VS_DEFPAL
Use default vehicle palette.
Functions related to vehicles.
EngineImageType
Visualisation contexts of vehicles and engines.
@ VEH_ROAD
Road vehicle type.
@ VEH_TRAIN
Train vehicle type.
uint32_t VehicleID
The type all our vehicle IDs have.
static const uint VEHICLE_LENGTH
The length of a vehicle in tile units.
void SetWindowClassesDirty(WindowClass cls)
Mark all windows of a particular class as dirty (in need of repainting)
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-...
void SetWindowWidgetDirty(WindowClass cls, WindowNumber number, WidgetID widget_index)
Mark a particular widget in a particular window as dirty (in need of repainting)
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
@ WC_ROADVEH_LIST
Road vehicle list; Window numbers:
@ WC_VEHICLE_DEPOT
Depot view; Window numbers:
@ WC_VEHICLE_DETAILS
Vehicle details; Window numbers:
@ WC_VEHICLE_VIEW
Vehicle view; Window numbers:
Entry point for OpenTTD to YAPF.
Trackdir YapfRoadVehicleChooseTrack(const RoadVehicle *v, TileIndex tile, DiagDirection enterdir, TrackdirBits trackdirs, bool &path_found, RoadVehPathCache &path_cache)
Finds the best path for given road vehicle using YAPF.
FindDepotData YapfRoadVehicleFindNearestDepot(const RoadVehicle *v, int max_penalty)
Used when user sends road vehicle to the nearest depot or if road vehicle needs servicing using YAPF.
Functions related to zooming.
int ScaleSpriteTrad(int value)
Scale traditional pixel dimensions to GUI zoom level, for drawing sprites.
int UnScaleGUI(int value)
Short-hand to apply GUI zoom level.