Fix #8316: Make sort industries by production and transported with a cargo filter...
[openttd-github.git] / src / train_cmd.cpp
blob17e298c33d21e96c6adc542eb73ab4b78706d9e4
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 "pathfinder/npf/npf_func.h"
15 #include "pathfinder/yapf/yapf.hpp"
16 #include "news_func.h"
17 #include "company_func.h"
18 #include "newgrf_sound.h"
19 #include "newgrf_text.h"
20 #include "strings_func.h"
21 #include "viewport_func.h"
22 #include "vehicle_func.h"
23 #include "sound_func.h"
24 #include "ai/ai.hpp"
25 #include "game/game.hpp"
26 #include "newgrf_station.h"
27 #include "effectvehicle_func.h"
28 #include "network/network.h"
29 #include "spritecache.h"
30 #include "core/random_func.hpp"
31 #include "company_base.h"
32 #include "newgrf.h"
33 #include "order_backup.h"
34 #include "zoom_func.h"
35 #include "newgrf_debug.h"
36 #include "framerate_type.h"
38 #include "table/strings.h"
39 #include "table/train_cmd.h"
41 #include "safeguards.h"
43 static Track ChooseTrainTrack(Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool force_res, bool *got_reservation, bool mark_stuck);
44 static bool TrainCheckIfLineEnds(Train *v, bool reverse = true);
45 bool TrainController(Train *v, Vehicle *nomove, bool reverse = true); // Also used in vehicle_sl.cpp.
46 static TileIndex TrainApproachingCrossingTile(const Train *v);
47 static void CheckIfTrainNeedsService(Train *v);
48 static void CheckNextTrainTile(Train *v);
50 static const byte _vehicle_initial_x_fract[4] = {10, 8, 4, 8};
51 static const byte _vehicle_initial_y_fract[4] = { 8, 4, 8, 10};
53 template <>
54 bool IsValidImageIndex<VEH_TRAIN>(uint8 image_index)
56 return image_index < lengthof(_engine_sprite_base);
60 /**
61 * Return the cargo weight multiplier to use for a rail vehicle
62 * @param cargo Cargo type to get multiplier for
63 * @return Cargo weight multiplier
65 byte FreightWagonMult(CargoID cargo)
67 if (!CargoSpec::Get(cargo)->is_freight) return 1;
68 return _settings_game.vehicle.freight_trains;
71 /** Checks if lengths of all rail vehicles are valid. If not, shows an error message. */
72 void CheckTrainsLengths()
74 bool first = true;
76 for (const Train *v : Train::Iterate()) {
77 if (v->First() == v && !(v->vehstatus & VS_CRASHED)) {
78 for (const Train *u = v, *w = v->Next(); w != nullptr; u = w, w = w->Next()) {
79 if (u->track != TRACK_BIT_DEPOT) {
80 if ((w->track != TRACK_BIT_DEPOT &&
81 std::max(abs(u->x_pos - w->x_pos), abs(u->y_pos - w->y_pos)) != u->CalcNextVehicleOffset()) ||
82 (w->track == TRACK_BIT_DEPOT && TicksToLeaveDepot(u) <= 0)) {
83 SetDParam(0, v->index);
84 SetDParam(1, v->owner);
85 ShowErrorMessage(STR_BROKEN_VEHICLE_LENGTH, INVALID_STRING_ID, WL_CRITICAL);
87 if (!_networking && first) {
88 first = false;
89 DoCommandP(0, PM_PAUSED_ERROR, 1, CMD_PAUSE);
91 /* Break so we warn only once for each train. */
92 break;
101 * Recalculates the cached stuff of a train. Should be called each time a vehicle is added
102 * to/removed from the chain, and when the game is loaded.
103 * Note: this needs to be called too for 'wagon chains' (in the depot, without an engine)
104 * @param allowed_changes Stuff that is allowed to change.
106 void Train::ConsistChanged(ConsistChangeFlags allowed_changes)
108 uint16 max_speed = UINT16_MAX;
110 assert(this->IsFrontEngine() || this->IsFreeWagon());
112 const RailVehicleInfo *rvi_v = RailVehInfo(this->engine_type);
113 EngineID first_engine = this->IsFrontEngine() ? this->engine_type : INVALID_ENGINE;
114 this->gcache.cached_total_length = 0;
115 this->compatible_railtypes = RAILTYPES_NONE;
117 bool train_can_tilt = true;
119 for (Train *u = this; u != nullptr; u = u->Next()) {
120 const RailVehicleInfo *rvi_u = RailVehInfo(u->engine_type);
122 /* Check the this->first cache. */
123 assert(u->First() == this);
125 /* update the 'first engine' */
126 u->gcache.first_engine = this == u ? INVALID_ENGINE : first_engine;
127 u->railtype = rvi_u->railtype;
129 if (u->IsEngine()) first_engine = u->engine_type;
131 /* Set user defined data to its default value */
132 u->tcache.user_def_data = rvi_u->user_def_data;
133 this->InvalidateNewGRFCache();
134 u->InvalidateNewGRFCache();
137 for (Train *u = this; u != nullptr; u = u->Next()) {
138 /* Update user defined data (must be done before other properties) */
139 u->tcache.user_def_data = GetVehicleProperty(u, PROP_TRAIN_USER_DATA, u->tcache.user_def_data);
140 this->InvalidateNewGRFCache();
141 u->InvalidateNewGRFCache();
144 for (Train *u = this; u != nullptr; u = u->Next()) {
145 const Engine *e_u = u->GetEngine();
146 const RailVehicleInfo *rvi_u = &e_u->u.rail;
148 if (!HasBit(e_u->info.misc_flags, EF_RAIL_TILTS)) train_can_tilt = false;
150 /* Cache wagon override sprite group. nullptr is returned if there is none */
151 u->tcache.cached_override = GetWagonOverrideSpriteSet(u->engine_type, u->cargo_type, u->gcache.first_engine);
153 /* Reset colour map */
154 u->colourmap = PAL_NONE;
156 /* Update powered-wagon-status and visual effect */
157 u->UpdateVisualEffect(true);
159 if (rvi_v->pow_wag_power != 0 && rvi_u->railveh_type == RAILVEH_WAGON &&
160 UsesWagonOverride(u) && !HasBit(u->vcache.cached_vis_effect, VE_DISABLE_WAGON_POWER)) {
161 /* wagon is powered */
162 SetBit(u->flags, VRF_POWEREDWAGON); // cache 'powered' status
163 } else {
164 ClrBit(u->flags, VRF_POWEREDWAGON);
167 if (!u->IsArticulatedPart()) {
168 /* Do not count powered wagons for the compatible railtypes, as wagons always
169 have railtype normal */
170 if (rvi_u->power > 0) {
171 this->compatible_railtypes |= GetRailTypeInfo(u->railtype)->powered_railtypes;
174 /* Some electric engines can be allowed to run on normal rail. It happens to all
175 * existing electric engines when elrails are disabled and then re-enabled */
176 if (HasBit(u->flags, VRF_EL_ENGINE_ALLOWED_NORMAL_RAIL)) {
177 u->railtype = RAILTYPE_RAIL;
178 u->compatible_railtypes |= RAILTYPES_RAIL;
181 /* max speed is the minimum of the speed limits of all vehicles in the consist */
182 if ((rvi_u->railveh_type != RAILVEH_WAGON || _settings_game.vehicle.wagon_speed_limits) && !UsesWagonOverride(u)) {
183 uint16 speed = GetVehicleProperty(u, PROP_TRAIN_SPEED, rvi_u->max_speed);
184 if (speed != 0) max_speed = std::min(speed, max_speed);
188 uint16 new_cap = e_u->DetermineCapacity(u);
189 if (allowed_changes & CCF_CAPACITY) {
190 /* Update vehicle capacity. */
191 if (u->cargo_cap > new_cap) u->cargo.Truncate(new_cap);
192 u->refit_cap = std::min(new_cap, u->refit_cap);
193 u->cargo_cap = new_cap;
194 } else {
195 /* Verify capacity hasn't changed. */
196 if (new_cap != u->cargo_cap) ShowNewGrfVehicleError(u->engine_type, STR_NEWGRF_BROKEN, STR_NEWGRF_BROKEN_CAPACITY, GBUG_VEH_CAPACITY, true);
198 u->vcache.cached_cargo_age_period = GetVehicleProperty(u, PROP_TRAIN_CARGO_AGE_PERIOD, e_u->info.cargo_age_period);
200 /* check the vehicle length (callback) */
201 uint16 veh_len = CALLBACK_FAILED;
202 if (e_u->GetGRF() != nullptr && e_u->GetGRF()->grf_version >= 8) {
203 /* Use callback 36 */
204 veh_len = GetVehicleProperty(u, PROP_TRAIN_SHORTEN_FACTOR, CALLBACK_FAILED);
206 if (veh_len != CALLBACK_FAILED && veh_len >= VEHICLE_LENGTH) {
207 ErrorUnknownCallbackResult(e_u->GetGRFID(), CBID_VEHICLE_LENGTH, veh_len);
209 } else if (HasBit(e_u->info.callback_mask, CBM_VEHICLE_LENGTH)) {
210 /* Use callback 11 */
211 veh_len = GetVehicleCallback(CBID_VEHICLE_LENGTH, 0, 0, u->engine_type, u);
213 if (veh_len == CALLBACK_FAILED) veh_len = rvi_u->shorten_factor;
214 veh_len = VEHICLE_LENGTH - Clamp(veh_len, 0, VEHICLE_LENGTH - 1);
216 if (allowed_changes & CCF_LENGTH) {
217 /* Update vehicle length. */
218 u->gcache.cached_veh_length = veh_len;
219 } else {
220 /* Verify length hasn't changed. */
221 if (veh_len != u->gcache.cached_veh_length) VehicleLengthChanged(u);
224 this->gcache.cached_total_length += u->gcache.cached_veh_length;
225 this->InvalidateNewGRFCache();
226 u->InvalidateNewGRFCache();
229 /* store consist weight/max speed in cache */
230 this->vcache.cached_max_speed = max_speed;
231 this->tcache.cached_tilt = train_can_tilt;
232 this->tcache.cached_max_curve_speed = this->GetCurveSpeedLimit();
234 /* 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) */
235 this->CargoChanged();
237 if (this->IsFrontEngine()) {
238 this->UpdateAcceleration();
239 SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
240 InvalidateWindowData(WC_VEHICLE_REFIT, this->index, VIWD_CONSIST_CHANGED);
241 InvalidateWindowData(WC_VEHICLE_ORDERS, this->index, VIWD_CONSIST_CHANGED);
242 InvalidateNewGRFInspectWindow(GSF_TRAINS, this->index);
247 * Get the stop location of (the center) of the front vehicle of a train at
248 * a platform of a station.
249 * @param station_id the ID of the station where we're stopping
250 * @param tile the tile where the vehicle currently is
251 * @param v the vehicle to get the stop location of
252 * @param station_ahead 'return' the amount of 1/16th tiles in front of the train
253 * @param station_length 'return' the station length in 1/16th tiles
254 * @return the location, calculated from the begin of the station to stop at.
256 int GetTrainStopLocation(StationID station_id, TileIndex tile, const Train *v, int *station_ahead, int *station_length)
258 const Station *st = Station::Get(station_id);
259 *station_ahead = st->GetPlatformLength(tile, DirToDiagDir(v->direction)) * TILE_SIZE;
260 *station_length = st->GetPlatformLength(tile) * TILE_SIZE;
262 /* Default to the middle of the station for stations stops that are not in
263 * the order list like intermediate stations when non-stop is disabled */
264 OrderStopLocation osl = OSL_PLATFORM_MIDDLE;
265 if (v->gcache.cached_total_length >= *station_length) {
266 /* The train is longer than the station, make it stop at the far end of the platform */
267 osl = OSL_PLATFORM_FAR_END;
268 } else if (v->current_order.IsType(OT_GOTO_STATION) && v->current_order.GetDestination() == station_id) {
269 osl = v->current_order.GetStopLocation();
272 /* The stop location of the FRONT! of the train */
273 int stop;
274 switch (osl) {
275 default: NOT_REACHED();
277 case OSL_PLATFORM_NEAR_END:
278 stop = v->gcache.cached_total_length;
279 break;
281 case OSL_PLATFORM_MIDDLE:
282 stop = *station_length - (*station_length - v->gcache.cached_total_length) / 2;
283 break;
285 case OSL_PLATFORM_FAR_END:
286 stop = *station_length;
287 break;
290 /* Subtract half the front vehicle length of the train so we get the real
291 * stop location of the train. */
292 return stop - (v->gcache.cached_veh_length + 1) / 2;
297 * Computes train speed limit caused by curves
298 * @return imposed speed limit
300 int Train::GetCurveSpeedLimit() const
302 assert(this->First() == this);
304 static const int absolute_max_speed = UINT16_MAX;
305 int max_speed = absolute_max_speed;
307 if (_settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) return max_speed;
309 int curvecount[2] = {0, 0};
311 /* first find the curve speed limit */
312 int numcurve = 0;
313 int sum = 0;
314 int pos = 0;
315 int lastpos = -1;
316 for (const Vehicle *u = this; u->Next() != nullptr; u = u->Next(), pos++) {
317 Direction this_dir = u->direction;
318 Direction next_dir = u->Next()->direction;
320 DirDiff dirdiff = DirDifference(this_dir, next_dir);
321 if (dirdiff == DIRDIFF_SAME) continue;
323 if (dirdiff == DIRDIFF_45LEFT) curvecount[0]++;
324 if (dirdiff == DIRDIFF_45RIGHT) curvecount[1]++;
325 if (dirdiff == DIRDIFF_45LEFT || dirdiff == DIRDIFF_45RIGHT) {
326 if (lastpos != -1) {
327 numcurve++;
328 sum += pos - lastpos;
329 if (pos - lastpos == 1 && max_speed > 88) {
330 max_speed = 88;
333 lastpos = pos;
336 /* if we have a 90 degree turn, fix the speed limit to 60 */
337 if (dirdiff == DIRDIFF_90LEFT || dirdiff == DIRDIFF_90RIGHT) {
338 max_speed = 61;
342 if (numcurve > 0 && max_speed > 88) {
343 if (curvecount[0] == 1 && curvecount[1] == 1) {
344 max_speed = absolute_max_speed;
345 } else {
346 sum /= numcurve;
347 max_speed = 232 - (13 - Clamp(sum, 1, 12)) * (13 - Clamp(sum, 1, 12));
351 if (max_speed != absolute_max_speed) {
352 /* Apply the current railtype's curve speed advantage */
353 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(this->tile));
354 max_speed += (max_speed / 2) * rti->curve_speed;
356 if (this->tcache.cached_tilt) {
357 /* Apply max_speed bonus of 20% for a tilting train */
358 max_speed += max_speed / 5;
362 return max_speed;
366 * Calculates the maximum speed of the vehicle under its current conditions.
367 * @return Maximum speed of the vehicle.
369 int Train::GetCurrentMaxSpeed() const
371 int max_speed = _settings_game.vehicle.train_acceleration_model == AM_ORIGINAL ?
372 this->gcache.cached_max_track_speed :
373 this->tcache.cached_max_curve_speed;
375 if (_settings_game.vehicle.train_acceleration_model == AM_REALISTIC && IsRailStationTile(this->tile)) {
376 StationID sid = GetStationIndex(this->tile);
377 if (this->current_order.ShouldStopAtStation(this, sid)) {
378 int station_ahead;
379 int station_length;
380 int stop_at = GetTrainStopLocation(sid, this->tile, this, &station_ahead, &station_length);
382 /* The distance to go is whatever is still ahead of the train minus the
383 * distance from the train's stop location to the end of the platform */
384 int distance_to_go = station_ahead / TILE_SIZE - (station_length - stop_at) / TILE_SIZE;
386 if (distance_to_go > 0) {
387 int st_max_speed = 120;
389 int delta_v = this->cur_speed / (distance_to_go + 1);
390 if (max_speed > (this->cur_speed - delta_v)) {
391 st_max_speed = this->cur_speed - (delta_v / 10);
394 st_max_speed = std::max(st_max_speed, 25 * distance_to_go);
395 max_speed = std::min(max_speed, st_max_speed);
400 for (const Train *u = this; u != nullptr; u = u->Next()) {
401 if (_settings_game.vehicle.train_acceleration_model == AM_REALISTIC && u->track == TRACK_BIT_DEPOT) {
402 max_speed = std::min(max_speed, 61);
403 break;
406 /* Vehicle is on the middle part of a bridge. */
407 if (u->track == TRACK_BIT_WORMHOLE && !(u->vehstatus & VS_HIDDEN)) {
408 max_speed = std::min<int>(max_speed, GetBridgeSpec(GetBridgeType(u->tile))->speed);
412 max_speed = std::min<int>(max_speed, this->current_order.GetMaxSpeed());
413 return std::min<int>(max_speed, this->gcache.cached_max_track_speed);
416 /** Update acceleration of the train from the cached power and weight. */
417 void Train::UpdateAcceleration()
419 assert(this->IsFrontEngine() || this->IsFreeWagon());
421 uint power = this->gcache.cached_power;
422 uint weight = this->gcache.cached_weight;
423 assert(weight != 0);
424 this->acceleration = Clamp(power / weight * 4, 1, 255);
428 * Get the width of a train vehicle image in the GUI.
429 * @param offset Additional offset for positioning the sprite; set to nullptr if not needed
430 * @return Width in pixels
432 int Train::GetDisplayImageWidth(Point *offset) const
434 int reference_width = TRAININFO_DEFAULT_VEHICLE_WIDTH;
435 int vehicle_pitch = 0;
437 const Engine *e = this->GetEngine();
438 if (e->GetGRF() != nullptr && is_custom_sprite(e->u.rail.image_index)) {
439 reference_width = e->GetGRF()->traininfo_vehicle_width;
440 vehicle_pitch = e->GetGRF()->traininfo_vehicle_pitch;
443 if (offset != nullptr) {
444 offset->x = ScaleGUITrad(reference_width) / 2;
445 offset->y = ScaleGUITrad(vehicle_pitch);
447 return ScaleGUITrad(this->gcache.cached_veh_length * reference_width / VEHICLE_LENGTH);
450 static SpriteID GetDefaultTrainSprite(uint8 spritenum, Direction direction)
452 assert(IsValidImageIndex<VEH_TRAIN>(spritenum));
453 return ((direction + _engine_sprite_add[spritenum]) & _engine_sprite_and[spritenum]) + _engine_sprite_base[spritenum];
457 * Get the sprite to display the train.
458 * @param direction Direction of view/travel.
459 * @param image_type Visualisation context.
460 * @return Sprite to display.
462 void Train::GetImage(Direction direction, EngineImageType image_type, VehicleSpriteSeq *result) const
464 uint8 spritenum = this->spritenum;
466 if (HasBit(this->flags, VRF_REVERSE_DIRECTION)) direction = ReverseDir(direction);
468 if (is_custom_sprite(spritenum)) {
469 GetCustomVehicleSprite(this, (Direction)(direction + 4 * IS_CUSTOM_SECONDHEAD_SPRITE(spritenum)), image_type, result);
470 if (result->IsValid()) return;
472 spritenum = this->GetEngine()->original_image_index;
475 assert(IsValidImageIndex<VEH_TRAIN>(spritenum));
476 SpriteID sprite = GetDefaultTrainSprite(spritenum, direction);
478 if (this->cargo.StoredCount() >= this->cargo_cap / 2U) sprite += _wagon_full_adder[spritenum];
480 result->Set(sprite);
483 static void GetRailIcon(EngineID engine, bool rear_head, int &y, EngineImageType image_type, VehicleSpriteSeq *result)
485 const Engine *e = Engine::Get(engine);
486 Direction dir = rear_head ? DIR_E : DIR_W;
487 uint8 spritenum = e->u.rail.image_index;
489 if (is_custom_sprite(spritenum)) {
490 GetCustomVehicleIcon(engine, dir, image_type, result);
491 if (result->IsValid()) {
492 if (e->GetGRF() != nullptr) {
493 y += ScaleGUITrad(e->GetGRF()->traininfo_vehicle_pitch);
495 return;
498 spritenum = Engine::Get(engine)->original_image_index;
501 if (rear_head) spritenum++;
503 result->Set(GetDefaultTrainSprite(spritenum, DIR_W));
506 void DrawTrainEngine(int left, int right, int preferred_x, int y, EngineID engine, PaletteID pal, EngineImageType image_type)
508 if (RailVehInfo(engine)->railveh_type == RAILVEH_MULTIHEAD) {
509 int yf = y;
510 int yr = y;
512 VehicleSpriteSeq seqf, seqr;
513 GetRailIcon(engine, false, yf, image_type, &seqf);
514 GetRailIcon(engine, true, yr, image_type, &seqr);
516 Rect rectf, rectr;
517 seqf.GetBounds(&rectf);
518 seqr.GetBounds(&rectr);
520 preferred_x = Clamp(preferred_x,
521 left - UnScaleGUI(rectf.left) + ScaleGUITrad(14),
522 right - UnScaleGUI(rectr.right) - ScaleGUITrad(15));
524 seqf.Draw(preferred_x - ScaleGUITrad(14), yf, pal, pal == PALETTE_CRASH);
525 seqr.Draw(preferred_x + ScaleGUITrad(15), yr, pal, pal == PALETTE_CRASH);
526 } else {
527 VehicleSpriteSeq seq;
528 GetRailIcon(engine, false, y, image_type, &seq);
530 Rect rect;
531 seq.GetBounds(&rect);
532 preferred_x = Clamp(preferred_x,
533 left - UnScaleGUI(rect.left),
534 right - UnScaleGUI(rect.right));
536 seq.Draw(preferred_x, y, pal, pal == PALETTE_CRASH);
541 * Get the size of the sprite of a train sprite heading west, or both heads (used for lists).
542 * @param engine The engine to get the sprite from.
543 * @param[out] width The width of the sprite.
544 * @param[out] height The height of the sprite.
545 * @param[out] xoffs Number of pixels to shift the sprite to the right.
546 * @param[out] yoffs Number of pixels to shift the sprite downwards.
547 * @param image_type Context the sprite is used in.
549 void GetTrainSpriteSize(EngineID engine, uint &width, uint &height, int &xoffs, int &yoffs, EngineImageType image_type)
551 int y = 0;
553 VehicleSpriteSeq seq;
554 GetRailIcon(engine, false, y, image_type, &seq);
556 Rect rect;
557 seq.GetBounds(&rect);
559 width = UnScaleGUI(rect.right - rect.left + 1);
560 height = UnScaleGUI(rect.bottom - rect.top + 1);
561 xoffs = UnScaleGUI(rect.left);
562 yoffs = UnScaleGUI(rect.top);
564 if (RailVehInfo(engine)->railveh_type == RAILVEH_MULTIHEAD) {
565 GetRailIcon(engine, true, y, image_type, &seq);
566 seq.GetBounds(&rect);
568 /* Calculate values relative to an imaginary center between the two sprites. */
569 width = ScaleGUITrad(TRAININFO_DEFAULT_VEHICLE_WIDTH) + UnScaleGUI(rect.right) - xoffs;
570 height = std::max<uint>(height, UnScaleGUI(rect.bottom - rect.top + 1));
571 xoffs = xoffs - ScaleGUITrad(TRAININFO_DEFAULT_VEHICLE_WIDTH) / 2;
572 yoffs = std::min(yoffs, UnScaleGUI(rect.top));
577 * Build a railroad wagon.
578 * @param tile tile of the depot where rail-vehicle is built.
579 * @param flags type of operation.
580 * @param e the engine to build.
581 * @param[out] ret the vehicle that has been built.
582 * @return the cost of this operation or an error.
584 static CommandCost CmdBuildRailWagon(TileIndex tile, DoCommandFlag flags, const Engine *e, Vehicle **ret)
586 const RailVehicleInfo *rvi = &e->u.rail;
588 /* Check that the wagon can drive on the track in question */
589 if (!IsCompatibleRail(rvi->railtype, GetRailType(tile))) return CMD_ERROR;
591 if (flags & DC_EXEC) {
592 Train *v = new Train();
593 *ret = v;
594 v->spritenum = rvi->image_index;
596 v->engine_type = e->index;
597 v->gcache.first_engine = INVALID_ENGINE; // needs to be set before first callback
599 DiagDirection dir = GetRailDepotDirection(tile);
601 v->direction = DiagDirToDir(dir);
602 v->tile = tile;
604 int x = TileX(tile) * TILE_SIZE | _vehicle_initial_x_fract[dir];
605 int y = TileY(tile) * TILE_SIZE | _vehicle_initial_y_fract[dir];
607 v->x_pos = x;
608 v->y_pos = y;
609 v->z_pos = GetSlopePixelZ(x, y);
610 v->owner = _current_company;
611 v->track = TRACK_BIT_DEPOT;
612 v->vehstatus = VS_HIDDEN | VS_DEFPAL;
614 v->SetWagon();
616 v->SetFreeWagon();
617 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
619 v->cargo_type = e->GetDefaultCargoType();
620 v->cargo_cap = rvi->capacity;
621 v->refit_cap = 0;
623 v->railtype = rvi->railtype;
625 v->date_of_last_service = _date;
626 v->build_year = _cur_year;
627 v->sprite_cache.sprite_seq.Set(SPR_IMG_QUERY);
628 v->random_bits = VehicleRandomBits();
630 v->group_id = DEFAULT_GROUP;
632 AddArticulatedParts(v);
634 _new_vehicle_id = v->index;
636 v->UpdatePosition();
637 v->First()->ConsistChanged(CCF_ARRANGE);
638 UpdateTrainGroupID(v->First());
640 CheckConsistencyOfArticulatedVehicle(v);
642 /* Try to connect the vehicle to one of free chains of wagons. */
643 for (Train *w : Train::Iterate()) {
644 if (w->tile == tile && ///< Same depot
645 w->IsFreeWagon() && ///< A free wagon chain
646 w->engine_type == e->index && ///< Same type
647 w->First() != v && ///< Don't connect to ourself
648 !(w->vehstatus & VS_CRASHED)) { ///< Not crashed/flooded
649 if (DoCommand(0, v->index | 1 << 20, w->Last()->index, DC_EXEC, CMD_MOVE_RAIL_VEHICLE).Succeeded()) {
650 break;
656 return CommandCost();
659 /** Move all free vehicles in the depot to the train */
660 static void NormalizeTrainVehInDepot(const Train *u)
662 for (const Train *v : Train::Iterate()) {
663 if (v->IsFreeWagon() && v->tile == u->tile &&
664 v->track == TRACK_BIT_DEPOT) {
665 if (DoCommand(0, v->index | 1 << 20, u->index, DC_EXEC,
666 CMD_MOVE_RAIL_VEHICLE).Failed())
667 break;
672 static void AddRearEngineToMultiheadedTrain(Train *v)
674 Train *u = new Train();
675 v->value >>= 1;
676 u->value = v->value;
677 u->direction = v->direction;
678 u->owner = v->owner;
679 u->tile = v->tile;
680 u->x_pos = v->x_pos;
681 u->y_pos = v->y_pos;
682 u->z_pos = v->z_pos;
683 u->track = TRACK_BIT_DEPOT;
684 u->vehstatus = v->vehstatus & ~VS_STOPPED;
685 u->spritenum = v->spritenum + 1;
686 u->cargo_type = v->cargo_type;
687 u->cargo_subtype = v->cargo_subtype;
688 u->cargo_cap = v->cargo_cap;
689 u->refit_cap = v->refit_cap;
690 u->railtype = v->railtype;
691 u->engine_type = v->engine_type;
692 u->date_of_last_service = v->date_of_last_service;
693 u->build_year = v->build_year;
694 u->sprite_cache.sprite_seq.Set(SPR_IMG_QUERY);
695 u->random_bits = VehicleRandomBits();
696 v->SetMultiheaded();
697 u->SetMultiheaded();
698 v->SetNext(u);
699 u->UpdatePosition();
701 /* Now we need to link the front and rear engines together */
702 v->other_multiheaded_part = u;
703 u->other_multiheaded_part = v;
707 * Build a railroad vehicle.
708 * @param tile tile of the depot where rail-vehicle is built.
709 * @param flags type of operation.
710 * @param e the engine to build.
711 * @param data bit 0 prevents any free cars from being added to the train.
712 * @param[out] ret the vehicle that has been built.
713 * @return the cost of this operation or an error.
715 CommandCost CmdBuildRailVehicle(TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **ret)
717 const RailVehicleInfo *rvi = &e->u.rail;
719 if (rvi->railveh_type == RAILVEH_WAGON) return CmdBuildRailWagon(tile, flags, e, ret);
721 /* Check if depot and new engine uses the same kind of tracks *
722 * We need to see if the engine got power on the tile to avoid electric engines in non-electric depots */
723 if (!HasPowerOnRail(rvi->railtype, GetRailType(tile))) return CMD_ERROR;
725 if (flags & DC_EXEC) {
726 DiagDirection dir = GetRailDepotDirection(tile);
727 int x = TileX(tile) * TILE_SIZE + _vehicle_initial_x_fract[dir];
728 int y = TileY(tile) * TILE_SIZE + _vehicle_initial_y_fract[dir];
730 Train *v = new Train();
731 *ret = v;
732 v->direction = DiagDirToDir(dir);
733 v->tile = tile;
734 v->owner = _current_company;
735 v->x_pos = x;
736 v->y_pos = y;
737 v->z_pos = GetSlopePixelZ(x, y);
738 v->track = TRACK_BIT_DEPOT;
739 v->vehstatus = VS_HIDDEN | VS_STOPPED | VS_DEFPAL;
740 v->spritenum = rvi->image_index;
741 v->cargo_type = e->GetDefaultCargoType();
742 v->cargo_cap = rvi->capacity;
743 v->refit_cap = 0;
744 v->last_station_visited = INVALID_STATION;
745 v->last_loading_station = INVALID_STATION;
747 v->engine_type = e->index;
748 v->gcache.first_engine = INVALID_ENGINE; // needs to be set before first callback
750 v->reliability = e->reliability;
751 v->reliability_spd_dec = e->reliability_spd_dec;
752 v->max_age = e->GetLifeLengthInDays();
754 v->railtype = rvi->railtype;
755 _new_vehicle_id = v->index;
757 v->SetServiceInterval(Company::Get(_current_company)->settings.vehicle.servint_trains);
758 v->date_of_last_service = _date;
759 v->build_year = _cur_year;
760 v->sprite_cache.sprite_seq.Set(SPR_IMG_QUERY);
761 v->random_bits = VehicleRandomBits();
763 if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) SetBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE);
764 v->SetServiceIntervalIsPercent(Company::Get(_current_company)->settings.vehicle.servint_ispercent);
766 v->group_id = DEFAULT_GROUP;
768 v->SetFrontEngine();
769 v->SetEngine();
771 v->UpdatePosition();
773 if (rvi->railveh_type == RAILVEH_MULTIHEAD) {
774 AddRearEngineToMultiheadedTrain(v);
775 } else {
776 AddArticulatedParts(v);
779 v->ConsistChanged(CCF_ARRANGE);
780 UpdateTrainGroupID(v);
782 if (!HasBit(data, 0) && !(flags & DC_AUTOREPLACE)) { // check if the cars should be added to the new vehicle
783 NormalizeTrainVehInDepot(v);
786 CheckConsistencyOfArticulatedVehicle(v);
789 return CommandCost();
792 static Train *FindGoodVehiclePos(const Train *src)
794 EngineID eng = src->engine_type;
795 TileIndex tile = src->tile;
797 for (Train *dst : Train::Iterate()) {
798 if (dst->IsFreeWagon() && dst->tile == tile && !(dst->vehstatus & VS_CRASHED)) {
799 /* check so all vehicles in the line have the same engine. */
800 Train *t = dst;
801 while (t->engine_type == eng) {
802 t = t->Next();
803 if (t == nullptr) return dst;
808 return nullptr;
811 /** Helper type for lists/vectors of trains */
812 typedef std::vector<Train *> TrainList;
815 * Make a backup of a train into a train list.
816 * @param list to make the backup in
817 * @param t the train to make the backup of
819 static void MakeTrainBackup(TrainList &list, Train *t)
821 for (; t != nullptr; t = t->Next()) list.push_back(t);
825 * Restore the train from the backup list.
826 * @param list the train to restore.
828 static void RestoreTrainBackup(TrainList &list)
830 /* No train, nothing to do. */
831 if (list.size() == 0) return;
833 Train *prev = nullptr;
834 /* Iterate over the list and rebuild it. */
835 for (Train *t : list) {
836 if (prev != nullptr) {
837 prev->SetNext(t);
838 } else if (t->Previous() != nullptr) {
839 /* Make sure the head of the train is always the first in the chain. */
840 t->Previous()->SetNext(nullptr);
842 prev = t;
847 * Remove the given wagon from its consist.
848 * @param part the part of the train to remove.
849 * @param chain whether to remove the whole chain.
851 static void RemoveFromConsist(Train *part, bool chain = false)
853 Train *tail = chain ? part->Last() : part->GetLastEnginePart();
855 /* Unlink at the front, but make it point to the next
856 * vehicle after the to be remove part. */
857 if (part->Previous() != nullptr) part->Previous()->SetNext(tail->Next());
859 /* Unlink at the back */
860 tail->SetNext(nullptr);
864 * Inserts a chain into the train at dst.
865 * @param dst the place where to append after.
866 * @param chain the chain to actually add.
868 static void InsertInConsist(Train *dst, Train *chain)
870 /* We do not want to add something in the middle of an articulated part. */
871 assert(dst != nullptr && (dst->Next() == nullptr || !dst->Next()->IsArticulatedPart()));
873 chain->Last()->SetNext(dst->Next());
874 dst->SetNext(chain);
878 * Normalise the dual heads in the train, i.e. if one is
879 * missing move that one to this train.
880 * @param t the train to normalise.
882 static void NormaliseDualHeads(Train *t)
884 for (; t != nullptr; t = t->GetNextVehicle()) {
885 if (!t->IsMultiheaded() || !t->IsEngine()) continue;
887 /* Make sure that there are no free cars before next engine */
888 Train *u;
889 for (u = t; u->Next() != nullptr && !u->Next()->IsEngine(); u = u->Next()) {}
891 if (u == t->other_multiheaded_part) continue;
893 /* Remove the part from the 'wrong' train */
894 RemoveFromConsist(t->other_multiheaded_part);
895 /* And add it to the 'right' train */
896 InsertInConsist(u, t->other_multiheaded_part);
901 * Normalise the sub types of the parts in this chain.
902 * @param chain the chain to normalise.
904 static void NormaliseSubtypes(Train *chain)
906 /* Nothing to do */
907 if (chain == nullptr) return;
909 /* We must be the first in the chain. */
910 assert(chain->Previous() == nullptr);
912 /* Set the appropriate bits for the first in the chain. */
913 if (chain->IsWagon()) {
914 chain->SetFreeWagon();
915 } else {
916 assert(chain->IsEngine());
917 chain->SetFrontEngine();
920 /* Now clear the bits for the rest of the chain */
921 for (Train *t = chain->Next(); t != nullptr; t = t->Next()) {
922 t->ClearFreeWagon();
923 t->ClearFrontEngine();
928 * Check/validate whether we may actually build a new train.
929 * @note All vehicles are/were 'heads' of their chains.
930 * @param original_dst The original destination chain.
931 * @param dst The destination chain after constructing the train.
932 * @param original_src The original source chain.
933 * @param src The source chain after constructing the train.
934 * @return possible error of this command.
936 static CommandCost CheckNewTrain(Train *original_dst, Train *dst, Train *original_src, Train *src)
938 /* Just add 'new' engines and subtract the original ones.
939 * If that's less than or equal to 0 we can be sure we did
940 * not add any engines (read: trains) along the way. */
941 if ((src != nullptr && src->IsEngine() ? 1 : 0) +
942 (dst != nullptr && dst->IsEngine() ? 1 : 0) -
943 (original_src != nullptr && original_src->IsEngine() ? 1 : 0) -
944 (original_dst != nullptr && original_dst->IsEngine() ? 1 : 0) <= 0) {
945 return CommandCost();
948 /* Get a free unit number and check whether it's within the bounds.
949 * There will always be a maximum of one new train. */
950 if (GetFreeUnitNumber(VEH_TRAIN) <= _settings_game.vehicle.max_trains) return CommandCost();
952 return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
956 * Check whether the train parts can be attached.
957 * @param t the train to check
958 * @return possible error of this command.
960 static CommandCost CheckTrainAttachment(Train *t)
962 /* No multi-part train, no need to check. */
963 if (t == nullptr || t->Next() == nullptr) return CommandCost();
965 /* The maximum length for a train. For each part we decrease this by one
966 * and if the result is negative the train is simply too long. */
967 int allowed_len = _settings_game.vehicle.max_train_length * TILE_SIZE - t->gcache.cached_veh_length;
969 /* For free-wagon chains, check if they are within the max_train_length limit. */
970 if (!t->IsEngine()) {
971 t = t->Next();
972 while (t != nullptr) {
973 allowed_len -= t->gcache.cached_veh_length;
975 t = t->Next();
978 if (allowed_len < 0) return_cmd_error(STR_ERROR_TRAIN_TOO_LONG);
979 return CommandCost();
982 Train *head = t;
983 Train *prev = t;
985 /* Break the prev -> t link so it always holds within the loop. */
986 t = t->Next();
987 prev->SetNext(nullptr);
989 /* Make sure the cache is cleared. */
990 head->InvalidateNewGRFCache();
992 while (t != nullptr) {
993 allowed_len -= t->gcache.cached_veh_length;
995 Train *next = t->Next();
997 /* Unlink the to-be-added piece; it is already unlinked from the previous
998 * part due to the fact that the prev -> t link is broken. */
999 t->SetNext(nullptr);
1001 /* Don't check callback for articulated or rear dual headed parts */
1002 if (!t->IsArticulatedPart() && !t->IsRearDualheaded()) {
1003 /* Back up and clear the first_engine data to avoid using wagon override group */
1004 EngineID first_engine = t->gcache.first_engine;
1005 t->gcache.first_engine = INVALID_ENGINE;
1007 /* We don't want the cache to interfere. head's cache is cleared before
1008 * the loop and after each callback does not need to be cleared here. */
1009 t->InvalidateNewGRFCache();
1011 uint16 callback = GetVehicleCallbackParent(CBID_TRAIN_ALLOW_WAGON_ATTACH, 0, 0, head->engine_type, t, head);
1013 /* Restore original first_engine data */
1014 t->gcache.first_engine = first_engine;
1016 /* We do not want to remember any cached variables from the test run */
1017 t->InvalidateNewGRFCache();
1018 head->InvalidateNewGRFCache();
1020 if (callback != CALLBACK_FAILED) {
1021 /* A failing callback means everything is okay */
1022 StringID error = STR_NULL;
1024 if (head->GetGRF()->grf_version < 8) {
1025 if (callback == 0xFD) error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
1026 if (callback < 0xFD) error = GetGRFStringID(head->GetGRFID(), 0xD000 + callback);
1027 if (callback >= 0x100) ErrorUnknownCallbackResult(head->GetGRFID(), CBID_TRAIN_ALLOW_WAGON_ATTACH, callback);
1028 } else {
1029 if (callback < 0x400) {
1030 error = GetGRFStringID(head->GetGRFID(), 0xD000 + callback);
1031 } else {
1032 switch (callback) {
1033 case 0x400: // allow if railtypes match (always the case for OpenTTD)
1034 case 0x401: // allow
1035 break;
1037 default: // unknown reason -> disallow
1038 case 0x402: // disallow attaching
1039 error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
1040 break;
1045 if (error != STR_NULL) return_cmd_error(error);
1049 /* And link it to the new part. */
1050 prev->SetNext(t);
1051 prev = t;
1052 t = next;
1055 if (allowed_len < 0) return_cmd_error(STR_ERROR_TRAIN_TOO_LONG);
1056 return CommandCost();
1060 * Validate whether we are going to create valid trains.
1061 * @note All vehicles are/were 'heads' of their chains.
1062 * @param original_dst The original destination chain.
1063 * @param dst The destination chain after constructing the train.
1064 * @param original_src The original source chain.
1065 * @param src The source chain after constructing the train.
1066 * @param check_limit Whether to check the vehicle limit.
1067 * @return possible error of this command.
1069 static CommandCost ValidateTrains(Train *original_dst, Train *dst, Train *original_src, Train *src, bool check_limit)
1071 /* Check whether we may actually construct the trains. */
1072 CommandCost ret = CheckTrainAttachment(src);
1073 if (ret.Failed()) return ret;
1074 ret = CheckTrainAttachment(dst);
1075 if (ret.Failed()) return ret;
1077 /* Check whether we need to build a new train. */
1078 return check_limit ? CheckNewTrain(original_dst, dst, original_src, src) : CommandCost();
1082 * Arrange the trains in the wanted way.
1083 * @param dst_head The destination chain of the to be moved vehicle.
1084 * @param dst The destination for the to be moved vehicle.
1085 * @param src_head The source chain of the to be moved vehicle.
1086 * @param src The to be moved vehicle.
1087 * @param move_chain Whether to move all vehicles after src or not.
1089 static void ArrangeTrains(Train **dst_head, Train *dst, Train **src_head, Train *src, bool move_chain)
1091 /* First determine the front of the two resulting trains */
1092 if (*src_head == *dst_head) {
1093 /* If we aren't moving part(s) to a new train, we are just moving the
1094 * front back and there is not destination head. */
1095 *dst_head = nullptr;
1096 } else if (*dst_head == nullptr) {
1097 /* If we are moving to a new train the head of the move train would become
1098 * the head of the new vehicle. */
1099 *dst_head = src;
1102 if (src == *src_head) {
1103 /* If we are moving the front of a train then we are, in effect, creating
1104 * a new head for the train. Point to that. Unless we are moving the whole
1105 * train in which case there is not 'source' train anymore.
1106 * In case we are a multiheaded part we want the complete thing to come
1107 * with us, so src->GetNextUnit(), however... when we are e.g. a wagon
1108 * that is followed by a rear multihead we do not want to include that. */
1109 *src_head = move_chain ? nullptr :
1110 (src->IsMultiheaded() ? src->GetNextUnit() : src->GetNextVehicle());
1113 /* Now it's just simply removing the part that we are going to move from the
1114 * source train and *if* the destination is a not a new train add the chain
1115 * at the destination location. */
1116 RemoveFromConsist(src, move_chain);
1117 if (*dst_head != src) InsertInConsist(dst, src);
1119 /* Now normalise the dual heads, that is move the dual heads around in such
1120 * a way that the head and rear of a dual head are in the same train */
1121 NormaliseDualHeads(*src_head);
1122 NormaliseDualHeads(*dst_head);
1126 * Normalise the head of the train again, i.e. that is tell the world that
1127 * we have changed and update all kinds of variables.
1128 * @param head the train to update.
1130 static void NormaliseTrainHead(Train *head)
1132 /* Not much to do! */
1133 if (head == nullptr) return;
1135 /* Tell the 'world' the train changed. */
1136 head->ConsistChanged(CCF_ARRANGE);
1137 UpdateTrainGroupID(head);
1139 /* Not a front engine, i.e. a free wagon chain. No need to do more. */
1140 if (!head->IsFrontEngine()) return;
1142 /* Update the refit button and window */
1143 InvalidateWindowData(WC_VEHICLE_REFIT, head->index, VIWD_CONSIST_CHANGED);
1144 SetWindowWidgetDirty(WC_VEHICLE_VIEW, head->index, WID_VV_REFIT);
1146 /* If we don't have a unit number yet, set one. */
1147 if (head->unitnumber != 0) return;
1148 head->unitnumber = GetFreeUnitNumber(VEH_TRAIN);
1152 * Move a rail vehicle around inside the depot.
1153 * @param tile unused
1154 * @param flags type of operation
1155 * Note: DC_AUTOREPLACE is set when autoreplace tries to undo its modifications or moves vehicles to temporary locations inside the depot.
1156 * @param p1 various bitstuffed elements
1157 * - p1 (bit 0 - 19) source vehicle index
1158 * - p1 (bit 20) move all vehicles following the source vehicle
1159 * @param p2 what wagon to put the source wagon AFTER, XXX - INVALID_VEHICLE to make a new line
1160 * @param text unused
1161 * @return the cost of this operation or an error
1163 CommandCost CmdMoveRailVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text)
1165 VehicleID s = GB(p1, 0, 20);
1166 VehicleID d = GB(p2, 0, 20);
1167 bool move_chain = HasBit(p1, 20);
1169 Train *src = Train::GetIfValid(s);
1170 if (src == nullptr) return CMD_ERROR;
1172 CommandCost ret = CheckOwnership(src->owner);
1173 if (ret.Failed()) return ret;
1175 /* Do not allow moving crashed vehicles inside the depot, it is likely to cause asserts later */
1176 if (src->vehstatus & VS_CRASHED) return CMD_ERROR;
1178 /* if nothing is selected as destination, try and find a matching vehicle to drag to. */
1179 Train *dst;
1180 if (d == INVALID_VEHICLE) {
1181 dst = (src->IsEngine() || (flags & DC_AUTOREPLACE)) ? nullptr : FindGoodVehiclePos(src);
1182 } else {
1183 dst = Train::GetIfValid(d);
1184 if (dst == nullptr) return CMD_ERROR;
1186 CommandCost ret = CheckOwnership(dst->owner);
1187 if (ret.Failed()) return ret;
1189 /* Do not allow appending to crashed vehicles, too */
1190 if (dst->vehstatus & VS_CRASHED) return CMD_ERROR;
1193 /* if an articulated part is being handled, deal with its parent vehicle */
1194 src = src->GetFirstEnginePart();
1195 if (dst != nullptr) {
1196 dst = dst->GetFirstEnginePart();
1199 /* don't move the same vehicle.. */
1200 if (src == dst) return CommandCost();
1202 /* locate the head of the two chains */
1203 Train *src_head = src->First();
1204 Train *dst_head;
1205 if (dst != nullptr) {
1206 dst_head = dst->First();
1207 if (dst_head->tile != src_head->tile) return CMD_ERROR;
1208 /* Now deal with articulated part of destination wagon */
1209 dst = dst->GetLastEnginePart();
1210 } else {
1211 dst_head = nullptr;
1214 if (src->IsRearDualheaded()) return_cmd_error(STR_ERROR_REAR_ENGINE_FOLLOW_FRONT);
1216 /* When moving all wagons, we can't have the same src_head and dst_head */
1217 if (move_chain && src_head == dst_head) return CommandCost();
1219 /* When moving a multiheaded part to be place after itself, bail out. */
1220 if (!move_chain && dst != nullptr && dst->IsRearDualheaded() && src == dst->other_multiheaded_part) return CommandCost();
1222 /* Check if all vehicles in the source train are stopped inside a depot. */
1223 if (!src_head->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
1225 /* Check if all vehicles in the destination train are stopped inside a depot. */
1226 if (dst_head != nullptr && !dst_head->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
1228 /* First make a backup of the order of the trains. That way we can do
1229 * whatever we want with the order and later on easily revert. */
1230 TrainList original_src;
1231 TrainList original_dst;
1233 MakeTrainBackup(original_src, src_head);
1234 MakeTrainBackup(original_dst, dst_head);
1236 /* Also make backup of the original heads as ArrangeTrains can change them.
1237 * For the destination head we do not care if it is the same as the source
1238 * head because in that case it's just a copy. */
1239 Train *original_src_head = src_head;
1240 Train *original_dst_head = (dst_head == src_head ? nullptr : dst_head);
1242 /* We want this information from before the rearrangement, but execute this after the validation.
1243 * original_src_head can't be nullptr; src is by definition != nullptr, so src_head can't be nullptr as
1244 * src->GetFirst() always yields non-nullptr, so eventually original_src_head != nullptr as well. */
1245 bool original_src_head_front_engine = original_src_head->IsFrontEngine();
1246 bool original_dst_head_front_engine = original_dst_head != nullptr && original_dst_head->IsFrontEngine();
1248 /* (Re)arrange the trains in the wanted arrangement. */
1249 ArrangeTrains(&dst_head, dst, &src_head, src, move_chain);
1251 if ((flags & DC_AUTOREPLACE) == 0) {
1252 /* If the autoreplace flag is set we do not need to test for the validity
1253 * because we are going to revert the train to its original state. As we
1254 * assume the original state was correct autoreplace can skip this. */
1255 CommandCost ret = ValidateTrains(original_dst_head, dst_head, original_src_head, src_head, true);
1256 if (ret.Failed()) {
1257 /* Restore the train we had. */
1258 RestoreTrainBackup(original_src);
1259 RestoreTrainBackup(original_dst);
1260 return ret;
1264 /* do it? */
1265 if (flags & DC_EXEC) {
1266 /* Remove old heads from the statistics */
1267 if (original_src_head_front_engine) GroupStatistics::CountVehicle(original_src_head, -1);
1268 if (original_dst_head_front_engine) GroupStatistics::CountVehicle(original_dst_head, -1);
1270 /* First normalise the sub types of the chains. */
1271 NormaliseSubtypes(src_head);
1272 NormaliseSubtypes(dst_head);
1274 /* There are 14 different cases:
1275 * 1) front engine gets moved to a new train, it stays a front engine.
1276 * a) the 'next' part is a wagon that becomes a free wagon chain.
1277 * b) the 'next' part is an engine that becomes a front engine.
1278 * c) there is no 'next' part, nothing else happens
1279 * 2) front engine gets moved to another train, it is not a front engine anymore
1280 * a) the 'next' part is a wagon that becomes a free wagon chain.
1281 * b) the 'next' part is an engine that becomes a front engine.
1282 * c) there is no 'next' part, nothing else happens
1283 * 3) front engine gets moved to later in the current train, it is not a front engine anymore.
1284 * a) the 'next' part is a wagon that becomes a free wagon chain.
1285 * b) the 'next' part is an engine that becomes a front engine.
1286 * 4) free wagon gets moved
1287 * a) the 'next' part is a wagon that becomes a free wagon chain.
1288 * b) the 'next' part is an engine that becomes a front engine.
1289 * c) there is no 'next' part, nothing else happens
1290 * 5) non front engine gets moved and becomes a new train, nothing else happens
1291 * 6) non front engine gets moved within a train / to another train, nothing happens
1292 * 7) wagon gets moved, nothing happens
1294 if (src == original_src_head && src->IsEngine() && !src->IsFrontEngine()) {
1295 /* Cases #2 and #3: the front engine gets trashed. */
1296 CloseWindowById(WC_VEHICLE_VIEW, src->index);
1297 CloseWindowById(WC_VEHICLE_ORDERS, src->index);
1298 CloseWindowById(WC_VEHICLE_REFIT, src->index);
1299 CloseWindowById(WC_VEHICLE_DETAILS, src->index);
1300 CloseWindowById(WC_VEHICLE_TIMETABLE, src->index);
1301 DeleteNewGRFInspectWindow(GSF_TRAINS, src->index);
1302 SetWindowDirty(WC_COMPANY, _current_company);
1304 /* Delete orders, group stuff and the unit number as we're not the
1305 * front of any vehicle anymore. */
1306 DeleteVehicleOrders(src);
1307 RemoveVehicleFromGroup(src);
1308 src->unitnumber = 0;
1311 /* We weren't a front engine but are becoming one. So
1312 * we should be put in the default group. */
1313 if (original_src_head != src && dst_head == src) {
1314 SetTrainGroupID(src, DEFAULT_GROUP);
1315 SetWindowDirty(WC_COMPANY, _current_company);
1318 /* Add new heads to statistics */
1319 if (src_head != nullptr && src_head->IsFrontEngine()) GroupStatistics::CountVehicle(src_head, 1);
1320 if (dst_head != nullptr && dst_head->IsFrontEngine()) GroupStatistics::CountVehicle(dst_head, 1);
1322 /* Handle 'new engine' part of cases #1b, #2b, #3b, #4b and #5 in NormaliseTrainHead. */
1323 NormaliseTrainHead(src_head);
1324 NormaliseTrainHead(dst_head);
1326 if ((flags & DC_NO_CARGO_CAP_CHECK) == 0) {
1327 CheckCargoCapacity(src_head);
1328 CheckCargoCapacity(dst_head);
1331 if (src_head != nullptr) src_head->First()->MarkDirty();
1332 if (dst_head != nullptr) dst_head->First()->MarkDirty();
1334 /* We are undoubtedly changing something in the depot and train list. */
1335 InvalidateWindowData(WC_VEHICLE_DEPOT, src->tile);
1336 InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
1337 } else {
1338 /* We don't want to execute what we're just tried. */
1339 RestoreTrainBackup(original_src);
1340 RestoreTrainBackup(original_dst);
1343 return CommandCost();
1347 * Sell a (single) train wagon/engine.
1348 * @param flags type of operation
1349 * @param t the train wagon to sell
1350 * @param data the selling mode
1351 * - data = 0: only sell the single dragged wagon/engine (and any belonging rear-engines)
1352 * - data = 1: sell the vehicle and all vehicles following it in the chain
1353 * if the wagon is dragged, don't delete the possibly belonging rear-engine to some front
1354 * @param user the user for the order backup.
1355 * @return the cost of this operation or an error
1357 CommandCost CmdSellRailWagon(DoCommandFlag flags, Vehicle *t, uint16 data, uint32 user)
1359 /* Sell a chain of vehicles or not? */
1360 bool sell_chain = HasBit(data, 0);
1362 Train *v = Train::From(t)->GetFirstEnginePart();
1363 Train *first = v->First();
1365 if (v->IsRearDualheaded()) return_cmd_error(STR_ERROR_REAR_ENGINE_FOLLOW_FRONT);
1367 /* First make a backup of the order of the train. That way we can do
1368 * whatever we want with the order and later on easily revert. */
1369 TrainList original;
1370 MakeTrainBackup(original, first);
1372 /* We need to keep track of the new head and the head of what we're going to sell. */
1373 Train *new_head = first;
1374 Train *sell_head = nullptr;
1376 /* Split the train in the wanted way. */
1377 ArrangeTrains(&sell_head, nullptr, &new_head, v, sell_chain);
1379 /* We don't need to validate the second train; it's going to be sold. */
1380 CommandCost ret = ValidateTrains(nullptr, nullptr, first, new_head, (flags & DC_AUTOREPLACE) == 0);
1381 if (ret.Failed()) {
1382 /* Restore the train we had. */
1383 RestoreTrainBackup(original);
1384 return ret;
1387 if (first->orders.list == nullptr && !OrderList::CanAllocateItem()) {
1388 /* Restore the train we had. */
1389 RestoreTrainBackup(original);
1390 return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
1393 CommandCost cost(EXPENSES_NEW_VEHICLES);
1394 for (Train *part = sell_head; part != nullptr; part = part->Next()) cost.AddCost(-part->value);
1396 /* do it? */
1397 if (flags & DC_EXEC) {
1398 /* First normalise the sub types of the chain. */
1399 NormaliseSubtypes(new_head);
1401 if (v == first && v->IsEngine() && !sell_chain && new_head != nullptr && new_head->IsFrontEngine()) {
1402 /* We are selling the front engine. In this case we want to
1403 * 'give' the order, unit number and such to the new head. */
1404 new_head->orders.list = first->orders.list;
1405 new_head->AddToShared(first);
1406 DeleteVehicleOrders(first);
1408 /* Copy other important data from the front engine */
1409 new_head->CopyVehicleConfigAndStatistics(first);
1410 GroupStatistics::CountVehicle(new_head, 1); // after copying over the profit
1411 } else if (v->IsPrimaryVehicle() && data & (MAKE_ORDER_BACKUP_FLAG >> 20)) {
1412 OrderBackup::Backup(v, user);
1415 /* We need to update the information about the train. */
1416 NormaliseTrainHead(new_head);
1418 /* We are undoubtedly changing something in the depot and train list. */
1419 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
1420 InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
1422 /* Actually delete the sold 'goods' */
1423 delete sell_head;
1424 } else {
1425 /* We don't want to execute what we're just tried. */
1426 RestoreTrainBackup(original);
1429 return cost;
1432 void Train::UpdateDeltaXY()
1434 /* Set common defaults. */
1435 this->x_offs = -1;
1436 this->y_offs = -1;
1437 this->x_extent = 3;
1438 this->y_extent = 3;
1439 this->z_extent = 6;
1440 this->x_bb_offs = 0;
1441 this->y_bb_offs = 0;
1443 if (!IsDiagonalDirection(this->direction)) {
1444 static const int _sign_table[] =
1446 /* x, y */
1447 -1, -1, // DIR_N
1448 -1, 1, // DIR_E
1449 1, 1, // DIR_S
1450 1, -1, // DIR_W
1453 int half_shorten = (VEHICLE_LENGTH - this->gcache.cached_veh_length) / 2;
1455 /* For all straight directions, move the bound box to the centre of the vehicle, but keep the size. */
1456 this->x_offs -= half_shorten * _sign_table[this->direction];
1457 this->y_offs -= half_shorten * _sign_table[this->direction + 1];
1458 this->x_extent += this->x_bb_offs = half_shorten * _sign_table[direction];
1459 this->y_extent += this->y_bb_offs = half_shorten * _sign_table[direction + 1];
1460 } else {
1461 switch (this->direction) {
1462 /* Shorten southern corner of the bounding box according the vehicle length
1463 * and center the bounding box on the vehicle. */
1464 case DIR_NE:
1465 this->x_offs = 1 - (this->gcache.cached_veh_length + 1) / 2;
1466 this->x_extent = this->gcache.cached_veh_length - 1;
1467 this->x_bb_offs = -1;
1468 break;
1470 case DIR_NW:
1471 this->y_offs = 1 - (this->gcache.cached_veh_length + 1) / 2;
1472 this->y_extent = this->gcache.cached_veh_length - 1;
1473 this->y_bb_offs = -1;
1474 break;
1476 /* Move northern corner of the bounding box down according to vehicle length
1477 * and center the bounding box on the vehicle. */
1478 case DIR_SW:
1479 this->x_offs = 1 + (this->gcache.cached_veh_length + 1) / 2 - VEHICLE_LENGTH;
1480 this->x_extent = VEHICLE_LENGTH - 1;
1481 this->x_bb_offs = VEHICLE_LENGTH - this->gcache.cached_veh_length - 1;
1482 break;
1484 case DIR_SE:
1485 this->y_offs = 1 + (this->gcache.cached_veh_length + 1) / 2 - VEHICLE_LENGTH;
1486 this->y_extent = VEHICLE_LENGTH - 1;
1487 this->y_bb_offs = VEHICLE_LENGTH - this->gcache.cached_veh_length - 1;
1488 break;
1490 default:
1491 NOT_REACHED();
1497 * Mark a train as stuck and stop it if it isn't stopped right now.
1498 * @param v %Train to mark as being stuck.
1500 static void MarkTrainAsStuck(Train *v)
1502 if (!HasBit(v->flags, VRF_TRAIN_STUCK)) {
1503 /* It is the first time the problem occurred, set the "train stuck" flag. */
1504 SetBit(v->flags, VRF_TRAIN_STUCK);
1506 v->wait_counter = 0;
1508 /* Stop train */
1509 v->cur_speed = 0;
1510 v->subspeed = 0;
1511 v->SetLastSpeed();
1513 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
1518 * Swap the two up/down flags in two ways:
1519 * - Swap values of \a swap_flag1 and \a swap_flag2, and
1520 * - If going up previously (#GVF_GOINGUP_BIT set), the #GVF_GOINGDOWN_BIT is set, and vice versa.
1521 * @param[in,out] swap_flag1 First train flag.
1522 * @param[in,out] swap_flag2 Second train flag.
1524 static void SwapTrainFlags(uint16 *swap_flag1, uint16 *swap_flag2)
1526 uint16 flag1 = *swap_flag1;
1527 uint16 flag2 = *swap_flag2;
1529 /* Clear the flags */
1530 ClrBit(*swap_flag1, GVF_GOINGUP_BIT);
1531 ClrBit(*swap_flag1, GVF_GOINGDOWN_BIT);
1532 ClrBit(*swap_flag2, GVF_GOINGUP_BIT);
1533 ClrBit(*swap_flag2, GVF_GOINGDOWN_BIT);
1535 /* Reverse the rail-flags (if needed) */
1536 if (HasBit(flag1, GVF_GOINGUP_BIT)) {
1537 SetBit(*swap_flag2, GVF_GOINGDOWN_BIT);
1538 } else if (HasBit(flag1, GVF_GOINGDOWN_BIT)) {
1539 SetBit(*swap_flag2, GVF_GOINGUP_BIT);
1541 if (HasBit(flag2, GVF_GOINGUP_BIT)) {
1542 SetBit(*swap_flag1, GVF_GOINGDOWN_BIT);
1543 } else if (HasBit(flag2, GVF_GOINGDOWN_BIT)) {
1544 SetBit(*swap_flag1, GVF_GOINGUP_BIT);
1549 * Updates some variables after swapping the vehicle.
1550 * @param v swapped vehicle
1552 static void UpdateStatusAfterSwap(Train *v)
1554 /* Reverse the direction. */
1555 if (v->track != TRACK_BIT_DEPOT) v->direction = ReverseDir(v->direction);
1557 /* Call the proper EnterTile function unless we are in a wormhole. */
1558 if (v->track != TRACK_BIT_WORMHOLE) {
1559 VehicleEnterTile(v, v->tile, v->x_pos, v->y_pos);
1560 } else {
1561 /* VehicleEnter_TunnelBridge() sets TRACK_BIT_WORMHOLE when the vehicle
1562 * is on the last bit of the bridge head (frame == TILE_SIZE - 1).
1563 * If we were swapped with such a vehicle, we have set TRACK_BIT_WORMHOLE,
1564 * when we shouldn't have. Check if this is the case. */
1565 TileIndex vt = TileVirtXY(v->x_pos, v->y_pos);
1566 if (IsTileType(vt, MP_TUNNELBRIDGE)) {
1567 VehicleEnterTile(v, vt, v->x_pos, v->y_pos);
1568 if (v->track != TRACK_BIT_WORMHOLE && IsBridgeTile(v->tile)) {
1569 /* We have just left the wormhole, possibly set the
1570 * "goingdown" bit. UpdateInclination() can be used
1571 * because we are at the border of the tile. */
1572 v->UpdatePosition();
1573 v->UpdateInclination(true, true);
1574 return;
1579 v->UpdatePosition();
1580 v->UpdateViewport(true, true);
1584 * Swap vehicles \a l and \a r in consist \a v, and reverse their direction.
1585 * @param v Consist to change.
1586 * @param l %Vehicle index in the consist of the first vehicle.
1587 * @param r %Vehicle index in the consist of the second vehicle.
1589 void ReverseTrainSwapVeh(Train *v, int l, int r)
1591 Train *a, *b;
1593 /* locate vehicles to swap */
1594 for (a = v; l != 0; l--) a = a->Next();
1595 for (b = v; r != 0; r--) b = b->Next();
1597 if (a != b) {
1598 /* swap the hidden bits */
1600 uint16 tmp = (a->vehstatus & ~VS_HIDDEN) | (b->vehstatus & VS_HIDDEN);
1601 b->vehstatus = (b->vehstatus & ~VS_HIDDEN) | (a->vehstatus & VS_HIDDEN);
1602 a->vehstatus = tmp;
1605 Swap(a->track, b->track);
1606 Swap(a->direction, b->direction);
1607 Swap(a->x_pos, b->x_pos);
1608 Swap(a->y_pos, b->y_pos);
1609 Swap(a->tile, b->tile);
1610 Swap(a->z_pos, b->z_pos);
1612 SwapTrainFlags(&a->gv_flags, &b->gv_flags);
1614 UpdateStatusAfterSwap(a);
1615 UpdateStatusAfterSwap(b);
1616 } else {
1617 /* Swap GVF_GOINGUP_BIT/GVF_GOINGDOWN_BIT.
1618 * This is a little bit redundant way, a->gv_flags will
1619 * be (re)set twice, but it reduces code duplication */
1620 SwapTrainFlags(&a->gv_flags, &a->gv_flags);
1621 UpdateStatusAfterSwap(a);
1627 * Check if the vehicle is a train
1628 * @param v vehicle on tile
1629 * @return v if it is a train, nullptr otherwise
1631 static Vehicle *TrainOnTileEnum(Vehicle *v, void *)
1633 return (v->type == VEH_TRAIN) ? v : nullptr;
1638 * Checks if a train is approaching a rail-road crossing
1639 * @param v vehicle on tile
1640 * @param data tile with crossing we are testing
1641 * @return v if it is approaching a crossing, nullptr otherwise
1643 static Vehicle *TrainApproachingCrossingEnum(Vehicle *v, void *data)
1645 if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) return nullptr;
1647 Train *t = Train::From(v);
1648 if (!t->IsFrontEngine()) return nullptr;
1650 TileIndex tile = *(TileIndex *)data;
1652 if (TrainApproachingCrossingTile(t) != tile) return nullptr;
1654 return t;
1659 * Finds a vehicle approaching rail-road crossing
1660 * @param tile tile to test
1661 * @return true if a vehicle is approaching the crossing
1662 * @pre tile is a rail-road crossing
1664 static bool TrainApproachingCrossing(TileIndex tile)
1666 assert(IsLevelCrossingTile(tile));
1668 DiagDirection dir = AxisToDiagDir(GetCrossingRailAxis(tile));
1669 TileIndex tile_from = tile + TileOffsByDiagDir(dir);
1671 if (HasVehicleOnPos(tile_from, &tile, &TrainApproachingCrossingEnum)) return true;
1673 dir = ReverseDiagDir(dir);
1674 tile_from = tile + TileOffsByDiagDir(dir);
1676 return HasVehicleOnPos(tile_from, &tile, &TrainApproachingCrossingEnum);
1681 * Sets correct crossing state
1682 * @param tile tile to update
1683 * @param sound should we play sound?
1684 * @pre tile is a rail-road crossing
1686 void UpdateLevelCrossing(TileIndex tile, bool sound)
1688 assert(IsLevelCrossingTile(tile));
1690 /* reserved || train on crossing || train approaching crossing */
1691 bool new_state = HasCrossingReservation(tile) || HasVehicleOnPos(tile, nullptr, &TrainOnTileEnum) || TrainApproachingCrossing(tile);
1693 if (new_state != IsCrossingBarred(tile)) {
1694 if (new_state && sound) {
1695 if (_settings_client.sound.ambient) SndPlayTileFx(SND_0E_LEVEL_CROSSING, tile);
1697 SetCrossingBarred(tile, new_state);
1698 MarkTileDirtyByTile(tile);
1704 * Bars crossing and plays ding-ding sound if not barred already
1705 * @param tile tile with crossing
1706 * @pre tile is a rail-road crossing
1708 static inline void MaybeBarCrossingWithSound(TileIndex tile)
1710 if (!IsCrossingBarred(tile)) {
1711 BarCrossing(tile);
1712 if (_settings_client.sound.ambient) SndPlayTileFx(SND_0E_LEVEL_CROSSING, tile);
1713 MarkTileDirtyByTile(tile);
1719 * Advances wagons for train reversing, needed for variable length wagons.
1720 * This one is called before the train is reversed.
1721 * @param v First vehicle in chain
1723 static void AdvanceWagonsBeforeSwap(Train *v)
1725 Train *base = v;
1726 Train *first = base; // first vehicle to move
1727 Train *last = v->Last(); // last vehicle to move
1728 uint length = CountVehiclesInChain(v);
1730 while (length > 2) {
1731 last = last->Previous();
1732 first = first->Next();
1734 int differential = base->CalcNextVehicleOffset() - last->CalcNextVehicleOffset();
1736 /* do not update images now
1737 * negative differential will be handled in AdvanceWagonsAfterSwap() */
1738 for (int i = 0; i < differential; i++) TrainController(first, last->Next());
1740 base = first; // == base->Next()
1741 length -= 2;
1747 * Advances wagons for train reversing, needed for variable length wagons.
1748 * This one is called after the train is reversed.
1749 * @param v First vehicle in chain
1751 static void AdvanceWagonsAfterSwap(Train *v)
1753 /* first of all, fix the situation when the train was entering a depot */
1754 Train *dep = v; // last vehicle in front of just left depot
1755 while (dep->Next() != nullptr && (dep->track == TRACK_BIT_DEPOT || dep->Next()->track != TRACK_BIT_DEPOT)) {
1756 dep = dep->Next(); // find first vehicle outside of a depot, with next vehicle inside a depot
1759 Train *leave = dep->Next(); // first vehicle in a depot we are leaving now
1761 if (leave != nullptr) {
1762 /* 'pull' next wagon out of the depot, so we won't miss it (it could stay in depot forever) */
1763 int d = TicksToLeaveDepot(dep);
1765 if (d <= 0) {
1766 leave->vehstatus &= ~VS_HIDDEN; // move it out of the depot
1767 leave->track = TrackToTrackBits(GetRailDepotTrack(leave->tile));
1768 for (int i = 0; i >= d; i--) TrainController(leave, nullptr); // maybe move it, and maybe let another wagon leave
1770 } else {
1771 dep = nullptr; // no vehicle in a depot, so no vehicle leaving a depot
1774 Train *base = v;
1775 Train *first = base; // first vehicle to move
1776 Train *last = v->Last(); // last vehicle to move
1777 uint length = CountVehiclesInChain(v);
1779 /* We have to make sure all wagons that leave a depot because of train reversing are moved correctly
1780 * they have already correct spacing, so we have to make sure they are moved how they should */
1781 bool nomove = (dep == nullptr); // If there is no vehicle leaving a depot, limit the number of wagons moved immediately.
1783 while (length > 2) {
1784 /* we reached vehicle (originally) in front of a depot, stop now
1785 * (we would move wagons that are already moved with new wagon length). */
1786 if (base == dep) break;
1788 /* the last wagon was that one leaving a depot, so do not move it anymore */
1789 if (last == dep) nomove = true;
1791 last = last->Previous();
1792 first = first->Next();
1794 int differential = last->CalcNextVehicleOffset() - base->CalcNextVehicleOffset();
1796 /* do not update images now */
1797 for (int i = 0; i < differential; i++) TrainController(first, (nomove ? last->Next() : nullptr));
1799 base = first; // == base->Next()
1800 length -= 2;
1805 * Turn a train around.
1806 * @param v %Train to turn around.
1808 void ReverseTrainDirection(Train *v)
1810 if (IsRailDepotTile(v->tile)) {
1811 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
1814 /* Clear path reservation in front if train is not stuck. */
1815 if (!HasBit(v->flags, VRF_TRAIN_STUCK)) FreeTrainTrackReservation(v);
1817 /* Check if we were approaching a rail/road-crossing */
1818 TileIndex crossing = TrainApproachingCrossingTile(v);
1820 /* count number of vehicles */
1821 int r = CountVehiclesInChain(v) - 1; // number of vehicles - 1
1823 AdvanceWagonsBeforeSwap(v);
1825 /* swap start<>end, start+1<>end-1, ... */
1826 int l = 0;
1827 do {
1828 ReverseTrainSwapVeh(v, l++, r--);
1829 } while (l <= r);
1831 AdvanceWagonsAfterSwap(v);
1833 if (IsRailDepotTile(v->tile)) {
1834 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
1837 ToggleBit(v->flags, VRF_TOGGLE_REVERSE);
1839 ClrBit(v->flags, VRF_REVERSING);
1841 /* recalculate cached data */
1842 v->ConsistChanged(CCF_TRACK);
1844 /* update all images */
1845 for (Train *u = v; u != nullptr; u = u->Next()) u->UpdateViewport(false, false);
1847 /* update crossing we were approaching */
1848 if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
1850 /* maybe we are approaching crossing now, after reversal */
1851 crossing = TrainApproachingCrossingTile(v);
1852 if (crossing != INVALID_TILE) MaybeBarCrossingWithSound(crossing);
1854 /* If we are inside a depot after reversing, don't bother with path reserving. */
1855 if (v->track == TRACK_BIT_DEPOT) {
1856 /* Can't be stuck here as inside a depot is always a safe tile. */
1857 if (HasBit(v->flags, VRF_TRAIN_STUCK)) SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
1858 ClrBit(v->flags, VRF_TRAIN_STUCK);
1859 return;
1862 /* VehicleExitDir does not always produce the desired dir for depots and
1863 * tunnels/bridges that is needed for UpdateSignalsOnSegment. */
1864 DiagDirection dir = VehicleExitDir(v->direction, v->track);
1865 if (IsRailDepotTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE)) dir = INVALID_DIAGDIR;
1867 if (UpdateSignalsOnSegment(v->tile, dir, v->owner) == SIGSEG_PBS || _settings_game.pf.reserve_paths) {
1868 /* If we are currently on a tile with conventional signals, we can't treat the
1869 * current tile as a safe tile or we would enter a PBS block without a reservation. */
1870 bool first_tile_okay = !(IsTileType(v->tile, MP_RAILWAY) &&
1871 HasSignalOnTrackdir(v->tile, v->GetVehicleTrackdir()) &&
1872 !IsPbsSignal(GetSignalType(v->tile, FindFirstTrack(v->track))));
1874 /* If we are on a depot tile facing outwards, do not treat the current tile as safe. */
1875 if (IsRailDepotTile(v->tile) && TrackdirToExitdir(v->GetVehicleTrackdir()) == GetRailDepotDirection(v->tile)) first_tile_okay = false;
1877 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
1878 if (TryPathReserve(v, false, first_tile_okay)) {
1879 /* Do a look-ahead now in case our current tile was already a safe tile. */
1880 CheckNextTrainTile(v);
1881 } else if (v->current_order.GetType() != OT_LOADING) {
1882 /* Do not wait for a way out when we're still loading */
1883 MarkTrainAsStuck(v);
1885 } else if (HasBit(v->flags, VRF_TRAIN_STUCK)) {
1886 /* A train not inside a PBS block can't be stuck. */
1887 ClrBit(v->flags, VRF_TRAIN_STUCK);
1888 v->wait_counter = 0;
1893 * Reverse train.
1894 * @param tile unused
1895 * @param flags type of operation
1896 * @param p1 train to reverse
1897 * @param p2 if true, reverse a unit in a train (needs to be in a depot)
1898 * @param text unused
1899 * @return the cost of this operation or an error
1901 CommandCost CmdReverseTrainDirection(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text)
1903 Train *v = Train::GetIfValid(p1);
1904 if (v == nullptr) return CMD_ERROR;
1906 CommandCost ret = CheckOwnership(v->owner);
1907 if (ret.Failed()) return ret;
1909 if (p2 != 0) {
1910 /* turn a single unit around */
1912 if (v->IsMultiheaded() || HasBit(EngInfo(v->engine_type)->callback_mask, CBM_VEHICLE_ARTIC_ENGINE)) {
1913 return_cmd_error(STR_ERROR_CAN_T_REVERSE_DIRECTION_RAIL_VEHICLE_MULTIPLE_UNITS);
1915 if (!HasBit(EngInfo(v->engine_type)->misc_flags, EF_RAIL_FLIPS)) return CMD_ERROR;
1917 Train *front = v->First();
1918 /* make sure the vehicle is stopped in the depot */
1919 if (!front->IsStoppedInDepot()) {
1920 return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
1923 if (flags & DC_EXEC) {
1924 ToggleBit(v->flags, VRF_REVERSE_DIRECTION);
1926 front->ConsistChanged(CCF_ARRANGE);
1927 SetWindowDirty(WC_VEHICLE_DEPOT, front->tile);
1928 SetWindowDirty(WC_VEHICLE_DETAILS, front->index);
1929 SetWindowDirty(WC_VEHICLE_VIEW, front->index);
1930 SetWindowClassesDirty(WC_TRAINS_LIST);
1932 } else {
1933 /* turn the whole train around */
1934 if ((v->vehstatus & VS_CRASHED) || v->breakdown_ctr != 0) return CMD_ERROR;
1936 if (flags & DC_EXEC) {
1937 /* Properly leave the station if we are loading and won't be loading anymore */
1938 if (v->current_order.IsType(OT_LOADING)) {
1939 const Vehicle *last = v;
1940 while (last->Next() != nullptr) last = last->Next();
1942 /* not a station || different station --> leave the station */
1943 if (!IsTileType(last->tile, MP_STATION) || GetStationIndex(last->tile) != GetStationIndex(v->tile)) {
1944 v->LeaveStation();
1948 /* We cancel any 'skip signal at dangers' here */
1949 v->force_proceed = TFP_NONE;
1950 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
1952 if (_settings_game.vehicle.train_acceleration_model != AM_ORIGINAL && v->cur_speed != 0) {
1953 ToggleBit(v->flags, VRF_REVERSING);
1954 } else {
1955 v->cur_speed = 0;
1956 v->SetLastSpeed();
1957 HideFillingPercent(&v->fill_percent_te_id);
1958 ReverseTrainDirection(v);
1962 return CommandCost();
1966 * Force a train through a red signal
1967 * @param tile unused
1968 * @param flags type of operation
1969 * @param p1 train to ignore the red signal
1970 * @param p2 unused
1971 * @param text unused
1972 * @return the cost of this operation or an error
1974 CommandCost CmdForceTrainProceed(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text)
1976 Train *t = Train::GetIfValid(p1);
1977 if (t == nullptr) return CMD_ERROR;
1979 if (!t->IsPrimaryVehicle()) return CMD_ERROR;
1981 CommandCost ret = CheckOwnership(t->owner);
1982 if (ret.Failed()) return ret;
1985 if (flags & DC_EXEC) {
1986 /* If we are forced to proceed, cancel that order.
1987 * If we are marked stuck we would want to force the train
1988 * to proceed to the next signal. In the other cases we
1989 * would like to pass the signal at danger and run till the
1990 * next signal we encounter. */
1991 t->force_proceed = t->force_proceed == TFP_SIGNAL ? TFP_NONE : HasBit(t->flags, VRF_TRAIN_STUCK) || t->IsChainInDepot() ? TFP_STUCK : TFP_SIGNAL;
1992 SetWindowDirty(WC_VEHICLE_VIEW, t->index);
1995 return CommandCost();
1999 * Try to find a depot nearby.
2000 * @param v %Train that wants a depot.
2001 * @param max_distance Maximal search distance.
2002 * @return Information where the closest train depot is located.
2003 * @pre The given vehicle must not be crashed!
2005 static FindDepotData FindClosestTrainDepot(Train *v, int max_distance)
2007 assert(!(v->vehstatus & VS_CRASHED));
2009 if (IsRailDepotTile(v->tile)) return FindDepotData(v->tile, 0);
2011 PBSTileInfo origin = FollowTrainReservation(v);
2012 if (IsRailDepotTile(origin.tile)) return FindDepotData(origin.tile, 0);
2014 switch (_settings_game.pf.pathfinder_for_trains) {
2015 case VPF_NPF: return NPFTrainFindNearestDepot(v, max_distance);
2016 case VPF_YAPF: return YapfTrainFindNearestDepot(v, max_distance);
2018 default: NOT_REACHED();
2023 * Locate the closest depot for this consist, and return the information to the caller.
2024 * @param[out] location If not \c nullptr and a depot is found, store its location in the given address.
2025 * @param[out] destination If not \c nullptr and a depot is found, store its index in the given address.
2026 * @param[out] reverse If not \c nullptr and a depot is found, store reversal information in the given address.
2027 * @return A depot has been found.
2029 bool Train::FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
2031 FindDepotData tfdd = FindClosestTrainDepot(this, 0);
2032 if (tfdd.best_length == UINT_MAX) return false;
2034 if (location != nullptr) *location = tfdd.tile;
2035 if (destination != nullptr) *destination = GetDepotIndex(tfdd.tile);
2036 if (reverse != nullptr) *reverse = tfdd.reverse;
2038 return true;
2041 /** Play a sound for a train leaving the station. */
2042 void Train::PlayLeaveStationSound() const
2044 static const SoundFx sfx[] = {
2045 SND_04_DEPARTURE_STEAM,
2046 SND_0A_DEPARTURE_TRAIN,
2047 SND_0A_DEPARTURE_TRAIN,
2048 SND_47_DEPARTURE_MONORAIL,
2049 SND_41_DEPARTURE_MAGLEV
2052 if (PlayVehicleSound(this, VSE_START)) return;
2054 EngineID engtype = this->engine_type;
2055 SndPlayVehicleFx(sfx[RailVehInfo(engtype)->engclass], this);
2059 * Check if the train is on the last reserved tile and try to extend the path then.
2060 * @param v %Train that needs its path extended.
2062 static void CheckNextTrainTile(Train *v)
2064 /* Don't do any look-ahead if path_backoff_interval is 255. */
2065 if (_settings_game.pf.path_backoff_interval == 255) return;
2067 /* Exit if we are inside a depot. */
2068 if (v->track == TRACK_BIT_DEPOT) return;
2070 switch (v->current_order.GetType()) {
2071 /* Exit if we reached our destination depot. */
2072 case OT_GOTO_DEPOT:
2073 if (v->tile == v->dest_tile) return;
2074 break;
2076 case OT_GOTO_WAYPOINT:
2077 /* If we reached our waypoint, make sure we see that. */
2078 if (IsRailWaypointTile(v->tile) && GetStationIndex(v->tile) == v->current_order.GetDestination()) ProcessOrders(v);
2079 break;
2081 case OT_NOTHING:
2082 case OT_LEAVESTATION:
2083 case OT_LOADING:
2084 /* Exit if the current order doesn't have a destination, but the train has orders. */
2085 if (v->GetNumOrders() > 0) return;
2086 break;
2088 default:
2089 break;
2091 /* Exit if we are on a station tile and are going to stop. */
2092 if (IsRailStationTile(v->tile) && v->current_order.ShouldStopAtStation(v, GetStationIndex(v->tile))) return;
2094 Trackdir td = v->GetVehicleTrackdir();
2096 /* On a tile with a red non-pbs signal, don't look ahead. */
2097 if (IsTileType(v->tile, MP_RAILWAY) && HasSignalOnTrackdir(v->tile, td) &&
2098 !IsPbsSignal(GetSignalType(v->tile, TrackdirToTrack(td))) &&
2099 GetSignalStateByTrackdir(v->tile, td) == SIGNAL_STATE_RED) return;
2101 CFollowTrackRail ft(v);
2102 if (!ft.Follow(v->tile, td)) return;
2104 if (!HasReservedTracks(ft.m_new_tile, TrackdirBitsToTrackBits(ft.m_new_td_bits))) {
2105 /* Next tile is not reserved. */
2106 if (KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE) {
2107 if (HasPbsSignalOnTrackdir(ft.m_new_tile, FindFirstTrackdir(ft.m_new_td_bits))) {
2108 /* If the next tile is a PBS signal, try to make a reservation. */
2109 TrackBits tracks = TrackdirBitsToTrackBits(ft.m_new_td_bits);
2110 if (Rail90DegTurnDisallowed(GetTileRailType(ft.m_old_tile), GetTileRailType(ft.m_new_tile))) {
2111 tracks &= ~TrackCrossesTracks(TrackdirToTrack(ft.m_old_td));
2113 ChooseTrainTrack(v, ft.m_new_tile, ft.m_exitdir, tracks, false, nullptr, false);
2120 * Will the train stay in the depot the next tick?
2121 * @param v %Train to check.
2122 * @return True if it stays in the depot, false otherwise.
2124 static bool CheckTrainStayInDepot(Train *v)
2126 /* bail out if not all wagons are in the same depot or not in a depot at all */
2127 for (const Train *u = v; u != nullptr; u = u->Next()) {
2128 if (u->track != TRACK_BIT_DEPOT || u->tile != v->tile) return false;
2131 /* if the train got no power, then keep it in the depot */
2132 if (v->gcache.cached_power == 0) {
2133 v->vehstatus |= VS_STOPPED;
2134 SetWindowDirty(WC_VEHICLE_DEPOT, v->tile);
2135 return true;
2138 SigSegState seg_state;
2140 if (v->force_proceed == TFP_NONE) {
2141 /* force proceed was not pressed */
2142 if (++v->wait_counter < 37) {
2143 SetWindowClassesDirty(WC_TRAINS_LIST);
2144 return true;
2147 v->wait_counter = 0;
2149 seg_state = _settings_game.pf.reserve_paths ? SIGSEG_PBS : UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
2150 if (seg_state == SIGSEG_FULL || HasDepotReservation(v->tile)) {
2151 /* Full and no PBS signal in block or depot reserved, can't exit. */
2152 SetWindowClassesDirty(WC_TRAINS_LIST);
2153 return true;
2155 } else {
2156 seg_state = _settings_game.pf.reserve_paths ? SIGSEG_PBS : UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
2159 /* We are leaving a depot, but have to go to the exact same one; re-enter. */
2160 if (v->current_order.IsType(OT_GOTO_DEPOT) && v->tile == v->dest_tile) {
2161 /* Service when depot has no reservation. */
2162 if (!HasDepotReservation(v->tile)) VehicleEnterDepot(v);
2163 return true;
2166 /* Only leave when we can reserve a path to our destination. */
2167 if (seg_state == SIGSEG_PBS && !TryPathReserve(v) && v->force_proceed == TFP_NONE) {
2168 /* No path and no force proceed. */
2169 SetWindowClassesDirty(WC_TRAINS_LIST);
2170 MarkTrainAsStuck(v);
2171 return true;
2174 SetDepotReservation(v->tile, true);
2175 if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(v->tile);
2177 VehicleServiceInDepot(v);
2178 SetWindowClassesDirty(WC_TRAINS_LIST);
2179 v->PlayLeaveStationSound();
2181 v->track = TRACK_BIT_X;
2182 if (v->direction & 2) v->track = TRACK_BIT_Y;
2184 v->vehstatus &= ~VS_HIDDEN;
2185 v->cur_speed = 0;
2187 v->UpdateViewport(true, true);
2188 v->UpdatePosition();
2189 UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
2190 v->UpdateAcceleration();
2191 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
2193 return false;
2197 * Clear the reservation of \a tile that was just left by a wagon on \a track_dir.
2198 * @param v %Train owning the reservation.
2199 * @param tile Tile with reservation to clear.
2200 * @param track_dir Track direction to clear.
2202 static void ClearPathReservation(const Train *v, TileIndex tile, Trackdir track_dir)
2204 DiagDirection dir = TrackdirToExitdir(track_dir);
2206 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
2207 /* Are we just leaving a tunnel/bridge? */
2208 if (GetTunnelBridgeDirection(tile) == ReverseDiagDir(dir)) {
2209 TileIndex end = GetOtherTunnelBridgeEnd(tile);
2211 if (TunnelBridgeIsFree(tile, end, v).Succeeded()) {
2212 /* Free the reservation only if no other train is on the tiles. */
2213 SetTunnelBridgeReservation(tile, false);
2214 SetTunnelBridgeReservation(end, false);
2216 if (_settings_client.gui.show_track_reservation) {
2217 if (IsBridge(tile)) {
2218 MarkBridgeDirty(tile);
2219 } else {
2220 MarkTileDirtyByTile(tile);
2221 MarkTileDirtyByTile(end);
2226 } else if (IsRailStationTile(tile)) {
2227 TileIndex new_tile = TileAddByDiagDir(tile, dir);
2228 /* If the new tile is not a further tile of the same station, we
2229 * clear the reservation for the whole platform. */
2230 if (!IsCompatibleTrainStationTile(new_tile, tile)) {
2231 SetRailStationPlatformReservation(tile, ReverseDiagDir(dir), false);
2233 } else {
2234 /* Any other tile */
2235 UnreserveRailTrack(tile, TrackdirToTrack(track_dir));
2240 * Free the reserved path in front of a vehicle.
2241 * @param v %Train owning the reserved path.
2243 void FreeTrainTrackReservation(const Train *v)
2245 assert(v->IsFrontEngine());
2247 TileIndex tile = v->tile;
2248 Trackdir td = v->GetVehicleTrackdir();
2249 bool free_tile = !(IsRailStationTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE));
2250 StationID station_id = IsRailStationTile(v->tile) ? GetStationIndex(v->tile) : INVALID_STATION;
2252 /* Can't be holding a reservation if we enter a depot. */
2253 if (IsRailDepotTile(tile) && TrackdirToExitdir(td) != GetRailDepotDirection(tile)) return;
2254 if (v->track == TRACK_BIT_DEPOT) {
2255 /* Front engine is in a depot. We enter if some part is not in the depot. */
2256 for (const Train *u = v; u != nullptr; u = u->Next()) {
2257 if (u->track != TRACK_BIT_DEPOT || u->tile != v->tile) return;
2260 /* Don't free reservation if it's not ours. */
2261 if (TracksOverlap(GetReservedTrackbits(tile) | TrackToTrackBits(TrackdirToTrack(td)))) return;
2263 CFollowTrackRail ft(v, GetRailTypeInfo(v->railtype)->compatible_railtypes);
2264 while (ft.Follow(tile, td)) {
2265 tile = ft.m_new_tile;
2266 TrackdirBits bits = ft.m_new_td_bits & TrackBitsToTrackdirBits(GetReservedTrackbits(tile));
2267 td = RemoveFirstTrackdir(&bits);
2268 assert(bits == TRACKDIR_BIT_NONE);
2270 if (!IsValidTrackdir(td)) break;
2272 if (IsTileType(tile, MP_RAILWAY)) {
2273 if (HasSignalOnTrackdir(tile, td) && !IsPbsSignal(GetSignalType(tile, TrackdirToTrack(td)))) {
2274 /* Conventional signal along trackdir: remove reservation and stop. */
2275 UnreserveRailTrack(tile, TrackdirToTrack(td));
2276 break;
2278 if (HasPbsSignalOnTrackdir(tile, td)) {
2279 if (GetSignalStateByTrackdir(tile, td) == SIGNAL_STATE_RED) {
2280 /* Red PBS signal? Can't be our reservation, would be green then. */
2281 break;
2282 } else {
2283 /* Turn the signal back to red. */
2284 SetSignalStateByTrackdir(tile, td, SIGNAL_STATE_RED);
2285 MarkTileDirtyByTile(tile);
2287 } else if (HasSignalOnTrackdir(tile, ReverseTrackdir(td)) && IsOnewaySignal(tile, TrackdirToTrack(td))) {
2288 break;
2292 /* Don't free first station/bridge/tunnel if we are on it. */
2293 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);
2295 free_tile = true;
2299 static const byte _initial_tile_subcoord[6][4][3] = {
2300 {{ 15, 8, 1 }, { 0, 0, 0 }, { 0, 8, 5 }, { 0, 0, 0 }},
2301 {{ 0, 0, 0 }, { 8, 0, 3 }, { 0, 0, 0 }, { 8, 15, 7 }},
2302 {{ 0, 0, 0 }, { 7, 0, 2 }, { 0, 7, 6 }, { 0, 0, 0 }},
2303 {{ 15, 8, 2 }, { 0, 0, 0 }, { 0, 0, 0 }, { 8, 15, 6 }},
2304 {{ 15, 7, 0 }, { 8, 0, 4 }, { 0, 0, 0 }, { 0, 0, 0 }},
2305 {{ 0, 0, 0 }, { 0, 0, 0 }, { 0, 8, 4 }, { 7, 15, 0 }},
2309 * Perform pathfinding for a train.
2311 * @param v The train
2312 * @param tile The tile the train is about to enter
2313 * @param enterdir Diagonal direction the train is coming from
2314 * @param tracks Usable tracks on the new tile
2315 * @param[out] path_found Whether a path has been found or not.
2316 * @param do_track_reservation Path reservation is requested
2317 * @param[out] dest State and destination of the requested path
2318 * @return The best track the train should follow
2320 static Track DoTrainPathfind(const Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool &path_found, bool do_track_reservation, PBSTileInfo *dest)
2322 switch (_settings_game.pf.pathfinder_for_trains) {
2323 case VPF_NPF: return NPFTrainChooseTrack(v, path_found, do_track_reservation, dest);
2324 case VPF_YAPF: return YapfTrainChooseTrack(v, tile, enterdir, tracks, path_found, do_track_reservation, dest);
2326 default: NOT_REACHED();
2331 * Extend a train path as far as possible. Stops on encountering a safe tile,
2332 * another reservation or a track choice.
2333 * @return INVALID_TILE indicates that the reservation failed.
2335 static PBSTileInfo ExtendTrainReservation(const Train *v, TrackBits *new_tracks, DiagDirection *enterdir)
2337 PBSTileInfo origin = FollowTrainReservation(v);
2339 CFollowTrackRail ft(v);
2341 TileIndex tile = origin.tile;
2342 Trackdir cur_td = origin.trackdir;
2343 while (ft.Follow(tile, cur_td)) {
2344 if (KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE) {
2345 /* Possible signal tile. */
2346 if (HasOnewaySignalBlockingTrackdir(ft.m_new_tile, FindFirstTrackdir(ft.m_new_td_bits))) break;
2349 if (Rail90DegTurnDisallowed(GetTileRailType(ft.m_old_tile), GetTileRailType(ft.m_new_tile))) {
2350 ft.m_new_td_bits &= ~TrackdirCrossesTrackdirs(ft.m_old_td);
2351 if (ft.m_new_td_bits == TRACKDIR_BIT_NONE) break;
2354 /* Station, depot or waypoint are a possible target. */
2355 bool target_seen = ft.m_is_station || (IsTileType(ft.m_new_tile, MP_RAILWAY) && !IsPlainRail(ft.m_new_tile));
2356 if (target_seen || KillFirstBit(ft.m_new_td_bits) != TRACKDIR_BIT_NONE) {
2357 /* Choice found or possible target encountered.
2358 * On finding a possible target, we need to stop and let the pathfinder handle the
2359 * remaining path. This is because we don't know if this target is in one of our
2360 * orders, so we might cause pathfinding to fail later on if we find a choice.
2361 * This failure would cause a bogous call to TryReserveSafePath which might reserve
2362 * a wrong path not leading to our next destination. */
2363 if (HasReservedTracks(ft.m_new_tile, TrackdirBitsToTrackBits(TrackdirReachesTrackdirs(ft.m_old_td)))) break;
2365 /* If we did skip some tiles, backtrack to the first skipped tile so the pathfinder
2366 * actually starts its search at the first unreserved tile. */
2367 if (ft.m_tiles_skipped != 0) ft.m_new_tile -= TileOffsByDiagDir(ft.m_exitdir) * ft.m_tiles_skipped;
2369 /* Choice found, path valid but not okay. Save info about the choice tile as well. */
2370 if (new_tracks != nullptr) *new_tracks = TrackdirBitsToTrackBits(ft.m_new_td_bits);
2371 if (enterdir != nullptr) *enterdir = ft.m_exitdir;
2372 return PBSTileInfo(ft.m_new_tile, ft.m_old_td, false);
2375 tile = ft.m_new_tile;
2376 cur_td = FindFirstTrackdir(ft.m_new_td_bits);
2378 if (IsSafeWaitingPosition(v, tile, cur_td, true, _settings_game.pf.forbid_90_deg)) {
2379 bool wp_free = IsWaitingPositionFree(v, tile, cur_td, _settings_game.pf.forbid_90_deg);
2380 if (!(wp_free && TryReserveRailTrack(tile, TrackdirToTrack(cur_td)))) break;
2381 /* Safe position is all good, path valid and okay. */
2382 return PBSTileInfo(tile, cur_td, true);
2385 if (!TryReserveRailTrack(tile, TrackdirToTrack(cur_td))) break;
2388 if (ft.m_err == CFollowTrackRail::EC_OWNER || ft.m_err == CFollowTrackRail::EC_NO_WAY) {
2389 /* End of line, path valid and okay. */
2390 return PBSTileInfo(ft.m_old_tile, ft.m_old_td, true);
2393 /* Sorry, can't reserve path, back out. */
2394 tile = origin.tile;
2395 cur_td = origin.trackdir;
2396 TileIndex stopped = ft.m_old_tile;
2397 Trackdir stopped_td = ft.m_old_td;
2398 while (tile != stopped || cur_td != stopped_td) {
2399 if (!ft.Follow(tile, cur_td)) break;
2401 if (Rail90DegTurnDisallowed(GetTileRailType(ft.m_old_tile), GetTileRailType(ft.m_new_tile))) {
2402 ft.m_new_td_bits &= ~TrackdirCrossesTrackdirs(ft.m_old_td);
2403 assert(ft.m_new_td_bits != TRACKDIR_BIT_NONE);
2405 assert(KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE);
2407 tile = ft.m_new_tile;
2408 cur_td = FindFirstTrackdir(ft.m_new_td_bits);
2410 UnreserveRailTrack(tile, TrackdirToTrack(cur_td));
2413 /* Path invalid. */
2414 return PBSTileInfo();
2418 * Try to reserve any path to a safe tile, ignoring the vehicle's destination.
2419 * Safe tiles are tiles in front of a signal, depots and station tiles at end of line.
2421 * @param v The vehicle.
2422 * @param tile The tile the search should start from.
2423 * @param td The trackdir the search should start from.
2424 * @param override_railtype Whether all physically compatible railtypes should be followed.
2425 * @return True if a path to a safe stopping tile could be reserved.
2427 static bool TryReserveSafeTrack(const Train *v, TileIndex tile, Trackdir td, bool override_railtype)
2429 switch (_settings_game.pf.pathfinder_for_trains) {
2430 case VPF_NPF: return NPFTrainFindNearestSafeTile(v, tile, td, override_railtype);
2431 case VPF_YAPF: return YapfTrainFindNearestSafeTile(v, tile, td, override_railtype);
2433 default: NOT_REACHED();
2437 /** This class will save the current order of a vehicle and restore it on destruction. */
2438 class VehicleOrderSaver {
2439 private:
2440 Train *v;
2441 Order old_order;
2442 TileIndex old_dest_tile;
2443 StationID old_last_station_visited;
2444 VehicleOrderID index;
2445 bool suppress_implicit_orders;
2447 public:
2448 VehicleOrderSaver(Train *_v) :
2449 v(_v),
2450 old_order(_v->current_order),
2451 old_dest_tile(_v->dest_tile),
2452 old_last_station_visited(_v->last_station_visited),
2453 index(_v->cur_real_order_index),
2454 suppress_implicit_orders(HasBit(_v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS))
2458 ~VehicleOrderSaver()
2460 this->v->current_order = this->old_order;
2461 this->v->dest_tile = this->old_dest_tile;
2462 this->v->last_station_visited = this->old_last_station_visited;
2463 SB(this->v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS, 1, suppress_implicit_orders ? 1: 0);
2467 * Set the current vehicle order to the next order in the order list.
2468 * @param skip_first Shall the first (i.e. active) order be skipped?
2469 * @return True if a suitable next order could be found.
2471 bool SwitchToNextOrder(bool skip_first)
2473 if (this->v->GetNumOrders() == 0) return false;
2475 if (skip_first) ++this->index;
2477 int depth = 0;
2479 do {
2480 /* Wrap around. */
2481 if (this->index >= this->v->GetNumOrders()) this->index = 0;
2483 Order *order = this->v->GetOrder(this->index);
2484 assert(order != nullptr);
2486 switch (order->GetType()) {
2487 case OT_GOTO_DEPOT:
2488 /* Skip service in depot orders when the train doesn't need service. */
2489 if ((order->GetDepotOrderType() & ODTFB_SERVICE) && !this->v->NeedsServicing()) break;
2490 FALLTHROUGH;
2491 case OT_GOTO_STATION:
2492 case OT_GOTO_WAYPOINT:
2493 this->v->current_order = *order;
2494 return UpdateOrderDest(this->v, order, 0, true);
2495 case OT_CONDITIONAL: {
2496 VehicleOrderID next = ProcessConditionalOrder(order, this->v);
2497 if (next != INVALID_VEH_ORDER_ID) {
2498 depth++;
2499 this->index = next;
2500 /* Don't increment next, so no break here. */
2501 continue;
2503 break;
2505 default:
2506 break;
2508 /* Don't increment inside the while because otherwise conditional
2509 * orders can lead to an infinite loop. */
2510 ++this->index;
2511 depth++;
2512 } while (this->index != this->v->cur_real_order_index && depth < this->v->GetNumOrders());
2514 return false;
2518 /* choose a track */
2519 static Track ChooseTrainTrack(Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool force_res, bool *got_reservation, bool mark_stuck)
2521 Track best_track = INVALID_TRACK;
2522 bool do_track_reservation = _settings_game.pf.reserve_paths || force_res;
2523 bool changed_signal = false;
2525 assert((tracks & ~TRACK_BIT_MASK) == 0);
2527 if (got_reservation != nullptr) *got_reservation = false;
2529 /* Don't use tracks here as the setting to forbid 90 deg turns might have been switched between reservation and now. */
2530 TrackBits res_tracks = (TrackBits)(GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir));
2531 /* Do we have a suitable reserved track? */
2532 if (res_tracks != TRACK_BIT_NONE) return FindFirstTrack(res_tracks);
2534 /* Quick return in case only one possible track is available */
2535 if (KillFirstBit(tracks) == TRACK_BIT_NONE) {
2536 Track track = FindFirstTrack(tracks);
2537 /* We need to check for signals only here, as a junction tile can't have signals. */
2538 if (track != INVALID_TRACK && HasPbsSignalOnTrackdir(tile, TrackEnterdirToTrackdir(track, enterdir))) {
2539 do_track_reservation = true;
2540 changed_signal = true;
2541 SetSignalStateByTrackdir(tile, TrackEnterdirToTrackdir(track, enterdir), SIGNAL_STATE_GREEN);
2542 } else if (!do_track_reservation) {
2543 return track;
2545 best_track = track;
2548 PBSTileInfo res_dest(tile, INVALID_TRACKDIR, false);
2549 DiagDirection dest_enterdir = enterdir;
2550 if (do_track_reservation) {
2551 res_dest = ExtendTrainReservation(v, &tracks, &dest_enterdir);
2552 if (res_dest.tile == INVALID_TILE) {
2553 /* Reservation failed? */
2554 if (mark_stuck) MarkTrainAsStuck(v);
2555 if (changed_signal) SetSignalStateByTrackdir(tile, TrackEnterdirToTrackdir(best_track, enterdir), SIGNAL_STATE_RED);
2556 return FindFirstTrack(tracks);
2558 if (res_dest.okay) {
2559 /* Got a valid reservation that ends at a safe target, quick exit. */
2560 if (got_reservation != nullptr) *got_reservation = true;
2561 if (changed_signal) MarkTileDirtyByTile(tile);
2562 TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
2563 return best_track;
2566 /* Check if the train needs service here, so it has a chance to always find a depot.
2567 * Also check if the current order is a service order so we don't reserve a path to
2568 * the destination but instead to the next one if service isn't needed. */
2569 CheckIfTrainNeedsService(v);
2570 if (v->current_order.IsType(OT_DUMMY) || v->current_order.IsType(OT_CONDITIONAL) || v->current_order.IsType(OT_GOTO_DEPOT)) ProcessOrders(v);
2573 /* Save the current train order. The destructor will restore the old order on function exit. */
2574 VehicleOrderSaver orders(v);
2576 /* If the current tile is the destination of the current order and
2577 * a reservation was requested, advance to the next order.
2578 * Don't advance on a depot order as depots are always safe end points
2579 * for a path and no look-ahead is necessary. This also avoids a
2580 * problem with depot orders not part of the order list when the
2581 * order list itself is empty. */
2582 if (v->current_order.IsType(OT_LEAVESTATION)) {
2583 orders.SwitchToNextOrder(false);
2584 } else if (v->current_order.IsType(OT_LOADING) || (!v->current_order.IsType(OT_GOTO_DEPOT) && (
2585 v->current_order.IsType(OT_GOTO_STATION) ?
2586 IsRailStationTile(v->tile) && v->current_order.GetDestination() == GetStationIndex(v->tile) :
2587 v->tile == v->dest_tile))) {
2588 orders.SwitchToNextOrder(true);
2591 if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
2592 /* Pathfinders are able to tell that route was only 'guessed'. */
2593 bool path_found = true;
2594 TileIndex new_tile = res_dest.tile;
2596 Track next_track = DoTrainPathfind(v, new_tile, dest_enterdir, tracks, path_found, do_track_reservation, &res_dest);
2597 if (new_tile == tile) best_track = next_track;
2598 v->HandlePathfindingResult(path_found);
2601 /* No track reservation requested -> finished. */
2602 if (!do_track_reservation) return best_track;
2604 /* A path was found, but could not be reserved. */
2605 if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
2606 if (mark_stuck) MarkTrainAsStuck(v);
2607 FreeTrainTrackReservation(v);
2608 return best_track;
2611 /* No possible reservation target found, we are probably lost. */
2612 if (res_dest.tile == INVALID_TILE) {
2613 /* Try to find any safe destination. */
2614 PBSTileInfo origin = FollowTrainReservation(v);
2615 if (TryReserveSafeTrack(v, origin.tile, origin.trackdir, false)) {
2616 TrackBits res = GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir);
2617 best_track = FindFirstTrack(res);
2618 TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
2619 if (got_reservation != nullptr) *got_reservation = true;
2620 if (changed_signal) MarkTileDirtyByTile(tile);
2621 } else {
2622 FreeTrainTrackReservation(v);
2623 if (mark_stuck) MarkTrainAsStuck(v);
2625 return best_track;
2628 if (got_reservation != nullptr) *got_reservation = true;
2630 /* Reservation target found and free, check if it is safe. */
2631 while (!IsSafeWaitingPosition(v, res_dest.tile, res_dest.trackdir, true, _settings_game.pf.forbid_90_deg)) {
2632 /* Extend reservation until we have found a safe position. */
2633 DiagDirection exitdir = TrackdirToExitdir(res_dest.trackdir);
2634 TileIndex next_tile = TileAddByDiagDir(res_dest.tile, exitdir);
2635 TrackBits reachable = TrackdirBitsToTrackBits((TrackdirBits)(GetTileTrackStatus(next_tile, TRANSPORT_RAIL, 0))) & DiagdirReachesTracks(exitdir);
2636 if (Rail90DegTurnDisallowed(GetTileRailType(res_dest.tile), GetTileRailType(next_tile))) {
2637 reachable &= ~TrackCrossesTracks(TrackdirToTrack(res_dest.trackdir));
2640 /* Get next order with destination. */
2641 if (orders.SwitchToNextOrder(true)) {
2642 PBSTileInfo cur_dest;
2643 bool path_found;
2644 DoTrainPathfind(v, next_tile, exitdir, reachable, path_found, true, &cur_dest);
2645 if (cur_dest.tile != INVALID_TILE) {
2646 res_dest = cur_dest;
2647 if (res_dest.okay) continue;
2648 /* Path found, but could not be reserved. */
2649 FreeTrainTrackReservation(v);
2650 if (mark_stuck) MarkTrainAsStuck(v);
2651 if (got_reservation != nullptr) *got_reservation = false;
2652 changed_signal = false;
2653 break;
2656 /* No order or no safe position found, try any position. */
2657 if (!TryReserveSafeTrack(v, res_dest.tile, res_dest.trackdir, true)) {
2658 FreeTrainTrackReservation(v);
2659 if (mark_stuck) MarkTrainAsStuck(v);
2660 if (got_reservation != nullptr) *got_reservation = false;
2661 changed_signal = false;
2663 break;
2666 TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
2668 if (changed_signal) MarkTileDirtyByTile(tile);
2670 return best_track;
2674 * Try to reserve a path to a safe position.
2676 * @param v The vehicle
2677 * @param mark_as_stuck Should the train be marked as stuck on a failed reservation?
2678 * @param first_tile_okay True if no path should be reserved if the current tile is a safe position.
2679 * @return True if a path could be reserved.
2681 bool TryPathReserve(Train *v, bool mark_as_stuck, bool first_tile_okay)
2683 assert(v->IsFrontEngine());
2685 /* We have to handle depots specially as the track follower won't look
2686 * at the depot tile itself but starts from the next tile. If we are still
2687 * inside the depot, a depot reservation can never be ours. */
2688 if (v->track == TRACK_BIT_DEPOT) {
2689 if (HasDepotReservation(v->tile)) {
2690 if (mark_as_stuck) MarkTrainAsStuck(v);
2691 return false;
2692 } else {
2693 /* Depot not reserved, but the next tile might be. */
2694 TileIndex next_tile = TileAddByDiagDir(v->tile, GetRailDepotDirection(v->tile));
2695 if (HasReservedTracks(next_tile, DiagdirReachesTracks(GetRailDepotDirection(v->tile)))) return false;
2699 Vehicle *other_train = nullptr;
2700 PBSTileInfo origin = FollowTrainReservation(v, &other_train);
2701 /* The path we are driving on is already blocked by some other train.
2702 * This can only happen in certain situations when mixing path and
2703 * block signals or when changing tracks and/or signals.
2704 * Exit here as doing any further reservations will probably just
2705 * make matters worse. */
2706 if (other_train != nullptr && other_train->index != v->index) {
2707 if (mark_as_stuck) MarkTrainAsStuck(v);
2708 return false;
2710 /* If we have a reserved path and the path ends at a safe tile, we are finished already. */
2711 if (origin.okay && (v->tile != origin.tile || first_tile_okay)) {
2712 /* Can't be stuck then. */
2713 if (HasBit(v->flags, VRF_TRAIN_STUCK)) SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
2714 ClrBit(v->flags, VRF_TRAIN_STUCK);
2715 return true;
2718 /* If we are in a depot, tentatively reserve the depot. */
2719 if (v->track == TRACK_BIT_DEPOT) {
2720 SetDepotReservation(v->tile, true);
2721 if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(v->tile);
2724 DiagDirection exitdir = TrackdirToExitdir(origin.trackdir);
2725 TileIndex new_tile = TileAddByDiagDir(origin.tile, exitdir);
2726 TrackBits reachable = TrackdirBitsToTrackBits(TrackStatusToTrackdirBits(GetTileTrackStatus(new_tile, TRANSPORT_RAIL, 0)) & DiagdirReachesTrackdirs(exitdir));
2728 if (Rail90DegTurnDisallowed(GetTileRailType(origin.tile), GetTileRailType(new_tile))) reachable &= ~TrackCrossesTracks(TrackdirToTrack(origin.trackdir));
2730 bool res_made = false;
2731 ChooseTrainTrack(v, new_tile, exitdir, reachable, true, &res_made, mark_as_stuck);
2733 if (!res_made) {
2734 /* Free the depot reservation as well. */
2735 if (v->track == TRACK_BIT_DEPOT) SetDepotReservation(v->tile, false);
2736 return false;
2739 if (HasBit(v->flags, VRF_TRAIN_STUCK)) {
2740 v->wait_counter = 0;
2741 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
2743 ClrBit(v->flags, VRF_TRAIN_STUCK);
2744 return true;
2748 static bool CheckReverseTrain(const Train *v)
2750 if (_settings_game.difficulty.line_reverse_mode != 0 ||
2751 v->track == TRACK_BIT_DEPOT || v->track == TRACK_BIT_WORMHOLE ||
2752 !(v->direction & 1)) {
2753 return false;
2756 assert(v->track != TRACK_BIT_NONE);
2758 switch (_settings_game.pf.pathfinder_for_trains) {
2759 case VPF_NPF: return NPFTrainCheckReverse(v);
2760 case VPF_YAPF: return YapfTrainCheckReverse(v);
2762 default: NOT_REACHED();
2767 * Get the location of the next station to visit.
2768 * @param station Next station to visit.
2769 * @return Location of the new station.
2771 TileIndex Train::GetOrderStationLocation(StationID station)
2773 if (station == this->last_station_visited) this->last_station_visited = INVALID_STATION;
2775 const Station *st = Station::Get(station);
2776 if (!(st->facilities & FACIL_TRAIN)) {
2777 /* The destination station has no trainstation tiles. */
2778 this->IncrementRealOrderIndex();
2779 return 0;
2782 return st->xy;
2785 /** Goods at the consist have changed, update the graphics, cargo, and acceleration. */
2786 void Train::MarkDirty()
2788 Train *v = this;
2789 do {
2790 v->colourmap = PAL_NONE;
2791 v->UpdateViewport(true, false);
2792 } while ((v = v->Next()) != nullptr);
2794 /* need to update acceleration and cached values since the goods on the train changed. */
2795 this->CargoChanged();
2796 this->UpdateAcceleration();
2800 * This function looks at the vehicle and updates its speed (cur_speed
2801 * and subspeed) variables. Furthermore, it returns the distance that
2802 * the train can drive this tick. #Vehicle::GetAdvanceDistance() determines
2803 * the distance to drive before moving a step on the map.
2804 * @return distance to drive.
2806 int Train::UpdateSpeed()
2808 switch (_settings_game.vehicle.train_acceleration_model) {
2809 default: NOT_REACHED();
2810 case AM_ORIGINAL:
2811 return this->DoUpdateSpeed(this->acceleration * (this->GetAccelerationStatus() == AS_BRAKE ? -4 : 2), 0, this->GetCurrentMaxSpeed());
2813 case AM_REALISTIC:
2814 return this->DoUpdateSpeed(this->GetAcceleration(), this->GetAccelerationStatus() == AS_BRAKE ? 0 : 2, this->GetCurrentMaxSpeed());
2819 * Trains enters a station, send out a news item if it is the first train, and start loading.
2820 * @param v Train that entered the station.
2821 * @param station Station visited.
2823 static void TrainEnterStation(Train *v, StationID station)
2825 v->last_station_visited = station;
2827 /* check if a train ever visited this station before */
2828 Station *st = Station::Get(station);
2829 if (!(st->had_vehicle_of_type & HVOT_TRAIN)) {
2830 st->had_vehicle_of_type |= HVOT_TRAIN;
2831 SetDParam(0, st->index);
2832 AddVehicleNewsItem(
2833 STR_NEWS_FIRST_TRAIN_ARRIVAL,
2834 v->owner == _local_company ? NT_ARRIVAL_COMPANY : NT_ARRIVAL_OTHER,
2835 v->index,
2836 st->index
2838 AI::NewEvent(v->owner, new ScriptEventStationFirstVehicle(st->index, v->index));
2839 Game::NewEvent(new ScriptEventStationFirstVehicle(st->index, v->index));
2842 v->force_proceed = TFP_NONE;
2843 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
2845 v->BeginLoading();
2847 TriggerStationRandomisation(st, v->tile, SRT_TRAIN_ARRIVES);
2848 TriggerStationAnimation(st, v->tile, SAT_TRAIN_ARRIVES);
2851 /* Check if the vehicle is compatible with the specified tile */
2852 static inline bool CheckCompatibleRail(const Train *v, TileIndex tile)
2854 return IsTileOwner(tile, v->owner) &&
2855 (!v->IsFrontEngine() || HasBit(v->compatible_railtypes, GetRailType(tile)));
2858 /** Data structure for storing engine speed changes of an acceleration type. */
2859 struct AccelerationSlowdownParams {
2860 byte small_turn; ///< Speed change due to a small turn.
2861 byte large_turn; ///< Speed change due to a large turn.
2862 byte z_up; ///< Fraction to remove when moving up.
2863 byte z_down; ///< Fraction to add when moving down.
2866 /** Speed update fractions for each acceleration type. */
2867 static const AccelerationSlowdownParams _accel_slowdown[] = {
2868 /* normal accel */
2869 {256 / 4, 256 / 2, 256 / 4, 2}, ///< normal
2870 {256 / 4, 256 / 2, 256 / 4, 2}, ///< monorail
2871 {0, 256 / 2, 256 / 4, 2}, ///< maglev
2875 * Modify the speed of the vehicle due to a change in altitude.
2876 * @param v %Train to update.
2877 * @param old_z Previous height.
2879 static inline void AffectSpeedByZChange(Train *v, int old_z)
2881 if (old_z == v->z_pos || _settings_game.vehicle.train_acceleration_model != AM_ORIGINAL) return;
2883 const AccelerationSlowdownParams *asp = &_accel_slowdown[GetRailTypeInfo(v->railtype)->acceleration_type];
2885 if (old_z < v->z_pos) {
2886 v->cur_speed -= (v->cur_speed * asp->z_up >> 8);
2887 } else {
2888 uint16 spd = v->cur_speed + asp->z_down;
2889 if (spd <= v->gcache.cached_max_track_speed) v->cur_speed = spd;
2893 static bool TrainMovedChangeSignals(TileIndex tile, DiagDirection dir)
2895 if (IsTileType(tile, MP_RAILWAY) &&
2896 GetRailTileType(tile) == RAIL_TILE_SIGNALS) {
2897 TrackdirBits tracks = TrackBitsToTrackdirBits(GetTrackBits(tile)) & DiagdirReachesTrackdirs(dir);
2898 Trackdir trackdir = FindFirstTrackdir(tracks);
2899 if (UpdateSignalsOnSegment(tile, TrackdirToExitdir(trackdir), GetTileOwner(tile)) == SIGSEG_PBS && HasSignalOnTrackdir(tile, trackdir)) {
2900 /* A PBS block with a non-PBS signal facing us? */
2901 if (!IsPbsSignal(GetSignalType(tile, TrackdirToTrack(trackdir)))) return true;
2904 return false;
2907 /** Tries to reserve track under whole train consist. */
2908 void Train::ReserveTrackUnderConsist() const
2910 for (const Train *u = this; u != nullptr; u = u->Next()) {
2911 switch (u->track) {
2912 case TRACK_BIT_WORMHOLE:
2913 TryReserveRailTrack(u->tile, DiagDirToDiagTrack(GetTunnelBridgeDirection(u->tile)));
2914 break;
2915 case TRACK_BIT_DEPOT:
2916 break;
2917 default:
2918 TryReserveRailTrack(u->tile, TrackBitsToTrack(u->track));
2919 break;
2925 * The train vehicle crashed!
2926 * Update its status and other parts around it.
2927 * @param flooded Crash was caused by flooding.
2928 * @return Number of people killed.
2930 uint Train::Crash(bool flooded)
2932 uint pass = 0;
2933 if (this->IsFrontEngine()) {
2934 pass += 2; // driver
2936 /* Remove the reserved path in front of the train if it is not stuck.
2937 * Also clear all reserved tracks the train is currently on. */
2938 if (!HasBit(this->flags, VRF_TRAIN_STUCK)) FreeTrainTrackReservation(this);
2939 for (const Train *v = this; v != nullptr; v = v->Next()) {
2940 ClearPathReservation(v, v->tile, v->GetVehicleTrackdir());
2941 if (IsTileType(v->tile, MP_TUNNELBRIDGE)) {
2942 /* ClearPathReservation will not free the wormhole exit
2943 * if the train has just entered the wormhole. */
2944 SetTunnelBridgeReservation(GetOtherTunnelBridgeEnd(v->tile), false);
2948 /* we may need to update crossing we were approaching,
2949 * but must be updated after the train has been marked crashed */
2950 TileIndex crossing = TrainApproachingCrossingTile(this);
2951 if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
2953 /* Remove the loading indicators (if any) */
2954 HideFillingPercent(&this->fill_percent_te_id);
2957 pass += this->GroundVehicleBase::Crash(flooded);
2959 this->crash_anim_pos = flooded ? 4000 : 1; // max 4440, disappear pretty fast when flooded
2960 return pass;
2964 * Marks train as crashed and creates an AI event.
2965 * Doesn't do anything if the train is crashed already.
2966 * @param v first vehicle of chain
2967 * @return number of victims (including 2 drivers; zero if train was already crashed)
2969 static uint TrainCrashed(Train *v)
2971 uint num = 0;
2973 /* do not crash train twice */
2974 if (!(v->vehstatus & VS_CRASHED)) {
2975 num = v->Crash();
2976 AI::NewEvent(v->owner, new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_TRAIN));
2977 Game::NewEvent(new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_TRAIN));
2980 /* Try to re-reserve track under already crashed train too.
2981 * Crash() clears the reservation! */
2982 v->ReserveTrackUnderConsist();
2984 return num;
2987 /** Temporary data storage for testing collisions. */
2988 struct TrainCollideChecker {
2989 Train *v; ///< %Vehicle we are testing for collision.
2990 uint num; ///< Total number of victims if train collided.
2994 * Collision test function.
2995 * @param v %Train vehicle to test collision with.
2996 * @param data %Train being examined.
2997 * @return \c nullptr (always continue search)
2999 static Vehicle *FindTrainCollideEnum(Vehicle *v, void *data)
3001 TrainCollideChecker *tcc = (TrainCollideChecker*)data;
3003 /* not a train or in depot */
3004 if (v->type != VEH_TRAIN || Train::From(v)->track == TRACK_BIT_DEPOT) return nullptr;
3006 /* do not crash into trains of another company. */
3007 if (v->owner != tcc->v->owner) return nullptr;
3009 /* get first vehicle now to make most usual checks faster */
3010 Train *coll = Train::From(v)->First();
3012 /* can't collide with own wagons */
3013 if (coll == tcc->v) return nullptr;
3015 int x_diff = v->x_pos - tcc->v->x_pos;
3016 int y_diff = v->y_pos - tcc->v->y_pos;
3018 /* Do fast calculation to check whether trains are not in close vicinity
3019 * and quickly reject trains distant enough for any collision.
3020 * Differences are shifted by 7, mapping range [-7 .. 8] into [0 .. 15]
3021 * Differences are then ORed and then we check for any higher bits */
3022 uint hash = (y_diff + 7) | (x_diff + 7);
3023 if (hash & ~15) return nullptr;
3025 /* Slower check using multiplication */
3026 int min_diff = (Train::From(v)->gcache.cached_veh_length + 1) / 2 + (tcc->v->gcache.cached_veh_length + 1) / 2 - 1;
3027 if (x_diff * x_diff + y_diff * y_diff > min_diff * min_diff) return nullptr;
3029 /* Happens when there is a train under bridge next to bridge head */
3030 if (abs(v->z_pos - tcc->v->z_pos) > 5) return nullptr;
3032 /* crash both trains */
3033 tcc->num += TrainCrashed(tcc->v);
3034 tcc->num += TrainCrashed(coll);
3036 return nullptr; // continue searching
3040 * Checks whether the specified train has a collision with another vehicle. If
3041 * so, destroys this vehicle, and the other vehicle if its subtype has TS_Front.
3042 * Reports the incident in a flashy news item, modifies station ratings and
3043 * plays a sound.
3044 * @param v %Train to test.
3046 static bool CheckTrainCollision(Train *v)
3048 /* can't collide in depot */
3049 if (v->track == TRACK_BIT_DEPOT) return false;
3051 assert(v->track == TRACK_BIT_WORMHOLE || TileVirtXY(v->x_pos, v->y_pos) == v->tile);
3053 TrainCollideChecker tcc;
3054 tcc.v = v;
3055 tcc.num = 0;
3057 /* find colliding vehicles */
3058 if (v->track == TRACK_BIT_WORMHOLE) {
3059 FindVehicleOnPos(v->tile, &tcc, FindTrainCollideEnum);
3060 FindVehicleOnPos(GetOtherTunnelBridgeEnd(v->tile), &tcc, FindTrainCollideEnum);
3061 } else {
3062 FindVehicleOnPosXY(v->x_pos, v->y_pos, &tcc, FindTrainCollideEnum);
3065 /* any dead -> no crash */
3066 if (tcc.num == 0) return false;
3068 SetDParam(0, tcc.num);
3069 AddTileNewsItem(STR_NEWS_TRAIN_CRASH, NT_ACCIDENT, v->tile);
3071 ModifyStationRatingAround(v->tile, v->owner, -160, 30);
3072 if (_settings_client.sound.disaster) SndPlayVehicleFx(SND_13_TRAIN_COLLISION, v);
3073 return true;
3076 static Vehicle *CheckTrainAtSignal(Vehicle *v, void *data)
3078 if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) return nullptr;
3080 Train *t = Train::From(v);
3081 DiagDirection exitdir = *(DiagDirection *)data;
3083 /* not front engine of a train, inside wormhole or depot, crashed */
3084 if (!t->IsFrontEngine() || !(t->track & TRACK_BIT_MASK)) return nullptr;
3086 if (t->cur_speed > 5 || VehicleExitDir(t->direction, t->track) != exitdir) return nullptr;
3088 return t;
3092 * Move a vehicle chain one movement stop forwards.
3093 * @param v First vehicle to move.
3094 * @param nomove Stop moving this and all following vehicles.
3095 * @param reverse Set to false to not execute the vehicle reversing. This does not change any other logic.
3096 * @return True if the vehicle could be moved forward, false otherwise.
3098 bool TrainController(Train *v, Vehicle *nomove, bool reverse)
3100 Train *first = v->First();
3101 Train *prev;
3102 bool direction_changed = false; // has direction of any part changed?
3104 /* For every vehicle after and including the given vehicle */
3105 for (prev = v->Previous(); v != nomove; prev = v, v = v->Next()) {
3106 DiagDirection enterdir = DIAGDIR_BEGIN;
3107 bool update_signals_crossing = false; // will we update signals or crossing state?
3109 GetNewVehiclePosResult gp = GetNewVehiclePos(v);
3110 if (v->track != TRACK_BIT_WORMHOLE) {
3111 /* Not inside tunnel */
3112 if (gp.old_tile == gp.new_tile) {
3113 /* Staying in the old tile */
3114 if (v->track == TRACK_BIT_DEPOT) {
3115 /* Inside depot */
3116 gp.x = v->x_pos;
3117 gp.y = v->y_pos;
3118 } else {
3119 /* Not inside depot */
3121 /* Reverse when we are at the end of the track already, do not move to the new position */
3122 if (v->IsFrontEngine() && !TrainCheckIfLineEnds(v, reverse)) return false;
3124 uint32 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
3125 if (HasBit(r, VETS_CANNOT_ENTER)) {
3126 goto invalid_rail;
3128 if (HasBit(r, VETS_ENTERED_STATION)) {
3129 /* The new position is the end of the platform */
3130 TrainEnterStation(v, r >> VETS_STATION_ID_OFFSET);
3133 } else {
3134 /* A new tile is about to be entered. */
3136 /* Determine what direction we're entering the new tile from */
3137 enterdir = DiagdirBetweenTiles(gp.old_tile, gp.new_tile);
3138 assert(IsValidDiagDirection(enterdir));
3140 /* Get the status of the tracks in the new tile and mask
3141 * away the bits that aren't reachable. */
3142 TrackStatus ts = GetTileTrackStatus(gp.new_tile, TRANSPORT_RAIL, 0, ReverseDiagDir(enterdir));
3143 TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(enterdir);
3145 TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
3146 TrackBits red_signals = TrackdirBitsToTrackBits(TrackStatusToRedSignals(ts) & reachable_trackdirs);
3148 TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
3149 if (Rail90DegTurnDisallowed(GetTileRailType(gp.old_tile), GetTileRailType(gp.new_tile)) && prev == nullptr) {
3150 /* We allow wagons to make 90 deg turns, because forbid_90_deg
3151 * can be switched on halfway a turn */
3152 bits &= ~TrackCrossesTracks(FindFirstTrack(v->track));
3155 if (bits == TRACK_BIT_NONE) goto invalid_rail;
3157 /* Check if the new tile constrains tracks that are compatible
3158 * with the current train, if not, bail out. */
3159 if (!CheckCompatibleRail(v, gp.new_tile)) goto invalid_rail;
3161 TrackBits chosen_track;
3162 if (prev == nullptr) {
3163 /* Currently the locomotive is active. Determine which one of the
3164 * available tracks to choose */
3165 chosen_track = TrackToTrackBits(ChooseTrainTrack(v, gp.new_tile, enterdir, bits, false, nullptr, true));
3166 assert(chosen_track & (bits | GetReservedTrackbits(gp.new_tile)));
3168 if (v->force_proceed != TFP_NONE && IsPlainRailTile(gp.new_tile) && HasSignals(gp.new_tile)) {
3169 /* For each signal we find decrease the counter by one.
3170 * We start at two, so the first signal we pass decreases
3171 * this to one, then if we reach the next signal it is
3172 * decreased to zero and we won't pass that new signal. */
3173 Trackdir dir = FindFirstTrackdir(trackdirbits);
3174 if (HasSignalOnTrackdir(gp.new_tile, dir) ||
3175 (HasSignalOnTrackdir(gp.new_tile, ReverseTrackdir(dir)) &&
3176 GetSignalType(gp.new_tile, TrackdirToTrack(dir)) != SIGTYPE_PBS)) {
3177 /* However, we do not want to be stopped by PBS signals
3178 * entered via the back. */
3179 v->force_proceed = (v->force_proceed == TFP_SIGNAL) ? TFP_STUCK : TFP_NONE;
3180 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
3184 /* Check if it's a red signal and that force proceed is not clicked. */
3185 if ((red_signals & chosen_track) && v->force_proceed == TFP_NONE) {
3186 /* In front of a red signal */
3187 Trackdir i = FindFirstTrackdir(trackdirbits);
3189 /* Don't handle stuck trains here. */
3190 if (HasBit(v->flags, VRF_TRAIN_STUCK)) return false;
3192 if (!HasSignalOnTrackdir(gp.new_tile, ReverseTrackdir(i))) {
3193 v->cur_speed = 0;
3194 v->subspeed = 0;
3195 v->progress = 255; // make sure that every bit of acceleration will hit the signal again, so speed stays 0.
3196 if (!_settings_game.pf.reverse_at_signals || ++v->wait_counter < _settings_game.pf.wait_oneway_signal * DAY_TICKS * 2) return false;
3197 } else if (HasSignalOnTrackdir(gp.new_tile, i)) {
3198 v->cur_speed = 0;
3199 v->subspeed = 0;
3200 v->progress = 255; // make sure that every bit of acceleration will hit the signal again, so speed stays 0.
3201 if (!_settings_game.pf.reverse_at_signals || ++v->wait_counter < _settings_game.pf.wait_twoway_signal * DAY_TICKS * 2) {
3202 DiagDirection exitdir = TrackdirToExitdir(i);
3203 TileIndex o_tile = TileAddByDiagDir(gp.new_tile, exitdir);
3205 exitdir = ReverseDiagDir(exitdir);
3207 /* check if a train is waiting on the other side */
3208 if (!HasVehicleOnPos(o_tile, &exitdir, &CheckTrainAtSignal)) return false;
3212 /* If we would reverse but are currently in a PBS block and
3213 * reversing of stuck trains is disabled, don't reverse.
3214 * This does not apply if the reason for reversing is a one-way
3215 * signal blocking us, because a train would then be stuck forever. */
3216 if (!_settings_game.pf.reverse_at_signals && !HasOnewaySignalBlockingTrackdir(gp.new_tile, i) &&
3217 UpdateSignalsOnSegment(v->tile, enterdir, v->owner) == SIGSEG_PBS) {
3218 v->wait_counter = 0;
3219 return false;
3221 goto reverse_train_direction;
3222 } else {
3223 TryReserveRailTrack(gp.new_tile, TrackBitsToTrack(chosen_track), false);
3225 } else {
3226 /* The wagon is active, simply follow the prev vehicle. */
3227 if (prev->tile == gp.new_tile) {
3228 /* Choose the same track as prev */
3229 if (prev->track == TRACK_BIT_WORMHOLE) {
3230 /* Vehicles entering tunnels enter the wormhole earlier than for bridges.
3231 * However, just choose the track into the wormhole. */
3232 assert(IsTunnel(prev->tile));
3233 chosen_track = bits;
3234 } else {
3235 chosen_track = prev->track;
3237 } else {
3238 /* Choose the track that leads to the tile where prev is.
3239 * This case is active if 'prev' is already on the second next tile, when 'v' just enters the next tile.
3240 * I.e. when the tile between them has only space for a single vehicle like
3241 * 1) horizontal/vertical track tiles and
3242 * 2) some orientations of tunnel entries, where the vehicle is already inside the wormhole at 8/16 from the tile edge.
3243 * Is also the train just reversing, the wagon inside the tunnel is 'on' the tile of the opposite tunnel entry.
3245 static const TrackBits _connecting_track[DIAGDIR_END][DIAGDIR_END] = {
3246 {TRACK_BIT_X, TRACK_BIT_LOWER, TRACK_BIT_NONE, TRACK_BIT_LEFT },
3247 {TRACK_BIT_UPPER, TRACK_BIT_Y, TRACK_BIT_LEFT, TRACK_BIT_NONE },
3248 {TRACK_BIT_NONE, TRACK_BIT_RIGHT, TRACK_BIT_X, TRACK_BIT_UPPER},
3249 {TRACK_BIT_RIGHT, TRACK_BIT_NONE, TRACK_BIT_LOWER, TRACK_BIT_Y }
3251 DiagDirection exitdir = DiagdirBetweenTiles(gp.new_tile, prev->tile);
3252 assert(IsValidDiagDirection(exitdir));
3253 chosen_track = _connecting_track[enterdir][exitdir];
3255 chosen_track &= bits;
3258 /* Make sure chosen track is a valid track */
3259 assert(
3260 chosen_track == TRACK_BIT_X || chosen_track == TRACK_BIT_Y ||
3261 chosen_track == TRACK_BIT_UPPER || chosen_track == TRACK_BIT_LOWER ||
3262 chosen_track == TRACK_BIT_LEFT || chosen_track == TRACK_BIT_RIGHT);
3264 /* Update XY to reflect the entrance to the new tile, and select the direction to use */
3265 const byte *b = _initial_tile_subcoord[FIND_FIRST_BIT(chosen_track)][enterdir];
3266 gp.x = (gp.x & ~0xF) | b[0];
3267 gp.y = (gp.y & ~0xF) | b[1];
3268 Direction chosen_dir = (Direction)b[2];
3270 /* Call the landscape function and tell it that the vehicle entered the tile */
3271 uint32 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
3272 if (HasBit(r, VETS_CANNOT_ENTER)) {
3273 goto invalid_rail;
3276 if (!HasBit(r, VETS_ENTERED_WORMHOLE)) {
3277 Track track = FindFirstTrack(chosen_track);
3278 Trackdir tdir = TrackDirectionToTrackdir(track, chosen_dir);
3279 if (v->IsFrontEngine() && HasPbsSignalOnTrackdir(gp.new_tile, tdir)) {
3280 SetSignalStateByTrackdir(gp.new_tile, tdir, SIGNAL_STATE_RED);
3281 MarkTileDirtyByTile(gp.new_tile);
3284 /* Clear any track reservation when the last vehicle leaves the tile */
3285 if (v->Next() == nullptr) ClearPathReservation(v, v->tile, v->GetVehicleTrackdir());
3287 v->tile = gp.new_tile;
3289 if (GetTileRailType(gp.new_tile) != GetTileRailType(gp.old_tile)) {
3290 v->First()->ConsistChanged(CCF_TRACK);
3293 v->track = chosen_track;
3294 assert(v->track);
3297 /* We need to update signal status, but after the vehicle position hash
3298 * has been updated by UpdateInclination() */
3299 update_signals_crossing = true;
3301 if (chosen_dir != v->direction) {
3302 if (prev == nullptr && _settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) {
3303 const AccelerationSlowdownParams *asp = &_accel_slowdown[GetRailTypeInfo(v->railtype)->acceleration_type];
3304 DirDiff diff = DirDifference(v->direction, chosen_dir);
3305 v->cur_speed -= (diff == DIRDIFF_45RIGHT || diff == DIRDIFF_45LEFT ? asp->small_turn : asp->large_turn) * v->cur_speed >> 8;
3307 direction_changed = true;
3308 v->direction = chosen_dir;
3311 if (v->IsFrontEngine()) {
3312 v->wait_counter = 0;
3314 /* If we are approaching a crossing that is reserved, play the sound now. */
3315 TileIndex crossing = TrainApproachingCrossingTile(v);
3316 if (crossing != INVALID_TILE && HasCrossingReservation(crossing) && _settings_client.sound.ambient) SndPlayTileFx(SND_0E_LEVEL_CROSSING, crossing);
3318 /* Always try to extend the reservation when entering a tile. */
3319 CheckNextTrainTile(v);
3322 if (HasBit(r, VETS_ENTERED_STATION)) {
3323 /* The new position is the location where we want to stop */
3324 TrainEnterStation(v, r >> VETS_STATION_ID_OFFSET);
3327 } else {
3328 if (IsTileType(gp.new_tile, MP_TUNNELBRIDGE) && HasBit(VehicleEnterTile(v, gp.new_tile, gp.x, gp.y), VETS_ENTERED_WORMHOLE)) {
3329 /* Perform look-ahead on tunnel exit. */
3330 if (v->IsFrontEngine()) {
3331 TryReserveRailTrack(gp.new_tile, DiagDirToDiagTrack(GetTunnelBridgeDirection(gp.new_tile)));
3332 CheckNextTrainTile(v);
3334 /* Prevent v->UpdateInclination() being called with wrong parameters.
3335 * This could happen if the train was reversed inside the tunnel/bridge. */
3336 if (gp.old_tile == gp.new_tile) {
3337 gp.old_tile = GetOtherTunnelBridgeEnd(gp.old_tile);
3339 } else {
3340 v->x_pos = gp.x;
3341 v->y_pos = gp.y;
3342 v->UpdatePosition();
3343 if ((v->vehstatus & VS_HIDDEN) == 0) v->Vehicle::UpdateViewport(true);
3344 continue;
3348 /* update image of train, as well as delta XY */
3349 v->UpdateDeltaXY();
3351 v->x_pos = gp.x;
3352 v->y_pos = gp.y;
3353 v->UpdatePosition();
3355 /* update the Z position of the vehicle */
3356 int old_z = v->UpdateInclination(gp.new_tile != gp.old_tile, false);
3358 if (prev == nullptr) {
3359 /* This is the first vehicle in the train */
3360 AffectSpeedByZChange(v, old_z);
3363 if (update_signals_crossing) {
3364 if (v->IsFrontEngine()) {
3365 if (TrainMovedChangeSignals(gp.new_tile, enterdir)) {
3366 /* We are entering a block with PBS signals right now, but
3367 * not through a PBS signal. This means we don't have a
3368 * reservation right now. As a conventional signal will only
3369 * ever be green if no other train is in the block, getting
3370 * a path should always be possible. If the player built
3371 * such a strange network that it is not possible, the train
3372 * will be marked as stuck and the player has to deal with
3373 * the problem. */
3374 if ((!HasReservedTracks(gp.new_tile, v->track) &&
3375 !TryReserveRailTrack(gp.new_tile, FindFirstTrack(v->track))) ||
3376 !TryPathReserve(v)) {
3377 MarkTrainAsStuck(v);
3382 /* Signals can only change when the first
3383 * (above) or the last vehicle moves. */
3384 if (v->Next() == nullptr) {
3385 TrainMovedChangeSignals(gp.old_tile, ReverseDiagDir(enterdir));
3386 if (IsLevelCrossingTile(gp.old_tile)) UpdateLevelCrossing(gp.old_tile);
3390 /* Do not check on every tick to save some computing time. */
3391 if (v->IsFrontEngine() && v->tick_counter % _settings_game.pf.path_backoff_interval == 0) CheckNextTrainTile(v);
3394 if (direction_changed) first->tcache.cached_max_curve_speed = first->GetCurveSpeedLimit();
3396 return true;
3398 invalid_rail:
3399 /* We've reached end of line?? */
3400 if (prev != nullptr) error("Disconnecting train");
3402 reverse_train_direction:
3403 if (reverse) {
3404 v->wait_counter = 0;
3405 v->cur_speed = 0;
3406 v->subspeed = 0;
3407 ReverseTrainDirection(v);
3410 return false;
3414 * Collect trackbits of all crashed train vehicles on a tile
3415 * @param v Vehicle passed from Find/HasVehicleOnPos()
3416 * @param data trackdirbits for the result
3417 * @return nullptr to iterate over all vehicles on the tile.
3419 static Vehicle *CollectTrackbitsFromCrashedVehiclesEnum(Vehicle *v, void *data)
3421 TrackBits *trackbits = (TrackBits *)data;
3423 if (v->type == VEH_TRAIN && (v->vehstatus & VS_CRASHED) != 0) {
3424 TrackBits train_tbits = Train::From(v)->track;
3425 if (train_tbits == TRACK_BIT_WORMHOLE) {
3426 /* Vehicle is inside a wormhole, v->track contains no useful value then. */
3427 *trackbits |= DiagDirToDiagTrackBits(GetTunnelBridgeDirection(v->tile));
3428 } else if (train_tbits != TRACK_BIT_DEPOT) {
3429 *trackbits |= train_tbits;
3433 return nullptr;
3437 * Deletes/Clears the last wagon of a crashed train. It takes the engine of the
3438 * train, then goes to the last wagon and deletes that. Each call to this function
3439 * will remove the last wagon of a crashed train. If this wagon was on a crossing,
3440 * or inside a tunnel/bridge, recalculate the signals as they might need updating
3441 * @param v the Vehicle of which last wagon is to be removed
3443 static void DeleteLastWagon(Train *v)
3445 Train *first = v->First();
3447 /* Go to the last wagon and delete the link pointing there
3448 * *u is then the one-before-last wagon, and *v the last
3449 * one which will physically be removed */
3450 Train *u = v;
3451 for (; v->Next() != nullptr; v = v->Next()) u = v;
3452 u->SetNext(nullptr);
3454 if (first != v) {
3455 /* Recalculate cached train properties */
3456 first->ConsistChanged(CCF_ARRANGE);
3457 /* Update the depot window if the first vehicle is in depot -
3458 * if v == first, then it is updated in PreDestructor() */
3459 if (first->track == TRACK_BIT_DEPOT) {
3460 SetWindowDirty(WC_VEHICLE_DEPOT, first->tile);
3462 v->last_station_visited = first->last_station_visited; // for PreDestructor
3465 /* 'v' shouldn't be accessed after it has been deleted */
3466 TrackBits trackbits = v->track;
3467 TileIndex tile = v->tile;
3468 Owner owner = v->owner;
3470 delete v;
3471 v = nullptr; // make sure nobody will try to read 'v' anymore
3473 if (trackbits == TRACK_BIT_WORMHOLE) {
3474 /* Vehicle is inside a wormhole, v->track contains no useful value then. */
3475 trackbits = DiagDirToDiagTrackBits(GetTunnelBridgeDirection(tile));
3478 Track track = TrackBitsToTrack(trackbits);
3479 if (HasReservedTracks(tile, trackbits)) {
3480 UnreserveRailTrack(tile, track);
3482 /* If there are still crashed vehicles on the tile, give the track reservation to them */
3483 TrackBits remaining_trackbits = TRACK_BIT_NONE;
3484 FindVehicleOnPos(tile, &remaining_trackbits, CollectTrackbitsFromCrashedVehiclesEnum);
3486 /* It is important that these two are the first in the loop, as reservation cannot deal with every trackbit combination */
3487 assert(TRACK_BEGIN == TRACK_X && TRACK_Y == TRACK_BEGIN + 1);
3488 for (Track t : SetTrackBitIterator(remaining_trackbits)) TryReserveRailTrack(tile, t);
3491 /* check if the wagon was on a road/rail-crossing */
3492 if (IsLevelCrossingTile(tile)) UpdateLevelCrossing(tile);
3494 /* Update signals */
3495 if (IsTileType(tile, MP_TUNNELBRIDGE) || IsRailDepotTile(tile)) {
3496 UpdateSignalsOnSegment(tile, INVALID_DIAGDIR, owner);
3497 } else {
3498 SetSignalsOnBothDir(tile, track, owner);
3503 * Rotate all vehicles of a (crashed) train chain randomly to animate the crash.
3504 * @param v First crashed vehicle.
3506 static void ChangeTrainDirRandomly(Train *v)
3508 static const DirDiff delta[] = {
3509 DIRDIFF_45LEFT, DIRDIFF_SAME, DIRDIFF_SAME, DIRDIFF_45RIGHT
3512 do {
3513 /* We don't need to twist around vehicles if they're not visible */
3514 if (!(v->vehstatus & VS_HIDDEN)) {
3515 v->direction = ChangeDir(v->direction, delta[GB(Random(), 0, 2)]);
3516 /* Refrain from updating the z position of the vehicle when on
3517 * a bridge, because UpdateInclination() will put the vehicle under
3518 * the bridge in that case */
3519 if (v->track != TRACK_BIT_WORMHOLE) {
3520 v->UpdatePosition();
3521 v->UpdateInclination(false, true);
3522 } else {
3523 v->UpdateViewport(false, true);
3526 } while ((v = v->Next()) != nullptr);
3530 * Handle a crashed train.
3531 * @param v First train vehicle.
3532 * @return %Vehicle chain still exists.
3534 static bool HandleCrashedTrain(Train *v)
3536 int state = ++v->crash_anim_pos;
3538 if (state == 4 && !(v->vehstatus & VS_HIDDEN)) {
3539 CreateEffectVehicleRel(v, 4, 4, 8, EV_EXPLOSION_LARGE);
3542 uint32 r;
3543 if (state <= 200 && Chance16R(1, 7, r)) {
3544 int index = (r * 10 >> 16);
3546 Vehicle *u = v;
3547 do {
3548 if (--index < 0) {
3549 r = Random();
3551 CreateEffectVehicleRel(u,
3552 GB(r, 8, 3) + 2,
3553 GB(r, 16, 3) + 2,
3554 GB(r, 0, 3) + 5,
3555 EV_EXPLOSION_SMALL);
3556 break;
3558 } while ((u = u->Next()) != nullptr);
3561 if (state <= 240 && !(v->tick_counter & 3)) ChangeTrainDirRandomly(v);
3563 if (state >= 4440 && !(v->tick_counter & 0x1F)) {
3564 bool ret = v->Next() != nullptr;
3565 DeleteLastWagon(v);
3566 return ret;
3569 return true;
3572 /** Maximum speeds for train that is broken down or approaching line end */
3573 static const uint16 _breakdown_speeds[16] = {
3574 225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, 15
3579 * Train is approaching line end, slow down and possibly reverse
3581 * @param v front train engine
3582 * @param signal not line end, just a red signal
3583 * @param reverse Set to false to not execute the vehicle reversing. This does not change any other logic.
3584 * @return true iff we did NOT have to reverse
3586 static bool TrainApproachingLineEnd(Train *v, bool signal, bool reverse)
3588 /* Calc position within the current tile */
3589 uint x = v->x_pos & 0xF;
3590 uint y = v->y_pos & 0xF;
3592 /* for diagonal directions, 'x' will be 0..15 -
3593 * for other directions, it will be 1, 3, 5, ..., 15 */
3594 switch (v->direction) {
3595 case DIR_N : x = ~x + ~y + 25; break;
3596 case DIR_NW: x = y; FALLTHROUGH;
3597 case DIR_NE: x = ~x + 16; break;
3598 case DIR_E : x = ~x + y + 9; break;
3599 case DIR_SE: x = y; break;
3600 case DIR_S : x = x + y - 7; break;
3601 case DIR_W : x = ~y + x + 9; break;
3602 default: break;
3605 /* Do not reverse when approaching red signal. Make sure the vehicle's front
3606 * does not cross the tile boundary when we do reverse, but as the vehicle's
3607 * location is based on their center, use half a vehicle's length as offset.
3608 * Multiply the half-length by two for straight directions to compensate that
3609 * we only get odd x offsets there. */
3610 if (!signal && x + (v->gcache.cached_veh_length + 1) / 2 * (IsDiagonalDirection(v->direction) ? 1 : 2) >= TILE_SIZE) {
3611 /* we are too near the tile end, reverse now */
3612 v->cur_speed = 0;
3613 if (reverse) ReverseTrainDirection(v);
3614 return false;
3617 /* slow down */
3618 v->vehstatus |= VS_TRAIN_SLOWING;
3619 uint16 break_speed = _breakdown_speeds[x & 0xF];
3620 if (break_speed < v->cur_speed) v->cur_speed = break_speed;
3622 return true;
3627 * Determines whether train would like to leave the tile
3628 * @param v train to test
3629 * @return true iff vehicle is NOT entering or inside a depot or tunnel/bridge
3631 static bool TrainCanLeaveTile(const Train *v)
3633 /* Exit if inside a tunnel/bridge or a depot */
3634 if (v->track == TRACK_BIT_WORMHOLE || v->track == TRACK_BIT_DEPOT) return false;
3636 TileIndex tile = v->tile;
3638 /* entering a tunnel/bridge? */
3639 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
3640 DiagDirection dir = GetTunnelBridgeDirection(tile);
3641 if (DiagDirToDir(dir) == v->direction) return false;
3644 /* entering a depot? */
3645 if (IsRailDepotTile(tile)) {
3646 DiagDirection dir = ReverseDiagDir(GetRailDepotDirection(tile));
3647 if (DiagDirToDir(dir) == v->direction) return false;
3650 return true;
3655 * Determines whether train is approaching a rail-road crossing
3656 * (thus making it barred)
3657 * @param v front engine of train
3658 * @return TileIndex of crossing the train is approaching, else INVALID_TILE
3659 * @pre v in non-crashed front engine
3661 static TileIndex TrainApproachingCrossingTile(const Train *v)
3663 assert(v->IsFrontEngine());
3664 assert(!(v->vehstatus & VS_CRASHED));
3666 if (!TrainCanLeaveTile(v)) return INVALID_TILE;
3668 DiagDirection dir = VehicleExitDir(v->direction, v->track);
3669 TileIndex tile = v->tile + TileOffsByDiagDir(dir);
3671 /* not a crossing || wrong axis || unusable rail (wrong type or owner) */
3672 if (!IsLevelCrossingTile(tile) || DiagDirToAxis(dir) == GetCrossingRoadAxis(tile) ||
3673 !CheckCompatibleRail(v, tile)) {
3674 return INVALID_TILE;
3677 return tile;
3682 * Checks for line end. Also, bars crossing at next tile if needed
3684 * @param v vehicle we are checking
3685 * @param reverse Set to false to not execute the vehicle reversing. This does not change any other logic.
3686 * @return true iff we did NOT have to reverse
3688 static bool TrainCheckIfLineEnds(Train *v, bool reverse)
3690 /* First, handle broken down train */
3692 int t = v->breakdown_ctr;
3693 if (t > 1) {
3694 v->vehstatus |= VS_TRAIN_SLOWING;
3696 uint16 break_speed = _breakdown_speeds[GB(~t, 4, 4)];
3697 if (break_speed < v->cur_speed) v->cur_speed = break_speed;
3698 } else {
3699 v->vehstatus &= ~VS_TRAIN_SLOWING;
3702 if (!TrainCanLeaveTile(v)) return true;
3704 /* Determine the non-diagonal direction in which we will exit this tile */
3705 DiagDirection dir = VehicleExitDir(v->direction, v->track);
3706 /* Calculate next tile */
3707 TileIndex tile = v->tile + TileOffsByDiagDir(dir);
3709 /* Determine the track status on the next tile */
3710 TrackStatus ts = GetTileTrackStatus(tile, TRANSPORT_RAIL, 0, ReverseDiagDir(dir));
3711 TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(dir);
3713 TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
3714 TrackdirBits red_signals = TrackStatusToRedSignals(ts) & reachable_trackdirs;
3716 /* We are sure the train is not entering a depot, it is detected above */
3718 /* mask unreachable track bits if we are forbidden to do 90deg turns */
3719 TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
3720 if (Rail90DegTurnDisallowed(GetTileRailType(v->tile), GetTileRailType(tile))) {
3721 bits &= ~TrackCrossesTracks(FindFirstTrack(v->track));
3724 /* no suitable trackbits at all || unusable rail (wrong type or owner) */
3725 if (bits == TRACK_BIT_NONE || !CheckCompatibleRail(v, tile)) {
3726 return TrainApproachingLineEnd(v, false, reverse);
3729 /* approaching red signal */
3730 if ((trackdirbits & red_signals) != 0) return TrainApproachingLineEnd(v, true, reverse);
3732 /* approaching a rail/road crossing? then make it red */
3733 if (IsLevelCrossingTile(tile)) MaybeBarCrossingWithSound(tile);
3735 return true;
3739 static bool TrainLocoHandler(Train *v, bool mode)
3741 /* train has crashed? */
3742 if (v->vehstatus & VS_CRASHED) {
3743 return mode ? true : HandleCrashedTrain(v); // 'this' can be deleted here
3746 if (v->force_proceed != TFP_NONE) {
3747 ClrBit(v->flags, VRF_TRAIN_STUCK);
3748 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
3751 /* train is broken down? */
3752 if (v->HandleBreakdown()) return true;
3754 if (HasBit(v->flags, VRF_REVERSING) && v->cur_speed == 0) {
3755 ReverseTrainDirection(v);
3758 /* exit if train is stopped */
3759 if ((v->vehstatus & VS_STOPPED) && v->cur_speed == 0) return true;
3761 bool valid_order = !v->current_order.IsType(OT_NOTHING) && v->current_order.GetType() != OT_CONDITIONAL;
3762 if (ProcessOrders(v) && CheckReverseTrain(v)) {
3763 v->wait_counter = 0;
3764 v->cur_speed = 0;
3765 v->subspeed = 0;
3766 ClrBit(v->flags, VRF_LEAVING_STATION);
3767 ReverseTrainDirection(v);
3768 return true;
3769 } else if (HasBit(v->flags, VRF_LEAVING_STATION)) {
3770 /* Try to reserve a path when leaving the station as we
3771 * might not be marked as wanting a reservation, e.g.
3772 * when an overlength train gets turned around in a station. */
3773 DiagDirection dir = VehicleExitDir(v->direction, v->track);
3774 if (IsRailDepotTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE)) dir = INVALID_DIAGDIR;
3776 if (UpdateSignalsOnSegment(v->tile, dir, v->owner) == SIGSEG_PBS || _settings_game.pf.reserve_paths) {
3777 TryPathReserve(v, true, true);
3779 ClrBit(v->flags, VRF_LEAVING_STATION);
3782 v->HandleLoading(mode);
3784 if (v->current_order.IsType(OT_LOADING)) return true;
3786 if (CheckTrainStayInDepot(v)) return true;
3788 if (!mode) v->ShowVisualEffect();
3790 /* We had no order but have an order now, do look ahead. */
3791 if (!valid_order && !v->current_order.IsType(OT_NOTHING)) {
3792 CheckNextTrainTile(v);
3795 /* Handle stuck trains. */
3796 if (!mode && HasBit(v->flags, VRF_TRAIN_STUCK)) {
3797 ++v->wait_counter;
3799 /* Should we try reversing this tick if still stuck? */
3800 bool turn_around = v->wait_counter % (_settings_game.pf.wait_for_pbs_path * DAY_TICKS) == 0 && _settings_game.pf.reverse_at_signals;
3802 if (!turn_around && v->wait_counter % _settings_game.pf.path_backoff_interval != 0 && v->force_proceed == TFP_NONE) return true;
3803 if (!TryPathReserve(v)) {
3804 /* Still stuck. */
3805 if (turn_around) ReverseTrainDirection(v);
3807 if (HasBit(v->flags, VRF_TRAIN_STUCK) && v->wait_counter > 2 * _settings_game.pf.wait_for_pbs_path * DAY_TICKS) {
3808 /* Show message to player. */
3809 if (_settings_client.gui.lost_vehicle_warn && v->owner == _local_company) {
3810 SetDParam(0, v->index);
3811 AddVehicleAdviceNewsItem(STR_NEWS_TRAIN_IS_STUCK, v->index);
3813 v->wait_counter = 0;
3815 /* Exit if force proceed not pressed, else reset stuck flag anyway. */
3816 if (v->force_proceed == TFP_NONE) return true;
3817 ClrBit(v->flags, VRF_TRAIN_STUCK);
3818 v->wait_counter = 0;
3819 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
3823 if (v->current_order.IsType(OT_LEAVESTATION)) {
3824 v->current_order.Free();
3825 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
3826 return true;
3829 int j = v->UpdateSpeed();
3831 /* we need to invalidate the widget if we are stopping from 'Stopping 0 km/h' to 'Stopped' */
3832 if (v->cur_speed == 0 && (v->vehstatus & VS_STOPPED)) {
3833 /* If we manually stopped, we're not force-proceeding anymore. */
3834 v->force_proceed = TFP_NONE;
3835 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
3838 int adv_spd = v->GetAdvanceDistance();
3839 if (j < adv_spd) {
3840 /* if the vehicle has speed 0, update the last_speed field. */
3841 if (v->cur_speed == 0) v->SetLastSpeed();
3842 } else {
3843 TrainCheckIfLineEnds(v);
3844 /* Loop until the train has finished moving. */
3845 for (;;) {
3846 j -= adv_spd;
3847 TrainController(v, nullptr);
3848 /* Don't continue to move if the train crashed. */
3849 if (CheckTrainCollision(v)) break;
3850 /* Determine distance to next map position */
3851 adv_spd = v->GetAdvanceDistance();
3853 /* No more moving this tick */
3854 if (j < adv_spd || v->cur_speed == 0) break;
3856 OrderType order_type = v->current_order.GetType();
3857 /* Do not skip waypoints (incl. 'via' stations) when passing through at full speed. */
3858 if ((order_type == OT_GOTO_WAYPOINT || order_type == OT_GOTO_STATION) &&
3859 (v->current_order.GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION) &&
3860 IsTileType(v->tile, MP_STATION) &&
3861 v->current_order.GetDestination() == GetStationIndex(v->tile)) {
3862 ProcessOrders(v);
3865 v->SetLastSpeed();
3868 for (Train *u = v; u != nullptr; u = u->Next()) {
3869 if ((u->vehstatus & VS_HIDDEN) != 0) continue;
3871 u->UpdateViewport(false, false);
3874 if (v->progress == 0) v->progress = j; // Save unused spd for next time, if TrainController didn't set progress
3876 return true;
3880 * Get running cost for the train consist.
3881 * @return Yearly running costs.
3883 Money Train::GetRunningCost() const
3885 Money cost = 0;
3886 const Train *v = this;
3888 do {
3889 const Engine *e = v->GetEngine();
3890 if (e->u.rail.running_cost_class == INVALID_PRICE) continue;
3892 uint cost_factor = GetVehicleProperty(v, PROP_TRAIN_RUNNING_COST_FACTOR, e->u.rail.running_cost);
3893 if (cost_factor == 0) continue;
3895 /* Halve running cost for multiheaded parts */
3896 if (v->IsMultiheaded()) cost_factor /= 2;
3898 cost += GetPrice(e->u.rail.running_cost_class, cost_factor, e->GetGRF());
3899 } while ((v = v->GetNextVehicle()) != nullptr);
3901 return cost;
3905 * Update train vehicle data for a tick.
3906 * @return True if the vehicle still exists, false if it has ceased to exist (front of consists only).
3908 bool Train::Tick()
3910 PerformanceAccumulator framerate(PFE_GL_TRAINS);
3912 this->tick_counter++;
3914 if (this->IsFrontEngine()) {
3915 if (!(this->vehstatus & VS_STOPPED) || this->cur_speed > 0) this->running_ticks++;
3917 this->current_order_time++;
3919 if (!TrainLocoHandler(this, false)) return false;
3921 return TrainLocoHandler(this, true);
3922 } else if (this->IsFreeWagon() && (this->vehstatus & VS_CRASHED)) {
3923 /* Delete flooded standalone wagon chain */
3924 if (++this->crash_anim_pos >= 4400) {
3925 delete this;
3926 return false;
3930 return true;
3934 * Check whether a train needs service, and if so, find a depot or service it.
3935 * @return v %Train to check.
3937 static void CheckIfTrainNeedsService(Train *v)
3939 if (Company::Get(v->owner)->settings.vehicle.servint_trains == 0 || !v->NeedsAutomaticServicing()) return;
3940 if (v->IsChainInDepot()) {
3941 VehicleServiceInDepot(v);
3942 return;
3945 uint max_penalty;
3946 switch (_settings_game.pf.pathfinder_for_trains) {
3947 case VPF_NPF: max_penalty = _settings_game.pf.npf.maximum_go_to_depot_penalty; break;
3948 case VPF_YAPF: max_penalty = _settings_game.pf.yapf.maximum_go_to_depot_penalty; break;
3949 default: NOT_REACHED();
3952 FindDepotData tfdd = FindClosestTrainDepot(v, max_penalty);
3953 /* Only go to the depot if it is not too far out of our way. */
3954 if (tfdd.best_length == UINT_MAX || tfdd.best_length > max_penalty) {
3955 if (v->current_order.IsType(OT_GOTO_DEPOT)) {
3956 /* If we were already heading for a depot but it has
3957 * suddenly moved farther away, we continue our normal
3958 * schedule? */
3959 v->current_order.MakeDummy();
3960 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
3962 return;
3965 DepotID depot = GetDepotIndex(tfdd.tile);
3967 if (v->current_order.IsType(OT_GOTO_DEPOT) &&
3968 v->current_order.GetDestination() != depot &&
3969 !Chance16(3, 16)) {
3970 return;
3973 SetBit(v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS);
3974 v->current_order.MakeGoToDepot(depot, ODTFB_SERVICE);
3975 v->dest_tile = tfdd.tile;
3976 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
3979 /** Update day counters of the train vehicle. */
3980 void Train::OnNewDay()
3982 AgeVehicle(this);
3984 if ((++this->day_counter & 7) == 0) DecreaseVehicleValue(this);
3986 if (this->IsFrontEngine()) {
3987 CheckVehicleBreakdown(this);
3989 CheckIfTrainNeedsService(this);
3991 CheckOrders(this);
3993 /* update destination */
3994 if (this->current_order.IsType(OT_GOTO_STATION)) {
3995 TileIndex tile = Station::Get(this->current_order.GetDestination())->train_station.tile;
3996 if (tile != INVALID_TILE) this->dest_tile = tile;
3999 if (this->running_ticks != 0) {
4000 /* running costs */
4001 CommandCost cost(EXPENSES_TRAIN_RUN, this->GetRunningCost() * this->running_ticks / (DAYS_IN_YEAR * DAY_TICKS));
4003 this->profit_this_year -= cost.GetCost();
4004 this->running_ticks = 0;
4006 SubtractMoneyFromCompanyFract(this->owner, cost);
4008 SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
4009 SetWindowClassesDirty(WC_TRAINS_LIST);
4015 * Get the tracks of the train vehicle.
4016 * @return Current tracks of the vehicle.
4018 Trackdir Train::GetVehicleTrackdir() const
4020 if (this->vehstatus & VS_CRASHED) return INVALID_TRACKDIR;
4022 if (this->track == TRACK_BIT_DEPOT) {
4023 /* We'll assume the train is facing outwards */
4024 return DiagDirToDiagTrackdir(GetRailDepotDirection(this->tile)); // Train in depot
4027 if (this->track == TRACK_BIT_WORMHOLE) {
4028 /* train in tunnel or on bridge, so just use its direction and assume a diagonal track */
4029 return DiagDirToDiagTrackdir(DirToDiagDir(this->direction));
4032 return TrackDirectionToTrackdir(FindFirstTrack(this->track), this->direction);