Fix #10490: Allow ships to exit depots if another is not moving at the exit point...
[openttd-github.git] / src / train_cmd.cpp
blob1a3d74b00b9ce83b8545666b16aeef30a954f100
1 /*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6 */
8 /** @file train_cmd.cpp Handling of trains. */
10 #include "stdafx.h"
11 #include "error.h"
12 #include "articulated_vehicles.h"
13 #include "command_func.h"
14 #include "error_func.h"
15 #include "pathfinder/npf/npf_func.h"
16 #include "pathfinder/yapf/yapf.hpp"
17 #include "news_func.h"
18 #include "company_func.h"
19 #include "newgrf_sound.h"
20 #include "newgrf_text.h"
21 #include "strings_func.h"
22 #include "viewport_func.h"
23 #include "vehicle_func.h"
24 #include "sound_func.h"
25 #include "ai/ai.hpp"
26 #include "game/game.hpp"
27 #include "newgrf_station.h"
28 #include "effectvehicle_func.h"
29 #include "network/network.h"
30 #include "spritecache.h"
31 #include "core/random_func.hpp"
32 #include "company_base.h"
33 #include "newgrf.h"
34 #include "order_backup.h"
35 #include "zoom_func.h"
36 #include "newgrf_debug.h"
37 #include "framerate_type.h"
38 #include "train_cmd.h"
39 #include "misc_cmd.h"
40 #include "timer/timer_game_calendar.h"
41 #include "timer/timer_game_economy.h"
43 #include "table/strings.h"
44 #include "table/train_sprites.h"
46 #include "safeguards.h"
48 static Track ChooseTrainTrack(Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool force_res, bool *got_reservation, bool mark_stuck);
49 static bool TrainCheckIfLineEnds(Train *v, bool reverse = true);
50 bool TrainController(Train *v, Vehicle *nomove, bool reverse = true); // Also used in vehicle_sl.cpp.
51 static TileIndex TrainApproachingCrossingTile(const Train *v);
52 static void CheckIfTrainNeedsService(Train *v);
53 static void CheckNextTrainTile(Train *v);
55 static const byte _vehicle_initial_x_fract[4] = {10, 8, 4, 8};
56 static const byte _vehicle_initial_y_fract[4] = { 8, 4, 8, 10};
58 template <>
59 bool IsValidImageIndex<VEH_TRAIN>(uint8_t image_index)
61 return image_index < lengthof(_engine_sprite_base);
65 /**
66 * Return the cargo weight multiplier to use for a rail vehicle
67 * @param cargo Cargo type to get multiplier for
68 * @return Cargo weight multiplier
70 byte FreightWagonMult(CargoID cargo)
72 if (!CargoSpec::Get(cargo)->is_freight) return 1;
73 return _settings_game.vehicle.freight_trains;
76 /** Checks if lengths of all rail vehicles are valid. If not, shows an error message. */
77 void CheckTrainsLengths()
79 bool first = true;
81 for (const Train *v : Train::Iterate()) {
82 if (v->First() == v && !(v->vehstatus & VS_CRASHED)) {
83 for (const Train *u = v, *w = v->Next(); w != nullptr; u = w, w = w->Next()) {
84 if (u->track != TRACK_BIT_DEPOT) {
85 if ((w->track != TRACK_BIT_DEPOT &&
86 std::max(abs(u->x_pos - w->x_pos), abs(u->y_pos - w->y_pos)) != u->CalcNextVehicleOffset()) ||
87 (w->track == TRACK_BIT_DEPOT && TicksToLeaveDepot(u) <= 0)) {
88 SetDParam(0, v->index);
89 SetDParam(1, v->owner);
90 ShowErrorMessage(STR_BROKEN_VEHICLE_LENGTH, INVALID_STRING_ID, WL_CRITICAL);
92 if (!_networking && first) {
93 first = false;
94 Command<CMD_PAUSE>::Post(PM_PAUSED_ERROR, true);
96 /* Break so we warn only once for each train. */
97 break;
106 * Recalculates the cached stuff of a train. Should be called each time a vehicle is added
107 * to/removed from the chain, and when the game is loaded.
108 * Note: this needs to be called too for 'wagon chains' (in the depot, without an engine)
109 * @param allowed_changes Stuff that is allowed to change.
111 void Train::ConsistChanged(ConsistChangeFlags allowed_changes)
113 uint16_t max_speed = UINT16_MAX;
115 assert(this->IsFrontEngine() || this->IsFreeWagon());
117 const RailVehicleInfo *rvi_v = RailVehInfo(this->engine_type);
118 EngineID first_engine = this->IsFrontEngine() ? this->engine_type : INVALID_ENGINE;
119 this->gcache.cached_total_length = 0;
120 this->compatible_railtypes = RAILTYPES_NONE;
122 bool train_can_tilt = true;
123 int min_curve_speed_mod = INT_MAX;
125 for (Train *u = this; u != nullptr; u = u->Next()) {
126 const RailVehicleInfo *rvi_u = RailVehInfo(u->engine_type);
128 /* Check the this->first cache. */
129 assert(u->First() == this);
131 /* update the 'first engine' */
132 u->gcache.first_engine = this == u ? INVALID_ENGINE : first_engine;
133 u->railtype = rvi_u->railtype;
135 if (u->IsEngine()) first_engine = u->engine_type;
137 /* Set user defined data to its default value */
138 u->tcache.user_def_data = rvi_u->user_def_data;
139 this->InvalidateNewGRFCache();
140 u->InvalidateNewGRFCache();
143 for (Train *u = this; u != nullptr; u = u->Next()) {
144 /* Update user defined data (must be done before other properties) */
145 u->tcache.user_def_data = GetVehicleProperty(u, PROP_TRAIN_USER_DATA, u->tcache.user_def_data);
146 this->InvalidateNewGRFCache();
147 u->InvalidateNewGRFCache();
150 for (Train *u = this; u != nullptr; u = u->Next()) {
151 const Engine *e_u = u->GetEngine();
152 const RailVehicleInfo *rvi_u = &e_u->u.rail;
154 if (!HasBit(e_u->info.misc_flags, EF_RAIL_TILTS)) train_can_tilt = false;
155 min_curve_speed_mod = std::min(min_curve_speed_mod, u->GetCurveSpeedModifier());
157 /* Cache wagon override sprite group. nullptr is returned if there is none */
158 u->tcache.cached_override = GetWagonOverrideSpriteSet(u->engine_type, u->cargo_type, u->gcache.first_engine);
160 /* Reset colour map */
161 u->colourmap = PAL_NONE;
163 /* Update powered-wagon-status and visual effect */
164 u->UpdateVisualEffect(true);
166 if (rvi_v->pow_wag_power != 0 && rvi_u->railveh_type == RAILVEH_WAGON &&
167 UsesWagonOverride(u) && !HasBit(u->vcache.cached_vis_effect, VE_DISABLE_WAGON_POWER)) {
168 /* wagon is powered */
169 SetBit(u->flags, VRF_POWEREDWAGON); // cache 'powered' status
170 } else {
171 ClrBit(u->flags, VRF_POWEREDWAGON);
174 if (!u->IsArticulatedPart()) {
175 /* Do not count powered wagons for the compatible railtypes, as wagons always
176 have railtype normal */
177 if (rvi_u->power > 0) {
178 this->compatible_railtypes |= GetRailTypeInfo(u->railtype)->powered_railtypes;
181 /* Some electric engines can be allowed to run on normal rail. It happens to all
182 * existing electric engines when elrails are disabled and then re-enabled */
183 if (HasBit(u->flags, VRF_EL_ENGINE_ALLOWED_NORMAL_RAIL)) {
184 u->railtype = RAILTYPE_RAIL;
185 u->compatible_railtypes |= RAILTYPES_RAIL;
188 /* max speed is the minimum of the speed limits of all vehicles in the consist */
189 if ((rvi_u->railveh_type != RAILVEH_WAGON || _settings_game.vehicle.wagon_speed_limits) && !UsesWagonOverride(u)) {
190 uint16_t speed = GetVehicleProperty(u, PROP_TRAIN_SPEED, rvi_u->max_speed);
191 if (speed != 0) max_speed = std::min(speed, max_speed);
195 uint16_t new_cap = e_u->DetermineCapacity(u);
196 if (allowed_changes & CCF_CAPACITY) {
197 /* Update vehicle capacity. */
198 if (u->cargo_cap > new_cap) u->cargo.Truncate(new_cap);
199 u->refit_cap = std::min(new_cap, u->refit_cap);
200 u->cargo_cap = new_cap;
201 } else {
202 /* Verify capacity hasn't changed. */
203 if (new_cap != u->cargo_cap) ShowNewGrfVehicleError(u->engine_type, STR_NEWGRF_BROKEN, STR_NEWGRF_BROKEN_CAPACITY, GBUG_VEH_CAPACITY, true);
205 u->vcache.cached_cargo_age_period = GetVehicleProperty(u, PROP_TRAIN_CARGO_AGE_PERIOD, e_u->info.cargo_age_period);
207 /* check the vehicle length (callback) */
208 uint16_t veh_len = CALLBACK_FAILED;
209 if (e_u->GetGRF() != nullptr && e_u->GetGRF()->grf_version >= 8) {
210 /* Use callback 36 */
211 veh_len = GetVehicleProperty(u, PROP_TRAIN_SHORTEN_FACTOR, CALLBACK_FAILED);
213 if (veh_len != CALLBACK_FAILED && veh_len >= VEHICLE_LENGTH) {
214 ErrorUnknownCallbackResult(e_u->GetGRFID(), CBID_VEHICLE_LENGTH, veh_len);
216 } else if (HasBit(e_u->info.callback_mask, CBM_VEHICLE_LENGTH)) {
217 /* Use callback 11 */
218 veh_len = GetVehicleCallback(CBID_VEHICLE_LENGTH, 0, 0, u->engine_type, u);
220 if (veh_len == CALLBACK_FAILED) veh_len = rvi_u->shorten_factor;
221 veh_len = VEHICLE_LENGTH - Clamp(veh_len, 0, VEHICLE_LENGTH - 1);
223 if (allowed_changes & CCF_LENGTH) {
224 /* Update vehicle length. */
225 u->gcache.cached_veh_length = veh_len;
226 } else {
227 /* Verify length hasn't changed. */
228 if (veh_len != u->gcache.cached_veh_length) VehicleLengthChanged(u);
231 this->gcache.cached_total_length += u->gcache.cached_veh_length;
232 this->InvalidateNewGRFCache();
233 u->InvalidateNewGRFCache();
236 /* store consist weight/max speed in cache */
237 this->vcache.cached_max_speed = max_speed;
238 this->tcache.cached_tilt = train_can_tilt;
239 this->tcache.cached_curve_speed_mod = min_curve_speed_mod;
240 this->tcache.cached_max_curve_speed = this->GetCurveSpeedLimit();
242 /* recalculate cached weights and power too (we do this *after* the rest, so it is known which wagons are powered and need extra weight added) */
243 this->CargoChanged();
245 if (this->IsFrontEngine()) {
246 this->UpdateAcceleration();
247 SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
248 InvalidateWindowData(WC_VEHICLE_REFIT, this->index, VIWD_CONSIST_CHANGED);
249 InvalidateWindowData(WC_VEHICLE_ORDERS, this->index, VIWD_CONSIST_CHANGED);
250 InvalidateNewGRFInspectWindow(GSF_TRAINS, this->index);
255 * Get the stop location of (the center) of the front vehicle of a train at
256 * a platform of a station.
257 * @param station_id the ID of the station where we're stopping
258 * @param tile the tile where the vehicle currently is
259 * @param v the vehicle to get the stop location of
260 * @param station_ahead 'return' the amount of 1/16th tiles in front of the train
261 * @param station_length 'return' the station length in 1/16th tiles
262 * @return the location, calculated from the begin of the station to stop at.
264 int GetTrainStopLocation(StationID station_id, TileIndex tile, const Train *v, int *station_ahead, int *station_length)
266 const Station *st = Station::Get(station_id);
267 *station_ahead = st->GetPlatformLength(tile, DirToDiagDir(v->direction)) * TILE_SIZE;
268 *station_length = st->GetPlatformLength(tile) * TILE_SIZE;
270 /* Default to the middle of the station for stations stops that are not in
271 * the order list like intermediate stations when non-stop is disabled */
272 OrderStopLocation osl = OSL_PLATFORM_MIDDLE;
273 if (v->gcache.cached_total_length >= *station_length) {
274 /* The train is longer than the station, make it stop at the far end of the platform */
275 osl = OSL_PLATFORM_FAR_END;
276 } else if (v->current_order.IsType(OT_GOTO_STATION) && v->current_order.GetDestination() == station_id) {
277 osl = v->current_order.GetStopLocation();
280 /* The stop location of the FRONT! of the train */
281 int stop;
282 switch (osl) {
283 default: NOT_REACHED();
285 case OSL_PLATFORM_NEAR_END:
286 stop = v->gcache.cached_total_length;
287 break;
289 case OSL_PLATFORM_MIDDLE:
290 stop = *station_length - (*station_length - v->gcache.cached_total_length) / 2;
291 break;
293 case OSL_PLATFORM_FAR_END:
294 stop = *station_length;
295 break;
298 /* Subtract half the front vehicle length of the train so we get the real
299 * stop location of the train. */
300 return stop - (v->gcache.cached_veh_length + 1) / 2;
305 * Computes train speed limit caused by curves
306 * @return imposed speed limit
308 int Train::GetCurveSpeedLimit() const
310 assert(this->First() == this);
312 static const int absolute_max_speed = UINT16_MAX;
313 int max_speed = absolute_max_speed;
315 if (_settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) return max_speed;
317 int curvecount[2] = {0, 0};
319 /* first find the curve speed limit */
320 int numcurve = 0;
321 int sum = 0;
322 int pos = 0;
323 int lastpos = -1;
324 for (const Vehicle *u = this; u->Next() != nullptr; u = u->Next(), pos++) {
325 Direction this_dir = u->direction;
326 Direction next_dir = u->Next()->direction;
328 DirDiff dirdiff = DirDifference(this_dir, next_dir);
329 if (dirdiff == DIRDIFF_SAME) continue;
331 if (dirdiff == DIRDIFF_45LEFT) curvecount[0]++;
332 if (dirdiff == DIRDIFF_45RIGHT) curvecount[1]++;
333 if (dirdiff == DIRDIFF_45LEFT || dirdiff == DIRDIFF_45RIGHT) {
334 if (lastpos != -1) {
335 numcurve++;
336 sum += pos - lastpos;
337 if (pos - lastpos == 1 && max_speed > 88) {
338 max_speed = 88;
341 lastpos = pos;
344 /* if we have a 90 degree turn, fix the speed limit to 60 */
345 if (dirdiff == DIRDIFF_90LEFT || dirdiff == DIRDIFF_90RIGHT) {
346 max_speed = 61;
350 if (numcurve > 0 && max_speed > 88) {
351 if (curvecount[0] == 1 && curvecount[1] == 1) {
352 max_speed = absolute_max_speed;
353 } else {
354 sum /= numcurve;
355 max_speed = 232 - (13 - Clamp(sum, 1, 12)) * (13 - Clamp(sum, 1, 12));
359 if (max_speed != absolute_max_speed) {
360 /* Apply the current railtype's curve speed advantage */
361 const RailTypeInfo *rti = GetRailTypeInfo(GetRailType(this->tile));
362 max_speed += (max_speed / 2) * rti->curve_speed;
364 if (this->tcache.cached_tilt) {
365 /* Apply max_speed bonus of 20% for a tilting train */
366 max_speed += max_speed / 5;
369 /* Apply max_speed modifier (cached value is fixed-point binary with 8 fractional bits)
370 * and clamp the result to an acceptable range. */
371 max_speed += (max_speed * this->tcache.cached_curve_speed_mod) / 256;
372 max_speed = Clamp(max_speed, 2, absolute_max_speed);
375 return max_speed;
379 * Calculates the maximum speed of the vehicle under its current conditions.
380 * @return Maximum speed of the vehicle.
382 int Train::GetCurrentMaxSpeed() const
384 int max_speed = _settings_game.vehicle.train_acceleration_model == AM_ORIGINAL ?
385 this->gcache.cached_max_track_speed :
386 this->tcache.cached_max_curve_speed;
388 if (_settings_game.vehicle.train_acceleration_model == AM_REALISTIC && IsRailStationTile(this->tile)) {
389 StationID sid = GetStationIndex(this->tile);
390 if (this->current_order.ShouldStopAtStation(this, sid)) {
391 int station_ahead;
392 int station_length;
393 int stop_at = GetTrainStopLocation(sid, this->tile, this, &station_ahead, &station_length);
395 /* The distance to go is whatever is still ahead of the train minus the
396 * distance from the train's stop location to the end of the platform */
397 int distance_to_go = station_ahead / TILE_SIZE - (station_length - stop_at) / TILE_SIZE;
399 if (distance_to_go > 0) {
400 int st_max_speed = 120;
402 int delta_v = this->cur_speed / (distance_to_go + 1);
403 if (max_speed > (this->cur_speed - delta_v)) {
404 st_max_speed = this->cur_speed - (delta_v / 10);
407 st_max_speed = std::max(st_max_speed, 25 * distance_to_go);
408 max_speed = std::min(max_speed, st_max_speed);
413 for (const Train *u = this; u != nullptr; u = u->Next()) {
414 if (_settings_game.vehicle.train_acceleration_model == AM_REALISTIC && u->track == TRACK_BIT_DEPOT) {
415 max_speed = std::min(max_speed, 61);
416 break;
419 /* Vehicle is on the middle part of a bridge. */
420 if (u->track == TRACK_BIT_WORMHOLE && !(u->vehstatus & VS_HIDDEN)) {
421 max_speed = std::min<int>(max_speed, GetBridgeSpec(GetBridgeType(u->tile))->speed);
425 max_speed = std::min<int>(max_speed, this->current_order.GetMaxSpeed());
426 return std::min<int>(max_speed, this->gcache.cached_max_track_speed);
429 /** Update acceleration of the train from the cached power and weight. */
430 void Train::UpdateAcceleration()
432 assert(this->IsFrontEngine() || this->IsFreeWagon());
434 uint power = this->gcache.cached_power;
435 uint weight = this->gcache.cached_weight;
436 assert(weight != 0);
437 this->acceleration = Clamp(power / weight * 4, 1, 255);
440 int Train::GetCursorImageOffset() const
442 if (this->gcache.cached_veh_length != 8 && HasBit(this->flags, VRF_REVERSE_DIRECTION) && !HasBit(EngInfo(this->engine_type)->misc_flags, EF_RAIL_FLIPS)) {
443 int reference_width = TRAININFO_DEFAULT_VEHICLE_WIDTH;
445 const Engine *e = this->GetEngine();
446 if (e->GetGRF() != nullptr && is_custom_sprite(e->u.rail.image_index)) {
447 reference_width = e->GetGRF()->traininfo_vehicle_width;
450 return ScaleSpriteTrad((this->gcache.cached_veh_length - (int)VEHICLE_LENGTH) * reference_width / (int)VEHICLE_LENGTH);
452 return 0;
456 * Get the width of a train vehicle image in the GUI.
457 * @param offset Additional offset for positioning the sprite; set to nullptr if not needed
458 * @return Width in pixels
460 int Train::GetDisplayImageWidth(Point *offset) const
462 int reference_width = TRAININFO_DEFAULT_VEHICLE_WIDTH;
463 int vehicle_pitch = 0;
465 const Engine *e = this->GetEngine();
466 if (e->GetGRF() != nullptr && is_custom_sprite(e->u.rail.image_index)) {
467 reference_width = e->GetGRF()->traininfo_vehicle_width;
468 vehicle_pitch = e->GetGRF()->traininfo_vehicle_pitch;
471 if (offset != nullptr) {
472 if (HasBit(this->flags, VRF_REVERSE_DIRECTION) && !HasBit(EngInfo(this->engine_type)->misc_flags, EF_RAIL_FLIPS)) {
473 offset->x = ScaleSpriteTrad(((int)this->gcache.cached_veh_length - (int)VEHICLE_LENGTH / 2) * reference_width / (int)VEHICLE_LENGTH);
474 } else {
475 offset->x = ScaleSpriteTrad(reference_width) / 2;
477 offset->y = ScaleSpriteTrad(vehicle_pitch);
479 return ScaleSpriteTrad(this->gcache.cached_veh_length * reference_width / VEHICLE_LENGTH);
482 static SpriteID GetDefaultTrainSprite(uint8_t spritenum, Direction direction)
484 assert(IsValidImageIndex<VEH_TRAIN>(spritenum));
485 return ((direction + _engine_sprite_add[spritenum]) & _engine_sprite_and[spritenum]) + _engine_sprite_base[spritenum];
489 * Get the sprite to display the train.
490 * @param direction Direction of view/travel.
491 * @param image_type Visualisation context.
492 * @return Sprite to display.
494 void Train::GetImage(Direction direction, EngineImageType image_type, VehicleSpriteSeq *result) const
496 uint8_t spritenum = this->spritenum;
498 if (HasBit(this->flags, VRF_REVERSE_DIRECTION)) direction = ReverseDir(direction);
500 if (is_custom_sprite(spritenum)) {
501 GetCustomVehicleSprite(this, (Direction)(direction + 4 * IS_CUSTOM_SECONDHEAD_SPRITE(spritenum)), image_type, result);
502 if (result->IsValid()) return;
504 spritenum = this->GetEngine()->original_image_index;
507 assert(IsValidImageIndex<VEH_TRAIN>(spritenum));
508 SpriteID sprite = GetDefaultTrainSprite(spritenum, direction);
510 if (this->cargo.StoredCount() >= this->cargo_cap / 2U) sprite += _wagon_full_adder[spritenum];
512 result->Set(sprite);
515 static void GetRailIcon(EngineID engine, bool rear_head, int &y, EngineImageType image_type, VehicleSpriteSeq *result)
517 const Engine *e = Engine::Get(engine);
518 Direction dir = rear_head ? DIR_E : DIR_W;
519 uint8_t spritenum = e->u.rail.image_index;
521 if (is_custom_sprite(spritenum)) {
522 GetCustomVehicleIcon(engine, dir, image_type, result);
523 if (result->IsValid()) {
524 if (e->GetGRF() != nullptr) {
525 y += ScaleSpriteTrad(e->GetGRF()->traininfo_vehicle_pitch);
527 return;
530 spritenum = Engine::Get(engine)->original_image_index;
533 if (rear_head) spritenum++;
535 result->Set(GetDefaultTrainSprite(spritenum, DIR_W));
538 void DrawTrainEngine(int left, int right, int preferred_x, int y, EngineID engine, PaletteID pal, EngineImageType image_type)
540 if (RailVehInfo(engine)->railveh_type == RAILVEH_MULTIHEAD) {
541 int yf = y;
542 int yr = y;
544 VehicleSpriteSeq seqf, seqr;
545 GetRailIcon(engine, false, yf, image_type, &seqf);
546 GetRailIcon(engine, true, yr, image_type, &seqr);
548 Rect rectf, rectr;
549 seqf.GetBounds(&rectf);
550 seqr.GetBounds(&rectr);
552 preferred_x = Clamp(preferred_x,
553 left - UnScaleGUI(rectf.left) + ScaleSpriteTrad(14),
554 right - UnScaleGUI(rectr.right) - ScaleSpriteTrad(15));
556 seqf.Draw(preferred_x - ScaleSpriteTrad(14), yf, pal, pal == PALETTE_CRASH);
557 seqr.Draw(preferred_x + ScaleSpriteTrad(15), yr, pal, pal == PALETTE_CRASH);
558 } else {
559 VehicleSpriteSeq seq;
560 GetRailIcon(engine, false, y, image_type, &seq);
562 Rect rect;
563 seq.GetBounds(&rect);
564 preferred_x = Clamp(preferred_x,
565 left - UnScaleGUI(rect.left),
566 right - UnScaleGUI(rect.right));
568 seq.Draw(preferred_x, y, pal, pal == PALETTE_CRASH);
573 * Get the size of the sprite of a train sprite heading west, or both heads (used for lists).
574 * @param engine The engine to get the sprite from.
575 * @param[out] width The width of the sprite.
576 * @param[out] height The height of the sprite.
577 * @param[out] xoffs Number of pixels to shift the sprite to the right.
578 * @param[out] yoffs Number of pixels to shift the sprite downwards.
579 * @param image_type Context the sprite is used in.
581 void GetTrainSpriteSize(EngineID engine, uint &width, uint &height, int &xoffs, int &yoffs, EngineImageType image_type)
583 int y = 0;
585 VehicleSpriteSeq seq;
586 GetRailIcon(engine, false, y, image_type, &seq);
588 Rect rect;
589 seq.GetBounds(&rect);
591 width = UnScaleGUI(rect.Width());
592 height = UnScaleGUI(rect.Height());
593 xoffs = UnScaleGUI(rect.left);
594 yoffs = UnScaleGUI(rect.top);
596 if (RailVehInfo(engine)->railveh_type == RAILVEH_MULTIHEAD) {
597 GetRailIcon(engine, true, y, image_type, &seq);
598 seq.GetBounds(&rect);
600 /* Calculate values relative to an imaginary center between the two sprites. */
601 width = ScaleSpriteTrad(TRAININFO_DEFAULT_VEHICLE_WIDTH) + UnScaleGUI(rect.right) - xoffs;
602 height = std::max<uint>(height, UnScaleGUI(rect.Height()));
603 xoffs = xoffs - ScaleSpriteTrad(TRAININFO_DEFAULT_VEHICLE_WIDTH) / 2;
604 yoffs = std::min(yoffs, UnScaleGUI(rect.top));
609 * Build a railroad wagon.
610 * @param flags type of operation.
611 * @param tile tile of the depot where rail-vehicle is built.
612 * @param e the engine to build.
613 * @param[out] ret the vehicle that has been built.
614 * @return the cost of this operation or an error.
616 static CommandCost CmdBuildRailWagon(DoCommandFlag flags, TileIndex tile, const Engine *e, Vehicle **ret)
618 const RailVehicleInfo *rvi = &e->u.rail;
620 /* Check that the wagon can drive on the track in question */
621 if (!IsCompatibleRail(rvi->railtype, GetRailType(tile))) return CMD_ERROR;
623 if (flags & DC_EXEC) {
624 Train *v = new Train();
625 *ret = v;
626 v->spritenum = rvi->image_index;
628 v->engine_type = e->index;
629 v->gcache.first_engine = INVALID_ENGINE; // needs to be set before first callback
631 DiagDirection dir = GetRailDepotDirection(tile);
633 v->direction = DiagDirToDir(dir);
634 v->tile = tile;
636 int x = TileX(tile) * TILE_SIZE | _vehicle_initial_x_fract[dir];
637 int y = TileY(tile) * TILE_SIZE | _vehicle_initial_y_fract[dir];
639 v->x_pos = x;
640 v->y_pos = y;
641 v->z_pos = GetSlopePixelZ(x, y, true);
642 v->owner = _current_company;
643 v->track = TRACK_BIT_DEPOT;
644 v->vehstatus = VS_HIDDEN | VS_DEFPAL;
646 v->SetWagon();
648 v->SetFreeWagon();
649 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
651 v->cargo_type = e->GetDefaultCargoType();
652 assert(IsValidCargoID(v->cargo_type));
653 v->cargo_cap = rvi->capacity;
654 v->refit_cap = 0;
656 v->railtype = rvi->railtype;
658 v->date_of_last_service = TimerGameEconomy::date;
659 v->date_of_last_service_newgrf = TimerGameCalendar::date;
660 v->build_year = TimerGameCalendar::year;
661 v->sprite_cache.sprite_seq.Set(SPR_IMG_QUERY);
662 v->random_bits = Random();
664 v->group_id = DEFAULT_GROUP;
666 if (TestVehicleBuildProbability(v, v->engine_type, BuildProbabilityType::Reversed)) SetBit(v->flags, VRF_REVERSE_DIRECTION);
667 AddArticulatedParts(v);
669 v->UpdatePosition();
670 v->First()->ConsistChanged(CCF_ARRANGE);
671 UpdateTrainGroupID(v->First());
673 CheckConsistencyOfArticulatedVehicle(v);
675 /* Try to connect the vehicle to one of free chains of wagons. */
676 for (Train *w : Train::Iterate()) {
677 if (w->tile == tile && ///< Same depot
678 w->IsFreeWagon() && ///< A free wagon chain
679 w->engine_type == e->index && ///< Same type
680 w->First() != v && ///< Don't connect to ourself
681 !(w->vehstatus & VS_CRASHED)) { ///< Not crashed/flooded
682 if (Command<CMD_MOVE_RAIL_VEHICLE>::Do(DC_EXEC, v->index, w->Last()->index, true).Succeeded()) {
683 break;
689 return CommandCost();
692 /** Move all free vehicles in the depot to the train */
693 void NormalizeTrainVehInDepot(const Train *u)
695 assert(u->IsEngine());
696 for (const Train *v : Train::Iterate()) {
697 if (v->IsFreeWagon() && v->tile == u->tile &&
698 v->track == TRACK_BIT_DEPOT) {
699 if (Command<CMD_MOVE_RAIL_VEHICLE>::Do(DC_EXEC, v->index, u->index, true).Failed()) {
700 break;
706 static void AddRearEngineToMultiheadedTrain(Train *v)
708 Train *u = new Train();
709 v->value >>= 1;
710 u->value = v->value;
711 u->direction = v->direction;
712 u->owner = v->owner;
713 u->tile = v->tile;
714 u->x_pos = v->x_pos;
715 u->y_pos = v->y_pos;
716 u->z_pos = v->z_pos;
717 u->track = TRACK_BIT_DEPOT;
718 u->vehstatus = v->vehstatus & ~VS_STOPPED;
719 u->spritenum = v->spritenum + 1;
720 u->cargo_type = v->cargo_type;
721 u->cargo_subtype = v->cargo_subtype;
722 u->cargo_cap = v->cargo_cap;
723 u->refit_cap = v->refit_cap;
724 u->railtype = v->railtype;
725 u->engine_type = v->engine_type;
726 u->date_of_last_service = v->date_of_last_service;
727 u->date_of_last_service_newgrf = v->date_of_last_service_newgrf;
728 u->build_year = v->build_year;
729 u->sprite_cache.sprite_seq.Set(SPR_IMG_QUERY);
730 u->random_bits = Random();
731 v->SetMultiheaded();
732 u->SetMultiheaded();
733 v->SetNext(u);
734 if (TestVehicleBuildProbability(u, u->engine_type, BuildProbabilityType::Reversed)) SetBit(u->flags, VRF_REVERSE_DIRECTION);
735 u->UpdatePosition();
737 /* Now we need to link the front and rear engines together */
738 v->other_multiheaded_part = u;
739 u->other_multiheaded_part = v;
743 * Build a railroad vehicle.
744 * @param flags type of operation.
745 * @param tile tile of the depot where rail-vehicle is built.
746 * @param e the engine to build.
747 * @param[out] ret the vehicle that has been built.
748 * @return the cost of this operation or an error.
750 CommandCost CmdBuildRailVehicle(DoCommandFlag flags, TileIndex tile, const Engine *e, Vehicle **ret)
752 const RailVehicleInfo *rvi = &e->u.rail;
754 if (rvi->railveh_type == RAILVEH_WAGON) return CmdBuildRailWagon(flags, tile, e, ret);
756 /* Check if depot and new engine uses the same kind of tracks *
757 * We need to see if the engine got power on the tile to avoid electric engines in non-electric depots */
758 if (!HasPowerOnRail(rvi->railtype, GetRailType(tile))) return CMD_ERROR;
760 if (flags & DC_EXEC) {
761 DiagDirection dir = GetRailDepotDirection(tile);
762 int x = TileX(tile) * TILE_SIZE + _vehicle_initial_x_fract[dir];
763 int y = TileY(tile) * TILE_SIZE + _vehicle_initial_y_fract[dir];
765 Train *v = new Train();
766 *ret = v;
767 v->direction = DiagDirToDir(dir);
768 v->tile = tile;
769 v->owner = _current_company;
770 v->x_pos = x;
771 v->y_pos = y;
772 v->z_pos = GetSlopePixelZ(x, y, true);
773 v->track = TRACK_BIT_DEPOT;
774 v->vehstatus = VS_HIDDEN | VS_STOPPED | VS_DEFPAL;
775 v->spritenum = rvi->image_index;
776 v->cargo_type = e->GetDefaultCargoType();
777 assert(IsValidCargoID(v->cargo_type));
778 v->cargo_cap = rvi->capacity;
779 v->refit_cap = 0;
780 v->last_station_visited = INVALID_STATION;
781 v->last_loading_station = INVALID_STATION;
783 v->engine_type = e->index;
784 v->gcache.first_engine = INVALID_ENGINE; // needs to be set before first callback
786 v->reliability = e->reliability;
787 v->reliability_spd_dec = e->reliability_spd_dec;
788 v->max_age = e->GetLifeLengthInDays();
790 v->railtype = rvi->railtype;
792 v->SetServiceInterval(Company::Get(_current_company)->settings.vehicle.servint_trains);
793 v->date_of_last_service = TimerGameEconomy::date;
794 v->date_of_last_service_newgrf = TimerGameCalendar::date;
795 v->build_year = TimerGameCalendar::year;
796 v->sprite_cache.sprite_seq.Set(SPR_IMG_QUERY);
797 v->random_bits = Random();
799 if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) SetBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE);
800 v->SetServiceIntervalIsPercent(Company::Get(_current_company)->settings.vehicle.servint_ispercent);
802 v->group_id = DEFAULT_GROUP;
804 v->SetFrontEngine();
805 v->SetEngine();
807 if (TestVehicleBuildProbability(v, v->engine_type, BuildProbabilityType::Reversed)) SetBit(v->flags, VRF_REVERSE_DIRECTION);
808 v->UpdatePosition();
810 if (rvi->railveh_type == RAILVEH_MULTIHEAD) {
811 AddRearEngineToMultiheadedTrain(v);
812 } else {
813 AddArticulatedParts(v);
816 v->ConsistChanged(CCF_ARRANGE);
817 UpdateTrainGroupID(v);
819 CheckConsistencyOfArticulatedVehicle(v);
822 return CommandCost();
825 static Train *FindGoodVehiclePos(const Train *src)
827 EngineID eng = src->engine_type;
828 TileIndex tile = src->tile;
830 for (Train *dst : Train::Iterate()) {
831 if (dst->IsFreeWagon() && dst->tile == tile && !(dst->vehstatus & VS_CRASHED)) {
832 /* check so all vehicles in the line have the same engine. */
833 Train *t = dst;
834 while (t->engine_type == eng) {
835 t = t->Next();
836 if (t == nullptr) return dst;
841 return nullptr;
844 /** Helper type for lists/vectors of trains */
845 typedef std::vector<Train *> TrainList;
848 * Make a backup of a train into a train list.
849 * @param list to make the backup in
850 * @param t the train to make the backup of
852 static void MakeTrainBackup(TrainList &list, Train *t)
854 for (; t != nullptr; t = t->Next()) list.push_back(t);
858 * Restore the train from the backup list.
859 * @param list the train to restore.
861 static void RestoreTrainBackup(TrainList &list)
863 /* No train, nothing to do. */
864 if (list.empty()) return;
866 Train *prev = nullptr;
867 /* Iterate over the list and rebuild it. */
868 for (Train *t : list) {
869 if (prev != nullptr) {
870 prev->SetNext(t);
871 } else if (t->Previous() != nullptr) {
872 /* Make sure the head of the train is always the first in the chain. */
873 t->Previous()->SetNext(nullptr);
875 prev = t;
880 * Remove the given wagon from its consist.
881 * @param part the part of the train to remove.
882 * @param chain whether to remove the whole chain.
884 static void RemoveFromConsist(Train *part, bool chain = false)
886 Train *tail = chain ? part->Last() : part->GetLastEnginePart();
888 /* Unlink at the front, but make it point to the next
889 * vehicle after the to be remove part. */
890 if (part->Previous() != nullptr) part->Previous()->SetNext(tail->Next());
892 /* Unlink at the back */
893 tail->SetNext(nullptr);
897 * Inserts a chain into the train at dst.
898 * @param dst the place where to append after.
899 * @param chain the chain to actually add.
901 static void InsertInConsist(Train *dst, Train *chain)
903 /* We do not want to add something in the middle of an articulated part. */
904 assert(dst != nullptr && (dst->Next() == nullptr || !dst->Next()->IsArticulatedPart()));
906 chain->Last()->SetNext(dst->Next());
907 dst->SetNext(chain);
911 * Normalise the dual heads in the train, i.e. if one is
912 * missing move that one to this train.
913 * @param t the train to normalise.
915 static void NormaliseDualHeads(Train *t)
917 for (; t != nullptr; t = t->GetNextVehicle()) {
918 if (!t->IsMultiheaded() || !t->IsEngine()) continue;
920 /* Make sure that there are no free cars before next engine */
921 Train *u;
922 for (u = t; u->Next() != nullptr && !u->Next()->IsEngine(); u = u->Next()) {}
924 if (u == t->other_multiheaded_part) continue;
926 /* Remove the part from the 'wrong' train */
927 RemoveFromConsist(t->other_multiheaded_part);
928 /* And add it to the 'right' train */
929 InsertInConsist(u, t->other_multiheaded_part);
934 * Normalise the sub types of the parts in this chain.
935 * @param chain the chain to normalise.
937 static void NormaliseSubtypes(Train *chain)
939 /* Nothing to do */
940 if (chain == nullptr) return;
942 /* We must be the first in the chain. */
943 assert(chain->Previous() == nullptr);
945 /* Set the appropriate bits for the first in the chain. */
946 if (chain->IsWagon()) {
947 chain->SetFreeWagon();
948 } else {
949 assert(chain->IsEngine());
950 chain->SetFrontEngine();
953 /* Now clear the bits for the rest of the chain */
954 for (Train *t = chain->Next(); t != nullptr; t = t->Next()) {
955 t->ClearFreeWagon();
956 t->ClearFrontEngine();
961 * Check/validate whether we may actually build a new train.
962 * @note All vehicles are/were 'heads' of their chains.
963 * @param original_dst The original destination chain.
964 * @param dst The destination chain after constructing the train.
965 * @param original_src The original source chain.
966 * @param src The source chain after constructing the train.
967 * @return possible error of this command.
969 static CommandCost CheckNewTrain(Train *original_dst, Train *dst, Train *original_src, Train *src)
971 /* Just add 'new' engines and subtract the original ones.
972 * If that's less than or equal to 0 we can be sure we did
973 * not add any engines (read: trains) along the way. */
974 if ((src != nullptr && src->IsEngine() ? 1 : 0) +
975 (dst != nullptr && dst->IsEngine() ? 1 : 0) -
976 (original_src != nullptr && original_src->IsEngine() ? 1 : 0) -
977 (original_dst != nullptr && original_dst->IsEngine() ? 1 : 0) <= 0) {
978 return CommandCost();
981 /* Get a free unit number and check whether it's within the bounds.
982 * There will always be a maximum of one new train. */
983 if (GetFreeUnitNumber(VEH_TRAIN) <= _settings_game.vehicle.max_trains) return CommandCost();
985 return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
989 * Check whether the train parts can be attached.
990 * @param t the train to check
991 * @return possible error of this command.
993 static CommandCost CheckTrainAttachment(Train *t)
995 /* No multi-part train, no need to check. */
996 if (t == nullptr || t->Next() == nullptr) return CommandCost();
998 /* The maximum length for a train. For each part we decrease this by one
999 * and if the result is negative the train is simply too long. */
1000 int allowed_len = _settings_game.vehicle.max_train_length * TILE_SIZE - t->gcache.cached_veh_length;
1002 /* For free-wagon chains, check if they are within the max_train_length limit. */
1003 if (!t->IsEngine()) {
1004 t = t->Next();
1005 while (t != nullptr) {
1006 allowed_len -= t->gcache.cached_veh_length;
1008 t = t->Next();
1011 if (allowed_len < 0) return_cmd_error(STR_ERROR_TRAIN_TOO_LONG);
1012 return CommandCost();
1015 Train *head = t;
1016 Train *prev = t;
1018 /* Break the prev -> t link so it always holds within the loop. */
1019 t = t->Next();
1020 prev->SetNext(nullptr);
1022 /* Make sure the cache is cleared. */
1023 head->InvalidateNewGRFCache();
1025 while (t != nullptr) {
1026 allowed_len -= t->gcache.cached_veh_length;
1028 Train *next = t->Next();
1030 /* Unlink the to-be-added piece; it is already unlinked from the previous
1031 * part due to the fact that the prev -> t link is broken. */
1032 t->SetNext(nullptr);
1034 /* Don't check callback for articulated or rear dual headed parts */
1035 if (!t->IsArticulatedPart() && !t->IsRearDualheaded()) {
1036 /* Back up and clear the first_engine data to avoid using wagon override group */
1037 EngineID first_engine = t->gcache.first_engine;
1038 t->gcache.first_engine = INVALID_ENGINE;
1040 /* We don't want the cache to interfere. head's cache is cleared before
1041 * the loop and after each callback does not need to be cleared here. */
1042 t->InvalidateNewGRFCache();
1044 uint16_t callback = GetVehicleCallbackParent(CBID_TRAIN_ALLOW_WAGON_ATTACH, 0, 0, head->engine_type, t, head);
1046 /* Restore original first_engine data */
1047 t->gcache.first_engine = first_engine;
1049 /* We do not want to remember any cached variables from the test run */
1050 t->InvalidateNewGRFCache();
1051 head->InvalidateNewGRFCache();
1053 if (callback != CALLBACK_FAILED) {
1054 /* A failing callback means everything is okay */
1055 StringID error = STR_NULL;
1057 if (head->GetGRF()->grf_version < 8) {
1058 if (callback == 0xFD) error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
1059 if (callback < 0xFD) error = GetGRFStringID(head->GetGRFID(), 0xD000 + callback);
1060 if (callback >= 0x100) ErrorUnknownCallbackResult(head->GetGRFID(), CBID_TRAIN_ALLOW_WAGON_ATTACH, callback);
1061 } else {
1062 if (callback < 0x400) {
1063 error = GetGRFStringID(head->GetGRFID(), 0xD000 + callback);
1064 } else {
1065 switch (callback) {
1066 case 0x400: // allow if railtypes match (always the case for OpenTTD)
1067 case 0x401: // allow
1068 break;
1070 default: // unknown reason -> disallow
1071 case 0x402: // disallow attaching
1072 error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
1073 break;
1078 if (error != STR_NULL) return_cmd_error(error);
1082 /* And link it to the new part. */
1083 prev->SetNext(t);
1084 prev = t;
1085 t = next;
1088 if (allowed_len < 0) return_cmd_error(STR_ERROR_TRAIN_TOO_LONG);
1089 return CommandCost();
1093 * Validate whether we are going to create valid trains.
1094 * @note All vehicles are/were 'heads' of their chains.
1095 * @param original_dst The original destination chain.
1096 * @param dst The destination chain after constructing the train.
1097 * @param original_src The original source chain.
1098 * @param src The source chain after constructing the train.
1099 * @param check_limit Whether to check the vehicle limit.
1100 * @return possible error of this command.
1102 static CommandCost ValidateTrains(Train *original_dst, Train *dst, Train *original_src, Train *src, bool check_limit)
1104 /* Check whether we may actually construct the trains. */
1105 CommandCost ret = CheckTrainAttachment(src);
1106 if (ret.Failed()) return ret;
1107 ret = CheckTrainAttachment(dst);
1108 if (ret.Failed()) return ret;
1110 /* Check whether we need to build a new train. */
1111 return check_limit ? CheckNewTrain(original_dst, dst, original_src, src) : CommandCost();
1115 * Arrange the trains in the wanted way.
1116 * @param dst_head The destination chain of the to be moved vehicle.
1117 * @param dst The destination for the to be moved vehicle.
1118 * @param src_head The source chain of the to be moved vehicle.
1119 * @param src The to be moved vehicle.
1120 * @param move_chain Whether to move all vehicles after src or not.
1122 static void ArrangeTrains(Train **dst_head, Train *dst, Train **src_head, Train *src, bool move_chain)
1124 /* First determine the front of the two resulting trains */
1125 if (*src_head == *dst_head) {
1126 /* If we aren't moving part(s) to a new train, we are just moving the
1127 * front back and there is not destination head. */
1128 *dst_head = nullptr;
1129 } else if (*dst_head == nullptr) {
1130 /* If we are moving to a new train the head of the move train would become
1131 * the head of the new vehicle. */
1132 *dst_head = src;
1135 if (src == *src_head) {
1136 /* If we are moving the front of a train then we are, in effect, creating
1137 * a new head for the train. Point to that. Unless we are moving the whole
1138 * train in which case there is not 'source' train anymore.
1139 * In case we are a multiheaded part we want the complete thing to come
1140 * with us, so src->GetNextUnit(), however... when we are e.g. a wagon
1141 * that is followed by a rear multihead we do not want to include that. */
1142 *src_head = move_chain ? nullptr :
1143 (src->IsMultiheaded() ? src->GetNextUnit() : src->GetNextVehicle());
1146 /* Now it's just simply removing the part that we are going to move from the
1147 * source train and *if* the destination is a not a new train add the chain
1148 * at the destination location. */
1149 RemoveFromConsist(src, move_chain);
1150 if (*dst_head != src) InsertInConsist(dst, src);
1152 /* Now normalise the dual heads, that is move the dual heads around in such
1153 * a way that the head and rear of a dual head are in the same train */
1154 NormaliseDualHeads(*src_head);
1155 NormaliseDualHeads(*dst_head);
1159 * Normalise the head of the train again, i.e. that is tell the world that
1160 * we have changed and update all kinds of variables.
1161 * @param head the train to update.
1163 static void NormaliseTrainHead(Train *head)
1165 /* Not much to do! */
1166 if (head == nullptr) return;
1168 /* Tell the 'world' the train changed. */
1169 head->ConsistChanged(CCF_ARRANGE);
1170 UpdateTrainGroupID(head);
1172 /* Not a front engine, i.e. a free wagon chain. No need to do more. */
1173 if (!head->IsFrontEngine()) return;
1175 /* Update the refit button and window */
1176 InvalidateWindowData(WC_VEHICLE_REFIT, head->index, VIWD_CONSIST_CHANGED);
1177 SetWindowWidgetDirty(WC_VEHICLE_VIEW, head->index, WID_VV_REFIT);
1179 /* If we don't have a unit number yet, set one. */
1180 if (head->unitnumber != 0) return;
1181 head->unitnumber = GetFreeUnitNumber(VEH_TRAIN);
1185 * Move a rail vehicle around inside the depot.
1186 * @param flags type of operation
1187 * Note: DC_AUTOREPLACE is set when autoreplace tries to undo its modifications or moves vehicles to temporary locations inside the depot.
1188 * @param src_veh source vehicle index
1189 * @param dest_veh what wagon to put the source wagon AFTER, XXX - INVALID_VEHICLE to make a new line
1190 * @param move_chain move all vehicles following the source vehicle
1191 * @return the cost of this operation or an error
1193 CommandCost CmdMoveRailVehicle(DoCommandFlag flags, VehicleID src_veh, VehicleID dest_veh, bool move_chain)
1195 Train *src = Train::GetIfValid(src_veh);
1196 if (src == nullptr) return CMD_ERROR;
1198 CommandCost ret = CheckOwnership(src->owner);
1199 if (ret.Failed()) return ret;
1201 /* Do not allow moving crashed vehicles inside the depot, it is likely to cause asserts later */
1202 if (src->vehstatus & VS_CRASHED) return CMD_ERROR;
1204 /* if nothing is selected as destination, try and find a matching vehicle to drag to. */
1205 Train *dst;
1206 if (dest_veh == INVALID_VEHICLE) {
1207 dst = (src->IsEngine() || (flags & DC_AUTOREPLACE)) ? nullptr : FindGoodVehiclePos(src);
1208 } else {
1209 dst = Train::GetIfValid(dest_veh);
1210 if (dst == nullptr) return CMD_ERROR;
1212 ret = CheckOwnership(dst->owner);
1213 if (ret.Failed()) return ret;
1215 /* Do not allow appending to crashed vehicles, too */
1216 if (dst->vehstatus & VS_CRASHED) return CMD_ERROR;
1219 /* if an articulated part is being handled, deal with its parent vehicle */
1220 src = src->GetFirstEnginePart();
1221 if (dst != nullptr) {
1222 dst = dst->GetFirstEnginePart();
1225 /* don't move the same vehicle.. */
1226 if (src == dst) return CommandCost();
1228 /* locate the head of the two chains */
1229 Train *src_head = src->First();
1230 Train *dst_head;
1231 if (dst != nullptr) {
1232 dst_head = dst->First();
1233 if (dst_head->tile != src_head->tile) return CMD_ERROR;
1234 /* Now deal with articulated part of destination wagon */
1235 dst = dst->GetLastEnginePart();
1236 } else {
1237 dst_head = nullptr;
1240 if (src->IsRearDualheaded()) return_cmd_error(STR_ERROR_REAR_ENGINE_FOLLOW_FRONT);
1242 /* When moving all wagons, we can't have the same src_head and dst_head */
1243 if (move_chain && src_head == dst_head) return CommandCost();
1245 /* When moving a multiheaded part to be place after itself, bail out. */
1246 if (!move_chain && dst != nullptr && dst->IsRearDualheaded() && src == dst->other_multiheaded_part) return CommandCost();
1248 /* Check if all vehicles in the source train are stopped inside a depot. */
1249 if (!src_head->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
1251 /* Check if all vehicles in the destination train are stopped inside a depot. */
1252 if (dst_head != nullptr && !dst_head->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
1254 /* First make a backup of the order of the trains. That way we can do
1255 * whatever we want with the order and later on easily revert. */
1256 TrainList original_src;
1257 TrainList original_dst;
1259 MakeTrainBackup(original_src, src_head);
1260 MakeTrainBackup(original_dst, dst_head);
1262 /* Also make backup of the original heads as ArrangeTrains can change them.
1263 * For the destination head we do not care if it is the same as the source
1264 * head because in that case it's just a copy. */
1265 Train *original_src_head = src_head;
1266 Train *original_dst_head = (dst_head == src_head ? nullptr : dst_head);
1268 /* We want this information from before the rearrangement, but execute this after the validation.
1269 * original_src_head can't be nullptr; src is by definition != nullptr, so src_head can't be nullptr as
1270 * src->GetFirst() always yields non-nullptr, so eventually original_src_head != nullptr as well. */
1271 bool original_src_head_front_engine = original_src_head->IsFrontEngine();
1272 bool original_dst_head_front_engine = original_dst_head != nullptr && original_dst_head->IsFrontEngine();
1274 /* (Re)arrange the trains in the wanted arrangement. */
1275 ArrangeTrains(&dst_head, dst, &src_head, src, move_chain);
1277 if ((flags & DC_AUTOREPLACE) == 0) {
1278 /* If the autoreplace flag is set we do not need to test for the validity
1279 * because we are going to revert the train to its original state. As we
1280 * assume the original state was correct autoreplace can skip this. */
1281 ret = ValidateTrains(original_dst_head, dst_head, original_src_head, src_head, true);
1282 if (ret.Failed()) {
1283 /* Restore the train we had. */
1284 RestoreTrainBackup(original_src);
1285 RestoreTrainBackup(original_dst);
1286 return ret;
1290 /* do it? */
1291 if (flags & DC_EXEC) {
1292 /* Remove old heads from the statistics */
1293 if (original_src_head_front_engine) GroupStatistics::CountVehicle(original_src_head, -1);
1294 if (original_dst_head_front_engine) GroupStatistics::CountVehicle(original_dst_head, -1);
1296 /* First normalise the sub types of the chains. */
1297 NormaliseSubtypes(src_head);
1298 NormaliseSubtypes(dst_head);
1300 /* There are 14 different cases:
1301 * 1) front engine gets moved to a new train, it stays a front engine.
1302 * a) the 'next' part is a wagon that becomes a free wagon chain.
1303 * b) the 'next' part is an engine that becomes a front engine.
1304 * c) there is no 'next' part, nothing else happens
1305 * 2) front engine gets moved to another train, it is not a front engine anymore
1306 * a) the 'next' part is a wagon that becomes a free wagon chain.
1307 * b) the 'next' part is an engine that becomes a front engine.
1308 * c) there is no 'next' part, nothing else happens
1309 * 3) front engine gets moved to later in the current train, it is not a front engine anymore.
1310 * a) the 'next' part is a wagon that becomes a free wagon chain.
1311 * b) the 'next' part is an engine that becomes a front engine.
1312 * 4) free wagon gets moved
1313 * a) the 'next' part is a wagon that becomes a free wagon chain.
1314 * b) the 'next' part is an engine that becomes a front engine.
1315 * c) there is no 'next' part, nothing else happens
1316 * 5) non front engine gets moved and becomes a new train, nothing else happens
1317 * 6) non front engine gets moved within a train / to another train, nothing happens
1318 * 7) wagon gets moved, nothing happens
1320 if (src == original_src_head && src->IsEngine() && !src->IsFrontEngine()) {
1321 /* Cases #2 and #3: the front engine gets trashed. */
1322 CloseWindowById(WC_VEHICLE_VIEW, src->index);
1323 CloseWindowById(WC_VEHICLE_ORDERS, src->index);
1324 CloseWindowById(WC_VEHICLE_REFIT, src->index);
1325 CloseWindowById(WC_VEHICLE_DETAILS, src->index);
1326 CloseWindowById(WC_VEHICLE_TIMETABLE, src->index);
1327 DeleteNewGRFInspectWindow(GSF_TRAINS, src->index);
1328 SetWindowDirty(WC_COMPANY, _current_company);
1330 if (src_head != nullptr && src_head->IsFrontEngine()) {
1331 /* Cases #?b: Transfer order, unit number and other stuff
1332 * to the new front engine. */
1333 src_head->orders = src->orders;
1334 if (src_head->orders != nullptr) src_head->AddToShared(src);
1335 src_head->CopyVehicleConfigAndStatistics(src);
1337 /* Remove stuff not valid anymore for non-front engines. */
1338 DeleteVehicleOrders(src);
1339 src->unitnumber = 0;
1340 src->name.clear();
1343 /* We weren't a front engine but are becoming one. So
1344 * we should be put in the default group. */
1345 if (original_src_head != src && dst_head == src) {
1346 SetTrainGroupID(src, DEFAULT_GROUP);
1347 SetWindowDirty(WC_COMPANY, _current_company);
1350 /* Add new heads to statistics */
1351 if (src_head != nullptr && src_head->IsFrontEngine()) GroupStatistics::CountVehicle(src_head, 1);
1352 if (dst_head != nullptr && dst_head->IsFrontEngine()) GroupStatistics::CountVehicle(dst_head, 1);
1354 /* Handle 'new engine' part of cases #1b, #2b, #3b, #4b and #5 in NormaliseTrainHead. */
1355 NormaliseTrainHead(src_head);
1356 NormaliseTrainHead(dst_head);
1358 if ((flags & DC_NO_CARGO_CAP_CHECK) == 0) {
1359 CheckCargoCapacity(src_head);
1360 CheckCargoCapacity(dst_head);
1363 if (src_head != nullptr) src_head->First()->MarkDirty();
1364 if (dst_head != nullptr) dst_head->First()->MarkDirty();
1366 /* We are undoubtedly changing something in the depot and train list. */
1367 InvalidateWindowData(WC_VEHICLE_DEPOT, src->tile);
1368 InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
1369 } else {
1370 /* We don't want to execute what we're just tried. */
1371 RestoreTrainBackup(original_src);
1372 RestoreTrainBackup(original_dst);
1375 return CommandCost();
1379 * Sell a (single) train wagon/engine.
1380 * @param flags type of operation
1381 * @param t the train wagon to sell
1382 * @param sell_chain the selling mode
1383 * - sell_chain = false: only sell the single dragged wagon/engine (and any belonging rear-engines)
1384 * - sell_chain = true: sell the vehicle and all vehicles following it in the chain
1385 * if the wagon is dragged, don't delete the possibly belonging rear-engine to some front
1386 * @param backup_order make order backup?
1387 * @param user the user for the order backup.
1388 * @return the cost of this operation or an error
1390 CommandCost CmdSellRailWagon(DoCommandFlag flags, Vehicle *t, bool sell_chain, bool backup_order, ClientID user)
1392 Train *v = Train::From(t)->GetFirstEnginePart();
1393 Train *first = v->First();
1395 if (v->IsRearDualheaded()) return_cmd_error(STR_ERROR_REAR_ENGINE_FOLLOW_FRONT);
1397 /* First make a backup of the order of the train. That way we can do
1398 * whatever we want with the order and later on easily revert. */
1399 TrainList original;
1400 MakeTrainBackup(original, first);
1402 /* We need to keep track of the new head and the head of what we're going to sell. */
1403 Train *new_head = first;
1404 Train *sell_head = nullptr;
1406 /* Split the train in the wanted way. */
1407 ArrangeTrains(&sell_head, nullptr, &new_head, v, sell_chain);
1409 /* We don't need to validate the second train; it's going to be sold. */
1410 CommandCost ret = ValidateTrains(nullptr, nullptr, first, new_head, (flags & DC_AUTOREPLACE) == 0);
1411 if (ret.Failed()) {
1412 /* Restore the train we had. */
1413 RestoreTrainBackup(original);
1414 return ret;
1417 if (first->orders == nullptr && !OrderList::CanAllocateItem()) {
1418 /* Restore the train we had. */
1419 RestoreTrainBackup(original);
1420 return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
1423 CommandCost cost(EXPENSES_NEW_VEHICLES);
1424 for (Train *part = sell_head; part != nullptr; part = part->Next()) cost.AddCost(-part->value);
1426 /* do it? */
1427 if (flags & DC_EXEC) {
1428 /* First normalise the sub types of the chain. */
1429 NormaliseSubtypes(new_head);
1431 if (v == first && !sell_chain && new_head != nullptr && new_head->IsFrontEngine()) {
1432 if (v->IsEngine()) {
1433 /* We are selling the front engine. In this case we want to
1434 * 'give' the order, unit number and such to the new head. */
1435 new_head->orders = first->orders;
1436 new_head->AddToShared(first);
1437 DeleteVehicleOrders(first);
1439 /* Copy other important data from the front engine */
1440 new_head->CopyVehicleConfigAndStatistics(first);
1442 GroupStatistics::CountVehicle(new_head, 1); // after copying over the profit, if required
1443 } else if (v->IsPrimaryVehicle() && backup_order) {
1444 OrderBackup::Backup(v, user);
1447 /* We need to update the information about the train. */
1448 NormaliseTrainHead(new_head);
1450 /* We are undoubtedly changing something in the depot and train list. */
1451 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
1452 InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
1454 /* Actually delete the sold 'goods' */
1455 delete sell_head;
1456 } else {
1457 /* We don't want to execute what we're just tried. */
1458 RestoreTrainBackup(original);
1461 return cost;
1464 void Train::UpdateDeltaXY()
1466 /* Set common defaults. */
1467 this->x_offs = -1;
1468 this->y_offs = -1;
1469 this->x_extent = 3;
1470 this->y_extent = 3;
1471 this->z_extent = 6;
1472 this->x_bb_offs = 0;
1473 this->y_bb_offs = 0;
1475 /* Set if flipped and engine is NOT flagged with custom flip handling. */
1476 int flipped = HasBit(this->flags, VRF_REVERSE_DIRECTION) && !HasBit(EngInfo(this->engine_type)->misc_flags, EF_RAIL_FLIPS);
1477 /* If flipped and vehicle length is odd, we need to adjust the bounding box offset slightly. */
1478 int flip_offs = flipped && (this->gcache.cached_veh_length & 1);
1480 Direction dir = this->direction;
1481 if (flipped) dir = ReverseDir(dir);
1483 if (!IsDiagonalDirection(dir)) {
1484 static const int _sign_table[] =
1486 /* x, y */
1487 -1, -1, // DIR_N
1488 -1, 1, // DIR_E
1489 1, 1, // DIR_S
1490 1, -1, // DIR_W
1493 int half_shorten = (VEHICLE_LENGTH - this->gcache.cached_veh_length + flipped) / 2;
1495 /* For all straight directions, move the bound box to the centre of the vehicle, but keep the size. */
1496 this->x_offs -= half_shorten * _sign_table[dir];
1497 this->y_offs -= half_shorten * _sign_table[dir + 1];
1498 this->x_extent += this->x_bb_offs = half_shorten * _sign_table[dir];
1499 this->y_extent += this->y_bb_offs = half_shorten * _sign_table[dir + 1];
1500 } else {
1501 switch (dir) {
1502 /* Shorten southern corner of the bounding box according the vehicle length
1503 * and center the bounding box on the vehicle. */
1504 case DIR_NE:
1505 this->x_offs = 1 - (this->gcache.cached_veh_length + 1) / 2 + flip_offs;
1506 this->x_extent = this->gcache.cached_veh_length - 1;
1507 this->x_bb_offs = -1;
1508 break;
1510 case DIR_NW:
1511 this->y_offs = 1 - (this->gcache.cached_veh_length + 1) / 2 + flip_offs;
1512 this->y_extent = this->gcache.cached_veh_length - 1;
1513 this->y_bb_offs = -1;
1514 break;
1516 /* Move northern corner of the bounding box down according to vehicle length
1517 * and center the bounding box on the vehicle. */
1518 case DIR_SW:
1519 this->x_offs = 1 + (this->gcache.cached_veh_length + 1) / 2 - VEHICLE_LENGTH - flip_offs;
1520 this->x_extent = VEHICLE_LENGTH - 1;
1521 this->x_bb_offs = VEHICLE_LENGTH - this->gcache.cached_veh_length - 1;
1522 break;
1524 case DIR_SE:
1525 this->y_offs = 1 + (this->gcache.cached_veh_length + 1) / 2 - VEHICLE_LENGTH - flip_offs;
1526 this->y_extent = VEHICLE_LENGTH - 1;
1527 this->y_bb_offs = VEHICLE_LENGTH - this->gcache.cached_veh_length - 1;
1528 break;
1530 default:
1531 NOT_REACHED();
1537 * Mark a train as stuck and stop it if it isn't stopped right now.
1538 * @param v %Train to mark as being stuck.
1540 static void MarkTrainAsStuck(Train *v)
1542 if (!HasBit(v->flags, VRF_TRAIN_STUCK)) {
1543 /* It is the first time the problem occurred, set the "train stuck" flag. */
1544 SetBit(v->flags, VRF_TRAIN_STUCK);
1546 v->wait_counter = 0;
1548 /* Stop train */
1549 v->cur_speed = 0;
1550 v->subspeed = 0;
1551 v->SetLastSpeed();
1553 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
1558 * Swap the two up/down flags in two ways:
1559 * - Swap values of \a swap_flag1 and \a swap_flag2, and
1560 * - If going up previously (#GVF_GOINGUP_BIT set), the #GVF_GOINGDOWN_BIT is set, and vice versa.
1561 * @param[in,out] swap_flag1 First train flag.
1562 * @param[in,out] swap_flag2 Second train flag.
1564 static void SwapTrainFlags(uint16_t *swap_flag1, uint16_t *swap_flag2)
1566 uint16_t flag1 = *swap_flag1;
1567 uint16_t flag2 = *swap_flag2;
1569 /* Clear the flags */
1570 ClrBit(*swap_flag1, GVF_GOINGUP_BIT);
1571 ClrBit(*swap_flag1, GVF_GOINGDOWN_BIT);
1572 ClrBit(*swap_flag2, GVF_GOINGUP_BIT);
1573 ClrBit(*swap_flag2, GVF_GOINGDOWN_BIT);
1575 /* Reverse the rail-flags (if needed) */
1576 if (HasBit(flag1, GVF_GOINGUP_BIT)) {
1577 SetBit(*swap_flag2, GVF_GOINGDOWN_BIT);
1578 } else if (HasBit(flag1, GVF_GOINGDOWN_BIT)) {
1579 SetBit(*swap_flag2, GVF_GOINGUP_BIT);
1581 if (HasBit(flag2, GVF_GOINGUP_BIT)) {
1582 SetBit(*swap_flag1, GVF_GOINGDOWN_BIT);
1583 } else if (HasBit(flag2, GVF_GOINGDOWN_BIT)) {
1584 SetBit(*swap_flag1, GVF_GOINGUP_BIT);
1589 * Updates some variables after swapping the vehicle.
1590 * @param v swapped vehicle
1592 static void UpdateStatusAfterSwap(Train *v)
1594 /* Reverse the direction. */
1595 if (v->track != TRACK_BIT_DEPOT) v->direction = ReverseDir(v->direction);
1597 /* Call the proper EnterTile function unless we are in a wormhole. */
1598 if (v->track != TRACK_BIT_WORMHOLE) {
1599 VehicleEnterTile(v, v->tile, v->x_pos, v->y_pos);
1600 } else {
1601 /* VehicleEnter_TunnelBridge() sets TRACK_BIT_WORMHOLE when the vehicle
1602 * is on the last bit of the bridge head (frame == TILE_SIZE - 1).
1603 * If we were swapped with such a vehicle, we have set TRACK_BIT_WORMHOLE,
1604 * when we shouldn't have. Check if this is the case. */
1605 TileIndex vt = TileVirtXY(v->x_pos, v->y_pos);
1606 if (IsTileType(vt, MP_TUNNELBRIDGE)) {
1607 VehicleEnterTile(v, vt, v->x_pos, v->y_pos);
1608 if (v->track != TRACK_BIT_WORMHOLE && IsBridgeTile(v->tile)) {
1609 /* We have just left the wormhole, possibly set the
1610 * "goingdown" bit. UpdateInclination() can be used
1611 * because we are at the border of the tile. */
1612 v->UpdatePosition();
1613 v->UpdateInclination(true, true);
1614 return;
1619 v->UpdatePosition();
1620 v->UpdateViewport(true, true);
1624 * Swap vehicles \a l and \a r in consist \a v, and reverse their direction.
1625 * @param v Consist to change.
1626 * @param l %Vehicle index in the consist of the first vehicle.
1627 * @param r %Vehicle index in the consist of the second vehicle.
1629 void ReverseTrainSwapVeh(Train *v, int l, int r)
1631 Train *a, *b;
1633 /* locate vehicles to swap */
1634 for (a = v; l != 0; l--) a = a->Next();
1635 for (b = v; r != 0; r--) b = b->Next();
1637 if (a != b) {
1638 /* swap the hidden bits */
1640 uint16_t tmp = (a->vehstatus & ~VS_HIDDEN) | (b->vehstatus & VS_HIDDEN);
1641 b->vehstatus = (b->vehstatus & ~VS_HIDDEN) | (a->vehstatus & VS_HIDDEN);
1642 a->vehstatus = tmp;
1645 Swap(a->track, b->track);
1646 Swap(a->direction, b->direction);
1647 Swap(a->x_pos, b->x_pos);
1648 Swap(a->y_pos, b->y_pos);
1649 Swap(a->tile, b->tile);
1650 Swap(a->z_pos, b->z_pos);
1652 SwapTrainFlags(&a->gv_flags, &b->gv_flags);
1654 UpdateStatusAfterSwap(a);
1655 UpdateStatusAfterSwap(b);
1656 } else {
1657 /* Swap GVF_GOINGUP_BIT/GVF_GOINGDOWN_BIT.
1658 * This is a little bit redundant way, a->gv_flags will
1659 * be (re)set twice, but it reduces code duplication */
1660 SwapTrainFlags(&a->gv_flags, &a->gv_flags);
1661 UpdateStatusAfterSwap(a);
1667 * Check if the vehicle is a train
1668 * @param v vehicle on tile
1669 * @return v if it is a train, nullptr otherwise
1671 static Vehicle *TrainOnTileEnum(Vehicle *v, void *)
1673 return (v->type == VEH_TRAIN) ? v : nullptr;
1677 * Check if a level crossing tile has a train on it
1678 * @param tile tile to test
1679 * @return true if a train is on the crossing
1680 * @pre tile is a level crossing
1682 bool TrainOnCrossing(TileIndex tile)
1684 assert(IsLevelCrossingTile(tile));
1686 return HasVehicleOnPos(tile, nullptr, &TrainOnTileEnum);
1691 * Checks if a train is approaching a rail-road crossing
1692 * @param v vehicle on tile
1693 * @param data tile with crossing we are testing
1694 * @return v if it is approaching a crossing, nullptr otherwise
1696 static Vehicle *TrainApproachingCrossingEnum(Vehicle *v, void *data)
1698 if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) return nullptr;
1700 Train *t = Train::From(v);
1701 if (!t->IsFrontEngine()) return nullptr;
1703 TileIndex tile = *(TileIndex *)data;
1705 if (TrainApproachingCrossingTile(t) != tile) return nullptr;
1707 return t;
1712 * Finds a vehicle approaching rail-road crossing
1713 * @param tile tile to test
1714 * @return true if a vehicle is approaching the crossing
1715 * @pre tile is a rail-road crossing
1717 static bool TrainApproachingCrossing(TileIndex tile)
1719 assert(IsLevelCrossingTile(tile));
1721 DiagDirection dir = AxisToDiagDir(GetCrossingRailAxis(tile));
1722 TileIndex tile_from = tile + TileOffsByDiagDir(dir);
1724 if (HasVehicleOnPos(tile_from, &tile, &TrainApproachingCrossingEnum)) return true;
1726 dir = ReverseDiagDir(dir);
1727 tile_from = tile + TileOffsByDiagDir(dir);
1729 return HasVehicleOnPos(tile_from, &tile, &TrainApproachingCrossingEnum);
1733 * Check if a level crossing should be barred.
1734 * @param tile The tile to check.
1735 * @return True if the crossing should be barred, else false.
1737 static inline bool CheckLevelCrossing(TileIndex tile)
1739 /* reserved || train on crossing || train approaching crossing */
1740 return HasCrossingReservation(tile) || TrainOnCrossing(tile) || TrainApproachingCrossing(tile);
1744 * Sets a level crossing tile to the correct state.
1745 * @param tile Tile to update.
1746 * @param sound Should we play sound?
1747 * @param force_barred Should we set the crossing to barred?
1748 * @pre tile is a rail-road crossing.
1750 static void UpdateLevelCrossingTile(TileIndex tile, bool sound, bool force_barred)
1752 assert(IsLevelCrossingTile(tile));
1753 bool set_barred;
1755 /* We force the crossing to be barred when an adjacent crossing is barred, otherwise let it decide for itself. */
1756 set_barred = force_barred || CheckLevelCrossing(tile);
1758 /* The state has changed */
1759 if (set_barred != IsCrossingBarred(tile)) {
1760 if (set_barred && sound && _settings_client.sound.ambient) SndPlayTileFx(SND_0E_LEVEL_CROSSING, tile);
1761 SetCrossingBarred(tile, set_barred);
1762 MarkTileDirtyByTile(tile);
1767 * Update a level crossing to barred or open (crossing may include multiple adjacent tiles).
1768 * @param tile Tile which causes the update.
1769 * @param sound Should we play sound?
1770 * @param force_bar Should we force the crossing to be barred?
1772 void UpdateLevelCrossing(TileIndex tile, bool sound, bool force_bar)
1774 if (!IsLevelCrossingTile(tile)) return;
1776 bool forced_state = force_bar;
1778 const Axis axis = GetCrossingRoadAxis(tile);
1779 const DiagDirection dir1 = AxisToDiagDir(axis);
1780 const DiagDirection dir2 = ReverseDiagDir(dir1);
1782 /* Check if an adjacent crossing is barred. */
1783 for (DiagDirection dir : { dir1, dir2 }) {
1784 for (TileIndex t = tile; !forced_state && t < Map::Size() && IsLevelCrossingTile(t) && GetCrossingRoadAxis(t) == axis; t = TileAddByDiagDir(t, dir)) {
1785 forced_state |= CheckLevelCrossing(t);
1789 /* Now that we know whether all tiles in this crossing should be barred or open,
1790 * we need to update those tiles. We start with the tile itself, then look along the road axis. */
1791 UpdateLevelCrossingTile(tile, sound, forced_state);
1792 for (DiagDirection dir : { dir1, dir2 }) {
1793 for (TileIndex t = TileAddByDiagDir(tile, dir); t < Map::Size() && IsLevelCrossingTile(t) && GetCrossingRoadAxis(t) == axis; t = TileAddByDiagDir(t, dir)) {
1794 UpdateLevelCrossingTile(t, sound, forced_state);
1800 * Find adjacent level crossing tiles in this multi-track crossing and mark them dirty.
1801 * @param tile The tile which causes the update.
1802 * @param road_axis The road axis.
1804 void MarkDirtyAdjacentLevelCrossingTiles(TileIndex tile, Axis road_axis)
1806 const DiagDirection dir1 = AxisToDiagDir(road_axis);
1807 const DiagDirection dir2 = ReverseDiagDir(dir1);
1808 for (DiagDirection dir : { dir1, dir2 }) {
1809 const TileIndex t = TileAddByDiagDir(tile, dir);
1810 if (t < Map::Size() && IsLevelCrossingTile(t) && GetCrossingRoadAxis(t) == road_axis) {
1811 MarkTileDirtyByTile(t);
1817 * Update adjacent level crossing tiles in this multi-track crossing, due to removal of a level crossing tile.
1818 * @param tile The crossing tile which has been or is about to be removed, and which caused the update.
1819 * @param road_axis The road axis.
1821 void UpdateAdjacentLevelCrossingTilesOnLevelCrossingRemoval(TileIndex tile, Axis road_axis)
1823 const DiagDirection dir1 = AxisToDiagDir(road_axis);
1824 const DiagDirection dir2 = ReverseDiagDir(dir1);
1825 for (DiagDirection dir : { dir1, dir2 }) {
1826 const TileIndexDiff diff = TileOffsByDiagDir(dir);
1827 bool occupied = false;
1828 for (TileIndex t = tile + diff; t < Map::Size() && IsLevelCrossingTile(t) && GetCrossingRoadAxis(t) == road_axis; t += diff) {
1829 occupied |= CheckLevelCrossing(t);
1831 if (occupied) {
1832 /* Mark the immediately adjacent tile dirty */
1833 const TileIndex t = tile + diff;
1834 if (t < Map::Size() && IsLevelCrossingTile(t) && GetCrossingRoadAxis(t) == road_axis) {
1835 MarkTileDirtyByTile(t);
1837 } else {
1838 /* Unbar the crossing tiles in this direction as necessary */
1839 for (TileIndex t = tile + diff; t < Map::Size() && IsLevelCrossingTile(t) && GetCrossingRoadAxis(t) == road_axis; t += diff) {
1840 if (IsCrossingBarred(t)) {
1841 /* The crossing tile is barred, unbar it and continue to check the next tile */
1842 SetCrossingBarred(t, false);
1843 MarkTileDirtyByTile(t);
1844 } else {
1845 /* The crossing tile is already unbarred, mark the tile dirty and stop checking */
1846 MarkTileDirtyByTile(t);
1847 break;
1855 * Bars crossing and plays ding-ding sound if not barred already
1856 * @param tile tile with crossing
1857 * @pre tile is a rail-road crossing
1859 static inline void MaybeBarCrossingWithSound(TileIndex tile)
1861 if (!IsCrossingBarred(tile)) {
1862 SetCrossingReservation(tile, true);
1863 UpdateLevelCrossing(tile, true);
1869 * Advances wagons for train reversing, needed for variable length wagons.
1870 * This one is called before the train is reversed.
1871 * @param v First vehicle in chain
1873 static void AdvanceWagonsBeforeSwap(Train *v)
1875 Train *base = v;
1876 Train *first = base; // first vehicle to move
1877 Train *last = v->Last(); // last vehicle to move
1878 uint length = CountVehiclesInChain(v);
1880 while (length > 2) {
1881 last = last->Previous();
1882 first = first->Next();
1884 int differential = base->CalcNextVehicleOffset() - last->CalcNextVehicleOffset();
1886 /* do not update images now
1887 * negative differential will be handled in AdvanceWagonsAfterSwap() */
1888 for (int i = 0; i < differential; i++) TrainController(first, last->Next());
1890 base = first; // == base->Next()
1891 length -= 2;
1897 * Advances wagons for train reversing, needed for variable length wagons.
1898 * This one is called after the train is reversed.
1899 * @param v First vehicle in chain
1901 static void AdvanceWagonsAfterSwap(Train *v)
1903 /* first of all, fix the situation when the train was entering a depot */
1904 Train *dep = v; // last vehicle in front of just left depot
1905 while (dep->Next() != nullptr && (dep->track == TRACK_BIT_DEPOT || dep->Next()->track != TRACK_BIT_DEPOT)) {
1906 dep = dep->Next(); // find first vehicle outside of a depot, with next vehicle inside a depot
1909 Train *leave = dep->Next(); // first vehicle in a depot we are leaving now
1911 if (leave != nullptr) {
1912 /* 'pull' next wagon out of the depot, so we won't miss it (it could stay in depot forever) */
1913 int d = TicksToLeaveDepot(dep);
1915 if (d <= 0) {
1916 leave->vehstatus &= ~VS_HIDDEN; // move it out of the depot
1917 leave->track = TrackToTrackBits(GetRailDepotTrack(leave->tile));
1918 for (int i = 0; i >= d; i--) TrainController(leave, nullptr); // maybe move it, and maybe let another wagon leave
1920 } else {
1921 dep = nullptr; // no vehicle in a depot, so no vehicle leaving a depot
1924 Train *base = v;
1925 Train *first = base; // first vehicle to move
1926 Train *last = v->Last(); // last vehicle to move
1927 uint length = CountVehiclesInChain(v);
1929 /* We have to make sure all wagons that leave a depot because of train reversing are moved correctly
1930 * they have already correct spacing, so we have to make sure they are moved how they should */
1931 bool nomove = (dep == nullptr); // If there is no vehicle leaving a depot, limit the number of wagons moved immediately.
1933 while (length > 2) {
1934 /* we reached vehicle (originally) in front of a depot, stop now
1935 * (we would move wagons that are already moved with new wagon length). */
1936 if (base == dep) break;
1938 /* the last wagon was that one leaving a depot, so do not move it anymore */
1939 if (last == dep) nomove = true;
1941 last = last->Previous();
1942 first = first->Next();
1944 int differential = last->CalcNextVehicleOffset() - base->CalcNextVehicleOffset();
1946 /* do not update images now */
1947 for (int i = 0; i < differential; i++) TrainController(first, (nomove ? last->Next() : nullptr));
1949 base = first; // == base->Next()
1950 length -= 2;
1954 static bool IsWholeTrainInsideDepot(const Train *v)
1956 for (const Train *u = v; u != nullptr; u = u->Next()) {
1957 if (u->track != TRACK_BIT_DEPOT || u->tile != v->tile) return false;
1959 return true;
1963 * Turn a train around.
1964 * @param v %Train to turn around.
1966 void ReverseTrainDirection(Train *v)
1968 if (IsRailDepotTile(v->tile)) {
1969 if (IsWholeTrainInsideDepot(v)) return;
1970 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
1973 /* Clear path reservation in front if train is not stuck. */
1974 if (!HasBit(v->flags, VRF_TRAIN_STUCK)) FreeTrainTrackReservation(v);
1976 /* Check if we were approaching a rail/road-crossing */
1977 TileIndex crossing = TrainApproachingCrossingTile(v);
1979 /* count number of vehicles */
1980 int r = CountVehiclesInChain(v) - 1; // number of vehicles - 1
1982 AdvanceWagonsBeforeSwap(v);
1984 /* swap start<>end, start+1<>end-1, ... */
1985 int l = 0;
1986 do {
1987 ReverseTrainSwapVeh(v, l++, r--);
1988 } while (l <= r);
1990 AdvanceWagonsAfterSwap(v);
1992 if (IsRailDepotTile(v->tile)) {
1993 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
1996 ToggleBit(v->flags, VRF_TOGGLE_REVERSE);
1998 ClrBit(v->flags, VRF_REVERSING);
2000 /* recalculate cached data */
2001 v->ConsistChanged(CCF_TRACK);
2003 /* update all images */
2004 for (Train *u = v; u != nullptr; u = u->Next()) u->UpdateViewport(false, false);
2006 /* update crossing we were approaching */
2007 if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
2009 /* maybe we are approaching crossing now, after reversal */
2010 crossing = TrainApproachingCrossingTile(v);
2011 if (crossing != INVALID_TILE) MaybeBarCrossingWithSound(crossing);
2013 /* If we are inside a depot after reversing, don't bother with path reserving. */
2014 if (v->track == TRACK_BIT_DEPOT) {
2015 /* Can't be stuck here as inside a depot is always a safe tile. */
2016 if (HasBit(v->flags, VRF_TRAIN_STUCK)) SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
2017 ClrBit(v->flags, VRF_TRAIN_STUCK);
2018 return;
2021 /* VehicleExitDir does not always produce the desired dir for depots and
2022 * tunnels/bridges that is needed for UpdateSignalsOnSegment. */
2023 DiagDirection dir = VehicleExitDir(v->direction, v->track);
2024 if (IsRailDepotTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE)) dir = INVALID_DIAGDIR;
2026 if (UpdateSignalsOnSegment(v->tile, dir, v->owner) == SIGSEG_PBS || _settings_game.pf.reserve_paths) {
2027 /* If we are currently on a tile with conventional signals, we can't treat the
2028 * current tile as a safe tile or we would enter a PBS block without a reservation. */
2029 bool first_tile_okay = !(IsTileType(v->tile, MP_RAILWAY) &&
2030 HasSignalOnTrackdir(v->tile, v->GetVehicleTrackdir()) &&
2031 !IsPbsSignal(GetSignalType(v->tile, FindFirstTrack(v->track))));
2033 /* If we are on a depot tile facing outwards, do not treat the current tile as safe. */
2034 if (IsRailDepotTile(v->tile) && TrackdirToExitdir(v->GetVehicleTrackdir()) == GetRailDepotDirection(v->tile)) first_tile_okay = false;
2036 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
2037 if (TryPathReserve(v, false, first_tile_okay)) {
2038 /* Do a look-ahead now in case our current tile was already a safe tile. */
2039 CheckNextTrainTile(v);
2040 } else if (v->current_order.GetType() != OT_LOADING) {
2041 /* Do not wait for a way out when we're still loading */
2042 MarkTrainAsStuck(v);
2044 } else if (HasBit(v->flags, VRF_TRAIN_STUCK)) {
2045 /* A train not inside a PBS block can't be stuck. */
2046 ClrBit(v->flags, VRF_TRAIN_STUCK);
2047 v->wait_counter = 0;
2052 * Reverse train.
2053 * @param flags type of operation
2054 * @param veh_id train to reverse
2055 * @param reverse_single_veh if true, reverse a unit in a train (needs to be in a depot)
2056 * @return the cost of this operation or an error
2058 CommandCost CmdReverseTrainDirection(DoCommandFlag flags, VehicleID veh_id, bool reverse_single_veh)
2060 Train *v = Train::GetIfValid(veh_id);
2061 if (v == nullptr) return CMD_ERROR;
2063 CommandCost ret = CheckOwnership(v->owner);
2064 if (ret.Failed()) return ret;
2066 if (reverse_single_veh) {
2067 /* turn a single unit around */
2069 if (v->IsMultiheaded() || HasBit(EngInfo(v->engine_type)->callback_mask, CBM_VEHICLE_ARTIC_ENGINE)) {
2070 return_cmd_error(STR_ERROR_CAN_T_REVERSE_DIRECTION_RAIL_VEHICLE_MULTIPLE_UNITS);
2073 Train *front = v->First();
2074 /* make sure the vehicle is stopped in the depot */
2075 if (!front->IsStoppedInDepot()) {
2076 return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
2079 if (flags & DC_EXEC) {
2080 ToggleBit(v->flags, VRF_REVERSE_DIRECTION);
2082 front->ConsistChanged(CCF_ARRANGE);
2083 SetWindowDirty(WC_VEHICLE_DEPOT, front->tile);
2084 SetWindowDirty(WC_VEHICLE_DETAILS, front->index);
2085 SetWindowDirty(WC_VEHICLE_VIEW, front->index);
2086 SetWindowClassesDirty(WC_TRAINS_LIST);
2088 } else {
2089 /* turn the whole train around */
2090 if (!v->IsPrimaryVehicle()) return CMD_ERROR;
2091 if ((v->vehstatus & VS_CRASHED) || v->breakdown_ctr != 0) return CMD_ERROR;
2093 if (flags & DC_EXEC) {
2094 /* Properly leave the station if we are loading and won't be loading anymore */
2095 if (v->current_order.IsType(OT_LOADING)) {
2096 const Vehicle *last = v;
2097 while (last->Next() != nullptr) last = last->Next();
2099 /* not a station || different station --> leave the station */
2100 if (!IsTileType(last->tile, MP_STATION) || GetStationIndex(last->tile) != GetStationIndex(v->tile)) {
2101 v->LeaveStation();
2105 /* We cancel any 'skip signal at dangers' here */
2106 v->force_proceed = TFP_NONE;
2107 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
2109 if (_settings_game.vehicle.train_acceleration_model != AM_ORIGINAL && v->cur_speed != 0) {
2110 ToggleBit(v->flags, VRF_REVERSING);
2111 } else {
2112 v->cur_speed = 0;
2113 v->SetLastSpeed();
2114 HideFillingPercent(&v->fill_percent_te_id);
2115 ReverseTrainDirection(v);
2118 /* Unbunching data is no longer valid. */
2119 v->ResetDepotUnbunching();
2122 return CommandCost();
2126 * Force a train through a red signal
2127 * @param flags type of operation
2128 * @param veh_id train to ignore the red signal
2129 * @return the cost of this operation or an error
2131 CommandCost CmdForceTrainProceed(DoCommandFlag flags, VehicleID veh_id)
2133 Train *t = Train::GetIfValid(veh_id);
2134 if (t == nullptr) return CMD_ERROR;
2136 if (!t->IsPrimaryVehicle()) return CMD_ERROR;
2138 CommandCost ret = CheckOwnership(t->owner);
2139 if (ret.Failed()) return ret;
2142 if (flags & DC_EXEC) {
2143 /* If we are forced to proceed, cancel that order.
2144 * If we are marked stuck we would want to force the train
2145 * to proceed to the next signal. In the other cases we
2146 * would like to pass the signal at danger and run till the
2147 * next signal we encounter. */
2148 t->force_proceed = t->force_proceed == TFP_SIGNAL ? TFP_NONE : HasBit(t->flags, VRF_TRAIN_STUCK) || t->IsChainInDepot() ? TFP_STUCK : TFP_SIGNAL;
2149 SetWindowDirty(WC_VEHICLE_VIEW, t->index);
2151 /* Unbunching data is no longer valid. */
2152 t->ResetDepotUnbunching();
2155 return CommandCost();
2159 * Try to find a depot nearby.
2160 * @param v %Train that wants a depot.
2161 * @param max_distance Maximal search distance.
2162 * @return Information where the closest train depot is located.
2163 * @pre The given vehicle must not be crashed!
2165 static FindDepotData FindClosestTrainDepot(Train *v, int max_distance)
2167 assert(!(v->vehstatus & VS_CRASHED));
2169 if (IsRailDepotTile(v->tile)) return FindDepotData(v->tile, 0);
2171 PBSTileInfo origin = FollowTrainReservation(v);
2172 if (IsRailDepotTile(origin.tile)) return FindDepotData(origin.tile, 0);
2174 switch (_settings_game.pf.pathfinder_for_trains) {
2175 case VPF_NPF: return NPFTrainFindNearestDepot(v, max_distance);
2176 case VPF_YAPF: return YapfTrainFindNearestDepot(v, max_distance);
2178 default: NOT_REACHED();
2182 ClosestDepot Train::FindClosestDepot()
2184 FindDepotData tfdd = FindClosestTrainDepot(this, 0);
2185 if (tfdd.best_length == UINT_MAX) return ClosestDepot();
2187 return ClosestDepot(tfdd.tile, GetDepotIndex(tfdd.tile), tfdd.reverse);
2190 /** Play a sound for a train leaving the station. */
2191 void Train::PlayLeaveStationSound(bool force) const
2193 static const SoundFx sfx[] = {
2194 SND_04_DEPARTURE_STEAM,
2195 SND_0A_DEPARTURE_TRAIN,
2196 SND_0A_DEPARTURE_TRAIN,
2197 SND_47_DEPARTURE_MONORAIL,
2198 SND_41_DEPARTURE_MAGLEV
2201 if (PlayVehicleSound(this, VSE_START, force)) return;
2203 SndPlayVehicleFx(sfx[RailVehInfo(this->engine_type)->engclass], this);
2207 * Check if the train is on the last reserved tile and try to extend the path then.
2208 * @param v %Train that needs its path extended.
2210 static void CheckNextTrainTile(Train *v)
2212 /* Don't do any look-ahead if path_backoff_interval is 255. */
2213 if (_settings_game.pf.path_backoff_interval == 255) return;
2215 /* Exit if we are inside a depot. */
2216 if (v->track == TRACK_BIT_DEPOT) return;
2218 switch (v->current_order.GetType()) {
2219 /* Exit if we reached our destination depot. */
2220 case OT_GOTO_DEPOT:
2221 if (v->tile == v->dest_tile) return;
2222 break;
2224 case OT_GOTO_WAYPOINT:
2225 /* If we reached our waypoint, make sure we see that. */
2226 if (IsRailWaypointTile(v->tile) && GetStationIndex(v->tile) == v->current_order.GetDestination()) ProcessOrders(v);
2227 break;
2229 case OT_NOTHING:
2230 case OT_LEAVESTATION:
2231 case OT_LOADING:
2232 /* Exit if the current order doesn't have a destination, but the train has orders. */
2233 if (v->GetNumOrders() > 0) return;
2234 break;
2236 default:
2237 break;
2239 /* Exit if we are on a station tile and are going to stop. */
2240 if (IsRailStationTile(v->tile) && v->current_order.ShouldStopAtStation(v, GetStationIndex(v->tile))) return;
2242 Trackdir td = v->GetVehicleTrackdir();
2244 /* On a tile with a red non-pbs signal, don't look ahead. */
2245 if (IsTileType(v->tile, MP_RAILWAY) && HasSignalOnTrackdir(v->tile, td) &&
2246 !IsPbsSignal(GetSignalType(v->tile, TrackdirToTrack(td))) &&
2247 GetSignalStateByTrackdir(v->tile, td) == SIGNAL_STATE_RED) return;
2249 CFollowTrackRail ft(v);
2250 if (!ft.Follow(v->tile, td)) return;
2252 if (!HasReservedTracks(ft.m_new_tile, TrackdirBitsToTrackBits(ft.m_new_td_bits))) {
2253 /* Next tile is not reserved. */
2254 if (KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE) {
2255 if (HasPbsSignalOnTrackdir(ft.m_new_tile, FindFirstTrackdir(ft.m_new_td_bits))) {
2256 /* If the next tile is a PBS signal, try to make a reservation. */
2257 TrackBits tracks = TrackdirBitsToTrackBits(ft.m_new_td_bits);
2258 if (Rail90DegTurnDisallowed(GetTileRailType(ft.m_old_tile), GetTileRailType(ft.m_new_tile))) {
2259 tracks &= ~TrackCrossesTracks(TrackdirToTrack(ft.m_old_td));
2261 ChooseTrainTrack(v, ft.m_new_tile, ft.m_exitdir, tracks, false, nullptr, false);
2268 * Will the train stay in the depot the next tick?
2269 * @param v %Train to check.
2270 * @return True if it stays in the depot, false otherwise.
2272 static bool CheckTrainStayInDepot(Train *v)
2274 /* bail out if not all wagons are in the same depot or not in a depot at all */
2275 for (const Train *u = v; u != nullptr; u = u->Next()) {
2276 if (u->track != TRACK_BIT_DEPOT || u->tile != v->tile) return false;
2279 /* if the train got no power, then keep it in the depot */
2280 if (v->gcache.cached_power == 0) {
2281 v->vehstatus |= VS_STOPPED;
2282 SetWindowDirty(WC_VEHICLE_DEPOT, v->tile);
2283 return true;
2286 /* Check if we should wait here for unbunching. */
2287 if (v->IsWaitingForUnbunching()) return true;
2289 SigSegState seg_state;
2291 if (v->force_proceed == TFP_NONE) {
2292 /* force proceed was not pressed */
2293 if (++v->wait_counter < 37) {
2294 SetWindowClassesDirty(WC_TRAINS_LIST);
2295 return true;
2298 v->wait_counter = 0;
2300 seg_state = _settings_game.pf.reserve_paths ? SIGSEG_PBS : UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
2301 if (seg_state == SIGSEG_FULL || HasDepotReservation(v->tile)) {
2302 /* Full and no PBS signal in block or depot reserved, can't exit. */
2303 SetWindowClassesDirty(WC_TRAINS_LIST);
2304 return true;
2306 } else {
2307 seg_state = _settings_game.pf.reserve_paths ? SIGSEG_PBS : UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
2310 /* We are leaving a depot, but have to go to the exact same one; re-enter. */
2311 if (v->current_order.IsType(OT_GOTO_DEPOT) && v->tile == v->dest_tile) {
2312 /* Service when depot has no reservation. */
2313 if (!HasDepotReservation(v->tile)) VehicleEnterDepot(v);
2314 return true;
2317 /* Only leave when we can reserve a path to our destination. */
2318 if (seg_state == SIGSEG_PBS && !TryPathReserve(v) && v->force_proceed == TFP_NONE) {
2319 /* No path and no force proceed. */
2320 SetWindowClassesDirty(WC_TRAINS_LIST);
2321 MarkTrainAsStuck(v);
2322 return true;
2325 SetDepotReservation(v->tile, true);
2326 if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(v->tile);
2328 VehicleServiceInDepot(v);
2329 v->LeaveUnbunchingDepot();
2330 v->PlayLeaveStationSound();
2331 SetWindowClassesDirty(WC_TRAINS_LIST);
2333 v->track = TRACK_BIT_X;
2334 if (v->direction & 2) v->track = TRACK_BIT_Y;
2336 v->vehstatus &= ~VS_HIDDEN;
2337 v->cur_speed = 0;
2339 v->UpdateViewport(true, true);
2340 v->UpdatePosition();
2341 UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
2342 v->UpdateAcceleration();
2343 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
2345 return false;
2349 * Clear the reservation of \a tile that was just left by a wagon on \a track_dir.
2350 * @param v %Train owning the reservation.
2351 * @param tile Tile with reservation to clear.
2352 * @param track_dir Track direction to clear.
2354 static void ClearPathReservation(const Train *v, TileIndex tile, Trackdir track_dir)
2356 DiagDirection dir = TrackdirToExitdir(track_dir);
2358 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
2359 /* Are we just leaving a tunnel/bridge? */
2360 if (GetTunnelBridgeDirection(tile) == ReverseDiagDir(dir)) {
2361 TileIndex end = GetOtherTunnelBridgeEnd(tile);
2363 if (TunnelBridgeIsFree(tile, end, v).Succeeded()) {
2364 /* Free the reservation only if no other train is on the tiles. */
2365 SetTunnelBridgeReservation(tile, false);
2366 SetTunnelBridgeReservation(end, false);
2368 if (_settings_client.gui.show_track_reservation) {
2369 if (IsBridge(tile)) {
2370 MarkBridgeDirty(tile);
2371 } else {
2372 MarkTileDirtyByTile(tile);
2373 MarkTileDirtyByTile(end);
2378 } else if (IsRailStationTile(tile)) {
2379 TileIndex new_tile = TileAddByDiagDir(tile, dir);
2380 /* If the new tile is not a further tile of the same station, we
2381 * clear the reservation for the whole platform. */
2382 if (!IsCompatibleTrainStationTile(new_tile, tile)) {
2383 SetRailStationPlatformReservation(tile, ReverseDiagDir(dir), false);
2385 } else {
2386 /* Any other tile */
2387 UnreserveRailTrack(tile, TrackdirToTrack(track_dir));
2392 * Free the reserved path in front of a vehicle.
2393 * @param v %Train owning the reserved path.
2395 void FreeTrainTrackReservation(const Train *v)
2397 assert(v->IsFrontEngine());
2399 TileIndex tile = v->tile;
2400 Trackdir td = v->GetVehicleTrackdir();
2401 bool free_tile = !(IsRailStationTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE));
2402 StationID station_id = IsRailStationTile(v->tile) ? GetStationIndex(v->tile) : INVALID_STATION;
2404 /* Can't be holding a reservation if we enter a depot. */
2405 if (IsRailDepotTile(tile) && TrackdirToExitdir(td) != GetRailDepotDirection(tile)) return;
2406 if (v->track == TRACK_BIT_DEPOT) {
2407 /* Front engine is in a depot. We enter if some part is not in the depot. */
2408 for (const Train *u = v; u != nullptr; u = u->Next()) {
2409 if (u->track != TRACK_BIT_DEPOT || u->tile != v->tile) return;
2412 /* Don't free reservation if it's not ours. */
2413 if (TracksOverlap(GetReservedTrackbits(tile) | TrackToTrackBits(TrackdirToTrack(td)))) return;
2415 CFollowTrackRail ft(v, GetRailTypeInfo(v->railtype)->compatible_railtypes);
2416 while (ft.Follow(tile, td)) {
2417 tile = ft.m_new_tile;
2418 TrackdirBits bits = ft.m_new_td_bits & TrackBitsToTrackdirBits(GetReservedTrackbits(tile));
2419 td = RemoveFirstTrackdir(&bits);
2420 assert(bits == TRACKDIR_BIT_NONE);
2422 if (!IsValidTrackdir(td)) break;
2424 if (IsTileType(tile, MP_RAILWAY)) {
2425 if (HasSignalOnTrackdir(tile, td) && !IsPbsSignal(GetSignalType(tile, TrackdirToTrack(td)))) {
2426 /* Conventional signal along trackdir: remove reservation and stop. */
2427 UnreserveRailTrack(tile, TrackdirToTrack(td));
2428 break;
2430 if (HasPbsSignalOnTrackdir(tile, td)) {
2431 if (GetSignalStateByTrackdir(tile, td) == SIGNAL_STATE_RED) {
2432 /* Red PBS signal? Can't be our reservation, would be green then. */
2433 break;
2434 } else {
2435 /* Turn the signal back to red. */
2436 SetSignalStateByTrackdir(tile, td, SIGNAL_STATE_RED);
2437 MarkTileDirtyByTile(tile);
2439 } else if (HasSignalOnTrackdir(tile, ReverseTrackdir(td)) && IsOnewaySignal(tile, TrackdirToTrack(td))) {
2440 break;
2444 /* Don't free first station/bridge/tunnel if we are on it. */
2445 if (free_tile || (!(ft.m_is_station && GetStationIndex(ft.m_new_tile) == station_id) && !ft.m_is_tunnel && !ft.m_is_bridge)) ClearPathReservation(v, tile, td);
2447 free_tile = true;
2451 static const byte _initial_tile_subcoord[6][4][3] = {
2452 {{ 15, 8, 1 }, { 0, 0, 0 }, { 0, 8, 5 }, { 0, 0, 0 }},
2453 {{ 0, 0, 0 }, { 8, 0, 3 }, { 0, 0, 0 }, { 8, 15, 7 }},
2454 {{ 0, 0, 0 }, { 7, 0, 2 }, { 0, 7, 6 }, { 0, 0, 0 }},
2455 {{ 15, 8, 2 }, { 0, 0, 0 }, { 0, 0, 0 }, { 8, 15, 6 }},
2456 {{ 15, 7, 0 }, { 8, 0, 4 }, { 0, 0, 0 }, { 0, 0, 0 }},
2457 {{ 0, 0, 0 }, { 0, 0, 0 }, { 0, 8, 4 }, { 7, 15, 0 }},
2461 * Perform pathfinding for a train.
2463 * @param v The train
2464 * @param tile The tile the train is about to enter
2465 * @param enterdir Diagonal direction the train is coming from
2466 * @param tracks Usable tracks on the new tile
2467 * @param[out] path_found Whether a path has been found or not.
2468 * @param do_track_reservation Path reservation is requested
2469 * @param[out] dest State and destination of the requested path
2470 * @param[out] final_dest Final tile of the best path found
2471 * @return The best track the train should follow
2473 static Track DoTrainPathfind(const Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool &path_found, bool do_track_reservation, PBSTileInfo *dest, TileIndex *final_dest)
2475 if (final_dest != nullptr) *final_dest = INVALID_TILE;
2477 switch (_settings_game.pf.pathfinder_for_trains) {
2478 case VPF_NPF: return NPFTrainChooseTrack(v, path_found, do_track_reservation, dest);
2479 case VPF_YAPF: return YapfTrainChooseTrack(v, tile, enterdir, tracks, path_found, do_track_reservation, dest, final_dest);
2481 default: NOT_REACHED();
2486 * Extend a train path as far as possible. Stops on encountering a safe tile,
2487 * another reservation or a track choice.
2488 * @return INVALID_TILE indicates that the reservation failed.
2490 static PBSTileInfo ExtendTrainReservation(const Train *v, TrackBits *new_tracks, DiagDirection *enterdir)
2492 PBSTileInfo origin = FollowTrainReservation(v);
2494 CFollowTrackRail ft(v);
2496 TileIndex tile = origin.tile;
2497 Trackdir cur_td = origin.trackdir;
2498 while (ft.Follow(tile, cur_td)) {
2499 if (KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE) {
2500 /* Possible signal tile. */
2501 if (HasOnewaySignalBlockingTrackdir(ft.m_new_tile, FindFirstTrackdir(ft.m_new_td_bits))) break;
2504 if (Rail90DegTurnDisallowed(GetTileRailType(ft.m_old_tile), GetTileRailType(ft.m_new_tile))) {
2505 ft.m_new_td_bits &= ~TrackdirCrossesTrackdirs(ft.m_old_td);
2506 if (ft.m_new_td_bits == TRACKDIR_BIT_NONE) break;
2509 /* Station, depot or waypoint are a possible target. */
2510 bool target_seen = ft.m_is_station || (IsTileType(ft.m_new_tile, MP_RAILWAY) && !IsPlainRail(ft.m_new_tile));
2511 if (target_seen || KillFirstBit(ft.m_new_td_bits) != TRACKDIR_BIT_NONE) {
2512 /* Choice found or possible target encountered.
2513 * On finding a possible target, we need to stop and let the pathfinder handle the
2514 * remaining path. This is because we don't know if this target is in one of our
2515 * orders, so we might cause pathfinding to fail later on if we find a choice.
2516 * This failure would cause a bogous call to TryReserveSafePath which might reserve
2517 * a wrong path not leading to our next destination. */
2518 if (HasReservedTracks(ft.m_new_tile, TrackdirBitsToTrackBits(TrackdirReachesTrackdirs(ft.m_old_td)))) break;
2520 /* If we did skip some tiles, backtrack to the first skipped tile so the pathfinder
2521 * actually starts its search at the first unreserved tile. */
2522 if (ft.m_tiles_skipped != 0) ft.m_new_tile -= TileOffsByDiagDir(ft.m_exitdir) * ft.m_tiles_skipped;
2524 /* Choice found, path valid but not okay. Save info about the choice tile as well. */
2525 if (new_tracks != nullptr) *new_tracks = TrackdirBitsToTrackBits(ft.m_new_td_bits);
2526 if (enterdir != nullptr) *enterdir = ft.m_exitdir;
2527 return PBSTileInfo(ft.m_new_tile, ft.m_old_td, false);
2530 tile = ft.m_new_tile;
2531 cur_td = FindFirstTrackdir(ft.m_new_td_bits);
2533 if (IsSafeWaitingPosition(v, tile, cur_td, true, _settings_game.pf.forbid_90_deg)) {
2534 bool wp_free = IsWaitingPositionFree(v, tile, cur_td, _settings_game.pf.forbid_90_deg);
2535 if (!(wp_free && TryReserveRailTrack(tile, TrackdirToTrack(cur_td)))) break;
2536 /* Safe position is all good, path valid and okay. */
2537 return PBSTileInfo(tile, cur_td, true);
2540 if (!TryReserveRailTrack(tile, TrackdirToTrack(cur_td))) break;
2543 if (ft.m_err == CFollowTrackRail::EC_OWNER || ft.m_err == CFollowTrackRail::EC_NO_WAY) {
2544 /* End of line, path valid and okay. */
2545 return PBSTileInfo(ft.m_old_tile, ft.m_old_td, true);
2548 /* Sorry, can't reserve path, back out. */
2549 tile = origin.tile;
2550 cur_td = origin.trackdir;
2551 TileIndex stopped = ft.m_old_tile;
2552 Trackdir stopped_td = ft.m_old_td;
2553 while (tile != stopped || cur_td != stopped_td) {
2554 if (!ft.Follow(tile, cur_td)) break;
2556 if (Rail90DegTurnDisallowed(GetTileRailType(ft.m_old_tile), GetTileRailType(ft.m_new_tile))) {
2557 ft.m_new_td_bits &= ~TrackdirCrossesTrackdirs(ft.m_old_td);
2558 assert(ft.m_new_td_bits != TRACKDIR_BIT_NONE);
2560 assert(KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE);
2562 tile = ft.m_new_tile;
2563 cur_td = FindFirstTrackdir(ft.m_new_td_bits);
2565 UnreserveRailTrack(tile, TrackdirToTrack(cur_td));
2568 /* Path invalid. */
2569 return PBSTileInfo();
2573 * Try to reserve any path to a safe tile, ignoring the vehicle's destination.
2574 * Safe tiles are tiles in front of a signal, depots and station tiles at end of line.
2576 * @param v The vehicle.
2577 * @param tile The tile the search should start from.
2578 * @param td The trackdir the search should start from.
2579 * @param override_railtype Whether all physically compatible railtypes should be followed.
2580 * @return True if a path to a safe stopping tile could be reserved.
2582 static bool TryReserveSafeTrack(const Train *v, TileIndex tile, Trackdir td, bool override_railtype)
2584 switch (_settings_game.pf.pathfinder_for_trains) {
2585 case VPF_NPF: return NPFTrainFindNearestSafeTile(v, tile, td, override_railtype);
2586 case VPF_YAPF: return YapfTrainFindNearestSafeTile(v, tile, td, override_railtype);
2588 default: NOT_REACHED();
2592 /** This class will save the current order of a vehicle and restore it on destruction. */
2593 class VehicleOrderSaver {
2594 private:
2595 Train *v;
2596 Order old_order;
2597 TileIndex old_dest_tile;
2598 StationID old_last_station_visited;
2599 VehicleOrderID index;
2600 bool suppress_implicit_orders;
2601 bool restored;
2603 public:
2604 VehicleOrderSaver(Train *_v) :
2605 v(_v),
2606 old_order(_v->current_order),
2607 old_dest_tile(_v->dest_tile),
2608 old_last_station_visited(_v->last_station_visited),
2609 index(_v->cur_real_order_index),
2610 suppress_implicit_orders(HasBit(_v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS)),
2611 restored(false)
2616 * Restore the saved order to the vehicle.
2618 void Restore()
2620 this->v->current_order = this->old_order;
2621 this->v->dest_tile = this->old_dest_tile;
2622 this->v->last_station_visited = this->old_last_station_visited;
2623 SB(this->v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS, 1, suppress_implicit_orders ? 1: 0);
2624 this->restored = true;
2628 * Restore the saved order to the vehicle, if Restore() has not already been called.
2630 ~VehicleOrderSaver()
2632 if (!this->restored) this->Restore();
2636 * Set the current vehicle order to the next order in the order list.
2637 * @param skip_first Shall the first (i.e. active) order be skipped?
2638 * @return True if a suitable next order could be found.
2640 bool SwitchToNextOrder(bool skip_first)
2642 if (this->v->GetNumOrders() == 0) return false;
2644 if (skip_first) ++this->index;
2646 int depth = 0;
2648 do {
2649 /* Wrap around. */
2650 if (this->index >= this->v->GetNumOrders()) this->index = 0;
2652 Order *order = this->v->GetOrder(this->index);
2653 assert(order != nullptr);
2655 switch (order->GetType()) {
2656 case OT_GOTO_DEPOT:
2657 /* Skip service in depot orders when the train doesn't need service. */
2658 if ((order->GetDepotOrderType() & ODTFB_SERVICE) && !this->v->NeedsServicing()) break;
2659 [[fallthrough]];
2660 case OT_GOTO_STATION:
2661 case OT_GOTO_WAYPOINT:
2662 this->v->current_order = *order;
2663 return UpdateOrderDest(this->v, order, 0, true);
2664 case OT_CONDITIONAL: {
2665 VehicleOrderID next = ProcessConditionalOrder(order, this->v);
2666 if (next != INVALID_VEH_ORDER_ID) {
2667 depth++;
2668 this->index = next;
2669 /* Don't increment next, so no break here. */
2670 continue;
2672 break;
2674 default:
2675 break;
2677 /* Don't increment inside the while because otherwise conditional
2678 * orders can lead to an infinite loop. */
2679 ++this->index;
2680 depth++;
2681 } while (this->index != this->v->cur_real_order_index && depth < this->v->GetNumOrders());
2683 return false;
2687 /* choose a track */
2688 static Track ChooseTrainTrack(Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool force_res, bool *got_reservation, bool mark_stuck)
2690 Track best_track = INVALID_TRACK;
2691 bool do_track_reservation = _settings_game.pf.reserve_paths || force_res;
2692 bool changed_signal = false;
2693 TileIndex final_dest = INVALID_TILE;
2695 assert((tracks & ~TRACK_BIT_MASK) == 0);
2697 if (got_reservation != nullptr) *got_reservation = false;
2699 /* Don't use tracks here as the setting to forbid 90 deg turns might have been switched between reservation and now. */
2700 TrackBits res_tracks = (TrackBits)(GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir));
2701 /* Do we have a suitable reserved track? */
2702 if (res_tracks != TRACK_BIT_NONE) return FindFirstTrack(res_tracks);
2704 /* Quick return in case only one possible track is available */
2705 if (KillFirstBit(tracks) == TRACK_BIT_NONE) {
2706 Track track = FindFirstTrack(tracks);
2707 /* We need to check for signals only here, as a junction tile can't have signals. */
2708 if (track != INVALID_TRACK && HasPbsSignalOnTrackdir(tile, TrackEnterdirToTrackdir(track, enterdir))) {
2709 do_track_reservation = true;
2710 changed_signal = true;
2711 SetSignalStateByTrackdir(tile, TrackEnterdirToTrackdir(track, enterdir), SIGNAL_STATE_GREEN);
2712 } else if (!do_track_reservation) {
2713 return track;
2715 best_track = track;
2718 PBSTileInfo res_dest(tile, INVALID_TRACKDIR, false);
2719 DiagDirection dest_enterdir = enterdir;
2720 if (do_track_reservation) {
2721 res_dest = ExtendTrainReservation(v, &tracks, &dest_enterdir);
2722 if (res_dest.tile == INVALID_TILE) {
2723 /* Reservation failed? */
2724 if (mark_stuck) MarkTrainAsStuck(v);
2725 if (changed_signal) SetSignalStateByTrackdir(tile, TrackEnterdirToTrackdir(best_track, enterdir), SIGNAL_STATE_RED);
2726 return FindFirstTrack(tracks);
2728 if (res_dest.okay) {
2729 /* Got a valid reservation that ends at a safe target, quick exit. */
2730 if (got_reservation != nullptr) *got_reservation = true;
2731 if (changed_signal) MarkTileDirtyByTile(tile);
2732 TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
2733 return best_track;
2736 /* Check if the train needs service here, so it has a chance to always find a depot.
2737 * Also check if the current order is a service order so we don't reserve a path to
2738 * the destination but instead to the next one if service isn't needed. */
2739 CheckIfTrainNeedsService(v);
2740 if (v->current_order.IsType(OT_DUMMY) || v->current_order.IsType(OT_CONDITIONAL) || v->current_order.IsType(OT_GOTO_DEPOT)) ProcessOrders(v);
2743 /* Save the current train order. The destructor will restore the old order on function exit. */
2744 VehicleOrderSaver orders(v);
2746 /* If the current tile is the destination of the current order and
2747 * a reservation was requested, advance to the next order.
2748 * Don't advance on a depot order as depots are always safe end points
2749 * for a path and no look-ahead is necessary. This also avoids a
2750 * problem with depot orders not part of the order list when the
2751 * order list itself is empty. */
2752 if (v->current_order.IsType(OT_LEAVESTATION)) {
2753 orders.SwitchToNextOrder(false);
2754 } else if (v->current_order.IsType(OT_LOADING) || (!v->current_order.IsType(OT_GOTO_DEPOT) && (
2755 v->current_order.IsType(OT_GOTO_STATION) ?
2756 IsRailStationTile(v->tile) && v->current_order.GetDestination() == GetStationIndex(v->tile) :
2757 v->tile == v->dest_tile))) {
2758 orders.SwitchToNextOrder(true);
2761 if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
2762 /* Pathfinders are able to tell that route was only 'guessed'. */
2763 bool path_found = true;
2764 TileIndex new_tile = res_dest.tile;
2766 Track next_track = DoTrainPathfind(v, new_tile, dest_enterdir, tracks, path_found, do_track_reservation, &res_dest, &final_dest);
2767 if (new_tile == tile) best_track = next_track;
2768 v->HandlePathfindingResult(path_found);
2771 /* No track reservation requested -> finished. */
2772 if (!do_track_reservation) return best_track;
2774 /* A path was found, but could not be reserved. */
2775 if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
2776 if (mark_stuck) MarkTrainAsStuck(v);
2777 FreeTrainTrackReservation(v);
2778 return best_track;
2781 /* No possible reservation target found, we are probably lost. */
2782 if (res_dest.tile == INVALID_TILE) {
2783 /* Try to find any safe destination. */
2784 PBSTileInfo origin = FollowTrainReservation(v);
2785 if (TryReserveSafeTrack(v, origin.tile, origin.trackdir, false)) {
2786 TrackBits res = GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir);
2787 best_track = FindFirstTrack(res);
2788 TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
2789 if (got_reservation != nullptr) *got_reservation = true;
2790 if (changed_signal) MarkTileDirtyByTile(tile);
2791 } else {
2792 FreeTrainTrackReservation(v);
2793 if (mark_stuck) MarkTrainAsStuck(v);
2795 return best_track;
2798 if (got_reservation != nullptr) *got_reservation = true;
2800 /* Reservation target found and free, check if it is safe. */
2801 while (!IsSafeWaitingPosition(v, res_dest.tile, res_dest.trackdir, true, _settings_game.pf.forbid_90_deg)) {
2802 /* Extend reservation until we have found a safe position. */
2803 DiagDirection exitdir = TrackdirToExitdir(res_dest.trackdir);
2804 TileIndex next_tile = TileAddByDiagDir(res_dest.tile, exitdir);
2805 TrackBits reachable = TrackdirBitsToTrackBits((TrackdirBits)(GetTileTrackStatus(next_tile, TRANSPORT_RAIL, 0))) & DiagdirReachesTracks(exitdir);
2806 if (Rail90DegTurnDisallowed(GetTileRailType(res_dest.tile), GetTileRailType(next_tile))) {
2807 reachable &= ~TrackCrossesTracks(TrackdirToTrack(res_dest.trackdir));
2810 /* Get next order with destination. */
2811 if (orders.SwitchToNextOrder(true)) {
2812 PBSTileInfo cur_dest;
2813 bool path_found;
2814 DoTrainPathfind(v, next_tile, exitdir, reachable, path_found, true, &cur_dest, nullptr);
2815 if (cur_dest.tile != INVALID_TILE) {
2816 res_dest = cur_dest;
2817 if (res_dest.okay) continue;
2818 /* Path found, but could not be reserved. */
2819 FreeTrainTrackReservation(v);
2820 if (mark_stuck) MarkTrainAsStuck(v);
2821 if (got_reservation != nullptr) *got_reservation = false;
2822 changed_signal = false;
2823 break;
2826 /* No order or no safe position found, try any position. */
2827 if (!TryReserveSafeTrack(v, res_dest.tile, res_dest.trackdir, true)) {
2828 FreeTrainTrackReservation(v);
2829 if (mark_stuck) MarkTrainAsStuck(v);
2830 if (got_reservation != nullptr) *got_reservation = false;
2831 changed_signal = false;
2833 break;
2836 TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
2838 if (changed_signal) MarkTileDirtyByTile(tile);
2840 orders.Restore();
2841 if (v->current_order.IsType(OT_GOTO_DEPOT) &&
2842 (v->current_order.GetDepotActionType() & ODATFB_NEAREST_DEPOT) &&
2843 final_dest != INVALID_TILE && IsRailDepotTile(final_dest)) {
2844 v->current_order.SetDestination(GetDepotIndex(final_dest));
2845 v->dest_tile = final_dest;
2846 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
2849 return best_track;
2853 * Try to reserve a path to a safe position.
2855 * @param v The vehicle
2856 * @param mark_as_stuck Should the train be marked as stuck on a failed reservation?
2857 * @param first_tile_okay True if no path should be reserved if the current tile is a safe position.
2858 * @return True if a path could be reserved.
2860 bool TryPathReserve(Train *v, bool mark_as_stuck, bool first_tile_okay)
2862 assert(v->IsFrontEngine());
2864 /* We have to handle depots specially as the track follower won't look
2865 * at the depot tile itself but starts from the next tile. If we are still
2866 * inside the depot, a depot reservation can never be ours. */
2867 if (v->track == TRACK_BIT_DEPOT) {
2868 if (HasDepotReservation(v->tile)) {
2869 if (mark_as_stuck) MarkTrainAsStuck(v);
2870 return false;
2871 } else {
2872 /* Depot not reserved, but the next tile might be. */
2873 TileIndex next_tile = TileAddByDiagDir(v->tile, GetRailDepotDirection(v->tile));
2874 if (HasReservedTracks(next_tile, DiagdirReachesTracks(GetRailDepotDirection(v->tile)))) return false;
2878 Vehicle *other_train = nullptr;
2879 PBSTileInfo origin = FollowTrainReservation(v, &other_train);
2880 /* The path we are driving on is already blocked by some other train.
2881 * This can only happen in certain situations when mixing path and
2882 * block signals or when changing tracks and/or signals.
2883 * Exit here as doing any further reservations will probably just
2884 * make matters worse. */
2885 if (other_train != nullptr && other_train->index != v->index) {
2886 if (mark_as_stuck) MarkTrainAsStuck(v);
2887 return false;
2889 /* If we have a reserved path and the path ends at a safe tile, we are finished already. */
2890 if (origin.okay && (v->tile != origin.tile || first_tile_okay)) {
2891 /* Can't be stuck then. */
2892 if (HasBit(v->flags, VRF_TRAIN_STUCK)) SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
2893 ClrBit(v->flags, VRF_TRAIN_STUCK);
2894 return true;
2897 /* If we are in a depot, tentatively reserve the depot. */
2898 if (v->track == TRACK_BIT_DEPOT) {
2899 SetDepotReservation(v->tile, true);
2900 if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(v->tile);
2903 DiagDirection exitdir = TrackdirToExitdir(origin.trackdir);
2904 TileIndex new_tile = TileAddByDiagDir(origin.tile, exitdir);
2905 TrackBits reachable = TrackdirBitsToTrackBits(TrackStatusToTrackdirBits(GetTileTrackStatus(new_tile, TRANSPORT_RAIL, 0)) & DiagdirReachesTrackdirs(exitdir));
2907 if (Rail90DegTurnDisallowed(GetTileRailType(origin.tile), GetTileRailType(new_tile))) reachable &= ~TrackCrossesTracks(TrackdirToTrack(origin.trackdir));
2909 bool res_made = false;
2910 ChooseTrainTrack(v, new_tile, exitdir, reachable, true, &res_made, mark_as_stuck);
2912 if (!res_made) {
2913 /* Free the depot reservation as well. */
2914 if (v->track == TRACK_BIT_DEPOT) SetDepotReservation(v->tile, false);
2915 return false;
2918 if (HasBit(v->flags, VRF_TRAIN_STUCK)) {
2919 v->wait_counter = 0;
2920 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
2922 ClrBit(v->flags, VRF_TRAIN_STUCK);
2923 return true;
2927 static bool CheckReverseTrain(const Train *v)
2929 if (_settings_game.difficulty.line_reverse_mode != 0 ||
2930 v->track == TRACK_BIT_DEPOT || v->track == TRACK_BIT_WORMHOLE ||
2931 !(v->direction & 1)) {
2932 return false;
2935 assert(v->track != TRACK_BIT_NONE);
2937 switch (_settings_game.pf.pathfinder_for_trains) {
2938 case VPF_NPF: return NPFTrainCheckReverse(v);
2939 case VPF_YAPF: return YapfTrainCheckReverse(v);
2941 default: NOT_REACHED();
2946 * Get the location of the next station to visit.
2947 * @param station Next station to visit.
2948 * @return Location of the new station.
2950 TileIndex Train::GetOrderStationLocation(StationID station)
2952 if (station == this->last_station_visited) this->last_station_visited = INVALID_STATION;
2954 const Station *st = Station::Get(station);
2955 if (!(st->facilities & FACIL_TRAIN)) {
2956 /* The destination station has no trainstation tiles. */
2957 this->IncrementRealOrderIndex();
2958 return 0;
2961 return st->xy;
2964 /** Goods at the consist have changed, update the graphics, cargo, and acceleration. */
2965 void Train::MarkDirty()
2967 Train *v = this;
2968 do {
2969 v->colourmap = PAL_NONE;
2970 v->UpdateViewport(true, false);
2971 } while ((v = v->Next()) != nullptr);
2973 /* need to update acceleration and cached values since the goods on the train changed. */
2974 this->CargoChanged();
2975 this->UpdateAcceleration();
2979 * This function looks at the vehicle and updates its speed (cur_speed
2980 * and subspeed) variables. Furthermore, it returns the distance that
2981 * the train can drive this tick. #Vehicle::GetAdvanceDistance() determines
2982 * the distance to drive before moving a step on the map.
2983 * @return distance to drive.
2985 int Train::UpdateSpeed()
2987 switch (_settings_game.vehicle.train_acceleration_model) {
2988 default: NOT_REACHED();
2989 case AM_ORIGINAL:
2990 return this->DoUpdateSpeed(this->acceleration * (this->GetAccelerationStatus() == AS_BRAKE ? -4 : 2), 0, this->GetCurrentMaxSpeed());
2992 case AM_REALISTIC:
2993 return this->DoUpdateSpeed(this->GetAcceleration(), this->GetAccelerationStatus() == AS_BRAKE ? 0 : 2, this->GetCurrentMaxSpeed());
2998 * Trains enters a station, send out a news item if it is the first train, and start loading.
2999 * @param v Train that entered the station.
3000 * @param station Station visited.
3002 static void TrainEnterStation(Train *v, StationID station)
3004 v->last_station_visited = station;
3006 /* check if a train ever visited this station before */
3007 Station *st = Station::Get(station);
3008 if (!(st->had_vehicle_of_type & HVOT_TRAIN)) {
3009 st->had_vehicle_of_type |= HVOT_TRAIN;
3010 SetDParam(0, st->index);
3011 AddVehicleNewsItem(
3012 STR_NEWS_FIRST_TRAIN_ARRIVAL,
3013 v->owner == _local_company ? NT_ARRIVAL_COMPANY : NT_ARRIVAL_OTHER,
3014 v->index,
3015 st->index
3017 AI::NewEvent(v->owner, new ScriptEventStationFirstVehicle(st->index, v->index));
3018 Game::NewEvent(new ScriptEventStationFirstVehicle(st->index, v->index));
3021 v->force_proceed = TFP_NONE;
3022 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
3024 v->BeginLoading();
3026 TriggerStationRandomisation(st, v->tile, SRT_TRAIN_ARRIVES);
3027 TriggerStationAnimation(st, v->tile, SAT_TRAIN_ARRIVES);
3030 /* Check if the vehicle is compatible with the specified tile */
3031 static inline bool CheckCompatibleRail(const Train *v, TileIndex tile)
3033 return IsTileOwner(tile, v->owner) &&
3034 (!v->IsFrontEngine() || HasBit(v->compatible_railtypes, GetRailType(tile)));
3037 /** Data structure for storing engine speed changes of an acceleration type. */
3038 struct AccelerationSlowdownParams {
3039 byte small_turn; ///< Speed change due to a small turn.
3040 byte large_turn; ///< Speed change due to a large turn.
3041 byte z_up; ///< Fraction to remove when moving up.
3042 byte z_down; ///< Fraction to add when moving down.
3045 /** Speed update fractions for each acceleration type. */
3046 static const AccelerationSlowdownParams _accel_slowdown[] = {
3047 /* normal accel */
3048 {256 / 4, 256 / 2, 256 / 4, 2}, ///< normal
3049 {256 / 4, 256 / 2, 256 / 4, 2}, ///< monorail
3050 {0, 256 / 2, 256 / 4, 2}, ///< maglev
3054 * Modify the speed of the vehicle due to a change in altitude.
3055 * @param v %Train to update.
3056 * @param old_z Previous height.
3058 static inline void AffectSpeedByZChange(Train *v, int old_z)
3060 if (old_z == v->z_pos || _settings_game.vehicle.train_acceleration_model != AM_ORIGINAL) return;
3062 const AccelerationSlowdownParams *asp = &_accel_slowdown[GetRailTypeInfo(v->railtype)->acceleration_type];
3064 if (old_z < v->z_pos) {
3065 v->cur_speed -= (v->cur_speed * asp->z_up >> 8);
3066 } else {
3067 uint16_t spd = v->cur_speed + asp->z_down;
3068 if (spd <= v->gcache.cached_max_track_speed) v->cur_speed = spd;
3072 static bool TrainMovedChangeSignals(TileIndex tile, DiagDirection dir)
3074 if (IsTileType(tile, MP_RAILWAY) &&
3075 GetRailTileType(tile) == RAIL_TILE_SIGNALS) {
3076 TrackdirBits tracks = TrackBitsToTrackdirBits(GetTrackBits(tile)) & DiagdirReachesTrackdirs(dir);
3077 Trackdir trackdir = FindFirstTrackdir(tracks);
3078 if (UpdateSignalsOnSegment(tile, TrackdirToExitdir(trackdir), GetTileOwner(tile)) == SIGSEG_PBS && HasSignalOnTrackdir(tile, trackdir)) {
3079 /* A PBS block with a non-PBS signal facing us? */
3080 if (!IsPbsSignal(GetSignalType(tile, TrackdirToTrack(trackdir)))) return true;
3083 return false;
3086 /** Tries to reserve track under whole train consist. */
3087 void Train::ReserveTrackUnderConsist() const
3089 for (const Train *u = this; u != nullptr; u = u->Next()) {
3090 switch (u->track) {
3091 case TRACK_BIT_WORMHOLE:
3092 TryReserveRailTrack(u->tile, DiagDirToDiagTrack(GetTunnelBridgeDirection(u->tile)));
3093 break;
3094 case TRACK_BIT_DEPOT:
3095 break;
3096 default:
3097 TryReserveRailTrack(u->tile, TrackBitsToTrack(u->track));
3098 break;
3104 * The train vehicle crashed!
3105 * Update its status and other parts around it.
3106 * @param flooded Crash was caused by flooding.
3107 * @return Number of people killed.
3109 uint Train::Crash(bool flooded)
3111 uint pass = 0;
3112 if (this->IsFrontEngine()) {
3113 pass += 2; // driver
3115 /* Remove the reserved path in front of the train if it is not stuck.
3116 * Also clear all reserved tracks the train is currently on. */
3117 if (!HasBit(this->flags, VRF_TRAIN_STUCK)) FreeTrainTrackReservation(this);
3118 for (const Train *v = this; v != nullptr; v = v->Next()) {
3119 ClearPathReservation(v, v->tile, v->GetVehicleTrackdir());
3120 if (IsTileType(v->tile, MP_TUNNELBRIDGE)) {
3121 /* ClearPathReservation will not free the wormhole exit
3122 * if the train has just entered the wormhole. */
3123 SetTunnelBridgeReservation(GetOtherTunnelBridgeEnd(v->tile), false);
3127 /* we may need to update crossing we were approaching,
3128 * but must be updated after the train has been marked crashed */
3129 TileIndex crossing = TrainApproachingCrossingTile(this);
3130 if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
3132 /* Remove the loading indicators (if any) */
3133 HideFillingPercent(&this->fill_percent_te_id);
3136 pass += this->GroundVehicleBase::Crash(flooded);
3138 this->crash_anim_pos = flooded ? 4000 : 1; // max 4440, disappear pretty fast when flooded
3139 return pass;
3143 * Marks train as crashed and creates an AI event.
3144 * Doesn't do anything if the train is crashed already.
3145 * @param v first vehicle of chain
3146 * @return number of victims (including 2 drivers; zero if train was already crashed)
3148 static uint TrainCrashed(Train *v)
3150 uint num = 0;
3152 /* do not crash train twice */
3153 if (!(v->vehstatus & VS_CRASHED)) {
3154 num = v->Crash();
3155 AI::NewEvent(v->owner, new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_TRAIN));
3156 Game::NewEvent(new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_TRAIN));
3159 /* Try to re-reserve track under already crashed train too.
3160 * Crash() clears the reservation! */
3161 v->ReserveTrackUnderConsist();
3163 return num;
3166 /** Temporary data storage for testing collisions. */
3167 struct TrainCollideChecker {
3168 Train *v; ///< %Vehicle we are testing for collision.
3169 uint num; ///< Total number of victims if train collided.
3173 * Collision test function.
3174 * @param v %Train vehicle to test collision with.
3175 * @param data %Train being examined.
3176 * @return \c nullptr (always continue search)
3178 static Vehicle *FindTrainCollideEnum(Vehicle *v, void *data)
3180 TrainCollideChecker *tcc = (TrainCollideChecker*)data;
3182 /* not a train or in depot */
3183 if (v->type != VEH_TRAIN || Train::From(v)->track == TRACK_BIT_DEPOT) return nullptr;
3185 /* do not crash into trains of another company. */
3186 if (v->owner != tcc->v->owner) return nullptr;
3188 /* get first vehicle now to make most usual checks faster */
3189 Train *coll = Train::From(v)->First();
3191 /* can't collide with own wagons */
3192 if (coll == tcc->v) return nullptr;
3194 int x_diff = v->x_pos - tcc->v->x_pos;
3195 int y_diff = v->y_pos - tcc->v->y_pos;
3197 /* Do fast calculation to check whether trains are not in close vicinity
3198 * and quickly reject trains distant enough for any collision.
3199 * Differences are shifted by 7, mapping range [-7 .. 8] into [0 .. 15]
3200 * Differences are then ORed and then we check for any higher bits */
3201 uint hash = (y_diff + 7) | (x_diff + 7);
3202 if (hash & ~15) return nullptr;
3204 /* Slower check using multiplication */
3205 int min_diff = (Train::From(v)->gcache.cached_veh_length + 1) / 2 + (tcc->v->gcache.cached_veh_length + 1) / 2 - 1;
3206 if (x_diff * x_diff + y_diff * y_diff > min_diff * min_diff) return nullptr;
3208 /* Happens when there is a train under bridge next to bridge head */
3209 if (abs(v->z_pos - tcc->v->z_pos) > 5) return nullptr;
3211 /* crash both trains */
3212 tcc->num += TrainCrashed(tcc->v);
3213 tcc->num += TrainCrashed(coll);
3215 return nullptr; // continue searching
3219 * Checks whether the specified train has a collision with another vehicle. If
3220 * so, destroys this vehicle, and the other vehicle if its subtype has TS_Front.
3221 * Reports the incident in a flashy news item, modifies station ratings and
3222 * plays a sound.
3223 * @param v %Train to test.
3225 static bool CheckTrainCollision(Train *v)
3227 /* can't collide in depot */
3228 if (v->track == TRACK_BIT_DEPOT) return false;
3230 assert(v->track == TRACK_BIT_WORMHOLE || TileVirtXY(v->x_pos, v->y_pos) == v->tile);
3232 TrainCollideChecker tcc;
3233 tcc.v = v;
3234 tcc.num = 0;
3236 /* find colliding vehicles */
3237 if (v->track == TRACK_BIT_WORMHOLE) {
3238 FindVehicleOnPos(v->tile, &tcc, FindTrainCollideEnum);
3239 FindVehicleOnPos(GetOtherTunnelBridgeEnd(v->tile), &tcc, FindTrainCollideEnum);
3240 } else {
3241 FindVehicleOnPosXY(v->x_pos, v->y_pos, &tcc, FindTrainCollideEnum);
3244 /* any dead -> no crash */
3245 if (tcc.num == 0) return false;
3247 SetDParam(0, tcc.num);
3248 AddTileNewsItem(STR_NEWS_TRAIN_CRASH, NT_ACCIDENT, v->tile);
3250 ModifyStationRatingAround(v->tile, v->owner, -160, 30);
3251 if (_settings_client.sound.disaster) SndPlayVehicleFx(SND_13_TRAIN_COLLISION, v);
3252 return true;
3255 static Vehicle *CheckTrainAtSignal(Vehicle *v, void *data)
3257 if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) return nullptr;
3259 Train *t = Train::From(v);
3260 DiagDirection exitdir = *(DiagDirection *)data;
3262 /* not front engine of a train, inside wormhole or depot, crashed */
3263 if (!t->IsFrontEngine() || !(t->track & TRACK_BIT_MASK)) return nullptr;
3265 if (t->cur_speed > 5 || VehicleExitDir(t->direction, t->track) != exitdir) return nullptr;
3267 return t;
3271 * Move a vehicle chain one movement stop forwards.
3272 * @param v First vehicle to move.
3273 * @param nomove Stop moving this and all following vehicles.
3274 * @param reverse Set to false to not execute the vehicle reversing. This does not change any other logic.
3275 * @return True if the vehicle could be moved forward, false otherwise.
3277 bool TrainController(Train *v, Vehicle *nomove, bool reverse)
3279 Train *first = v->First();
3280 Train *prev;
3281 bool direction_changed = false; // has direction of any part changed?
3283 /* For every vehicle after and including the given vehicle */
3284 for (prev = v->Previous(); v != nomove; prev = v, v = v->Next()) {
3285 DiagDirection enterdir = DIAGDIR_BEGIN;
3286 bool update_signals_crossing = false; // will we update signals or crossing state?
3288 GetNewVehiclePosResult gp = GetNewVehiclePos(v);
3289 if (v->track != TRACK_BIT_WORMHOLE) {
3290 /* Not inside tunnel */
3291 if (gp.old_tile == gp.new_tile) {
3292 /* Staying in the old tile */
3293 if (v->track == TRACK_BIT_DEPOT) {
3294 /* Inside depot */
3295 gp.x = v->x_pos;
3296 gp.y = v->y_pos;
3297 } else {
3298 /* Not inside depot */
3300 /* Reverse when we are at the end of the track already, do not move to the new position */
3301 if (v->IsFrontEngine() && !TrainCheckIfLineEnds(v, reverse)) return false;
3303 uint32_t r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
3304 if (HasBit(r, VETS_CANNOT_ENTER)) {
3305 goto invalid_rail;
3307 if (HasBit(r, VETS_ENTERED_STATION)) {
3308 /* The new position is the end of the platform */
3309 TrainEnterStation(v, r >> VETS_STATION_ID_OFFSET);
3312 } else {
3313 /* A new tile is about to be entered. */
3315 /* Determine what direction we're entering the new tile from */
3316 enterdir = DiagdirBetweenTiles(gp.old_tile, gp.new_tile);
3317 assert(IsValidDiagDirection(enterdir));
3319 /* Get the status of the tracks in the new tile and mask
3320 * away the bits that aren't reachable. */
3321 TrackStatus ts = GetTileTrackStatus(gp.new_tile, TRANSPORT_RAIL, 0, ReverseDiagDir(enterdir));
3322 TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(enterdir);
3324 TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
3325 TrackBits red_signals = TrackdirBitsToTrackBits(TrackStatusToRedSignals(ts) & reachable_trackdirs);
3327 TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
3328 if (Rail90DegTurnDisallowed(GetTileRailType(gp.old_tile), GetTileRailType(gp.new_tile)) && prev == nullptr) {
3329 /* We allow wagons to make 90 deg turns, because forbid_90_deg
3330 * can be switched on halfway a turn */
3331 bits &= ~TrackCrossesTracks(FindFirstTrack(v->track));
3334 if (bits == TRACK_BIT_NONE) goto invalid_rail;
3336 /* Check if the new tile constrains tracks that are compatible
3337 * with the current train, if not, bail out. */
3338 if (!CheckCompatibleRail(v, gp.new_tile)) goto invalid_rail;
3340 TrackBits chosen_track;
3341 if (prev == nullptr) {
3342 /* Currently the locomotive is active. Determine which one of the
3343 * available tracks to choose */
3344 chosen_track = TrackToTrackBits(ChooseTrainTrack(v, gp.new_tile, enterdir, bits, false, nullptr, true));
3345 assert(chosen_track & (bits | GetReservedTrackbits(gp.new_tile)));
3347 if (v->force_proceed != TFP_NONE && IsPlainRailTile(gp.new_tile) && HasSignals(gp.new_tile)) {
3348 /* For each signal we find decrease the counter by one.
3349 * We start at two, so the first signal we pass decreases
3350 * this to one, then if we reach the next signal it is
3351 * decreased to zero and we won't pass that new signal. */
3352 Trackdir dir = FindFirstTrackdir(trackdirbits);
3353 if (HasSignalOnTrackdir(gp.new_tile, dir) ||
3354 (HasSignalOnTrackdir(gp.new_tile, ReverseTrackdir(dir)) &&
3355 GetSignalType(gp.new_tile, TrackdirToTrack(dir)) != SIGTYPE_PBS)) {
3356 /* However, we do not want to be stopped by PBS signals
3357 * entered via the back. */
3358 v->force_proceed = (v->force_proceed == TFP_SIGNAL) ? TFP_STUCK : TFP_NONE;
3359 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
3363 /* Check if it's a red signal and that force proceed is not clicked. */
3364 if ((red_signals & chosen_track) && v->force_proceed == TFP_NONE) {
3365 /* In front of a red signal */
3366 Trackdir i = FindFirstTrackdir(trackdirbits);
3368 /* Don't handle stuck trains here. */
3369 if (HasBit(v->flags, VRF_TRAIN_STUCK)) return false;
3371 if (!HasSignalOnTrackdir(gp.new_tile, ReverseTrackdir(i))) {
3372 v->cur_speed = 0;
3373 v->subspeed = 0;
3374 v->progress = 255; // make sure that every bit of acceleration will hit the signal again, so speed stays 0.
3375 if (!_settings_game.pf.reverse_at_signals || ++v->wait_counter < _settings_game.pf.wait_oneway_signal * Ticks::DAY_TICKS * 2) return false;
3376 } else if (HasSignalOnTrackdir(gp.new_tile, i)) {
3377 v->cur_speed = 0;
3378 v->subspeed = 0;
3379 v->progress = 255; // make sure that every bit of acceleration will hit the signal again, so speed stays 0.
3380 if (!_settings_game.pf.reverse_at_signals || ++v->wait_counter < _settings_game.pf.wait_twoway_signal * Ticks::DAY_TICKS * 2) {
3381 DiagDirection exitdir = TrackdirToExitdir(i);
3382 TileIndex o_tile = TileAddByDiagDir(gp.new_tile, exitdir);
3384 exitdir = ReverseDiagDir(exitdir);
3386 /* check if a train is waiting on the other side */
3387 if (!HasVehicleOnPos(o_tile, &exitdir, &CheckTrainAtSignal)) return false;
3391 /* If we would reverse but are currently in a PBS block and
3392 * reversing of stuck trains is disabled, don't reverse.
3393 * This does not apply if the reason for reversing is a one-way
3394 * signal blocking us, because a train would then be stuck forever. */
3395 if (!_settings_game.pf.reverse_at_signals && !HasOnewaySignalBlockingTrackdir(gp.new_tile, i) &&
3396 UpdateSignalsOnSegment(v->tile, enterdir, v->owner) == SIGSEG_PBS) {
3397 v->wait_counter = 0;
3398 return false;
3400 goto reverse_train_direction;
3401 } else {
3402 TryReserveRailTrack(gp.new_tile, TrackBitsToTrack(chosen_track), false);
3404 } else {
3405 /* The wagon is active, simply follow the prev vehicle. */
3406 if (prev->tile == gp.new_tile) {
3407 /* Choose the same track as prev */
3408 if (prev->track == TRACK_BIT_WORMHOLE) {
3409 /* Vehicles entering tunnels enter the wormhole earlier than for bridges.
3410 * However, just choose the track into the wormhole. */
3411 assert(IsTunnel(prev->tile));
3412 chosen_track = bits;
3413 } else {
3414 chosen_track = prev->track;
3416 } else {
3417 /* Choose the track that leads to the tile where prev is.
3418 * This case is active if 'prev' is already on the second next tile, when 'v' just enters the next tile.
3419 * I.e. when the tile between them has only space for a single vehicle like
3420 * 1) horizontal/vertical track tiles and
3421 * 2) some orientations of tunnel entries, where the vehicle is already inside the wormhole at 8/16 from the tile edge.
3422 * Is also the train just reversing, the wagon inside the tunnel is 'on' the tile of the opposite tunnel entry.
3424 static const TrackBits _connecting_track[DIAGDIR_END][DIAGDIR_END] = {
3425 {TRACK_BIT_X, TRACK_BIT_LOWER, TRACK_BIT_NONE, TRACK_BIT_LEFT },
3426 {TRACK_BIT_UPPER, TRACK_BIT_Y, TRACK_BIT_LEFT, TRACK_BIT_NONE },
3427 {TRACK_BIT_NONE, TRACK_BIT_RIGHT, TRACK_BIT_X, TRACK_BIT_UPPER},
3428 {TRACK_BIT_RIGHT, TRACK_BIT_NONE, TRACK_BIT_LOWER, TRACK_BIT_Y }
3430 DiagDirection exitdir = DiagdirBetweenTiles(gp.new_tile, prev->tile);
3431 assert(IsValidDiagDirection(exitdir));
3432 chosen_track = _connecting_track[enterdir][exitdir];
3434 chosen_track &= bits;
3437 /* Make sure chosen track is a valid track */
3438 assert(
3439 chosen_track == TRACK_BIT_X || chosen_track == TRACK_BIT_Y ||
3440 chosen_track == TRACK_BIT_UPPER || chosen_track == TRACK_BIT_LOWER ||
3441 chosen_track == TRACK_BIT_LEFT || chosen_track == TRACK_BIT_RIGHT);
3443 /* Update XY to reflect the entrance to the new tile, and select the direction to use */
3444 const byte *b = _initial_tile_subcoord[FindFirstBit(chosen_track)][enterdir];
3445 gp.x = (gp.x & ~0xF) | b[0];
3446 gp.y = (gp.y & ~0xF) | b[1];
3447 Direction chosen_dir = (Direction)b[2];
3449 /* Call the landscape function and tell it that the vehicle entered the tile */
3450 uint32_t r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
3451 if (HasBit(r, VETS_CANNOT_ENTER)) {
3452 goto invalid_rail;
3455 if (!HasBit(r, VETS_ENTERED_WORMHOLE)) {
3456 Track track = FindFirstTrack(chosen_track);
3457 Trackdir tdir = TrackDirectionToTrackdir(track, chosen_dir);
3458 if (v->IsFrontEngine() && HasPbsSignalOnTrackdir(gp.new_tile, tdir)) {
3459 SetSignalStateByTrackdir(gp.new_tile, tdir, SIGNAL_STATE_RED);
3460 MarkTileDirtyByTile(gp.new_tile);
3463 /* Clear any track reservation when the last vehicle leaves the tile */
3464 if (v->Next() == nullptr) ClearPathReservation(v, v->tile, v->GetVehicleTrackdir());
3466 v->tile = gp.new_tile;
3468 if (GetTileRailType(gp.new_tile) != GetTileRailType(gp.old_tile)) {
3469 v->First()->ConsistChanged(CCF_TRACK);
3472 v->track = chosen_track;
3473 assert(v->track);
3476 /* We need to update signal status, but after the vehicle position hash
3477 * has been updated by UpdateInclination() */
3478 update_signals_crossing = true;
3480 if (chosen_dir != v->direction) {
3481 if (prev == nullptr && _settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) {
3482 const AccelerationSlowdownParams *asp = &_accel_slowdown[GetRailTypeInfo(v->railtype)->acceleration_type];
3483 DirDiff diff = DirDifference(v->direction, chosen_dir);
3484 v->cur_speed -= (diff == DIRDIFF_45RIGHT || diff == DIRDIFF_45LEFT ? asp->small_turn : asp->large_turn) * v->cur_speed >> 8;
3486 direction_changed = true;
3487 v->direction = chosen_dir;
3490 if (v->IsFrontEngine()) {
3491 v->wait_counter = 0;
3493 /* If we are approaching a crossing that is reserved, play the sound now. */
3494 TileIndex crossing = TrainApproachingCrossingTile(v);
3495 if (crossing != INVALID_TILE && HasCrossingReservation(crossing) && _settings_client.sound.ambient) SndPlayTileFx(SND_0E_LEVEL_CROSSING, crossing);
3497 /* Always try to extend the reservation when entering a tile. */
3498 CheckNextTrainTile(v);
3501 if (HasBit(r, VETS_ENTERED_STATION)) {
3502 /* The new position is the location where we want to stop */
3503 TrainEnterStation(v, r >> VETS_STATION_ID_OFFSET);
3506 } else {
3507 if (IsTileType(gp.new_tile, MP_TUNNELBRIDGE) && HasBit(VehicleEnterTile(v, gp.new_tile, gp.x, gp.y), VETS_ENTERED_WORMHOLE)) {
3508 /* Perform look-ahead on tunnel exit. */
3509 if (v->IsFrontEngine()) {
3510 TryReserveRailTrack(gp.new_tile, DiagDirToDiagTrack(GetTunnelBridgeDirection(gp.new_tile)));
3511 CheckNextTrainTile(v);
3513 /* Prevent v->UpdateInclination() being called with wrong parameters.
3514 * This could happen if the train was reversed inside the tunnel/bridge. */
3515 if (gp.old_tile == gp.new_tile) {
3516 gp.old_tile = GetOtherTunnelBridgeEnd(gp.old_tile);
3518 } else {
3519 v->x_pos = gp.x;
3520 v->y_pos = gp.y;
3521 v->UpdatePosition();
3522 if ((v->vehstatus & VS_HIDDEN) == 0) v->Vehicle::UpdateViewport(true);
3523 continue;
3527 /* update image of train, as well as delta XY */
3528 v->UpdateDeltaXY();
3530 v->x_pos = gp.x;
3531 v->y_pos = gp.y;
3532 v->UpdatePosition();
3534 /* update the Z position of the vehicle */
3535 int old_z = v->UpdateInclination(gp.new_tile != gp.old_tile, false);
3537 if (prev == nullptr) {
3538 /* This is the first vehicle in the train */
3539 AffectSpeedByZChange(v, old_z);
3542 if (update_signals_crossing) {
3543 if (v->IsFrontEngine()) {
3544 if (TrainMovedChangeSignals(gp.new_tile, enterdir)) {
3545 /* We are entering a block with PBS signals right now, but
3546 * not through a PBS signal. This means we don't have a
3547 * reservation right now. As a conventional signal will only
3548 * ever be green if no other train is in the block, getting
3549 * a path should always be possible. If the player built
3550 * such a strange network that it is not possible, the train
3551 * will be marked as stuck and the player has to deal with
3552 * the problem. */
3553 if ((!HasReservedTracks(gp.new_tile, v->track) &&
3554 !TryReserveRailTrack(gp.new_tile, FindFirstTrack(v->track))) ||
3555 !TryPathReserve(v)) {
3556 MarkTrainAsStuck(v);
3561 /* Signals can only change when the first
3562 * (above) or the last vehicle moves. */
3563 if (v->Next() == nullptr) {
3564 TrainMovedChangeSignals(gp.old_tile, ReverseDiagDir(enterdir));
3565 if (IsLevelCrossingTile(gp.old_tile)) UpdateLevelCrossing(gp.old_tile);
3569 /* Do not check on every tick to save some computing time. */
3570 if (v->IsFrontEngine() && v->tick_counter % _settings_game.pf.path_backoff_interval == 0) CheckNextTrainTile(v);
3573 if (direction_changed) first->tcache.cached_max_curve_speed = first->GetCurveSpeedLimit();
3575 return true;
3577 invalid_rail:
3578 /* We've reached end of line?? */
3579 if (prev != nullptr) FatalError("Disconnecting train");
3581 reverse_train_direction:
3582 if (reverse) {
3583 v->wait_counter = 0;
3584 v->cur_speed = 0;
3585 v->subspeed = 0;
3586 ReverseTrainDirection(v);
3589 return false;
3593 * Collect trackbits of all crashed train vehicles on a tile
3594 * @param v Vehicle passed from Find/HasVehicleOnPos()
3595 * @param data trackdirbits for the result
3596 * @return nullptr to iterate over all vehicles on the tile.
3598 static Vehicle *CollectTrackbitsFromCrashedVehiclesEnum(Vehicle *v, void *data)
3600 TrackBits *trackbits = (TrackBits *)data;
3602 if (v->type == VEH_TRAIN && (v->vehstatus & VS_CRASHED) != 0) {
3603 TrackBits train_tbits = Train::From(v)->track;
3604 if (train_tbits == TRACK_BIT_WORMHOLE) {
3605 /* Vehicle is inside a wormhole, v->track contains no useful value then. */
3606 *trackbits |= DiagDirToDiagTrackBits(GetTunnelBridgeDirection(v->tile));
3607 } else if (train_tbits != TRACK_BIT_DEPOT) {
3608 *trackbits |= train_tbits;
3612 return nullptr;
3615 static bool IsRailStationPlatformOccupied(TileIndex tile)
3617 TileIndexDiff delta = (GetRailStationAxis(tile) == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
3619 for (TileIndex t = tile; IsCompatibleTrainStationTile(t, tile); t -= delta) {
3620 if (HasVehicleOnPos(t, nullptr, &TrainOnTileEnum)) return true;
3622 for (TileIndex t = tile + delta; IsCompatibleTrainStationTile(t, tile); t += delta) {
3623 if (HasVehicleOnPos(t, nullptr, &TrainOnTileEnum)) return true;
3626 return false;
3630 * Deletes/Clears the last wagon of a crashed train. It takes the engine of the
3631 * train, then goes to the last wagon and deletes that. Each call to this function
3632 * will remove the last wagon of a crashed train. If this wagon was on a crossing,
3633 * or inside a tunnel/bridge, recalculate the signals as they might need updating
3634 * @param v the Vehicle of which last wagon is to be removed
3636 static void DeleteLastWagon(Train *v)
3638 Train *first = v->First();
3640 /* Go to the last wagon and delete the link pointing there
3641 * *u is then the one-before-last wagon, and *v the last
3642 * one which will physically be removed */
3643 Train *u = v;
3644 for (; v->Next() != nullptr; v = v->Next()) u = v;
3645 u->SetNext(nullptr);
3647 if (first != v) {
3648 /* Recalculate cached train properties */
3649 first->ConsistChanged(CCF_ARRANGE);
3650 /* Update the depot window if the first vehicle is in depot -
3651 * if v == first, then it is updated in PreDestructor() */
3652 if (first->track == TRACK_BIT_DEPOT) {
3653 SetWindowDirty(WC_VEHICLE_DEPOT, first->tile);
3655 v->last_station_visited = first->last_station_visited; // for PreDestructor
3658 /* 'v' shouldn't be accessed after it has been deleted */
3659 TrackBits trackbits = v->track;
3660 TileIndex tile = v->tile;
3661 Owner owner = v->owner;
3663 delete v;
3664 v = nullptr; // make sure nobody will try to read 'v' anymore
3666 if (trackbits == TRACK_BIT_WORMHOLE) {
3667 /* Vehicle is inside a wormhole, v->track contains no useful value then. */
3668 trackbits = DiagDirToDiagTrackBits(GetTunnelBridgeDirection(tile));
3671 Track track = TrackBitsToTrack(trackbits);
3672 if (HasReservedTracks(tile, trackbits)) {
3673 UnreserveRailTrack(tile, track);
3675 /* If there are still crashed vehicles on the tile, give the track reservation to them */
3676 TrackBits remaining_trackbits = TRACK_BIT_NONE;
3677 FindVehicleOnPos(tile, &remaining_trackbits, CollectTrackbitsFromCrashedVehiclesEnum);
3679 /* It is important that these two are the first in the loop, as reservation cannot deal with every trackbit combination */
3680 assert(TRACK_BEGIN == TRACK_X && TRACK_Y == TRACK_BEGIN + 1);
3681 for (Track t : SetTrackBitIterator(remaining_trackbits)) TryReserveRailTrack(tile, t);
3684 /* check if the wagon was on a road/rail-crossing */
3685 if (IsLevelCrossingTile(tile)) UpdateLevelCrossing(tile);
3687 if (IsRailStationTile(tile)) {
3688 bool occupied = IsRailStationPlatformOccupied(tile);
3689 DiagDirection dir = AxisToDiagDir(GetRailStationAxis(tile));
3690 SetRailStationPlatformReservation(tile, dir, occupied);
3691 SetRailStationPlatformReservation(tile, ReverseDiagDir(dir), occupied);
3694 /* Update signals */
3695 if (IsTileType(tile, MP_TUNNELBRIDGE) || IsRailDepotTile(tile)) {
3696 UpdateSignalsOnSegment(tile, INVALID_DIAGDIR, owner);
3697 } else {
3698 SetSignalsOnBothDir(tile, track, owner);
3703 * Rotate all vehicles of a (crashed) train chain randomly to animate the crash.
3704 * @param v First crashed vehicle.
3706 static void ChangeTrainDirRandomly(Train *v)
3708 static const DirDiff delta[] = {
3709 DIRDIFF_45LEFT, DIRDIFF_SAME, DIRDIFF_SAME, DIRDIFF_45RIGHT
3712 do {
3713 /* We don't need to twist around vehicles if they're not visible */
3714 if (!(v->vehstatus & VS_HIDDEN)) {
3715 v->direction = ChangeDir(v->direction, delta[GB(Random(), 0, 2)]);
3716 /* Refrain from updating the z position of the vehicle when on
3717 * a bridge, because UpdateInclination() will put the vehicle under
3718 * the bridge in that case */
3719 if (v->track != TRACK_BIT_WORMHOLE) {
3720 v->UpdatePosition();
3721 v->UpdateInclination(false, true);
3722 } else {
3723 v->UpdateViewport(false, true);
3726 } while ((v = v->Next()) != nullptr);
3730 * Handle a crashed train.
3731 * @param v First train vehicle.
3732 * @return %Vehicle chain still exists.
3734 static bool HandleCrashedTrain(Train *v)
3736 int state = ++v->crash_anim_pos;
3738 if (state == 4 && !(v->vehstatus & VS_HIDDEN)) {
3739 CreateEffectVehicleRel(v, 4, 4, 8, EV_EXPLOSION_LARGE);
3742 uint32_t r;
3743 if (state <= 200 && Chance16R(1, 7, r)) {
3744 int index = (r * 10 >> 16);
3746 Vehicle *u = v;
3747 do {
3748 if (--index < 0) {
3749 r = Random();
3751 CreateEffectVehicleRel(u,
3752 GB(r, 8, 3) + 2,
3753 GB(r, 16, 3) + 2,
3754 GB(r, 0, 3) + 5,
3755 EV_EXPLOSION_SMALL);
3756 break;
3758 } while ((u = u->Next()) != nullptr);
3761 if (state <= 240 && !(v->tick_counter & 3)) ChangeTrainDirRandomly(v);
3763 if (state >= 4440 && !(v->tick_counter & 0x1F)) {
3764 bool ret = v->Next() != nullptr;
3765 DeleteLastWagon(v);
3766 return ret;
3769 return true;
3772 /** Maximum speeds for train that is broken down or approaching line end */
3773 static const uint16_t _breakdown_speeds[16] = {
3774 225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, 15
3779 * Train is approaching line end, slow down and possibly reverse
3781 * @param v front train engine
3782 * @param signal not line end, just a red signal
3783 * @param reverse Set to false to not execute the vehicle reversing. This does not change any other logic.
3784 * @return true iff we did NOT have to reverse
3786 static bool TrainApproachingLineEnd(Train *v, bool signal, bool reverse)
3788 /* Calc position within the current tile */
3789 uint x = v->x_pos & 0xF;
3790 uint y = v->y_pos & 0xF;
3792 /* for diagonal directions, 'x' will be 0..15 -
3793 * for other directions, it will be 1, 3, 5, ..., 15 */
3794 switch (v->direction) {
3795 case DIR_N : x = ~x + ~y + 25; break;
3796 case DIR_NW: x = y; [[fallthrough]];
3797 case DIR_NE: x = ~x + 16; break;
3798 case DIR_E : x = ~x + y + 9; break;
3799 case DIR_SE: x = y; break;
3800 case DIR_S : x = x + y - 7; break;
3801 case DIR_W : x = ~y + x + 9; break;
3802 default: break;
3805 /* Do not reverse when approaching red signal. Make sure the vehicle's front
3806 * does not cross the tile boundary when we do reverse, but as the vehicle's
3807 * location is based on their center, use half a vehicle's length as offset.
3808 * Multiply the half-length by two for straight directions to compensate that
3809 * we only get odd x offsets there. */
3810 if (!signal && x + (v->gcache.cached_veh_length + 1) / 2 * (IsDiagonalDirection(v->direction) ? 1 : 2) >= TILE_SIZE) {
3811 /* we are too near the tile end, reverse now */
3812 v->cur_speed = 0;
3813 if (reverse) ReverseTrainDirection(v);
3814 return false;
3817 /* slow down */
3818 v->vehstatus |= VS_TRAIN_SLOWING;
3819 uint16_t break_speed = _breakdown_speeds[x & 0xF];
3820 if (break_speed < v->cur_speed) v->cur_speed = break_speed;
3822 return true;
3827 * Determines whether train would like to leave the tile
3828 * @param v train to test
3829 * @return true iff vehicle is NOT entering or inside a depot or tunnel/bridge
3831 static bool TrainCanLeaveTile(const Train *v)
3833 /* Exit if inside a tunnel/bridge or a depot */
3834 if (v->track == TRACK_BIT_WORMHOLE || v->track == TRACK_BIT_DEPOT) return false;
3836 TileIndex tile = v->tile;
3838 /* entering a tunnel/bridge? */
3839 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
3840 DiagDirection dir = GetTunnelBridgeDirection(tile);
3841 if (DiagDirToDir(dir) == v->direction) return false;
3844 /* entering a depot? */
3845 if (IsRailDepotTile(tile)) {
3846 DiagDirection dir = ReverseDiagDir(GetRailDepotDirection(tile));
3847 if (DiagDirToDir(dir) == v->direction) return false;
3850 return true;
3855 * Determines whether train is approaching a rail-road crossing
3856 * (thus making it barred)
3857 * @param v front engine of train
3858 * @return TileIndex of crossing the train is approaching, else INVALID_TILE
3859 * @pre v in non-crashed front engine
3861 static TileIndex TrainApproachingCrossingTile(const Train *v)
3863 assert(v->IsFrontEngine());
3864 assert(!(v->vehstatus & VS_CRASHED));
3866 if (!TrainCanLeaveTile(v)) return INVALID_TILE;
3868 DiagDirection dir = VehicleExitDir(v->direction, v->track);
3869 TileIndex tile = v->tile + TileOffsByDiagDir(dir);
3871 /* not a crossing || wrong axis || unusable rail (wrong type or owner) */
3872 if (!IsLevelCrossingTile(tile) || DiagDirToAxis(dir) == GetCrossingRoadAxis(tile) ||
3873 !CheckCompatibleRail(v, tile)) {
3874 return INVALID_TILE;
3877 return tile;
3882 * Checks for line end. Also, bars crossing at next tile if needed
3884 * @param v vehicle we are checking
3885 * @param reverse Set to false to not execute the vehicle reversing. This does not change any other logic.
3886 * @return true iff we did NOT have to reverse
3888 static bool TrainCheckIfLineEnds(Train *v, bool reverse)
3890 /* First, handle broken down train */
3892 int t = v->breakdown_ctr;
3893 if (t > 1) {
3894 v->vehstatus |= VS_TRAIN_SLOWING;
3896 uint16_t break_speed = _breakdown_speeds[GB(~t, 4, 4)];
3897 if (break_speed < v->cur_speed) v->cur_speed = break_speed;
3898 } else {
3899 v->vehstatus &= ~VS_TRAIN_SLOWING;
3902 if (!TrainCanLeaveTile(v)) return true;
3904 /* Determine the non-diagonal direction in which we will exit this tile */
3905 DiagDirection dir = VehicleExitDir(v->direction, v->track);
3906 /* Calculate next tile */
3907 TileIndex tile = v->tile + TileOffsByDiagDir(dir);
3909 /* Determine the track status on the next tile */
3910 TrackStatus ts = GetTileTrackStatus(tile, TRANSPORT_RAIL, 0, ReverseDiagDir(dir));
3911 TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(dir);
3913 TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
3914 TrackdirBits red_signals = TrackStatusToRedSignals(ts) & reachable_trackdirs;
3916 /* We are sure the train is not entering a depot, it is detected above */
3918 /* mask unreachable track bits if we are forbidden to do 90deg turns */
3919 TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
3920 if (Rail90DegTurnDisallowed(GetTileRailType(v->tile), GetTileRailType(tile))) {
3921 bits &= ~TrackCrossesTracks(FindFirstTrack(v->track));
3924 /* no suitable trackbits at all || unusable rail (wrong type or owner) */
3925 if (bits == TRACK_BIT_NONE || !CheckCompatibleRail(v, tile)) {
3926 return TrainApproachingLineEnd(v, false, reverse);
3929 /* approaching red signal */
3930 if ((trackdirbits & red_signals) != 0) return TrainApproachingLineEnd(v, true, reverse);
3932 /* approaching a rail/road crossing? then make it red */
3933 if (IsLevelCrossingTile(tile)) MaybeBarCrossingWithSound(tile);
3935 return true;
3939 static bool TrainLocoHandler(Train *v, bool mode)
3941 /* train has crashed? */
3942 if (v->vehstatus & VS_CRASHED) {
3943 return mode ? true : HandleCrashedTrain(v); // 'this' can be deleted here
3946 if (v->force_proceed != TFP_NONE) {
3947 ClrBit(v->flags, VRF_TRAIN_STUCK);
3948 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
3951 /* train is broken down? */
3952 if (v->HandleBreakdown()) return true;
3954 if (HasBit(v->flags, VRF_REVERSING) && v->cur_speed == 0) {
3955 ReverseTrainDirection(v);
3958 /* exit if train is stopped */
3959 if ((v->vehstatus & VS_STOPPED) && v->cur_speed == 0) return true;
3961 bool valid_order = !v->current_order.IsType(OT_NOTHING) && v->current_order.GetType() != OT_CONDITIONAL;
3962 if (ProcessOrders(v) && CheckReverseTrain(v)) {
3963 v->wait_counter = 0;
3964 v->cur_speed = 0;
3965 v->subspeed = 0;
3966 ClrBit(v->flags, VRF_LEAVING_STATION);
3967 ReverseTrainDirection(v);
3968 return true;
3969 } else if (HasBit(v->flags, VRF_LEAVING_STATION)) {
3970 /* Try to reserve a path when leaving the station as we
3971 * might not be marked as wanting a reservation, e.g.
3972 * when an overlength train gets turned around in a station. */
3973 DiagDirection dir = VehicleExitDir(v->direction, v->track);
3974 if (IsRailDepotTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE)) dir = INVALID_DIAGDIR;
3976 if (UpdateSignalsOnSegment(v->tile, dir, v->owner) == SIGSEG_PBS || _settings_game.pf.reserve_paths) {
3977 TryPathReserve(v, true, true);
3979 ClrBit(v->flags, VRF_LEAVING_STATION);
3982 v->HandleLoading(mode);
3984 if (v->current_order.IsType(OT_LOADING)) return true;
3986 if (CheckTrainStayInDepot(v)) return true;
3988 if (!mode) v->ShowVisualEffect();
3990 /* We had no order but have an order now, do look ahead. */
3991 if (!valid_order && !v->current_order.IsType(OT_NOTHING)) {
3992 CheckNextTrainTile(v);
3995 /* Handle stuck trains. */
3996 if (!mode && HasBit(v->flags, VRF_TRAIN_STUCK)) {
3997 ++v->wait_counter;
3999 /* Should we try reversing this tick if still stuck? */
4000 bool turn_around = v->wait_counter % (_settings_game.pf.wait_for_pbs_path * Ticks::DAY_TICKS) == 0 && _settings_game.pf.reverse_at_signals;
4002 if (!turn_around && v->wait_counter % _settings_game.pf.path_backoff_interval != 0 && v->force_proceed == TFP_NONE) return true;
4003 if (!TryPathReserve(v)) {
4004 /* Still stuck. */
4005 if (turn_around) ReverseTrainDirection(v);
4007 if (HasBit(v->flags, VRF_TRAIN_STUCK) && v->wait_counter > 2 * _settings_game.pf.wait_for_pbs_path * Ticks::DAY_TICKS) {
4008 /* Show message to player. */
4009 if (_settings_client.gui.lost_vehicle_warn && v->owner == _local_company) {
4010 SetDParam(0, v->index);
4011 AddVehicleAdviceNewsItem(STR_NEWS_TRAIN_IS_STUCK, v->index);
4013 v->wait_counter = 0;
4015 /* Exit if force proceed not pressed, else reset stuck flag anyway. */
4016 if (v->force_proceed == TFP_NONE) return true;
4017 ClrBit(v->flags, VRF_TRAIN_STUCK);
4018 v->wait_counter = 0;
4019 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
4023 if (v->current_order.IsType(OT_LEAVESTATION)) {
4024 v->current_order.Free();
4025 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
4026 return true;
4029 int j = v->UpdateSpeed();
4031 /* we need to invalidate the widget if we are stopping from 'Stopping 0 km/h' to 'Stopped' */
4032 if (v->cur_speed == 0 && (v->vehstatus & VS_STOPPED)) {
4033 /* If we manually stopped, we're not force-proceeding anymore. */
4034 v->force_proceed = TFP_NONE;
4035 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
4038 int adv_spd = v->GetAdvanceDistance();
4039 if (j < adv_spd) {
4040 /* if the vehicle has speed 0, update the last_speed field. */
4041 if (v->cur_speed == 0) v->SetLastSpeed();
4042 } else {
4043 TrainCheckIfLineEnds(v);
4044 /* Loop until the train has finished moving. */
4045 for (;;) {
4046 j -= adv_spd;
4047 TrainController(v, nullptr);
4048 /* Don't continue to move if the train crashed. */
4049 if (CheckTrainCollision(v)) break;
4050 /* Determine distance to next map position */
4051 adv_spd = v->GetAdvanceDistance();
4053 /* No more moving this tick */
4054 if (j < adv_spd || v->cur_speed == 0) break;
4056 OrderType order_type = v->current_order.GetType();
4057 /* Do not skip waypoints (incl. 'via' stations) when passing through at full speed. */
4058 if ((order_type == OT_GOTO_WAYPOINT || order_type == OT_GOTO_STATION) &&
4059 (v->current_order.GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION) &&
4060 IsTileType(v->tile, MP_STATION) &&
4061 v->current_order.GetDestination() == GetStationIndex(v->tile)) {
4062 ProcessOrders(v);
4065 v->SetLastSpeed();
4068 for (Train *u = v; u != nullptr; u = u->Next()) {
4069 if ((u->vehstatus & VS_HIDDEN) != 0) continue;
4071 u->UpdateViewport(false, false);
4074 if (v->progress == 0) v->progress = j; // Save unused spd for next time, if TrainController didn't set progress
4076 return true;
4080 * Get running cost for the train consist.
4081 * @return Yearly running costs.
4083 Money Train::GetRunningCost() const
4085 Money cost = 0;
4086 const Train *v = this;
4088 do {
4089 const Engine *e = v->GetEngine();
4090 if (e->u.rail.running_cost_class == INVALID_PRICE) continue;
4092 uint cost_factor = GetVehicleProperty(v, PROP_TRAIN_RUNNING_COST_FACTOR, e->u.rail.running_cost);
4093 if (cost_factor == 0) continue;
4095 /* Halve running cost for multiheaded parts */
4096 if (v->IsMultiheaded()) cost_factor /= 2;
4098 cost += GetPrice(e->u.rail.running_cost_class, cost_factor, e->GetGRF());
4099 } while ((v = v->GetNextVehicle()) != nullptr);
4101 return cost;
4105 * Update train vehicle data for a tick.
4106 * @return True if the vehicle still exists, false if it has ceased to exist (front of consists only).
4108 bool Train::Tick()
4110 this->tick_counter++;
4112 if (this->IsFrontEngine()) {
4113 PerformanceAccumulator framerate(PFE_GL_TRAINS);
4115 if (!(this->vehstatus & VS_STOPPED) || this->cur_speed > 0) this->running_ticks++;
4117 this->current_order_time++;
4119 if (!TrainLocoHandler(this, false)) return false;
4121 return TrainLocoHandler(this, true);
4122 } else if (this->IsFreeWagon() && (this->vehstatus & VS_CRASHED)) {
4123 /* Delete flooded standalone wagon chain */
4124 if (++this->crash_anim_pos >= 4400) {
4125 delete this;
4126 return false;
4130 return true;
4134 * Check whether a train needs service, and if so, find a depot or service it.
4135 * @return v %Train to check.
4137 static void CheckIfTrainNeedsService(Train *v)
4139 if (Company::Get(v->owner)->settings.vehicle.servint_trains == 0 || !v->NeedsAutomaticServicing()) return;
4140 if (v->IsChainInDepot()) {
4141 VehicleServiceInDepot(v);
4142 return;
4145 uint max_penalty;
4146 switch (_settings_game.pf.pathfinder_for_trains) {
4147 case VPF_NPF: max_penalty = _settings_game.pf.npf.maximum_go_to_depot_penalty; break;
4148 case VPF_YAPF: max_penalty = _settings_game.pf.yapf.maximum_go_to_depot_penalty; break;
4149 default: NOT_REACHED();
4152 FindDepotData tfdd = FindClosestTrainDepot(v, max_penalty);
4153 /* Only go to the depot if it is not too far out of our way. */
4154 if (tfdd.best_length == UINT_MAX || tfdd.best_length > max_penalty) {
4155 if (v->current_order.IsType(OT_GOTO_DEPOT)) {
4156 /* If we were already heading for a depot but it has
4157 * suddenly moved farther away, we continue our normal
4158 * schedule? */
4159 v->current_order.MakeDummy();
4160 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
4162 return;
4165 DepotID depot = GetDepotIndex(tfdd.tile);
4167 if (v->current_order.IsType(OT_GOTO_DEPOT) &&
4168 v->current_order.GetDestination() != depot &&
4169 !Chance16(3, 16)) {
4170 return;
4173 SetBit(v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS);
4174 v->current_order.MakeGoToDepot(depot, ODTFB_SERVICE, ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS, ODATFB_NEAREST_DEPOT);
4175 v->dest_tile = tfdd.tile;
4176 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
4179 /** Calendar day handler. */
4180 void Train::OnNewCalendarDay()
4182 AgeVehicle(this);
4185 /** Economy day handler. */
4186 void Train::OnNewEconomyDay()
4188 if ((++this->day_counter & 7) == 0) DecreaseVehicleValue(this);
4190 if (this->IsFrontEngine()) {
4191 CheckVehicleBreakdown(this);
4193 CheckIfTrainNeedsService(this);
4195 CheckOrders(this);
4197 /* update destination */
4198 if (this->current_order.IsType(OT_GOTO_STATION)) {
4199 TileIndex tile = Station::Get(this->current_order.GetDestination())->train_station.tile;
4200 if (tile != INVALID_TILE) this->dest_tile = tile;
4203 if (this->running_ticks != 0) {
4204 /* running costs */
4205 CommandCost cost(EXPENSES_TRAIN_RUN, this->GetRunningCost() * this->running_ticks / (CalendarTime::DAYS_IN_YEAR * Ticks::DAY_TICKS));
4207 this->profit_this_year -= cost.GetCost();
4208 this->running_ticks = 0;
4210 SubtractMoneyFromCompanyFract(this->owner, cost);
4212 SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
4213 SetWindowClassesDirty(WC_TRAINS_LIST);
4219 * Get the tracks of the train vehicle.
4220 * @return Current tracks of the vehicle.
4222 Trackdir Train::GetVehicleTrackdir() const
4224 if (this->vehstatus & VS_CRASHED) return INVALID_TRACKDIR;
4226 if (this->track == TRACK_BIT_DEPOT) {
4227 /* We'll assume the train is facing outwards */
4228 return DiagDirToDiagTrackdir(GetRailDepotDirection(this->tile)); // Train in depot
4231 if (this->track == TRACK_BIT_WORMHOLE) {
4232 /* train in tunnel or on bridge, so just use its direction and assume a diagonal track */
4233 return DiagDirToDiagTrackdir(DirToDiagDir(this->direction));
4236 return TrackDirectionToTrackdir(FindFirstTrack(this->track), this->direction);
4239 uint16_t Train::GetMaxWeight() const
4241 uint16_t weight = CargoSpec::Get(this->cargo_type)->WeightOfNUnitsInTrain(this->GetEngine()->DetermineCapacity(this));
4243 /* Vehicle weight is not added for articulated parts. */
4244 if (!this->IsArticulatedPart()) {
4245 weight += GetVehicleProperty(this, PROP_TRAIN_WEIGHT, RailVehInfo(this->engine_type)->weight);
4248 /* Powered wagons have extra weight added. */
4249 if (HasBit(this->flags, VRF_POWEREDWAGON)) {
4250 weight += RailVehInfo(this->gcache.first_engine)->pow_wag_weight;
4253 return weight;