56 #include "table/strings.h" 61 static const uint GEN_HASHX_BITS = 6;
62 static const uint GEN_HASHY_BITS = 6;
65 static const uint GEN_HASHX_BUCKET_BITS = 7;
66 static const uint GEN_HASHY_BUCKET_BITS = 6;
69 #define GEN_HASHX(x) GB((x), GEN_HASHX_BUCKET_BITS + ZOOM_LVL_SHIFT, GEN_HASHX_BITS) 70 #define GEN_HASHY(y) (GB((y), GEN_HASHY_BUCKET_BITS + ZOOM_LVL_SHIFT, GEN_HASHY_BITS) << GEN_HASHX_BITS) 71 #define GEN_HASH(x, y) (GEN_HASHY(y) + GEN_HASHX(x)) 74 static const int GEN_HASHX_SIZE = 1 << (GEN_HASHX_BUCKET_BITS + GEN_HASHX_BITS + ZOOM_LVL_SHIFT);
75 static const int GEN_HASHY_SIZE = 1 << (GEN_HASHY_BUCKET_BITS + GEN_HASHY_BITS + ZOOM_LVL_SHIFT);
78 static const int GEN_HASHX_INC = 1;
79 static const int GEN_HASHY_INC = 1 << GEN_HASHX_BITS;
82 static const uint GEN_HASHX_MASK = (1 << GEN_HASHX_BITS) - 1;
83 static const uint GEN_HASHY_MASK = ((1 << GEN_HASHY_BITS) - 1) << GEN_HASHX_BITS;
101 bounds->left = bounds->top = bounds->right = bounds->bottom = 0;
102 for (uint i = 0; i < this->count; ++i) {
105 bounds->left = spr->
x_offs;
106 bounds->top = spr->
y_offs;
110 if (spr->
x_offs < bounds->left) bounds->left = spr->
x_offs;
111 if (spr->
y_offs < bounds->top) bounds->top = spr->
y_offs;
114 if (right > bounds->right) bounds->right = right;
115 if (bottom > bounds->bottom) bounds->bottom = bottom;
129 for (uint i = 0; i < this->count; ++i) {
130 PaletteID pal = force_pal || !this->seq[i].
pal ? default_pal : this->seq[i].
pal;
192 if (this->ServiceIntervalIsPercent() ?
193 (this->reliability >= this->GetEngine()->reliability * (100 - this->GetServiceInterval()) / 100) :
194 (this->date_of_last_service + this->GetServiceInterval() >=
_date)) {
208 bool pending_replace =
false;
210 if (needed_money > c->
money)
return false;
213 bool replace_when_old =
false;
219 if (replace_when_old && !v->NeedsAutorenewing(c,
false))
continue;
222 uint32 available_cargo_types, union_mask;
225 if (union_mask != 0) {
233 if (!
HasBit(available_cargo_types, cargo_type))
continue;
239 pending_replace =
true;
240 needed_money += 2 *
Engine::Get(new_engine)->GetCost();
241 if (needed_money > c->
money)
return false;
244 return pending_replace;
254 if (this->HasDepotOrder())
return false;
255 if (this->current_order.IsType(OT_LOADING))
return false;
256 if (this->current_order.IsType(OT_GOTO_DEPOT) && this->current_order.GetDepotOrderType() !=
ODTFB_SERVICE)
return false;
257 return NeedsServicing();
263 assert(this->Previous() == NULL);
267 if (this->IsPrimaryVehicle()) this->vehstatus |=
VS_STOPPED;
269 for (
Vehicle *v =
this; v != NULL; v = v->
Next()) {
273 v->MarkAllViewportsDirty();
282 delete this->cargo_payment;
283 assert(this->cargo_payment == NULL);
303 if (grfconfig == NULL)
return;
317 GetString(buffer, part1,
lastof(buffer));
318 DEBUG(grf, 0,
"%s", buffer + 3);
321 GetString(buffer, part2,
lastof(buffer));
322 DEBUG(grf, 0,
"%s", buffer + 3);
350 this->fill_percent_te_id = INVALID_TE_ID;
352 this->colourmap = PAL_NONE;
353 this->cargo_age_counter = 1;
354 this->last_station_visited = INVALID_STATION;
355 this->last_loading_station = INVALID_STATION;
364 return GB(Random(), 0, 8);
369 const int HASH_BITS = 7;
370 const int HASH_SIZE = 1 << HASH_BITS;
371 const int HASH_MASK = HASH_SIZE - 1;
372 const int TOTAL_HASH_SIZE = 1 << (HASH_BITS * 2);
373 const int TOTAL_HASH_MASK = TOTAL_HASH_SIZE - 1;
377 const int HASH_RES = 0;
379 static Vehicle *_vehicle_tile_hash[TOTAL_HASH_SIZE];
381 static Vehicle *VehicleFromTileHash(
int xl,
int yl,
int xu,
int yu,
void *data, VehicleFromPosProc *proc,
bool find_first)
383 for (
int y = yl; ; y = (y + (1 << HASH_BITS)) & (HASH_MASK << HASH_BITS)) {
384 for (
int x = xl; ; x = (x + 1) & HASH_MASK) {
385 Vehicle *v = _vehicle_tile_hash[(x + y) & TOTAL_HASH_MASK];
388 if (find_first && a != NULL)
return a;
412 const int COLL_DIST = 6;
415 int xl =
GB((x - COLL_DIST) /
TILE_SIZE, HASH_RES, HASH_BITS);
416 int xu =
GB((x + COLL_DIST) /
TILE_SIZE, HASH_RES, HASH_BITS);
417 int yl =
GB((y - COLL_DIST) /
TILE_SIZE, HASH_RES, HASH_BITS) << HASH_BITS;
418 int yu =
GB((y + COLL_DIST) /
TILE_SIZE, HASH_RES, HASH_BITS) << HASH_BITS;
420 return VehicleFromTileHash(xl, yl, xu, yu, data, proc, find_first);
470 int x =
GB(
TileX(tile), HASH_RES, HASH_BITS);
471 int y =
GB(
TileY(tile), HASH_RES, HASH_BITS) << HASH_BITS;
473 Vehicle *v = _vehicle_tile_hash[(x + y) & TOTAL_HASH_MASK];
475 if (v->
tile != tile)
continue;
478 if (find_first && a != NULL)
return a;
528 if (v->
z_pos > z)
return NULL;
555 if (v == (
const Vehicle *)data)
return NULL;
587 if ((t->track != rail_bits) && !
TracksOverlap(t->track | rail_bits))
return NULL;
611 static void UpdateVehicleTileHash(
Vehicle *v,
bool remove)
620 int y =
GB(
TileY(v->
tile), HASH_RES, HASH_BITS) << HASH_BITS;
621 new_hash = &_vehicle_tile_hash[(x + y) & TOTAL_HASH_MASK];
624 if (old_hash == new_hash)
return;
627 if (old_hash != NULL) {
633 if (new_hash != NULL) {
644 static Vehicle *_vehicle_viewport_hash[1 << (GEN_HASHX_BITS + GEN_HASHY_BITS)];
646 static void UpdateVehicleViewportHash(
Vehicle *v,
int x,
int y)
648 Vehicle **old_hash, **new_hash;
649 int old_x = v->
coord.left;
650 int old_y = v->
coord.top;
652 new_hash = (x ==
INVALID_COORD) ? NULL : &_vehicle_viewport_hash[GEN_HASH(x, y)];
653 old_hash = (old_x ==
INVALID_COORD) ? NULL : &_vehicle_viewport_hash[GEN_HASH(old_x, old_y)];
655 if (old_hash == new_hash)
return;
658 if (old_hash != NULL) {
664 if (new_hash != NULL) {
672 void ResetVehicleHash()
676 memset(_vehicle_viewport_hash, 0,
sizeof(_vehicle_viewport_hash));
677 memset(_vehicle_tile_hash, 0,
sizeof(_vehicle_tile_hash));
680 void ResetVehicleColourMap()
693 void InitializeVehicles()
695 _vehicles_to_autoreplace.
Reset();
699 uint CountVehiclesInChain(
const Vehicle *v)
702 do count++;
while ((v = v->
Next()) != NULL);
712 switch (this->type) {
715 return !this->IsArticulatedPart() &&
719 default:
return false;
729 switch (this->type) {
734 default:
return false;
755 return this->GetEngine()->GetGRF();
765 return this->GetEngine()->GetGRFID();
794 AI::NewEvent(this->owner,
new ScriptEventVehicleLost(this->index));
804 if (CleaningPool())
return;
808 st->loading_vehicles.remove(
this);
811 this->CancelReservation(INVALID_STATION, st);
812 delete this->cargo_payment;
813 assert(this->cargo_payment == NULL);
816 if (this->IsEngineCountable()) {
825 if (this->type ==
VEH_AIRCRAFT && this->IsPrimaryVehicle()) {
835 if (this->type ==
VEH_ROAD && this->IsPrimaryVehicle()) {
843 if (this->Previous() == NULL) {
847 if (this->IsPrimaryVehicle()) {
858 this->cargo.Truncate();
862 extern void StopGlobalFollowVehicle(
const Vehicle *v);
863 StopGlobalFollowVehicle(
this);
870 if (CleaningPool()) {
871 this->cargo.OnCleanPool();
884 UpdateVehicleTileHash(
this,
true);
914 if (_game_mode != GM_NORMAL)
return;
919 if (v == NULL)
continue;
925 if (
HasBit(callback, 0)) {
926 TriggerVehicle(v, VEHICLE_TRIGGER_CALLBACK_32);
942 void CallVehicleTicks()
944 _vehicles_to_autoreplace.
Clear();
1050 if (error_message == STR_ERROR_AUTOREPLACE_NOTHING_TO_DO || error_message ==
INVALID_STRING_ID)
continue;
1052 if (error_message == STR_ERROR_NOT_ENOUGH_CASH_REQUIRES_CURRENCY) error_message = STR_ERROR_AUTOREPLACE_MONEY_LIMIT;
1055 if (error_message == STR_ERROR_TRAIN_TOO_LONG_AFTER_REPLACEMENT) {
1056 message = error_message;
1058 message = STR_NEWS_VEHICLE_AUTORENEW_FAILED;
1090 for (uint i = 0; i < v->
sprite_seq.count; ++i) {
1106 const int l = dpi->left;
1107 const int r = dpi->left + dpi->width;
1108 const int t = dpi->top;
1109 const int b = dpi->top + dpi->height;
1120 xu = GEN_HASHX_MASK;
1129 yu = GEN_HASHY_MASK;
1132 for (
int y = yl;; y = (y + GEN_HASHY_INC) & GEN_HASHY_MASK) {
1133 for (
int x = xl;; x = (x + GEN_HASHX_INC) & GEN_HASHX_MASK) {
1134 const Vehicle *v = _vehicle_viewport_hash[x + y];
1138 l <= v->
coord.right &&
1139 t <= v->
coord.bottom &&
1140 r >= v->
coord.left &&
1141 b >= v->
coord.top) {
1164 uint dist, best_dist = UINT_MAX;
1166 if ((uint)(x -= vp->
left) >= (uint)vp->
width || (uint)(y -= vp->
top) >= (uint)vp->
height)
return NULL;
1173 x >= v->coord.left && x <= v->coord.right &&
1174 y >= v->coord.top && y <= v->coord.bottom) {
1177 abs(((v->coord.left + v->coord.right) >> 1) - x),
1178 abs(((v->coord.top + v->coord.bottom) >> 1) - y)
1181 if (dist < best_dist) {
1201 static const byte _breakdown_chance[64] = {
1202 3, 3, 3, 3, 3, 3, 3, 3,
1203 4, 4, 5, 5, 6, 6, 7, 7,
1204 8, 8, 9, 9, 10, 10, 11, 11,
1205 12, 13, 13, 13, 13, 14, 15, 16,
1206 17, 19, 21, 25, 28, 31, 34, 37,
1207 40, 44, 48, 52, 56, 60, 64, 68,
1208 72, 80, 90, 100, 110, 120, 130, 140,
1209 150, 170, 190, 210, 230, 250, 250, 250,
1212 void CheckVehicleBreakdown(
Vehicle *v)
1222 v->
cur_speed < 5 || _game_mode == GM_MENU) {
1226 uint32 r = Random();
1261 switch (this->breakdown_ctr) {
1266 this->breakdown_ctr = 1;
1268 if (this->breakdowns_since_last_service != 255) {
1269 this->breakdowns_since_last_service++;
1276 this->cur_speed = 0;
1281 (train_or_ship ? SND_10_TRAIN_BREAKDOWN : SND_0F_VEHICLE_BREAKDOWN) :
1282 (train_or_ship ? SND_3A_COMEDY_BREAKDOWN_2 : SND_35_COMEDY_BREAKDOWN),
this);
1301 if ((this->tick_counter & (this->type ==
VEH_TRAIN ? 3 : 1)) == 0) {
1302 if (--this->breakdown_delay == 0) {
1303 this->breakdown_ctr = 0;
1311 if (!this->current_order.IsType(OT_LOADING)) this->breakdown_ctr--;
1345 str = STR_NEWS_VEHICLE_IS_GETTING_OLD;
1346 }
else if (age == 0) {
1347 str = STR_NEWS_VEHICLE_IS_GETTING_VERY_OLD;
1349 str = STR_NEWS_VEHICLE_IS_GETTING_VERY_OLD_AND;
1373 bool loading =
false;
1379 assert(colour == NULL || (st != NULL && is_loading));
1385 for (
const Vehicle *v = front; v != NULL; v = v->
Next()) {
1388 if (v->
cargo_cap != 0 && colour != NULL) {
1390 loading |= !order_no_load &&
1397 if (colour != NULL) {
1398 if (unloading == 0 && loading) {
1399 *colour = STR_PERCENT_UP;
1400 }
else if (unloading == 0 && !loading) {
1401 *colour = STR_PERCENT_NONE;
1402 }
else if (cars == unloading || !loading) {
1403 *colour = STR_PERCENT_DOWN;
1405 *colour = STR_PERCENT_UP_DOWN;
1410 if (max == 0)
return 100;
1413 if (count * 2 < max) {
1415 return CeilDiv(count * 100, max);
1418 return (count * 100) /
max;
1429 assert(v == v->
First());
1465 default: NOT_REACHED();
1482 TriggerVehicle(v, VEHICLE_TRIGGER_DEPOT);
1505 _vehicles_to_autoreplace[v] =
false;
1511 }
else if (cost.
GetCost() != 0) {
1527 _vehicles_to_autoreplace[v] =
false;
1549 UpdateVehicleTileHash(
this,
false);
1560 this->sprite_seq.GetBounds(&new_coord);
1562 Point pt =
RemapCoords(this->x_pos + this->x_offs, this->y_pos + this->y_offs, this->z_pos);
1563 new_coord.left += pt.x;
1564 new_coord.top += pt.y;
1565 new_coord.right += pt.x + 2 * ZOOM_LVL_BASE;
1566 new_coord.bottom += pt.y + 2 * ZOOM_LVL_BASE;
1568 UpdateVehicleViewportHash(
this, new_coord.left, new_coord.top);
1570 Rect old_coord = this->coord;
1571 this->coord = new_coord;
1578 min(old_coord.left, this->coord.left),
1579 min(old_coord.top, this->coord.top),
1580 max(old_coord.right, this->coord.right),
1581 max(old_coord.bottom, this->coord.bottom));
1591 this->UpdatePosition();
1592 this->UpdateViewport(
true);
1610 static const int8 _delta_coord[16] = {
1611 -1,-1,-1, 0, 1, 1, 1, 0,
1612 -1, 0, 1, 1, 1, 0,-1,-1,
1626 static const Direction _new_direction_table[] = {
1636 if (y >= v->
y_pos) {
1637 if (y != v->
y_pos) i += 3;
1641 if (x >= v->
x_pos) {
1642 if (x != v->
x_pos) i++;
1679 if (v->
type == type && v->
owner == owner) {
1684 if (this->
maxid == 0)
return;
1689 this->
cache = CallocT<bool>(this->
maxid + 2);
1693 if (v->
type == type && v->
owner == owner) {
1702 if (this->maxid <= this->
curid)
return ++this->
curid;
1704 while (this->
cache[++this->curid]) { }
1723 default: NOT_REACHED();
1756 default: NOT_REACHED();
1763 FOR_ALL_ENGINES_OF_TYPE(e, type) {
1791 default: NOT_REACHED();
1796 engine_type = parent_engine_type;
1801 if (cargo_type ==
CT_INVALID) cargo_type = e->GetDefaultCargoType();
1802 if (cargo_type ==
CT_INVALID) cargo_type = CT_GOODS;
1806 return LS_PASSENGER_WAGON_STEAM;
1808 switch (RailVehInfo(parent_engine_type)->engclass) {
1809 default: NOT_REACHED();
1810 case EC_STEAM:
return LS_PASSENGER_WAGON_STEAM;
1811 case EC_DIESEL:
return LS_PASSENGER_WAGON_DIESEL;
1812 case EC_ELECTRIC:
return LS_PASSENGER_WAGON_ELECTRIC;
1813 case EC_MONORAIL:
return LS_PASSENGER_WAGON_MONORAIL;
1814 case EC_MAGLEV:
return LS_PASSENGER_WAGON_MAGLEV;
1818 return LS_FREIGHT_WAGON;
1823 switch (e->u.rail.engclass) {
1824 default: NOT_REACHED();
1826 case EC_DIESEL:
return is_mu ? LS_DMU : LS_DIESEL;
1827 case EC_ELECTRIC:
return is_mu ? LS_EMU : LS_ELECTRIC;
1836 engine_type = parent_engine_type;
1840 if (cargo_type ==
CT_INVALID) cargo_type = e->GetDefaultCargoType();
1841 if (cargo_type ==
CT_INVALID) cargo_type = CT_GOODS;
1853 if (cargo_type ==
CT_INVALID) cargo_type = e->GetDefaultCargoType();
1854 if (cargo_type ==
CT_INVALID) cargo_type = CT_GOODS;
1858 switch (e->u.air.subtype) {
1859 case AIR_HELI:
return LS_HELICOPTER;
1860 case AIR_CTOL:
return LS_SMALL_PLANE;
1861 case AIR_CTOL | AIR_FAST:
return LS_LARGE_PLANE;
1862 default: NOT_REACHED();
1888 if (!c->livery[scheme].
in_use) scheme = LS_DEFAULT;
1891 return &c->livery[scheme];
1900 if (map != PAL_NONE)
return map;
1909 assert_compile(PAL_NONE == 0);
1910 map =
GB(callback, 0, 14);
1913 if (!
HasBit(callback, 14)) {
1915 if (v != NULL)
const_cast<Vehicle *
>(v)->colourmap = map;
1931 if (twocc) map += livery->
colour2 * 16;
1934 if (v != NULL)
const_cast<Vehicle *
>(v)->colourmap = map;
1946 return GetEngineColourMap(engine_type, company,
INVALID_ENGINE, NULL);
1968 if (this->IsGroundVehicle()) {
1969 uint16 &gv_flags = this->GetGroundVehicleFlags();
1973 this->cur_implicit_order_index = this->cur_real_order_index;
1979 const Order *order = this->GetOrder(this->cur_implicit_order_index);
1980 while (order != NULL) {
1981 if (this->cur_implicit_order_index == this->cur_real_order_index)
break;
1983 if (order->
IsType(OT_IMPLICIT)) {
1984 DeleteOrder(
this, this->cur_implicit_order_index);
1986 order = this->GetOrder(this->cur_implicit_order_index);
1989 order = order->
next;
1990 this->cur_implicit_order_index++;
1994 if (order == NULL) {
1995 order = this->GetOrder(0);
1996 this->cur_implicit_order_index = 0;
2009 if (this->current_order.IsType(OT_GOTO_STATION) &&
2010 this->current_order.GetDestination() == this->last_station_visited) {
2011 this->DeleteUnreachedImplicitOrders();
2014 this->current_order.MakeLoading(
true);
2029 Order *in_list = this->GetOrder(this->cur_implicit_order_index);
2030 if (this->IsGroundVehicle() &&
2031 (in_list == NULL || !in_list->
IsType(OT_IMPLICIT) ||
2035 Order *prev_order = this->cur_implicit_order_index > 0 ? this->GetOrder(this->cur_implicit_order_index - 1) : (this->GetNumOrders() > 1 ? this->GetLastOrder() : NULL);
2036 if (prev_order == NULL ||
2037 (!prev_order->
IsType(OT_IMPLICIT) && !prev_order->
IsType(OT_GOTO_STATION)) ||
2045 int target_index = this->cur_implicit_order_index;
2047 while (target_index != this->cur_real_order_index || this->GetNumManualOrders() == 0) {
2048 const Order *order = this->GetOrder(target_index);
2049 if (order == NULL)
break;
2055 if (target_index >= this->orders.list->GetNumOrders()) {
2056 if (this->GetNumManualOrders() == 0 &&
2062 if (target_index == this->cur_implicit_order_index)
break;
2066 if (suppress_implicit_orders) {
2068 this->cur_implicit_order_index = target_index;
2072 const Order *order = this->GetOrder(this->cur_implicit_order_index);
2074 if (order->
IsType(OT_IMPLICIT)) {
2075 DeleteOrder(
this, this->cur_implicit_order_index);
2077 order = this->GetOrder(this->cur_implicit_order_index);
2080 order = order->
next;
2081 this->cur_implicit_order_index++;
2085 if (order == NULL) {
2086 order = this->GetOrder(0);
2087 this->cur_implicit_order_index = 0;
2089 assert(order != NULL);
2092 }
else if (!suppress_implicit_orders &&
2097 implicit_order->
MakeImplicit(this->last_station_visited);
2098 InsertOrder(
this, implicit_order, this->cur_implicit_order_index);
2099 if (this->cur_implicit_order_index > 0) --this->cur_implicit_order_index;
2103 uint16 &gv_flags = this->GetGroundVehicleFlags();
2108 this->current_order.MakeLoading(
false);
2111 if (this->last_loading_station != INVALID_STATION &&
2112 this->last_loading_station != this->last_station_visited &&
2113 ((this->current_order.GetLoadType() &
OLFB_NO_LOAD) == 0 ||
2126 this->cur_speed = 0;
2140 DEBUG(misc, 1,
"cancelling cargo reservation");
2154 assert(this->current_order.IsType(OT_LOADING));
2156 delete this->cargo_payment;
2157 assert(this->cargo_payment == NULL);
2162 if ((this->current_order.GetLoadType() &
OLFB_NO_LOAD) == 0 ||
2164 if (this->current_order.CanLeaveWithCargo(this->last_loading_station != INVALID_STATION)) {
2168 this->ResetRefitCaps();
2172 this->last_loading_station = this->last_station_visited;
2176 this->last_loading_station = INVALID_STATION;
2180 this->current_order.MakeLeaveStation();
2182 this->CancelReservation(INVALID_STATION, st);
2183 st->loading_vehicles.remove(
this);
2216 switch (this->current_order.GetType()) {
2218 uint wait_time =
max(this->current_order.GetTimetabledWait() - this->lateness_counter, 0);
2223 this->PlayLeaveStationSound();
2225 this->LeaveStation();
2228 const Order *order = this->GetOrder(this->cur_implicit_order_index);
2229 if (order == NULL ||
2230 (!order->
IsType(OT_IMPLICIT) && !order->
IsType(OT_GOTO_STATION)) ||
2237 case OT_DUMMY:
break;
2242 this->IncrementImplicitOrderIndex();
2251 for (
const Vehicle *v =
this; v != NULL; v = v->
Next()) {
2254 if (pair == capacities.
End()) {
2255 pair = capacities.
Append();
2264 uint Vehicle::GetConsistTotalCapacity()
const 2267 for (
const Vehicle *v =
this; v != NULL; v = v->
Next()) {
2282 if (ret.
Failed())
return ret;
2285 if (this->IsStoppedInDepot())
return CMD_ERROR;
2287 if (this->current_order.IsType(OT_GOTO_DEPOT)) {
2288 bool halt_in_depot = (this->current_order.GetDepotActionType() &
ODATFB_HALT) != 0;
2294 this->current_order.SetDepotOrderType(
ODTF_MANUAL);
2305 if (this->current_order.GetDepotOrderType() &
ODTFB_PART_OF_ORDERS) this->IncrementRealOrderIndex();
2307 if (this->IsGroundVehicle()) {
2308 uint16 &gv_flags = this->GetGroundVehicleFlags();
2312 this->current_order.MakeDummy();
2319 DestinationID destination;
2321 static const StringID no_depot[] = {STR_ERROR_UNABLE_TO_FIND_ROUTE_TO, STR_ERROR_UNABLE_TO_FIND_LOCAL_DEPOT, STR_ERROR_UNABLE_TO_FIND_LOCAL_DEPOT, STR_ERROR_CAN_T_SEND_AIRCRAFT_TO_HANGAR};
2322 if (!this->FindClosestDepot(&location, &destination, &reverse))
return_cmd_error(no_depot[this->type]);
2325 if (this->current_order.IsType(OT_LOADING)) this->LeaveStation();
2327 if (this->IsGroundVehicle() && this->GetNumManualOrders() > 0) {
2328 uint16 &gv_flags = this->GetGroundVehicleFlags();
2332 this->dest_tile = location;
2333 this->current_order.MakeGoToDepot(destination,
ODTF_MANUAL);
2361 const Engine *e = this->GetEngine();
2379 callback =
GB(callback, 0, 8);
2386 visual_effect = callback;
2410 this->vcache.cached_vis_effect = visual_effect;
2418 static const int8 _vehicle_smoke_pos[8] = {
2419 1, 1, 1, 0, -1, -1, -1, 0
2431 uint count =
GB(callback, 0, 2);
2432 bool auto_center =
HasBit(callback, 13);
2433 bool auto_rotate = !
HasBit(callback, 14);
2448 int8 x_center = _vehicle_smoke_pos[l_dir] * l_center;
2449 int8 y_center = _vehicle_smoke_pos[t_dir] * l_center;
2451 for (uint i = 0; i < count; i++) {
2453 uint type =
GB(reg, 0, 8);
2454 int8 x =
GB(reg, 8, 8);
2455 int8 y =
GB(reg, 16, 8);
2456 int8 z =
GB(reg, 24, 8);
2461 x = _vehicle_smoke_pos[l_dir] * l + _vehicle_smoke_pos[t_dir] * t;
2462 y = _vehicle_smoke_pos[t_dir] * l - _vehicle_smoke_pos[l_dir] * t;
2483 assert(this->IsPrimaryVehicle());
2493 this->cur_speed < 2) {
2498 uint max_speed = this->GetCurrentMaxSpeed();
2506 if (
HasBit(t->flags, VRF_REVERSING) ||
2522 if (effect_model >= VESM_END) effect_model =
VESM_NONE;
2549 switch (effect_model) {
2573 int power_weight_effect = 0;
2601 if (evt != EV_END && advanced) {
2604 }
else if (evt != EV_END) {
2612 int x = _vehicle_smoke_pos[v->
direction] * effect_offset;
2613 int y = _vehicle_smoke_pos[(v->
direction + 2) % 8] * effect_offset;
2622 }
while ((v = v->
Next()) != NULL);
2633 assert(
this != next);
2635 if (this->next != NULL) {
2637 for (
Vehicle *v = this->next; v != NULL; v = v->
Next()) {
2638 v->
first = this->next;
2645 if (this->next != NULL) {
2649 for (
Vehicle *v = this->next; v != NULL; v = v->
Next()) {
2650 v->
first = this->first;
2662 assert(this->previous_shared == NULL && this->next_shared == NULL);
2671 this->previous_shared = shared_chain;
2675 if (this->next_shared != NULL) this->next_shared->
previous_shared =
this;
2687 bool were_first = (this->FirstShared() ==
this);
2690 this->orders.list->RemoveVehicle(
this);
2694 this->previous_shared->next_shared = this->NextShared();
2697 if (this->next_shared != NULL) this->next_shared->previous_shared = this->previous_shared;
2700 if (this->orders.list->GetNumVehicles() == 1) {
2704 }
else if (were_first) {
2710 this->next_shared = NULL;
2711 this->previous_shared = NULL;
2714 void VehiclesYearlyLoop()
2721 if (v->
age >= 730 && profit < 0) {
2799 assert(this->IsGroundVehicle());
2814 assert(this->IsGroundVehicle());
2829 assert(this->IsGroundVehicle());
2844 assert(this->IsGroundVehicle());
2868 for (; u != NULL && num_vehicles > 0; num_vehicles--) {
2871 set.Include(u->
index);
void ViewportAddVehicles(DrawPixelInfo *dpi)
Add the vehicle sprites that should be drawn at a part of the screen.
Functions related to OTTD's strings.
void TriggerStationRandomisation(Station *st, TileIndex tile, StationRandomTrigger trigger, CargoID cargo_type)
Trigger station randomisation.
static TileType GetTileType(TileIndex tile)
Get the tiletype of a given tile.
bool HasVehicleOnPos(TileIndex tile, void *data, VehicleFromPosProc *proc)
Checks whether a vehicle is on a specific location.
VehicleSettings vehicle
options for vehicles
static bool HasPowerOnRail(RailType enginetype, RailType tiletype)
Checks if an engine of the given RailType got power on a tile with a given RailType.
Functions/types related to NewGRF debugging.
uint16 reliability
Current reliability of the engine.
CommandCost EnsureNoTrainOnTrackBits(TileIndex tile, TrackBits track_bits)
Tests if a vehicle interacts with the specified track bits.
uint32 PaletteID
The number of the palette.
static bool IsLocalCompany()
Is the current company the local company?
Vehicle * Previous() const
Get the previous vehicle of this vehicle.
Vehicle is stopped by the player.
VehicleCargoList cargo
The cargo this vehicle is carrying.
GameSettings _settings_game
Game settings of a running game or the scenario editor.
static void RunVehicleDayProc()
Increases the day counter for all vehicles and calls 1-day and 32-day handlers.
static Titem * GetIfValid(size_t index)
Returns Titem with given index.
uint32 motion_counter
counter to occasionally play a vehicle sound.
Money value
Value of the vehicle.
bool _networking
are we in networking mode?
int virtual_left
Virtual left coordinate.
void DecreaseVehicleValue(Vehicle *v)
Decrease the value of a vehicle.
static const uint CALLBACK_FAILED
Different values for Callback result evaluations.
void LoadUnloadStation(Station *st)
Load/unload the vehicles in this station according to the order they entered.
Data about how and where to blit pixels.
virtual void MarkDirty()
Marks the vehicles to be redrawn and updates cached variables.
The information about a vehicle list.
void ShowVisualEffect() const
Draw visual effects (smoke and/or sparks) for a vehicle chain.
bool UsesWagonOverride(const Vehicle *v)
Check if a wagon is currently using a wagon override.
Definition of link refreshing utility.
StationID targetairport
Airport to go to next.
static const int VEHICLE_PROFIT_MIN_AGE
Only vehicles older than this have a meaningful profit.
LiveryScheme
List of different livery schemes.
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
byte landscape
the landscape we're currently in
static bool Chance16I(const uint a, const uint b, const uint32 r)
Checks if a given randomize-number is below a given probability.
Money GetDisplayProfitThisYear() const
Gets the profit vehicle had this year.
DirectionByte direction
facing
Base class for roadstops.
Vehicle * hash_tile_next
NOSAVE: Next vehicle in the tile location hash.
Functions related to the autoreplace GUIs.
void ResetRefitCaps()
Reset all refit_cap in the consist to cargo_cap.
Train is just leaving a station.
Don't cancel current goto depot command if any.
const Pair * Find(const T &key) const
Finds given key in this map.
Vehicle has finished loading.
Functions and type for generating vehicle lists.
static RoadStopType GetRoadStopType(TileIndex t)
Get the road stop type of this tile.
static EngineID EngineReplacementForCompany(const Company *c, EngineID engine, GroupID group, bool *replace_when_old=NULL)
Retrieve the engine replacement for the given company and original engine type.
CommandCost EnsureNoVehicleOnGround(TileIndex tile)
Ensure there is no vehicle at the ground at the given position.
VehiclePool _vehicle_pool("Vehicle")
The pool with all our precious vehicles.
void InvalidateVehicleOrder(const Vehicle *v, int data)
Updates the widgets of a vehicle which contains the order-data.
Flag for an invalid DiagDirection.
void HandleAircraftEnterHangar(Aircraft *v)
Handle Aircraft specific tasks when an Aircraft enters a hangar.
int height
Screen height of the viewport.
static Titem * Get(size_t index)
Returns Titem with given index.
static Point RemapCoords(int x, int y, int z)
Map 3D world or tile coordinate to equivalent 2D coordinate as used in the viewports and smallmap...
Functions related to dates.
static bool IsInsideMM(const T x, const uint min, const uint max)
Checks if a value is in an interval.
Angle of 45 degrees left.
virtual uint Crash(bool flooded=false)
Crash the (whole) vehicle chain.
Vehicle ** hash_viewport_prev
NOSAVE: Previous vehicle in the visual location hash.
Conventional Take Off and Landing, i.e. planes.
static T ToggleBit(T &x, const uint8 y)
Toggles a bit in a variable.
void Reset()
Remove all items from the list and free allocated memory.
const AirportFTAClass * GetFTA() const
Get the finite-state machine for this airport or the finite-state machine for the dummy airport in ca...
Sparcs of electric engines.
byte breakdown_delay
Counter for managing breakdown length.
Use default vehicle palette.
Angle of 90 degrees right.
Vehicle is a shadow vehicle.
Base for the train class.
Other order modifications.
uint8 smoke_amount
amount of smoke/sparks locomotives produce
virtual ~Vehicle()
We want to 'destruct' the right class.
static T SetBit(T &x, const uint8 y)
Set a bit in a variable.
Called to spawn visual effects for vehicles.
void Leave(RoadVehicle *rv)
Leave the road stop.
byte pos
Next desired position of the aircraft.
void SetTransferLoadPlace(TileIndex xy)
Sets loaded_at_xy to the current station for all cargo to be transfered.
Can planes land on this airport type?
uint16 cur_speed
current speed
uint16 cached_cargo_age_period
Number of ticks before carried cargo is aged.
static void AddVehicleAdviceNewsItem(StringID string, VehicleID vehicle)
Adds a vehicle-advice news item.
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
Do not show black smoke during a breakdown.
Data structure describing a sprite.
Depot view; Window numbers:
uint16 cargo_age_counter
Ticks till cargo is aged next.
GRFFilePropsBase< NUM_CARGO+2 > grf_prop
Properties related the the grf file.
Functions to be called to log possibly unsafe game events.
Both directions faces to the same direction.
uint16 _returned_refit_capacity
Stores the capacity after a refit operation.
OrderList * list
Pointer to the order list for this vehicle.
Train * GetNextUnit() const
Get the next real (non-articulated part and non rear part of dualheaded engine) vehicle in the consis...
StationID last_loading_station
Last station the vehicle has stopped at and could possibly leave from with any cargo loaded...
byte visual_effect
Bitstuffed NewGRF visual effect data.
TileIndex dest_tile
Heading for this tile.
Vehicle ** hash_tile_prev
NOSAVE: Previous vehicle in the tile location hash.
uint16 wait_counter
Ticks waiting in front of a signal, ticks being stuck or a counter for forced proceeding through sign...
Implementation of simple mapping class.
Functions related to vehicles.
Aircraft, helicopters, rotors and their shadows belong to this class.
static bool IsWagon(EngineID index)
Determine whether an engine type is a wagon (and not a loco).
bool lost_vehicle_warn
if a vehicle can't find its destination, show a warning
void IncrementImplicitOrderIndex()
Increments cur_implicit_order_index, keeps care of the wrap-around and invalidates the GUI...
Trigger platform when train leaves.
void GetArticulatedRefitMasks(EngineID engine, bool include_initial_cargo_type, uint32 *union_mask, uint32 *intersection_mask)
Merges the refit_masks of all articulated parts.
static uint TileX(TileIndex tile)
Get the X component of a tile.
void VehicleEnterDepot(Vehicle *v)
Vehicle entirely entered the depot, update its status, orders, vehicle windows, service it...
const Livery * GetEngineLivery(EngineID engine_type, CompanyID company, EngineID parent_engine_type, const Vehicle *v, byte livery_setting)
Determines the livery for a vehicle.
void Draw(int x, int y, PaletteID default_pal, bool force_pal) const
Draw the sprite sequence.
UnitID max_aircraft
max planes in game per company
void Clear()
Remove all items from the list.
byte vehicle_breakdowns
likelihood of vehicles breaking down
Flags flags
Flags for this airport type.
void Change(const U &new_value)
Change the value of the variable.
static int ScaleByZoom(int value, ZoomLevel zoom)
Scale by zoom level, usually shift left (when zoom > ZOOM_LVL_NORMAL) When shifting right...
const T * Begin() const
Get the pointer to the first item (const)
Only service the vehicle.
void PreDestructor()
Destroy all stuff that (still) needs the virtual functions to work properly.
void LeaveStation()
Perform all actions when leaving a station.
DifficultySettings difficulty
settings related to the difficulty
TrackBitsByte state
The "track" the ship is following.
Tindex index
Index of this pool item.
Vehicle is flying in the air.
A special vehicle is one of the following:
static const int DAY_TICKS
1 day is 74 ticks; _date_fract used to be uint16 and incremented by 885.
PaletteID GetVehiclePalette(const Vehicle *v)
Get the colour map for a vehicle.
void SetNext(Vehicle *next)
Set the next vehicle of this vehicle.
void UpdateViewport(bool force_update, bool update_delta)
Update vehicle sprite- and position caches.
Vehicle is unloading cargo.
bool IsMultiheaded() const
Check if the vehicle is a multiheaded engine.
StationID last_station_visited
The last station we stopped at.
#define lastof(x)
Get the last element of an fixed size array.
bool CanBuildVehicleInfrastructure(VehicleType type)
Check whether we can build infrastructure for the given vehicle type.
bool in_use
Set if this livery should be used instead of the default livery.
uint16 reliability_spd_dec
Reliability decrease speed.
void UpdateViewport(bool dirty)
Update the vehicle on the viewport, updating the right hash and setting the new coordinates.
Simple vector template class.
void DeleteVehicleOrders(Vehicle *v, bool keep_orderlist, bool reset_order_indices)
Delete all orders from a vehicle.
void MarkTilesDirty(bool cargo_change) const
Marks the tiles of the station as dirty.
A game paused because a (critical) error.
Money GetCost() const
The costs as made up to this moment.
void HandlePathfindingResult(bool path_found)
Handle the pathfinding result, especially the lost status.
bool IsArticulatedVehicleCarryingDifferentCargoes(const Vehicle *v, CargoID *cargo_type)
Tests if all parts of an articulated vehicle are refitted to the same cargo.
void AircraftNextAirportPos_and_Order(Aircraft *v)
set the right pos when heading to other airports after takeoff
The most basic (normal) sprite.
Visual effects and wagon power.
#define CLRBITS(x, y)
Clears several bits in a variable.
T * GetFirstEnginePart()
Get the first part of an articulated engine.
static const byte LIT_COMPANY
Show the liveries of your own company.
LiveryScheme GetEngineLiveryScheme(EngineID engine_type, EngineID parent_engine_type, const Vehicle *v)
Determines the LiveryScheme for a vehicle.
First bit that contains the offset (0 = front, 8 = centre, 15 = rear)
Common return value for all commands.
uint32 cached_power
Total power of the consist (valid only for the first engine).
GrfSpecFeature GetGrfSpecFeature(TileIndex tile)
Get the GrfSpecFeature associated with the tile.
void StartSpriteCombine()
Starts a block of sprites, which are "combined" into a single bounding box.
StationCargoList cargo
The cargo packets of cargo waiting in this station.
static T max(const T a, const T b)
Returns the maximum of two values.
void MarkAllViewportsDirty() const
Marks viewports dirty where the vehicle's image is.
bool HasRating() const
Does this cargo have a rating at this station?
UnitID GetFreeUnitNumber(VehicleType type)
Get an unused unit number for a vehicle (if allowed).
Cached, frequently calculated values.
uint StoredCount() const
Returns sum of cargo on board the vehicle (ie not only reserved).
uint Return(uint max_move, StationCargoList *dest, StationID next_station)
Returns reserved cargo to the station and removes it from the cache.
static Train * From(Vehicle *v)
Converts a Vehicle to SpecializedVehicle with type checking.
CompanySettings settings
settings specific for each company
const T * End() const
Get the pointer behind the last valid item (const)
Generates sequence of free UnitID numbers.
bool NeedsAutomaticServicing() const
Checks if the current order should be interrupted for a service-in-depot order.
const Engine * GetEngine() const
Retrieves the engine of the vehicle.
Vehicle * next_shared
pointer to the next vehicle that shares the order
bool IsNormalAircraft() const
Check if the aircraft type is a normal flying device; eg not a rotor or a shadow. ...
GoodsEntry goods[NUM_CARGO]
Goods at this station.
static const uint TILE_SIZE
Tile size in world coordinates.
byte VehicleRandomBits()
Get a value for a vehicle's random_bits.
Use default from engine class.
FreeUnitIDGenerator(VehicleType type, CompanyID owner)
Initializes the structure.
static uint32 RandomRange(uint32 limit)
Pick a random number between 0 and limit - 1, inclusive.
VehicleSpriteSeq sprite_seq
Vehicle appearance.
Direction
Defines the 8 directions on the map.
static T SB(T &x, const uint8 s, const uint8 n, const U d)
Set n bits in x starting at bit s to d.
Vehicle * hash_viewport_next
NOSAVE: Next vehicle in the visual location hash.
OrderDepotActionFlags GetDepotActionType() const
What are we going to do when in the depot.
int8 x_bb_offs
x offset of vehicle bounding box
DepotCommand
Flags to add to p1 for goto depot commands.
uint32 GetGRFID() const
Retrieve the GRF ID of the NewGRF the engine is tied to.
Money profit_last_year
Profit last year << 8, low 8 bits are fract.
SmallPair< T, U > * Append(uint to_add=1)
Append an item and return it.
Order * next
Pointer to next order. If NULL, end of list.
EngineID first_engine
Cached EngineID of the front vehicle. INVALID_ENGINE for the front vehicle itself.
Class to backup a specific variable and restore it later.
replace/renew a vehicle while it is in a depot
CompanyByte _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
Value of offset corresponding to a position above the centre of the vehicle.
bool no_servicing_if_no_breakdowns
don't send vehicles to depot when breakdowns are disabled
Functions related to (drawing on) viewports.
Pseudo random number generator.
Vehicle ** hash_tile_current
NOSAVE: Cache of the current hash chain.
static const int32 INVALID_COORD
Sentinel for an invalid coordinate.
int8 y_bb_offs
y offset of vehicle bounding box
Angle of 45 degrees right.
byte breakdown_ctr
Counter for managing breakdown events.
Vehicle running normally.
The vehicle will stop at any station it passes and the destination.
byte subtype
subtype (Filled with values from #EffectVehicles/#TrainSubTypes/#AircraftSubTypes) ...
void EndSpriteCombine()
Terminates a block of sprites started by StartSpriteCombine.
static bool IsBridgeAbove(TileIndex t)
checks if a bridge is set above the ground of this tile
void InvalidateWindowClassesData(WindowClass cls, int data, bool gui_scope)
Mark window data of all windows of a given class as invalid (in need of re-computing) Note that by de...
TrackBits
Bitfield corresponding to Track.
Buses, trucks and trams belong to this class.
Critical errors, the MessageBox is shown in all cases.
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...
uint16 cargo_cap
total capacity
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 ShowErrorMessage(StringID summary_msg, StringID detailed_msg, WarningLevel wl, int x=0, int y=0, const GRFFile *textref_stack_grffile=NULL, uint textref_stack_size=0, const uint32 *textref_stack=NULL)
Display an error message in a window.
VehicleEnterTileProc * vehicle_enter_tile_proc
Called when a vehicle enters a tile.
Shared order list linking together the linked list of orders and the list of vehicles sharing this or...
void SetDParamStr(uint n, const char *str)
This function is used to "bind" a C string to a OpenTTD dparam slot.
OrderDepotTypeFlags GetDepotOrderType() const
What caused us going to the depot?
Vehicle orders; Window numbers:
Map related accessors for depots.
static void SpawnAdvancedVisualEffect(const Vehicle *v)
Call CBID_VEHICLE_SPAWN_VISUAL_EFFECT and spawn requested effects.
Some methods of Pool are placed here in order to reduce compilation time and binary size...
static uint32 GetRegister(uint i)
Gets the value of a so-called newgrf "register".
void UpdateCache()
Update the caches of this ship.
First bit used for the type of effect.
uint32 grf_bugs
NOSAVE: bugs in this GRF in this run,.
TransparencyOption GetTransparencyOption() const
Determines the transparency option affecting the effect.
virtual bool IsPrimaryVehicle() const
Whether this is the primary vehicle in the chain.
static bool IsTileType(TileIndex tile, TileType type)
Checks if a tile is a give tiletype.
int16 y_offs
Number of pixels to shift the sprite downwards.
static void DoDrawVehicle(const Vehicle *v)
Add vehicle sprite for drawing to the screen.
Functions related to errors.
UnitID unitnumber
unit number, for display purposes only
int y
x and y position of the vehicle after moving
CommandCost DoCommand(const CommandContainer *container, DoCommandFlag flags)
Shorthand for calling the long DoCommand with a container.
void MakeImplicit(StationID destination)
Makes this order an implicit order.
byte subtype
Type of aircraft.
void AgeVehicle(Vehicle *v)
Update age of a vehicle.
DateFract _date_fract
Fractional part of the day.
void DeleteVehicleNews(VehicleID vid, StringID news)
Delete a news item type about a vehicle.
static size_t GetPoolSize()
Returns first unused index.
Information about GRF, used in the game and (part of it) in savegames.
static bool IsRailStationTile(TileIndex t)
Is this tile a station tile and a rail station?
void ConsistChanged(ConsistChangeFlags allowed_changes)
Recalculates the cached stuff of a train.
bool IsRefit() const
Is this order a refit order.
UnitID max_roadveh
max trucks in game per company
Internal structure used in openttd - Finite sTate mAchine –> FTA.
The vehicle will not stop at any stations it passes including the destination.
bool HasVehicleOnPosXY(int x, int y, void *data, VehicleFromPosProc *proc)
Checks whether a vehicle in on a specific location.
bool NeedsServicing() const
Check if the vehicle needs to go to a depot in near future (if a opportunity presents itself) for ser...
void MakeDummy()
Makes this order a Dummy order.
int8 y_offs
y offset for vehicle sprite
GroundVehicleCache * GetGroundVehicleCache()
Access the ground vehicle cache of the vehicle.
VehicleType
Available vehicle types.
EngineClass engclass
Class of engine for this vehicle.
void MarkAllViewportsDirty(int left, int top, int right, int bottom)
Mark all viewports that display an area as dirty (in need of repaint).
void HideFillingPercent(TextEffectID *te_id)
Hide vehicle loading indicators.
Manually initiated order.
Don't load anymore during the next load cycle.
uint32 VehicleID
The type all our vehicle IDs have.
UnitID maxid
maximum ID at the moment of constructor call
StringID GetErrorMessage() const
Returns the error message of a command.
bool IsType(OrderType type) const
Check whether this order is of the given type.
CommandCost TunnelBridgeIsFree(TileIndex tile, TileIndex endtile, const Vehicle *ignore)
Finds vehicle in tunnel / bridge.
DoCommandFlag
List of flags for a command.
VisualEffectSpawnModel
Models for spawning visual effects.
T * Next() const
Get next vehicle in the chain.
byte callback_mask
Bitmask of vehicle callbacks that have to be called.
simple wagon, not motorized
Station with truck stops.
ClientSettings _settings_client
The current settings for this game.
Rail vehicle is a multiple-unit (DMU/EMU)
bool Succeeded() const
Did this command succeed?
void IncreaseStats(Station *st, CargoID cargo, StationID next_station_id, uint capacity, uint usage, EdgeUpdateMode mode)
Increase capacity for a link stat given by station cargo and next hop.
void PrepareUnload(Vehicle *front_v)
Prepare the vehicle to be unloaded.
Can helicopters land on this airport type?
Definition of base types and functions in a cross-platform compatible way.
PaletteID GetEnginePalette(EngineID engine_type, CompanyID company)
Get the colour map for an engine.
static const uint VEHICLE_LENGTH
The length of a vehicle in tile units.
bool IsArticulatedPart() const
Check if the vehicle is an articulated part of an engine.
A number of safeguards to prevent using unsafe methods.
Trigger platform when train leaves.
byte x_extent
x-extent of vehicle bounding box
static void Run(Vehicle *v, bool allow_merge=true, bool is_full_loading=false)
Refresh all links the given vehicle will visit.
void VehicleEnteredDepotThisTick(Vehicle *v)
Adds a vehicle to the list of vehicles that visited a depot this tick.
Vehicle uses two company colours.
void DeleteDepotHighlightOfVehicle(const Vehicle *v)
Removes the highlight of a vehicle in a depot window.
void DeleteOrder(Vehicle *v, VehicleOrderID sel_ord)
Delete an order but skip the parameter validation.
Vehicle refit; Window numbers:
DirDiff
Enumeration for the difference between two directions.
static uint CeilDiv(uint a, uint b)
Computes ceil(a / b) for non-negative a and b.
Station * GetTargetAirportIfValid(const Aircraft *v)
Returns aircraft's target station if v->target_airport is a valid station with airport.
struct AirportFTA * layout
state machine for airport
byte z_extent
z-extent of vehicle bounding box
byte visual_effect
Bitstuffed NewGRF visual effect data.
VehicleType type
Vehicle type, ie VEH_ROAD, VEH_TRAIN, etc.
Valid changes for arranging the consist in a depot.
Every 16 ticks while the vehicle is running (speed > 0).
CargoID cargo_type
type of cargo this vehicle is carrying
uint32 engine_renew_money
minimum amount of money before autorenew is used
uint ActionCount(MoveToAction action) const
Returns the amount of cargo designated for a given purpose.
CompanyMask company_avail
Bit for each company whether the engine is available for that company.
void AddToShared(Vehicle *shared_chain)
Adds this vehicle to a shared vehicle chain.
Change colour mapping of vehicle.
Information about a particular livery.
Effect vehicle type (smoke, explosions, sparks, bubbles)
Vehicle view; Window numbers:
static const byte LIT_ALL
Show the liveries of all companies.
GroupStatistics group_all[VEH_COMPANY_END]
NOSAVE: Statistics for the ALL_GROUP group.
Functions related to order backups.
Smoke of broken vehicles except aircraft.
bool IsFrontEngine() const
Check if the vehicle is a front engine.
GRFBugs
Encountered GRF bugs.
byte misc_flags
Miscellaneous flags.
Map accessor functions for bridges.
void FindVehicleOnPos(TileIndex tile, void *data, VehicleFromPosProc *proc)
Find a vehicle from a specific location.
TileIndex tile
Current tile index.
Road vehicle list; Window numbers:
CommandCost CheckOwnership(Owner owner, TileIndex tile)
Check whether the current owner owns something.
static void CountVehicle(const Vehicle *v, int delta)
Update num_vehicle when adding or removing a vehicle.
static Vehicle * VehicleFromPos(TileIndex tile, void *data, VehicleFromPosProc *proc, bool find_first)
Helper function for FindVehicleOnPos/HasVehicleOnPos.
Money money
Money owned by the company.
Vehicle timetable; Window numbers:
Every 16 ticks while the vehicle is stopped (speed == 0).
bool CanVehicleUseStation(EngineID engine_type, const Station *st)
Can this station be used by the given engine type?
Station view; Window numbers:
OrderLoadFlags GetLoadType() const
How must the consist be loaded?
Base class for all effect vehicles.
Basic functions/variables used all over the place.
static DirDiff DirDifference(Direction d0, Direction d1)
Calculate the difference between two directions.
Service the vehicle and then halt it.
bool IsRearDualheaded() const
Tell if we are dealing with the rear end of a multiheaded engine.
uint16 num_vehicle
Number of vehicles.
static Direction ChangeDir(Direction d, DirDiff delta)
Change a direction by a given difference.
int8 x_offs
x offset for vehicle sprite
StationFacilityByte facilities
The facilities that this station has.
Sprite sequence for a vehicle part.
uint64 flags
stores which blocks on the airport are taken. was 16 bit earlier on, then 32
Called to determine if a specific colour map should be used for a vehicle instead of the default live...
static T min(const T a, const T b)
Returns the minimum of two values.
static bool IsCargoInClass(CargoID c, CargoClass cc)
Does cargo c have cargo class cc?
byte previous_pos
Previous desired position of the aircraft.
uint16 refit_cap
Capacity left over from before last refit.
Functions related to sound.
byte breakdowns_since_last_service
Counter for the amount of breakdowns.
uint16 reliability
Reliability.
Functions to cache sprites in memory.
uint32 StringID
Numeric value that represents a string, independent of the selected language.
Vehicle * First() const
Get the first vehicle of this vehicle chain.
Vehicle's pathfinder is lost.
bool Failed() const
Did this command fail?
byte tick_counter
Increased by one for each tick.
EffectVehicle * CreateEffectVehicleRel(const Vehicle *v, int x, int y, int z, EffectVehicleType type)
Create an effect vehicle above a particular vehicle.
byte colour2
Second colour, for vehicles with 2CC support.
UnitID curid
last ID returned; 0 if none
All ships have this type.
void InvalidateAutoreplaceWindow(EngineID e, GroupID id_g)
Rebuild the left autoreplace list if an engine is removed or added.
void AddSortableSpriteToDraw(SpriteID image, PaletteID pal, int x, int y, int w, int h, int dz, int z, bool transparent, int bb_offset_x, int bb_offset_y, int bb_offset_z, const SubSprite *sub)
Draw a (transparent) sprite at given coordinates with a given bounding box.
bool PlayVehicleSound(const Vehicle *v, VehicleSoundEvent event)
Checks whether a NewGRF wants to play a different vehicle sound effect.
#define return_cmd_error(errcode)
Returns from a function with a specific StringID as error.
byte state
State of the airport.
int16 engine_renew_months
months before/after the maximum vehicle age a vehicle should be renewed
Base class for all pools.
bool engine_renew
is autorenew enabled
uint16 height
Height of the sprite.
static void NewEvent(CompanyID company, ScriptEvent *event)
Queue a new event for an AI.
#define DEBUG(name, level,...)
Output a line of debugging information.
'Train' is either a loco or a wagon.
static bool Chance16(const uint a, const uint b)
Flips a coin with given probability.
TileIndex old_tile
Current tile of the vehicle.
bool IsEngineCountable() const
Check if a vehicle is counted in num_engines in each company struct.
void MarkTileDirtyByTile(TileIndex tile, int bridge_level_offset)
Mark a tile given by its index dirty for repaint.
byte breakdown_chance
Current chance of breakdowns.
The vehicle is in a drive-through road stop.
#define INSTANTIATE_POOL_METHODS(name)
Force instantiation of pool methods so we don't get linker errors.
int left
Screen coordinate left egde of the viewport.
void DeleteWindowById(WindowClass cls, WindowNumber number, bool force)
Delete a window by its class and window number (if it is open).
VehicleEnterTileStatus VehicleEnterTile(Vehicle *v, TileIndex tile, int x, int y)
Call the tile callback function for a vehicle entering a tile.
static void UpdateProfits()
Recompute the profits for all groups.
void RemoveFromShared()
Removes the vehicle from the shared order list.
void AddVehicle(Vehicle *v)
Adds the given vehicle to this shared order list.
execute the given command
UnitID max_ships
max ships in game per company
Flag to disable visual effect.
static const EngineID INVALID_ENGINE
Constant denoting an invalid engine.
bool vehicle_income_warn
if a vehicle isn't generating income, show a warning
static const GroupID DEFAULT_GROUP
Ungrouped vehicles are in this group.
The vehicle will leave the depot right after arrival (serivce only)
uint16 width
Width of the sprite.
Functions related to companies.
Called for every vehicle every 32 days (not all on same date though).
RailType GetTileRailType(TileIndex tile)
Return the rail type of tile, or INVALID_RAILTYPE if this is no rail tile.
GetNewVehiclePosResult GetNewVehiclePos(const Vehicle *v)
Get position information of a vehicle when moving one pixel in the direction it is facing...
void UpdatePosition()
Update the position of the vehicle.
static StationID GetStationIndex(TileIndex t)
Get StationID from a tile.
static TileIndex TileVirtXY(uint x, uint y)
Get a tile from the virtual XY-coordinate.
GRFConfig * GetGRFConfig(uint32 grfid, uint32 mask)
Retrieve a NewGRF from the current config by its grfid.
static const PaletteID PALETTE_RECOLOUR_START
First recolour sprite for company colours.
Functions related to articulated vehicles.
void ErrorUnknownCallbackResult(uint32 grfid, uint16 cbid, uint16 cb_res)
Record that a NewGRF returned an unknown/invalid callback result.
Header file for NewGRF stations.
static T ClrBit(T &x, const uint8 y)
Clears a bit in a variable.
bool IsGroundVehicle() const
Check if the vehicle is a ground vehicle.
GUISettings gui
settings related to the GUI
const GRFFile * GetGRF() const
Retrieve the NewGRF the engine is tied to.
DestinationID GetDestination() const
Gets the destination of this order.
bool NeedsAutorenewing(const Company *c, bool use_renew_setting=true) const
Function to tell if a vehicle needs to be autorenewed.
void VehicleServiceInDepot(Vehicle *v)
Service a vehicle and all subsequent vehicles in the consist.
void SetWindowWidgetDirty(WindowClass cls, WindowNumber number, byte widget_index)
Mark a particular widget in a particular window as dirty (in need of repainting)
CargoList that is used for vehicles.
bool HandleBreakdown()
Handle all of the aspects of a vehicle breakdown This includes adding smoke and sounds, and ending the breakdown when appropriate.
static void ClearVehicle(const Vehicle *v)
Clear/update the (clone) vehicle from an order backup.
Data structure for viewport, display of a part of the world.
static const int MAX_VEHICLE_PIXEL_X
Maximum width of a vehicle in pixels in #ZOOM_LVL_BASE.
Used for vehicle var 0xFE bit 8 (toggled each time the train is reversed, accurate for first vehicle ...
uint16 EngineID
Unique identification number of an engine.
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo ID.
CompanyByte _current_company
Company currently doing an action.
Number of bits used for the effect type.
static Vehicle * EnsureNoVehicleProcZ(Vehicle *v, void *data)
Callback that returns 'real' vehicles lower or at height *(int*)data .
Ships list; Window numbers:
uint32 TileIndex
The index/ID of a Tile.
static const PaletteID PALETTE_CRASH
Recolour sprite greying of crashed vehicles.
static Vehicle * GetVehicleTunnelBridgeProc(Vehicle *v, void *data)
Procedure called for every vehicle found in tunnel/bridge in the hash map.
uint32 Pack() const
Pack a VehicleListIdentifier in a single uint32.
void DeleteGroupHighlightOfVehicle(const Vehicle *v)
Removes the highlight of a vehicle in a group window.
Functions related to depots.
void BeginLoading()
Prepare everything to begin the loading when arriving at a station.
Vehicle * Next() const
Get the next vehicle of this vehicle.
Date date_of_last_service
Last date the vehicle had a service at a depot.
void InsertOrder(Vehicle *v, Order *new_o, VehicleOrderID sel_ord)
Insert a new order but skip the validation.
void ShowNewGrfVehicleError(EngineID engine, StringID part1, StringID part2, GRFBugs bug_type, bool critical)
Displays a "NewGrf Bug" error message for a engine, and pauses the game if not networking.
Position information of a vehicle after it moved.
OrderSettings order
settings related to orders
void GetVehicleSet(VehicleSet &set, Vehicle *v, uint8 num_vehicles)
Calculates the set of vehicles that will be affected by a given selection.
void FindVehicleOnPosXY(int x, int y, void *data, VehicleFromPosProc *proc)
Find a vehicle from a specific location.
static const int MAX_VEHICLE_PIXEL_Y
Maximum height of a vehicle in pixels in #ZOOM_LVL_BASE.
Send the vehicle to the nearest depot.
static uint TileY(TileIndex tile)
Get the Y component of a tile.
static Vehicle * VehicleFromPosXY(int x, int y, void *data, VehicleFromPosProc *proc, bool find_first)
Helper function for FindVehicleOnPos/HasVehicleOnPos.
uint64 block
64 bit blocks (st->airport.flags), should be enough for the most complex airports ...
Powered wagon changed poweredness state when not inside a depot.
OwnerByte owner
Which company owns the vehicle?
UnitID NextID()
Returns next free UnitID.
SigSegState UpdateSignalsOnSegment(TileIndex tile, DiagDirection side, Owner owner)
Update signals, starting at one side of a tile Will check tile next to this at opposite side too...
static T abs(const T a)
Returns the absolute value of (scalar) variable.
TileIndex xy
Base tile of the station.
static void UpdateAutoreplace(CompanyID company)
Update autoreplace_defined and autoreplace_finished of all statistics of a company.
static uint GB(const T x, const uint8 s, const uint8 n)
Fetch n bits from x, started at bit s.
bool GamelogGRFBugReverse(uint32 grfid, uint16 internal_id)
Logs GRF bug - rail vehicle has different length after reversing.
Trains list; Window numbers:
Functions related to zooming.
Full load all cargoes of the consist.
void AgeCargo()
Ages the all cargo in this list.
Vehicle * next
pointer to the next vehicle in the chain
void SubtractMoneyFromCompany(CommandCost cost)
Subtract money from the _current_company, if the company is valid.
void DeleteUnreachedImplicitOrders()
Delete all implicit orders which were not reached.
void ReleaseDisastersTargetingVehicle(VehicleID vehicle)
Notify disasters that we are about to delete a vehicle.
const TileTypeProcs *const _tile_type_procs[16]
Tile callback functions for each type of tile.
Invalid transparency option.
SmallMap< Vehicle *, bool, 4 > AutoreplaceMap
List of vehicles that should check for autoreplace this tick.
Vehicle * previous_shared
NOSAVE: pointer to the previous vehicle in the shared order chain.
Reverse the visible direction of the vehicle.
bool show_track_reservation
highlight reserved tracks.
uint16 _returned_mail_refit_capacity
Stores the mail capacity after a refit operation (Aircraft only).
#define MAX_DAY
The number of days till the last day.
int16 x_offs
Number of pixels to shift the sprite to the right.
Station with train station.
Totally no unloading will be done.
static bool CanAllocateItem(size_t n=1)
Helper functions so we can use PoolItem::Function() instead of _poolitem_pool.Function() ...
Vehicle * CheckClickOnVehicle(const ViewPort *vp, int x, int y)
Find the vehicle close to the clicked coordinates.
virtual void OnNewDay()
Calls the new day handler of the vehicle.
bool HasEngineType() const
Check whether Vehicle::engine_type has any meaning.
Default value to indicate that visual effect should be based on engine class.
Aircraft list; Window numbers:
uint16 & GetGroundVehicleFlags()
Access the ground vehicle flags of the vehicle.
Vehicle details; Window numbers:
Functions/definitions that have something to do with groups.
Functions related to commands.
static bool IsValidID(size_t index)
Tests whether given index is a valid index for station of this type.
Coordinates of a point in 2D.
Vehicle * previous
NOSAVE: pointer to the previous vehicle in the chain.
uint8 CalcPercentVehicleFilled(const Vehicle *front, StringID *colour)
Calculates how full a vehicle is.
static bool IsValidID(size_t index)
Tests whether given index can be used to get valid (non-NULL) Titem.
uint16 local_id
id defined by the grf file for this entity
static void CountEngine(const Vehicle *v, int delta)
Update num_engines when adding/removing an engine.
uint32 GetGRFID() const
Retrieve the GRF ID of the NewGRF the vehicle is tied to.
uint16 UnitID
Type for the company global vehicle unit number.
Base classes related to the economy.
static WindowClass GetWindowClassForVehicleType(VehicleType vt)
Get WindowClass for vehicle list of given vehicle type.
void GetConsistFreeCapacities(SmallMap< CargoID, uint > &capacities) const
Get a map of cargoes and free capacities in the consist.
Load the cargo from the station.
void KeepAll()
Marks all cargo in the vehicle as to be kept.
UnitID max_trains
max trains in game per company
Declaration of link graph classes used for cargo distribution.
bool * cache
array of occupied unit id numbers
EffectVehicleType
Effect vehicle types.
Order * GetOrder(int index) const
Returns order 'index' of a vehicle or NULL when it doesn't exists.
static const StringID INVALID_STRING_ID
Constant representing an invalid string (16bit in case it is used in savegames)
CommandCost SendToDepot(DoCommandFlag flags, DepotCommand command)
Send this vehicle to the depot using the given command(s).
uint16 GetVehicleCallback(CallbackID callback, uint32 param1, uint32 param2, EngineID engine, const Vehicle *v)
Evaluate a newgrf callback for vehicles.
const char * GetName() const
Get the name of this grf.
uint8 cached_veh_length
Length of this vehicle in units of 1/VEHICLE_LENGTH of normal length. It is cached because this can b...
static bool IsTunnelTile(TileIndex t)
Is this a tunnel (entrance)?
Airport airport
Tile area the airport covers.
byte y_extent
y-extent of vehicle bounding box
Flag to disable wagon power.
EngineID engine_type
The type of engine used for this vehicle.
byte liveries
options for displaying company liveries, 0=none, 1=self, 2=all
const struct GRFFile * grffile
grf file that introduced this entity
ZoomLevel zoom
The zoom level of the viewport.
byte cached_vis_effect
Visual effect to show (see VisualEffect)
bool disable_unsuitable_building
disable infrastructure building when no suitable vehicles are available
virtual bool Tick()
Calls the tick handler of the vehicle.
uint16 vehicle_flags
Used for gradual loading and other miscellaneous things (.
static bool HasBit(const T x, const uint8 y)
Checks if a bit in a value is set.
Functions related to NewGRF provided sounds.
void Restore()
Restore the variable.
Base functions for all AIs.
#define FOR_ALL_VEHICLES(var)
Iterate over all vehicles.
Map accessors for tunnels.
const GRFFile * GetGRF() const
Retrieve the NewGRF the vehicle is tied to.
byte colour1
First colour, for all vehicles.
int virtual_top
Virtual top coordinate.
GameCreationSettings game_creation
settings used during the creation of a game (map)
Smoke of broken aircraft.
static void VehicleReachedProfitAge(const Vehicle *v)
Add a vehicle to the profit sum of its group.
Specification of a rectangle with absolute coordinates of all edges.
byte CargoID
Cargo slots to indicate a cargo type within a game.
static bool IsInvisibilitySet(TransparencyOption to)
Check if the invisibility option bit is set and if we aren't in the game menu (there's never transpar...
Road vehicle is a tram/light rail vehicle.
Owner
Enum for all companies/owners.
Length of rail vehicle changes when not inside a depot.
Flag for advanced effects.
static bool IsDepotTile(TileIndex tile)
Is the given tile a tile with a depot on it?
int top
Screen coordinate top edge of the viewport.
void ShowCostOrIncomeAnimation(int x, int y, int z, Money cost)
Display animated income or costs on the map.
Vehicle(VehicleType type=VEH_INVALID)
Vehicle constructor.
VehicleEnterTileStatus
The returned bits of VehicleEnterTile.
One direction is the opposite of the other one.
union Vehicle::@46 orders
The orders currently assigned to the vehicle.
SpriteID sprite
The 'real' sprite.
static const VehicleOrderID MAX_VEH_ORDER_ID
Last valid VehicleOrderID.
Money profit_this_year
Profit this year << 8, low 8 bits are fract.
void SetWindowClassesDirty(WindowClass cls)
Mark all windows of a particular class as dirty (in need of repainting)
This depot order is because of a regular order.
Functions related to news.
uint16 animation_state
State primarily used to change the graphics/behaviour.
Base classes/functions for stations.
VehicleCache vcache
Cache of often used vehicle values.
static Station * Get(size_t index)
Gets station with given index.
Date _date
Current date in days (day counter)
Number of bits used for the offset.
static Direction ReverseDir(Direction d)
Return the reverse of a direction.
Functions related to autoreplacing.
Company view; Window numbers:
Rect coord
NOSAVE: Graphical bounding box of the vehicle, i.e. what to redraw on moves.
TileIndex new_tile
Tile of the vehicle after moving.
Vehicle * first
NOSAVE: pointer to the first vehicle in the chain.
static bool IsCompanyBuildableVehicleType(VehicleType type)
Is the given vehicle type buildable by a company?
void DeleteNewGRFInspectWindow(GrfSpecFeature feature, uint index)
Delete inspect window for a given feature and index.
This depot order is because of the servicing limit.
VehicleOrderID cur_real_order_index
The index to the current real (non-implicit) order.
VehicleTypeByte type
Type of vehicle.
void HandleLoading(bool mode=false)
Handle the loading of the vehicle; when not it skips through dummy orders and does nothing in all oth...
Class for backupping variables and making sure they are restored later.
static const uint IMPLICIT_ORDER_ONLY_CAP
Maximum number of orders in implicit-only lists before we start searching harder for duplicates...
Functions related to effect vehicles.
static bool IsTransparencySet(TransparencyOption to)
Check if the transparency option bit is set and if we aren't in the game menu (there's never transpar...
uint32 cached_weight
Total weight of the consist (valid only for the first engine).
Disable insertion and removal of automatic orders until the vehicle completes the real order...
byte day_counter
Increased by one for each day.
void DrawSprite(SpriteID img, PaletteID pal, int x, int y, const SubSprite *sub, ZoomLevel zoom)
Draw a sprite, not in a viewport.
static bool TracksOverlap(TrackBits bits)
Checks if the given tracks overlap, ie form a crossing.
Order current_order
The current order (+ status, like: loading)
void UpdatePositionAndViewport()
Update the position of the vehicle, and update the viewport.
static RoadStop * GetByTile(TileIndex tile, RoadStopType type)
Find a roadstop at given tile.
void UpdateVisualEffect(bool allow_power_change=true)
Update the cached visual effect.
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-...
static const int DAYS_IN_LEAP_YEAR
sometimes, you need one day more...
bool IsEngine() const
Check if a vehicle is an engine (can be first in a consist).
TransparencyOption
Transparency option bits: which position in _transparency_opt stands for which transparency.
GroundVehicleCache gcache
Cache of often calculated values.
Visual effects and wagon power (trains, road vehicles and ships)
CargoID GetRefitCargo() const
Get the cargo to to refit to.
Vehicle is not clickable by the user (shadow vehicles).
SpriteID colourmap
NOSAVE: cached colour mapping.
byte visual_effect
Bitstuffed NewGRF visual effect data.
static int GetTileMaxPixelZ(TileIndex tile)
Get top height of the tile.
Dynamic data of a loaded NewGRF.
Vehicle visual effect (steam, diesel smoke or electric spark) is shown.
static void SetDParam(uint n, uint64 v)
Set a string parameter v at index n in the global string parameter array.
void CancelReservation(StationID next, Station *st)
Return all reserved cargo packets to the station and reset all packets staged for transfer...
static void SetDepotReservation(TileIndex t, bool b)
Set the reservation state of the depot.
PaletteID pal
The palette (use PAL_NONE) if not needed)
int width
Screen width of the viewport.
static Station * GetIfValid(size_t index)
Returns station if the index is a valid index for this station type.