Rearrange storage of reserved tracks for railway tiles
[openttd/fttd.git] / src / train_cmd.cpp
blob95c719f7c2f892cbd04721d53e07d51620c7bc85
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * 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.
6 * 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.
7 * 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/>.
8 */
10 /** @file train_cmd.cpp Handling of trains. */
12 #include "stdafx.h"
13 #include "error.h"
14 #include "articulated_vehicles.h"
15 #include "command_func.h"
16 #include "pathfinder/yapf/yapf.hpp"
17 #include "news_func.h"
18 #include "company_func.h"
19 #include "newgrf_sound.h"
20 #include "newgrf_text.h"
21 #include "strings_func.h"
22 #include "viewport_func.h"
23 #include "vehicle_func.h"
24 #include "sound_func.h"
25 #include "ai/ai.hpp"
26 #include "game/game.hpp"
27 #include "newgrf_station.h"
28 #include "effectvehicle_func.h"
29 #include "network/network.h"
30 #include "spritecache.h"
31 #include "core/random_func.hpp"
32 #include "company_base.h"
33 #include "newgrf.h"
34 #include "order_backup.h"
35 #include "zoom_func.h"
36 #include "signal_func.h"
37 #include "station_func.h"
38 #include "newgrf_debug.h"
39 #include "date_func.h"
41 #include "table/strings.h"
42 #include "table/train_cmd.h"
44 static bool ChooseTrainTrack(Train *v, RailPathPos origin, TileIndex tile, TrackdirBits trackdirs, bool force_res, Trackdir *best_trackdir = NULL);
45 static bool TryPathReserveFromDepot(Train *v);
46 static bool TrainCheckIfLineEnds(Train *v, bool reverse = true);
47 static StationID TrainEnterTile(Train *v, TileIndex tile, int x, int y);
48 bool TrainController(Train *v, Vehicle *nomove, bool reverse = true); // Also used in vehicle_sl.cpp.
49 static TileIndex TrainApproachingCrossingTile(const Train *v);
50 static void CheckIfTrainNeedsService(Train *v);
51 static void CheckNextTrainTile(Train *v);
53 static const byte _vehicle_initial_x_fract[4] = {10, 8, 4, 8};
54 static const byte _vehicle_initial_y_fract[4] = { 8, 4, 8, 10};
56 template <>
57 bool IsValidImageIndex<VEH_TRAIN>(uint8 image_index)
59 return image_index < lengthof(_engine_sprite_base);
62 /**
63 * Return the cargo weight multiplier to use for a rail vehicle
64 * @param cargo Cargo type to get multiplier for
65 * @return Cargo weight multiplier
67 byte FreightWagonMult(CargoID cargo)
69 if (!CargoSpec::Get(cargo)->is_freight) return 1;
70 return _settings_game.vehicle.freight_trains;
73 /** Checks if lengths of all rail vehicles are valid. If not, shows an error message. */
74 void CheckTrainsLengths()
76 const Train *v;
77 bool first = true;
79 FOR_ALL_TRAINS(v) {
80 if (v->First() == v && !(v->vehstatus & VS_CRASHED)) {
81 for (const Train *u = v, *w = v->Next(); w != NULL; u = w, w = w->Next()) {
82 if (u->trackdir != TRACKDIR_DEPOT) {
83 if ((w->trackdir != TRACKDIR_DEPOT &&
84 max(abs(u->x_pos - w->x_pos), abs(u->y_pos - w->y_pos)) != u->CalcNextVehicleOffset()) ||
85 (w->trackdir == TRACKDIR_DEPOT && TicksToLeaveDepot(u) <= 0)) {
86 SetDParam(0, v->index);
87 SetDParam(1, v->owner);
88 ShowErrorMessage(STR_BROKEN_VEHICLE_LENGTH, INVALID_STRING_ID, WL_CRITICAL);
90 if (!_networking && first) {
91 first = false;
92 DoCommandP(0, PM_PAUSED_ERROR, 1, CMD_PAUSE);
94 /* Break so we warn only once for each train. */
95 break;
104 * Recalculates the cached stuff of a train. Should be called each time a vehicle is added
105 * to/removed from the chain, and when the game is loaded.
106 * Note: this needs to be called too for 'wagon chains' (in the depot, without an engine)
107 * @param same_length should length of vehicles stay the same?
109 void Train::ConsistChanged(bool same_length)
111 uint16 max_speed = UINT16_MAX;
113 assert(this->IsFrontEngine() || this->IsFreeWagon());
115 const RailVehicleInfo *rvi_v = RailVehInfo(this->engine_type);
116 EngineID first_engine = this->IsFrontEngine() ? this->engine_type : INVALID_ENGINE;
117 this->gcache.cached_total_length = 0;
118 this->compatible_railtypes = RAILTYPES_NONE;
120 bool train_can_tilt = true;
122 for (Train *u = this; u != NULL; u = u->Next()) {
123 const RailVehicleInfo *rvi_u = RailVehInfo(u->engine_type);
125 /* Check the this->first cache. */
126 assert(u->First() == this);
128 /* update the 'first engine' */
129 u->gcache.first_engine = this == u ? INVALID_ENGINE : first_engine;
130 u->railtype = rvi_u->railtype;
132 if (u->IsEngine()) first_engine = u->engine_type;
134 /* Set user defined data to its default value */
135 u->tcache.user_def_data = rvi_u->user_def_data;
136 this->InvalidateNewGRFCache();
137 u->InvalidateNewGRFCache();
140 for (Train *u = this; u != NULL; u = u->Next()) {
141 /* Update user defined data (must be done before other properties) */
142 u->tcache.user_def_data = GetVehicleProperty(u, PROP_TRAIN_USER_DATA, u->tcache.user_def_data);
143 this->InvalidateNewGRFCache();
144 u->InvalidateNewGRFCache();
147 for (Train *u = this; u != NULL; u = u->Next()) {
148 const Engine *e_u = u->GetEngine();
149 const RailVehicleInfo *rvi_u = &e_u->u.rail;
151 if (!HasBit(e_u->info.misc_flags, EF_RAIL_TILTS)) train_can_tilt = false;
153 /* Cache wagon override sprite group. NULL is returned if there is none */
154 u->tcache.cached_override = GetWagonOverrideSpriteSet(u->engine_type, u->cargo_type, u->gcache.first_engine);
156 /* Reset colour map */
157 u->colourmap = PAL_NONE;
159 /* Update powered-wagon-status and visual effect */
160 u->UpdateVisualEffect(true);
162 if (rvi_v->pow_wag_power != 0 && rvi_u->railveh_type == RAILVEH_WAGON &&
163 UsesWagonOverride(u) && !HasBit(u->vcache.cached_vis_effect, VE_DISABLE_WAGON_POWER)) {
164 /* wagon is powered */
165 SetBit(u->flags, VRF_POWEREDWAGON); // cache 'powered' status
166 } else {
167 ClrBit(u->flags, VRF_POWEREDWAGON);
170 if (!u->IsArticulatedPart()) {
171 /* Do not count powered wagons for the compatible railtypes, as wagons always
172 have railtype normal */
173 if (rvi_u->power > 0) {
174 this->compatible_railtypes |= GetRailTypeInfo(u->railtype)->powered_railtypes;
177 /* Some electric engines can be allowed to run on normal rail. It happens to all
178 * existing electric engines when elrails are disabled and then re-enabled */
179 if (HasBit(u->flags, VRF_EL_ENGINE_ALLOWED_NORMAL_RAIL)) {
180 u->railtype = RAILTYPE_RAIL;
181 u->compatible_railtypes |= RAILTYPES_RAIL;
184 /* max speed is the minimum of the speed limits of all vehicles in the consist */
185 if ((rvi_u->railveh_type != RAILVEH_WAGON || _settings_game.vehicle.wagon_speed_limits) && !UsesWagonOverride(u)) {
186 uint16 speed = GetVehicleProperty(u, PROP_TRAIN_SPEED, rvi_u->max_speed);
187 if (speed != 0) max_speed = min(speed, max_speed);
191 uint16 new_cap = e_u->DetermineCapacity(u);
192 u->refit_cap = min(new_cap, u->refit_cap);
193 u->cargo_cap = new_cap;
194 u->vcache.cached_cargo_age_period = GetVehicleProperty(u, PROP_TRAIN_CARGO_AGE_PERIOD, e_u->info.cargo_age_period);
196 /* check the vehicle length (callback) */
197 uint16 veh_len = CALLBACK_FAILED;
198 if (e_u->GetGRF() != NULL && e_u->GetGRF()->grf_version >= 8) {
199 /* Use callback 36 */
200 veh_len = GetVehicleProperty(u, PROP_TRAIN_SHORTEN_FACTOR, CALLBACK_FAILED);
202 if (veh_len != CALLBACK_FAILED && veh_len >= VEHICLE_LENGTH) {
203 ErrorUnknownCallbackResult(e_u->GetGRFID(), CBID_VEHICLE_LENGTH, veh_len);
205 } else if (HasBit(e_u->info.callback_mask, CBM_VEHICLE_LENGTH)) {
206 /* Use callback 11 */
207 veh_len = GetVehicleCallback(CBID_VEHICLE_LENGTH, 0, 0, u->engine_type, u);
209 if (veh_len == CALLBACK_FAILED) veh_len = rvi_u->shorten_factor;
210 veh_len = VEHICLE_LENGTH - Clamp(veh_len, 0, VEHICLE_LENGTH - 1);
212 /* verify length hasn't changed */
213 if (same_length && veh_len != u->gcache.cached_veh_length) VehicleLengthChanged(u);
215 /* update vehicle length? */
216 if (!same_length) u->gcache.cached_veh_length = veh_len;
218 this->gcache.cached_total_length += u->gcache.cached_veh_length;
219 this->InvalidateNewGRFCache();
220 u->InvalidateNewGRFCache();
223 /* store consist weight/max speed in cache */
224 this->vcache.cached_max_speed = max_speed;
225 this->tcache.cached_tilt = train_can_tilt;
226 this->tcache.cached_max_curve_speed = this->GetCurveSpeedLimit();
228 /* 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) */
229 this->CargoChanged();
231 if (this->IsFrontEngine()) {
232 this->UpdateAcceleration();
233 SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
234 InvalidateWindowData(WC_VEHICLE_REFIT, this->index, VIWD_CONSIST_CHANGED);
235 InvalidateWindowData(WC_VEHICLE_ORDERS, this->index, VIWD_CONSIST_CHANGED);
236 InvalidateNewGRFInspectWindow(GSF_TRAINS, this->index);
241 * Get the stop location of (the center) of the front vehicle of a train at
242 * a platform of a station.
243 * @param station_id the ID of the station where we're stopping
244 * @param tile the tile where the vehicle currently is
245 * @param v the vehicle to get the stop location of
246 * @param station_ahead 'return' the amount of 1/16th tiles in front of the train
247 * @param station_length 'return' the station length in 1/16th tiles
248 * @return the location, calculated from the begin of the station to stop at.
250 int GetTrainStopLocation(StationID station_id, TileIndex tile, const Train *v, int *station_ahead, int *station_length)
252 const Station *st = Station::Get(station_id);
253 *station_ahead = st->GetPlatformLength(tile, DirToDiagDir(v->direction)) * TILE_SIZE;
254 *station_length = st->GetPlatformLength(tile) * TILE_SIZE;
256 /* Default to the middle of the station for stations stops that are not in
257 * the order list like intermediate stations when non-stop is disabled */
258 OrderStopLocation osl = OSL_PLATFORM_MIDDLE;
259 if (v->gcache.cached_total_length >= *station_length) {
260 /* The train is longer than the station, make it stop at the far end of the platform */
261 osl = OSL_PLATFORM_FAR_END;
262 } else if (v->current_order.IsType(OT_GOTO_STATION) && v->current_order.GetDestination() == station_id) {
263 osl = v->current_order.GetStopLocation();
266 /* The stop location of the FRONT! of the train */
267 int stop;
268 switch (osl) {
269 default: NOT_REACHED();
271 case OSL_PLATFORM_NEAR_END:
272 stop = v->gcache.cached_total_length;
273 break;
275 case OSL_PLATFORM_MIDDLE:
276 stop = *station_length - (*station_length - v->gcache.cached_total_length) / 2;
277 break;
279 case OSL_PLATFORM_FAR_END:
280 stop = *station_length;
281 break;
284 /* Subtract half the front vehicle length of the train so we get the real
285 * stop location of the train. */
286 return stop - (v->gcache.cached_veh_length + 1) / 2;
291 * Computes train speed limit caused by curves
292 * @return imposed speed limit
294 int Train::GetCurveSpeedLimit() const
296 assert(this->First() == this);
298 static const int absolute_max_speed = UINT16_MAX;
299 int max_speed = absolute_max_speed;
301 if (_settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) return max_speed;
303 int curvecount[2] = {0, 0};
305 /* first find the curve speed limit */
306 int numcurve = 0;
307 int sum = 0;
308 int pos = 0;
309 int lastpos = -1;
310 for (const Vehicle *u = this; u->Next() != NULL; u = u->Next(), pos++) {
311 Direction this_dir = u->direction;
312 Direction next_dir = u->Next()->direction;
314 DirDiff dirdiff = DirDifference(this_dir, next_dir);
315 if (dirdiff == DIRDIFF_SAME) continue;
317 if (dirdiff == DIRDIFF_45LEFT) curvecount[0]++;
318 if (dirdiff == DIRDIFF_45RIGHT) curvecount[1]++;
319 if (dirdiff == DIRDIFF_45LEFT || dirdiff == DIRDIFF_45RIGHT) {
320 if (lastpos != -1) {
321 numcurve++;
322 sum += pos - lastpos;
323 if (pos - lastpos == 1 && max_speed > 88) {
324 max_speed = 88;
327 lastpos = pos;
330 /* if we have a 90 degree turn, fix the speed limit to 60 */
331 if (dirdiff == DIRDIFF_90LEFT || dirdiff == DIRDIFF_90RIGHT) {
332 max_speed = 61;
336 if (numcurve > 0 && max_speed > 88) {
337 if (curvecount[0] == 1 && curvecount[1] == 1) {
338 max_speed = absolute_max_speed;
339 } else {
340 sum /= numcurve;
341 max_speed = 232 - (13 - Clamp(sum, 1, 12)) * (13 - Clamp(sum, 1, 12));
345 if (max_speed != absolute_max_speed) {
346 /* Apply the engine's rail type curve speed advantage, if it slowed by curves */
347 const RailtypeInfo *rti = GetRailTypeInfo(this->railtype);
348 max_speed += (max_speed / 2) * rti->curve_speed;
350 if (this->tcache.cached_tilt) {
351 /* Apply max_speed bonus of 20% for a tilting train */
352 max_speed += max_speed / 5;
356 return max_speed;
359 static uint FindTunnelPrevTrain(const Train *t, Vehicle **vv = NULL)
361 assert(maptile_is_rail_tunnel(t->tile));
362 assert(t->trackdir == TRACKDIR_WORMHOLE);
364 VehicleTileIterator iter (t->tile);
365 Vehicle *closest = NULL;
366 uint dist;
368 switch (GetTunnelBridgeDirection(t->tile)) {
369 default: NOT_REACHED();
371 case DIAGDIR_NE:
372 while (!iter.finished()) {
373 Vehicle *v = iter.next();
374 int pos = v->x_pos;
375 if (pos <= t->x_pos) continue; // v is behind
376 if (closest == NULL || pos < closest->x_pos) {
377 closest = v;
378 } else {
379 assert (pos != closest->x_pos);
382 dist = closest == NULL ? UINT_MAX : closest->x_pos - t->x_pos;
383 break;
385 case DIAGDIR_NW:
386 while (!iter.finished()) {
387 Vehicle *v = iter.next();
388 int pos = v->y_pos;
389 if (pos <= t->y_pos) continue; // v is behind
390 if (closest == NULL || pos < closest->y_pos) {
391 closest = v;
392 } else {
393 assert (pos != closest->y_pos);
396 dist = closest == NULL ? UINT_MAX : closest->y_pos - t->y_pos;
397 break;
399 case DIAGDIR_SW:
400 while (!iter.finished()) {
401 Vehicle *v = iter.next();
402 int pos = v->x_pos;
403 if (pos >= t->x_pos) continue; // v is behind
404 if (closest == NULL || pos > closest->x_pos) {
405 closest = v;
406 } else {
407 assert (pos != closest->x_pos);
410 dist = closest == NULL ? UINT_MAX : t->x_pos - closest->x_pos;
411 break;
413 case DIAGDIR_SE:
414 while (!iter.finished()) {
415 Vehicle *v = iter.next();
416 int pos = v->y_pos;
417 if (pos >= t->y_pos) continue; // v is behind
418 if (closest == NULL || pos > closest->y_pos) {
419 closest = v;
420 } else {
421 assert (pos != closest->y_pos);
424 dist = closest == NULL ? UINT_MAX : t->y_pos - closest->y_pos;
425 break;
428 if (vv != NULL) *vv = closest;
430 return dist;
434 * Calculates the maximum speed of the vehicle under its current conditions.
435 * @return Maximum speed of the vehicle.
437 int Train::GetCurrentMaxSpeed() const
439 int max_speed = _settings_game.vehicle.train_acceleration_model == AM_ORIGINAL ?
440 this->gcache.cached_max_track_speed :
441 this->tcache.cached_max_curve_speed;
443 if (_settings_game.vehicle.train_acceleration_model == AM_REALISTIC && IsRailStationTile(this->tile)) {
444 StationID sid = GetStationIndex(this->tile);
445 if (this->current_order.ShouldStopAtStation(this, sid)) {
446 int station_ahead;
447 int station_length;
448 int stop_at = GetTrainStopLocation(sid, this->tile, this, &station_ahead, &station_length);
450 /* The distance to go is whatever is still ahead of the train minus the
451 * distance from the train's stop location to the end of the platform */
452 int distance_to_go = station_ahead / TILE_SIZE - (station_length - stop_at) / TILE_SIZE;
454 if (distance_to_go > 0) {
455 int st_max_speed = 120;
457 int delta_v = this->cur_speed / (distance_to_go + 1);
458 if (max_speed > (this->cur_speed - delta_v)) {
459 st_max_speed = this->cur_speed - (delta_v / 10);
462 st_max_speed = max(st_max_speed, 25 * distance_to_go);
463 max_speed = min(max_speed, st_max_speed);
468 for (const Train *u = this; u != NULL; u = u->Next()) {
469 if (_settings_game.vehicle.train_acceleration_model == AM_REALISTIC && u->trackdir == TRACKDIR_DEPOT) {
470 max_speed = min(max_speed, 61);
471 break;
474 /* Vehicle is on the middle part of a bridge. */
475 if (u->trackdir == TRACKDIR_WORMHOLE && !(u->vehstatus & VS_HIDDEN)) {
476 max_speed = min(max_speed, GetBridgeSpec(GetRailBridgeType(u->tile))->speed);
480 if (this->trackdir == TRACKDIR_WORMHOLE && (this->vehstatus & VS_HIDDEN) && maptile_has_tunnel_signal(this->tile, false)) {
481 Vehicle *v;
482 uint dist = FindTunnelPrevTrain(this, &v);
484 if (dist <= TILE_SIZE) {
485 max_speed = 0;
486 } else if (v != NULL) {
487 max_speed = min(max_speed, (dist - TILE_SIZE) * this->GetAdvanceDistance() / 2);
488 if (dist < 2 * TILE_SIZE) max_speed = min(max_speed, v->cur_speed);
492 max_speed = min(max_speed, this->current_order.max_speed);
493 return min(max_speed, this->gcache.cached_max_track_speed);
496 /** Update acceleration of the train from the cached power and weight. */
497 void Train::UpdateAcceleration()
499 assert(this->IsFrontEngine() || this->IsFreeWagon());
501 uint power = this->gcache.cached_power;
502 uint weight = this->gcache.cached_weight;
503 assert(weight != 0);
504 this->acceleration = Clamp(power / weight * 4, 1, 255);
508 * Get the width of a train vehicle image in the GUI.
509 * @param offset Additional offset for positioning the sprite; set to NULL if not needed
510 * @return Width in pixels
512 int Train::GetDisplayImageWidth(Point *offset) const
514 int reference_width = TRAININFO_DEFAULT_VEHICLE_WIDTH;
515 int vehicle_pitch = 0;
517 const Engine *e = this->GetEngine();
518 if (e->GetGRF() != NULL && is_custom_sprite(e->u.rail.image_index)) {
519 reference_width = e->GetGRF()->traininfo_vehicle_width;
520 vehicle_pitch = e->GetGRF()->traininfo_vehicle_pitch;
523 if (offset != NULL) {
524 offset->x = reference_width / 2;
525 offset->y = vehicle_pitch;
527 return this->gcache.cached_veh_length * reference_width / VEHICLE_LENGTH;
530 static SpriteID GetDefaultTrainSprite(uint8 spritenum, Direction direction)
532 assert(IsValidImageIndex<VEH_TRAIN>(spritenum));
533 return ((direction + _engine_sprite_add[spritenum]) & _engine_sprite_and[spritenum]) + _engine_sprite_base[spritenum];
537 * Get the sprite to display the train.
538 * @param direction Direction of view/travel.
539 * @param image_type Visualisation context.
540 * @return Sprite to display.
542 SpriteID Train::GetImage(Direction direction, EngineImageType image_type) const
544 uint8 spritenum = this->spritenum;
545 SpriteID sprite;
547 if (HasBit(this->flags, VRF_REVERSE_DIRECTION)) direction = ReverseDir(direction);
549 if (is_custom_sprite(spritenum)) {
550 sprite = GetCustomVehicleSprite(this, (Direction)(direction + 4 * IS_CUSTOM_SECONDHEAD_SPRITE(spritenum)), image_type);
551 if (sprite != 0) return sprite;
553 spritenum = this->GetEngine()->original_image_index;
556 assert(IsValidImageIndex<VEH_TRAIN>(spritenum));
557 sprite = GetDefaultTrainSprite(spritenum, direction);
559 if (this->cargo.StoredCount() >= this->cargo_cap / 2U) sprite += _wagon_full_adder[spritenum];
561 return sprite;
564 static SpriteID GetRailIcon(EngineID engine, bool rear_head, int &y, EngineImageType image_type)
566 const Engine *e = Engine::Get(engine);
567 Direction dir = rear_head ? DIR_E : DIR_W;
568 uint8 spritenum = e->u.rail.image_index;
570 if (is_custom_sprite(spritenum)) {
571 SpriteID sprite = GetCustomVehicleIcon(engine, dir, image_type);
572 if (sprite != 0) {
573 if (e->GetGRF() != NULL) {
574 y += e->GetGRF()->traininfo_vehicle_pitch;
576 return sprite;
579 spritenum = Engine::Get(engine)->original_image_index;
582 if (rear_head) spritenum++;
584 return GetDefaultTrainSprite(spritenum, DIR_W);
587 void DrawTrainEngine(int left, int right, int preferred_x, int y, EngineID engine, PaletteID pal, EngineImageType image_type)
589 if (RailVehInfo(engine)->railveh_type == RAILVEH_MULTIHEAD) {
590 int yf = y;
591 int yr = y;
593 SpriteID spritef = GetRailIcon(engine, false, yf, image_type);
594 SpriteID spriter = GetRailIcon(engine, true, yr, image_type);
595 const Sprite *real_spritef = GetSprite(spritef, ST_NORMAL);
596 const Sprite *real_spriter = GetSprite(spriter, ST_NORMAL);
598 preferred_x = Clamp(preferred_x, left - UnScaleByZoom(real_spritef->x_offs, ZOOM_LVL_GUI) + 14, right - UnScaleByZoom(real_spriter->width, ZOOM_LVL_GUI) - UnScaleByZoom(real_spriter->x_offs, ZOOM_LVL_GUI) - 15);
600 DrawSprite(spritef, pal, preferred_x - 14, yf);
601 DrawSprite(spriter, pal, preferred_x + 15, yr);
602 } else {
603 SpriteID sprite = GetRailIcon(engine, false, y, image_type);
604 const Sprite *real_sprite = GetSprite(sprite, ST_NORMAL);
605 preferred_x = Clamp(preferred_x, left - UnScaleByZoom(real_sprite->x_offs, ZOOM_LVL_GUI), right - UnScaleByZoom(real_sprite->width, ZOOM_LVL_GUI) - UnScaleByZoom(real_sprite->x_offs, ZOOM_LVL_GUI));
606 DrawSprite(sprite, pal, preferred_x, y);
611 * Get the size of the sprite of a train sprite heading west, or both heads (used for lists).
612 * @param engine The engine to get the sprite from.
613 * @param[out] width The width of the sprite.
614 * @param[out] height The height of the sprite.
615 * @param[out] xoffs Number of pixels to shift the sprite to the right.
616 * @param[out] yoffs Number of pixels to shift the sprite downwards.
617 * @param image_type Context the sprite is used in.
619 void GetTrainSpriteSize(EngineID engine, uint &width, uint &height, int &xoffs, int &yoffs, EngineImageType image_type)
621 int y = 0;
623 SpriteID sprite = GetRailIcon(engine, false, y, image_type);
624 const Sprite *real_sprite = GetSprite(sprite, ST_NORMAL);
626 width = UnScaleByZoom(real_sprite->width, ZOOM_LVL_GUI);
627 height = UnScaleByZoom(real_sprite->height, ZOOM_LVL_GUI);
628 xoffs = UnScaleByZoom(real_sprite->x_offs, ZOOM_LVL_GUI);
629 yoffs = UnScaleByZoom(real_sprite->y_offs, ZOOM_LVL_GUI);
631 if (RailVehInfo(engine)->railveh_type == RAILVEH_MULTIHEAD) {
632 sprite = GetRailIcon(engine, true, y, image_type);
633 real_sprite = GetSprite(sprite, ST_NORMAL);
635 /* Calculate values relative to an imaginary center between the two sprites. */
636 width = TRAININFO_DEFAULT_VEHICLE_WIDTH + UnScaleByZoom(real_sprite->width, ZOOM_LVL_GUI) + UnScaleByZoom(real_sprite->x_offs, ZOOM_LVL_GUI) - xoffs;
637 height = max<uint>(height, UnScaleByZoom(real_sprite->height, ZOOM_LVL_GUI));
638 xoffs = xoffs - TRAININFO_DEFAULT_VEHICLE_WIDTH / 2;
639 yoffs = min(yoffs, UnScaleByZoom(real_sprite->y_offs, ZOOM_LVL_GUI));
644 * Build a railroad wagon.
645 * @param tile tile of the depot where rail-vehicle is built.
646 * @param flags type of operation.
647 * @param e the engine to build.
648 * @param ret[out] the vehicle that has been built.
649 * @return the cost of this operation or an error.
651 static CommandCost CmdBuildRailWagon(TileIndex tile, DoCommandFlag flags, const Engine *e, Vehicle **ret)
653 const RailVehicleInfo *rvi = &e->u.rail;
655 /* Check that the wagon can drive on the track in question */
656 if (!IsCompatibleRail(rvi->railtype, GetRailType(tile))) return CMD_ERROR;
658 if (flags & DC_EXEC) {
659 Train *v = new Train();
660 *ret = v;
661 v->spritenum = rvi->image_index;
663 v->engine_type = e->index;
664 v->gcache.first_engine = INVALID_ENGINE; // needs to be set before first callback
666 DiagDirection dir = GetGroundDepotDirection(tile);
668 v->direction = DiagDirToDir(dir);
669 v->tile = tile;
671 int x = TileX(tile) * TILE_SIZE | _vehicle_initial_x_fract[dir];
672 int y = TileY(tile) * TILE_SIZE | _vehicle_initial_y_fract[dir];
674 v->x_pos = x;
675 v->y_pos = y;
676 v->z_pos = GetSlopePixelZ(x, y);
677 v->owner = _current_company;
678 v->trackdir = TRACKDIR_DEPOT;
679 v->vehstatus = VS_HIDDEN | VS_DEFPAL;
681 v->SetWagon();
683 v->SetFreeWagon();
684 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
686 v->cargo_type = e->GetDefaultCargoType();
687 v->cargo_cap = rvi->capacity;
688 v->refit_cap = 0;
690 v->railtype = rvi->railtype;
692 v->build_year = _cur_year;
693 v->cur_image = SPR_IMG_QUERY;
694 v->random_bits = VehicleRandomBits();
696 v->group_id = DEFAULT_GROUP;
698 AddArticulatedParts(v);
700 _new_vehicle_id = v->index;
702 VehicleUpdatePosition(v);
703 v->First()->ConsistChanged(false);
704 UpdateTrainGroupID(v->First());
706 CheckConsistencyOfArticulatedVehicle(v);
708 /* Try to connect the vehicle to one of free chains of wagons. */
709 Train *w;
710 FOR_ALL_TRAINS(w) {
711 if (w->tile == tile && ///< Same depot
712 w->IsFreeWagon() && ///< A free wagon chain
713 w->engine_type == e->index && ///< Same type
714 w->First() != v && ///< Don't connect to ourself
715 !(w->vehstatus & VS_CRASHED)) { ///< Not crashed/flooded
716 DoCommand(0, v->index | 1 << 20, w->Last()->index, DC_EXEC, CMD_MOVE_RAIL_VEHICLE);
717 break;
722 return CommandCost();
725 /** Move all free vehicles in the depot to the train */
726 static void NormalizeTrainVehInDepot(const Train *u)
728 const Train *v;
729 FOR_ALL_TRAINS(v) {
730 if (v->IsFreeWagon() && v->tile == u->tile &&
731 v->trackdir == TRACKDIR_DEPOT) {
732 if (DoCommand(0, v->index | 1 << 20, u->index, DC_EXEC,
733 CMD_MOVE_RAIL_VEHICLE).Failed())
734 break;
739 static void AddRearEngineToMultiheadedTrain(Train *v)
741 Train *u = new Train();
742 v->value >>= 1;
743 u->value = v->value;
744 u->direction = v->direction;
745 u->owner = v->owner;
746 u->tile = v->tile;
747 u->x_pos = v->x_pos;
748 u->y_pos = v->y_pos;
749 u->z_pos = v->z_pos;
750 u->trackdir = TRACKDIR_DEPOT;
751 u->vehstatus = v->vehstatus & ~VS_STOPPED;
752 u->spritenum = v->spritenum + 1;
753 u->cargo_type = v->cargo_type;
754 u->cargo_subtype = v->cargo_subtype;
755 u->cargo_cap = v->cargo_cap;
756 u->refit_cap = v->refit_cap;
757 u->railtype = v->railtype;
758 u->engine_type = v->engine_type;
759 u->build_year = v->build_year;
760 u->cur_image = SPR_IMG_QUERY;
761 u->random_bits = VehicleRandomBits();
762 v->SetMultiheaded();
763 u->SetMultiheaded();
764 v->SetNext(u);
765 VehicleUpdatePosition(u);
767 /* Now we need to link the front and rear engines together */
768 v->other_multiheaded_part = u;
769 u->other_multiheaded_part = v;
773 * Build a railroad vehicle.
774 * @param tile tile of the depot where rail-vehicle is built.
775 * @param flags type of operation.
776 * @param e the engine to build.
777 * @param data bit 0 prevents any free cars from being added to the train.
778 * @param ret[out] the vehicle that has been built.
779 * @return the cost of this operation or an error.
781 CommandCost CmdBuildRailVehicle(TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **ret)
783 const RailVehicleInfo *rvi = &e->u.rail;
785 if (rvi->railveh_type == RAILVEH_WAGON) return CmdBuildRailWagon(tile, flags, e, ret);
787 /* Check if depot and new engine uses the same kind of tracks *
788 * We need to see if the engine got power on the tile to avoid electric engines in non-electric depots */
789 if (!HasPowerOnRail(rvi->railtype, GetRailType(tile))) return CMD_ERROR;
791 if (flags & DC_EXEC) {
792 DiagDirection dir = GetGroundDepotDirection(tile);
793 int x = TileX(tile) * TILE_SIZE + _vehicle_initial_x_fract[dir];
794 int y = TileY(tile) * TILE_SIZE + _vehicle_initial_y_fract[dir];
796 Train *v = new Train();
797 *ret = v;
798 v->direction = DiagDirToDir(dir);
799 v->tile = tile;
800 v->owner = _current_company;
801 v->x_pos = x;
802 v->y_pos = y;
803 v->z_pos = GetSlopePixelZ(x, y);
804 v->trackdir = TRACKDIR_DEPOT;
805 v->vehstatus = VS_HIDDEN | VS_STOPPED | VS_DEFPAL;
806 v->spritenum = rvi->image_index;
807 v->cargo_type = e->GetDefaultCargoType();
808 v->cargo_cap = rvi->capacity;
809 v->refit_cap = 0;
810 v->last_station_visited = INVALID_STATION;
811 v->last_loading_station = INVALID_STATION;
813 v->engine_type = e->index;
814 v->gcache.first_engine = INVALID_ENGINE; // needs to be set before first callback
816 v->reliability = e->reliability;
817 v->reliability_spd_dec = e->reliability_spd_dec;
818 v->max_age = e->GetLifeLengthInDays();
820 v->railtype = rvi->railtype;
821 _new_vehicle_id = v->index;
823 v->SetServiceInterval(Company::Get(_current_company)->settings.vehicle.servint_trains);
824 v->date_of_last_service = _date;
825 v->build_year = _cur_year;
826 v->cur_image = SPR_IMG_QUERY;
827 v->random_bits = VehicleRandomBits();
829 if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) SetBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE);
830 v->SetServiceIntervalIsPercent(Company::Get(_current_company)->settings.vehicle.servint_ispercent);
832 v->group_id = DEFAULT_GROUP;
834 v->SetFrontEngine();
835 v->SetEngine();
837 VehicleUpdatePosition(v);
839 if (rvi->railveh_type == RAILVEH_MULTIHEAD) {
840 AddRearEngineToMultiheadedTrain(v);
841 } else {
842 AddArticulatedParts(v);
845 v->ConsistChanged(false);
846 UpdateTrainGroupID(v);
848 if (!HasBit(data, 0) && !(flags & DC_AUTOREPLACE)) { // check if the cars should be added to the new vehicle
849 NormalizeTrainVehInDepot(v);
852 CheckConsistencyOfArticulatedVehicle(v);
855 return CommandCost();
858 static Train *FindGoodVehiclePos(const Train *src)
860 EngineID eng = src->engine_type;
861 TileIndex tile = src->tile;
863 Train *dst;
864 FOR_ALL_TRAINS(dst) {
865 if (dst->IsFreeWagon() && dst->tile == tile && !(dst->vehstatus & VS_CRASHED)) {
866 /* check so all vehicles in the line have the same engine. */
867 Train *t = dst;
868 while (t->engine_type == eng) {
869 t = t->Next();
870 if (t == NULL) return dst;
875 return NULL;
878 /** Helper type for lists/vectors of trains */
879 typedef SmallVector<Train *, 16> TrainList;
882 * Make a backup of a train into a train list.
883 * @param list to make the backup in
884 * @param t the train to make the backup of
886 static void MakeTrainBackup(TrainList &list, Train *t)
888 for (; t != NULL; t = t->Next()) *list.Append() = t;
892 * Restore the train from the backup list.
893 * @param list the train to restore.
895 static void RestoreTrainBackup(TrainList &list)
897 /* No train, nothing to do. */
898 if (list.Length() == 0) return;
900 Train *prev = NULL;
901 /* Iterate over the list and rebuild it. */
902 for (Train **iter = list.Begin(); iter != list.End(); iter++) {
903 Train *t = *iter;
904 if (prev != NULL) {
905 prev->SetNext(t);
906 } else if (t->Previous() != NULL) {
907 /* Make sure the head of the train is always the first in the chain. */
908 t->Previous()->SetNext(NULL);
910 prev = t;
915 * Remove the given wagon from its consist.
916 * @param part the part of the train to remove.
917 * @param chain whether to remove the whole chain.
919 static void RemoveFromConsist(Train *part, bool chain = false)
921 Train *tail = chain ? part->Last() : part->GetLastEnginePart();
923 /* Unlink at the front, but make it point to the next
924 * vehicle after the to be remove part. */
925 if (part->Previous() != NULL) part->Previous()->SetNext(tail->Next());
927 /* Unlink at the back */
928 tail->SetNext(NULL);
932 * Inserts a chain into the train at dst.
933 * @param dst the place where to append after.
934 * @param chain the chain to actually add.
936 static void InsertInConsist(Train *dst, Train *chain)
938 /* We do not want to add something in the middle of an articulated part. */
939 assert(dst->Next() == NULL || !dst->Next()->IsArticulatedPart());
941 chain->Last()->SetNext(dst->Next());
942 dst->SetNext(chain);
946 * Normalise the dual heads in the train, i.e. if one is
947 * missing move that one to this train.
948 * @param t the train to normalise.
950 static void NormaliseDualHeads(Train *t)
952 for (; t != NULL; t = t->GetNextVehicle()) {
953 if (!t->IsMultiheaded() || !t->IsEngine()) continue;
955 /* Make sure that there are no free cars before next engine */
956 Train *u;
957 for (u = t; u->Next() != NULL && !u->Next()->IsEngine(); u = u->Next()) {}
959 if (u == t->other_multiheaded_part) continue;
961 /* Remove the part from the 'wrong' train */
962 RemoveFromConsist(t->other_multiheaded_part);
963 /* And add it to the 'right' train */
964 InsertInConsist(u, t->other_multiheaded_part);
969 * Normalise the sub types of the parts in this chain.
970 * @param chain the chain to normalise.
972 static void NormaliseSubtypes(Train *chain)
974 /* Nothing to do */
975 if (chain == NULL) return;
977 /* We must be the first in the chain. */
978 assert(chain->Previous() == NULL);
980 /* Set the appropriate bits for the first in the chain. */
981 if (chain->IsWagon()) {
982 chain->SetFreeWagon();
983 } else {
984 assert(chain->IsEngine());
985 chain->SetFrontEngine();
988 /* Now clear the bits for the rest of the chain */
989 for (Train *t = chain->Next(); t != NULL; t = t->Next()) {
990 t->ClearFreeWagon();
991 t->ClearFrontEngine();
996 * Check/validate whether we may actually build a new train.
997 * @note All vehicles are/were 'heads' of their chains.
998 * @param original_dst The original destination chain.
999 * @param dst The destination chain after constructing the train.
1000 * @param original_dst The original source chain.
1001 * @param dst The source chain after constructing the train.
1002 * @return possible error of this command.
1004 static CommandCost CheckNewTrain(Train *original_dst, Train *dst, Train *original_src, Train *src)
1006 /* Just add 'new' engines and subtract the original ones.
1007 * If that's less than or equal to 0 we can be sure we did
1008 * not add any engines (read: trains) along the way. */
1009 if ((src != NULL && src->IsEngine() ? 1 : 0) +
1010 (dst != NULL && dst->IsEngine() ? 1 : 0) -
1011 (original_src != NULL && original_src->IsEngine() ? 1 : 0) -
1012 (original_dst != NULL && original_dst->IsEngine() ? 1 : 0) <= 0) {
1013 return CommandCost();
1016 /* Get a free unit number and check whether it's within the bounds.
1017 * There will always be a maximum of one new train. */
1018 if (GetFreeUnitNumber(VEH_TRAIN) <= _settings_game.vehicle.max_trains) return CommandCost();
1020 return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
1024 * Check whether the train parts can be attached.
1025 * @param t the train to check
1026 * @return possible error of this command.
1028 static CommandCost CheckTrainAttachment(Train *t)
1030 /* No multi-part train, no need to check. */
1031 if (t == NULL || t->Next() == NULL || !t->IsEngine()) return CommandCost();
1033 /* The maximum length for a train. For each part we decrease this by one
1034 * and if the result is negative the train is simply too long. */
1035 int allowed_len = _settings_game.vehicle.max_train_length * TILE_SIZE - t->gcache.cached_veh_length;
1037 Train *head = t;
1038 Train *prev = t;
1040 /* Break the prev -> t link so it always holds within the loop. */
1041 t = t->Next();
1042 prev->SetNext(NULL);
1044 /* Make sure the cache is cleared. */
1045 head->InvalidateNewGRFCache();
1047 while (t != NULL) {
1048 allowed_len -= t->gcache.cached_veh_length;
1050 Train *next = t->Next();
1052 /* Unlink the to-be-added piece; it is already unlinked from the previous
1053 * part due to the fact that the prev -> t link is broken. */
1054 t->SetNext(NULL);
1056 /* Don't check callback for articulated or rear dual headed parts */
1057 if (!t->IsArticulatedPart() && !t->IsRearDualheaded()) {
1058 /* Back up and clear the first_engine data to avoid using wagon override group */
1059 EngineID first_engine = t->gcache.first_engine;
1060 t->gcache.first_engine = INVALID_ENGINE;
1062 /* We don't want the cache to interfere. head's cache is cleared before
1063 * the loop and after each callback does not need to be cleared here. */
1064 t->InvalidateNewGRFCache();
1066 uint16 callback = GetVehicleCallbackParent(CBID_TRAIN_ALLOW_WAGON_ATTACH, 0, 0, head->engine_type, t, head);
1068 /* Restore original first_engine data */
1069 t->gcache.first_engine = first_engine;
1071 /* We do not want to remember any cached variables from the test run */
1072 t->InvalidateNewGRFCache();
1073 head->InvalidateNewGRFCache();
1075 if (callback != CALLBACK_FAILED) {
1076 /* A failing callback means everything is okay */
1077 StringID error = STR_NULL;
1079 if (head->GetGRF()->grf_version < 8) {
1080 if (callback == 0xFD) error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
1081 if (callback < 0xFD) error = GetGRFStringID(head->GetGRFID(), 0xD000 + callback);
1082 if (callback >= 0x100) ErrorUnknownCallbackResult(head->GetGRFID(), CBID_TRAIN_ALLOW_WAGON_ATTACH, callback);
1083 } else {
1084 if (callback < 0x400) {
1085 error = GetGRFStringID(head->GetGRFID(), 0xD000 + callback);
1086 } else {
1087 switch (callback) {
1088 case 0x400: // allow if railtypes match (always the case for OpenTTD)
1089 case 0x401: // allow
1090 break;
1092 default: // unknown reason -> disallow
1093 case 0x402: // disallow attaching
1094 error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
1095 break;
1100 if (error != STR_NULL) return_cmd_error(error);
1104 /* And link it to the new part. */
1105 prev->SetNext(t);
1106 prev = t;
1107 t = next;
1110 if (allowed_len < 0) return_cmd_error(STR_ERROR_TRAIN_TOO_LONG);
1111 return CommandCost();
1115 * Validate whether we are going to create valid trains.
1116 * @note All vehicles are/were 'heads' of their chains.
1117 * @param original_dst The original destination chain.
1118 * @param dst The destination chain after constructing the train.
1119 * @param original_dst The original source chain.
1120 * @param dst The source chain after constructing the train.
1121 * @param check_limit Whether to check the vehicle limit.
1122 * @return possible error of this command.
1124 static CommandCost ValidateTrains(Train *original_dst, Train *dst, Train *original_src, Train *src, bool check_limit)
1126 /* Check whether we may actually construct the trains. */
1127 CommandCost ret = CheckTrainAttachment(src);
1128 if (ret.Failed()) return ret;
1129 ret = CheckTrainAttachment(dst);
1130 if (ret.Failed()) return ret;
1132 /* Check whether we need to build a new train. */
1133 return check_limit ? CheckNewTrain(original_dst, dst, original_src, src) : CommandCost();
1137 * Arrange the trains in the wanted way.
1138 * @param dst_head The destination chain of the to be moved vehicle.
1139 * @param dst The destination for the to be moved vehicle.
1140 * @param src_head The source chain of the to be moved vehicle.
1141 * @param src The to be moved vehicle.
1142 * @param move_chain Whether to move all vehicles after src or not.
1144 static void ArrangeTrains(Train **dst_head, Train *dst, Train **src_head, Train *src, bool move_chain)
1146 /* First determine the front of the two resulting trains */
1147 if (*src_head == *dst_head) {
1148 /* If we aren't moving part(s) to a new train, we are just moving the
1149 * front back and there is not destination head. */
1150 *dst_head = NULL;
1151 } else if (*dst_head == NULL) {
1152 /* If we are moving to a new train the head of the move train would become
1153 * the head of the new vehicle. */
1154 *dst_head = src;
1157 if (src == *src_head) {
1158 /* If we are moving the front of a train then we are, in effect, creating
1159 * a new head for the train. Point to that. Unless we are moving the whole
1160 * train in which case there is not 'source' train anymore.
1161 * In case we are a multiheaded part we want the complete thing to come
1162 * with us, so src->GetNextUnit(), however... when we are e.g. a wagon
1163 * that is followed by a rear multihead we do not want to include that. */
1164 *src_head = move_chain ? NULL :
1165 (src->IsMultiheaded() ? src->GetNextUnit() : src->GetNextVehicle());
1168 /* Now it's just simply removing the part that we are going to move from the
1169 * source train and *if* the destination is a not a new train add the chain
1170 * at the destination location. */
1171 RemoveFromConsist(src, move_chain);
1172 if (*dst_head != src) InsertInConsist(dst, src);
1174 /* Now normalise the dual heads, that is move the dual heads around in such
1175 * a way that the head and rear of a dual head are in the same train */
1176 NormaliseDualHeads(*src_head);
1177 NormaliseDualHeads(*dst_head);
1181 * Normalise the head of the train again, i.e. that is tell the world that
1182 * we have changed and update all kinds of variables.
1183 * @param head the train to update.
1185 static void NormaliseTrainHead(Train *head)
1187 /* Not much to do! */
1188 if (head == NULL) return;
1190 /* Tell the 'world' the train changed. */
1191 head->ConsistChanged(false);
1192 UpdateTrainGroupID(head);
1194 /* Not a front engine, i.e. a free wagon chain. No need to do more. */
1195 if (!head->IsFrontEngine()) return;
1197 /* Update the refit button and window */
1198 InvalidateWindowData(WC_VEHICLE_REFIT, head->index, VIWD_CONSIST_CHANGED);
1199 SetWindowWidgetDirty(WC_VEHICLE_VIEW, head->index, WID_VV_REFIT);
1201 /* If we don't have a unit number yet, set one. */
1202 if (head->unitnumber != 0) return;
1203 head->unitnumber = GetFreeUnitNumber(VEH_TRAIN);
1207 * Move a rail vehicle around inside the depot.
1208 * @param tile unused
1209 * @param flags type of operation
1210 * Note: DC_AUTOREPLACE is set when autoreplace tries to undo its modifications or moves vehicles to temporary locations inside the depot.
1211 * @param p1 various bitstuffed elements
1212 * - p1 (bit 0 - 19) source vehicle index
1213 * - p1 (bit 20) move all vehicles following the source vehicle
1214 * @param p2 what wagon to put the source wagon AFTER, XXX - INVALID_VEHICLE to make a new line
1215 * @param text unused
1216 * @return the cost of this operation or an error
1218 CommandCost CmdMoveRailVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1220 VehicleID s = GB(p1, 0, 20);
1221 VehicleID d = GB(p2, 0, 20);
1222 bool move_chain = HasBit(p1, 20);
1224 Train *src = Train::GetIfValid(s);
1225 if (src == NULL) return CMD_ERROR;
1227 CommandCost ret = CheckOwnership(src->owner);
1228 if (ret.Failed()) return ret;
1230 /* Do not allow moving crashed vehicles inside the depot, it is likely to cause asserts later */
1231 if (src->vehstatus & VS_CRASHED) return CMD_ERROR;
1233 /* if nothing is selected as destination, try and find a matching vehicle to drag to. */
1234 Train *dst;
1235 if (d == INVALID_VEHICLE) {
1236 dst = src->IsEngine() ? NULL : FindGoodVehiclePos(src);
1237 } else {
1238 dst = Train::GetIfValid(d);
1239 if (dst == NULL) return CMD_ERROR;
1241 CommandCost ret = CheckOwnership(dst->owner);
1242 if (ret.Failed()) return ret;
1244 /* Do not allow appending to crashed vehicles, too */
1245 if (dst->vehstatus & VS_CRASHED) return CMD_ERROR;
1248 /* if an articulated part is being handled, deal with its parent vehicle */
1249 src = src->GetFirstEnginePart();
1250 if (dst != NULL) {
1251 dst = dst->GetFirstEnginePart();
1254 /* don't move the same vehicle.. */
1255 if (src == dst) return CommandCost();
1257 /* locate the head of the two chains */
1258 Train *src_head = src->First();
1259 Train *dst_head;
1260 if (dst != NULL) {
1261 dst_head = dst->First();
1262 if (dst_head->tile != src_head->tile) return CMD_ERROR;
1263 /* Now deal with articulated part of destination wagon */
1264 dst = dst->GetLastEnginePart();
1265 } else {
1266 dst_head = NULL;
1269 if (src->IsRearDualheaded()) return_cmd_error(STR_ERROR_REAR_ENGINE_FOLLOW_FRONT);
1271 /* When moving all wagons, we can't have the same src_head and dst_head */
1272 if (move_chain && src_head == dst_head) return CommandCost();
1274 /* When moving a multiheaded part to be place after itself, bail out. */
1275 if (!move_chain && dst != NULL && dst->IsRearDualheaded() && src == dst->other_multiheaded_part) return CommandCost();
1277 /* Check if all vehicles in the source train are stopped inside a depot. */
1278 if (!src_head->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
1280 /* Check if all vehicles in the destination train are stopped inside a depot. */
1281 if (dst_head != NULL && !dst_head->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
1283 /* First make a backup of the order of the trains. That way we can do
1284 * whatever we want with the order and later on easily revert. */
1285 TrainList original_src;
1286 TrainList original_dst;
1288 MakeTrainBackup(original_src, src_head);
1289 MakeTrainBackup(original_dst, dst_head);
1291 /* Also make backup of the original heads as ArrangeTrains can change them.
1292 * For the destination head we do not care if it is the same as the source
1293 * head because in that case it's just a copy. */
1294 Train *original_src_head = src_head;
1295 Train *original_dst_head = (dst_head == src_head ? NULL : dst_head);
1297 /* We want this information from before the rearrangement, but execute this after the validation.
1298 * original_src_head can't be NULL; src is by definition != NULL, so src_head can't be NULL as
1299 * src->GetFirst() always yields non-NULL, so eventually original_src_head != NULL as well. */
1300 bool original_src_head_front_engine = original_src_head->IsFrontEngine();
1301 bool original_dst_head_front_engine = original_dst_head != NULL && original_dst_head->IsFrontEngine();
1303 /* (Re)arrange the trains in the wanted arrangement. */
1304 ArrangeTrains(&dst_head, dst, &src_head, src, move_chain);
1306 if ((flags & DC_AUTOREPLACE) == 0) {
1307 /* If the autoreplace flag is set we do not need to test for the validity
1308 * because we are going to revert the train to its original state. As we
1309 * assume the original state was correct autoreplace can skip this. */
1310 CommandCost ret = ValidateTrains(original_dst_head, dst_head, original_src_head, src_head, true);
1311 if (ret.Failed()) {
1312 /* Restore the train we had. */
1313 RestoreTrainBackup(original_src);
1314 RestoreTrainBackup(original_dst);
1315 return ret;
1319 /* do it? */
1320 if (flags & DC_EXEC) {
1321 /* Remove old heads from the statistics */
1322 if (original_src_head_front_engine) GroupStatistics::CountVehicle(original_src_head, -1);
1323 if (original_dst_head_front_engine) GroupStatistics::CountVehicle(original_dst_head, -1);
1325 /* First normalise the sub types of the chains. */
1326 NormaliseSubtypes(src_head);
1327 NormaliseSubtypes(dst_head);
1329 /* There are 14 different cases:
1330 * 1) front engine gets moved to a new train, it stays a front engine.
1331 * a) the 'next' part is a wagon that becomes a free wagon chain.
1332 * b) the 'next' part is an engine that becomes a front engine.
1333 * c) there is no 'next' part, nothing else happens
1334 * 2) front engine gets moved to another train, it is not a front engine anymore
1335 * a) the 'next' part is a wagon that becomes a free wagon chain.
1336 * b) the 'next' part is an engine that becomes a front engine.
1337 * c) there is no 'next' part, nothing else happens
1338 * 3) front engine gets moved to later in the current train, it is not a front engine anymore.
1339 * a) the 'next' part is a wagon that becomes a free wagon chain.
1340 * b) the 'next' part is an engine that becomes a front engine.
1341 * 4) free wagon gets moved
1342 * a) the 'next' part is a wagon that becomes a free wagon chain.
1343 * b) the 'next' part is an engine that becomes a front engine.
1344 * c) there is no 'next' part, nothing else happens
1345 * 5) non front engine gets moved and becomes a new train, nothing else happens
1346 * 6) non front engine gets moved within a train / to another train, nothing hapens
1347 * 7) wagon gets moved, nothing happens
1349 if (src == original_src_head && src->IsEngine() && !src->IsFrontEngine()) {
1350 /* Cases #2 and #3: the front engine gets trashed. */
1351 DeleteWindowById(WC_VEHICLE_VIEW, src->index);
1352 DeleteWindowById(WC_VEHICLE_ORDERS, src->index);
1353 DeleteWindowById(WC_VEHICLE_REFIT, src->index);
1354 DeleteWindowById(WC_VEHICLE_DETAILS, src->index);
1355 DeleteWindowById(WC_VEHICLE_TIMETABLE, src->index);
1356 DeleteNewGRFInspectWindow(GSF_TRAINS, src->index);
1357 SetWindowDirty(WC_COMPANY, _current_company);
1359 /* Delete orders, group stuff and the unit number as we're not the
1360 * front of any vehicle anymore. */
1361 DeleteVehicleOrders(src);
1362 RemoveVehicleFromGroup(src);
1363 src->unitnumber = 0;
1366 /* We weren't a front engine but are becoming one. So
1367 * we should be put in the default group. */
1368 if (original_src_head != src && dst_head == src) {
1369 SetTrainGroupID(src, DEFAULT_GROUP);
1370 SetWindowDirty(WC_COMPANY, _current_company);
1373 /* Add new heads to statistics */
1374 if (src_head != NULL && src_head->IsFrontEngine()) GroupStatistics::CountVehicle(src_head, 1);
1375 if (dst_head != NULL && dst_head->IsFrontEngine()) GroupStatistics::CountVehicle(dst_head, 1);
1377 /* Handle 'new engine' part of cases #1b, #2b, #3b, #4b and #5 in NormaliseTrainHead. */
1378 NormaliseTrainHead(src_head);
1379 NormaliseTrainHead(dst_head);
1381 if ((flags & DC_NO_CARGO_CAP_CHECK) == 0) {
1382 CheckCargoCapacity(src_head);
1383 CheckCargoCapacity(dst_head);
1386 if (src_head != NULL) src_head->First()->MarkDirty();
1387 if (dst_head != NULL) dst_head->First()->MarkDirty();
1389 /* We are undoubtedly changing something in the depot and train list. */
1390 InvalidateWindowData(WC_VEHICLE_DEPOT, src->tile);
1391 InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
1392 } else {
1393 /* We don't want to execute what we're just tried. */
1394 RestoreTrainBackup(original_src);
1395 RestoreTrainBackup(original_dst);
1398 return CommandCost();
1402 * Sell a (single) train wagon/engine.
1403 * @param flags type of operation
1404 * @param t the train wagon to sell
1405 * @param data the selling mode
1406 * - data = 0: only sell the single dragged wagon/engine (and any belonging rear-engines)
1407 * - data = 1: sell the vehicle and all vehicles following it in the chain
1408 * if the wagon is dragged, don't delete the possibly belonging rear-engine to some front
1409 * @param user the user for the order backup.
1410 * @return the cost of this operation or an error
1412 CommandCost CmdSellRailWagon(DoCommandFlag flags, Vehicle *t, uint16 data, uint32 user)
1414 /* Sell a chain of vehicles or not? */
1415 bool sell_chain = HasBit(data, 0);
1417 Train *v = Train::From(t)->GetFirstEnginePart();
1418 Train *first = v->First();
1420 if (v->IsRearDualheaded()) return_cmd_error(STR_ERROR_REAR_ENGINE_FOLLOW_FRONT);
1422 /* First make a backup of the order of the train. That way we can do
1423 * whatever we want with the order and later on easily revert. */
1424 TrainList original;
1425 MakeTrainBackup(original, first);
1427 /* We need to keep track of the new head and the head of what we're going to sell. */
1428 Train *new_head = first;
1429 Train *sell_head = NULL;
1431 /* Split the train in the wanted way. */
1432 ArrangeTrains(&sell_head, NULL, &new_head, v, sell_chain);
1434 /* We don't need to validate the second train; it's going to be sold. */
1435 CommandCost ret = ValidateTrains(NULL, NULL, first, new_head, (flags & DC_AUTOREPLACE) == 0);
1436 if (ret.Failed()) {
1437 /* Restore the train we had. */
1438 RestoreTrainBackup(original);
1439 return ret;
1442 CommandCost cost(EXPENSES_NEW_VEHICLES);
1443 for (Train *t = sell_head; t != NULL; t = t->Next()) cost.AddCost(-t->value);
1445 if (first->orders.list == NULL && !OrderList::CanAllocateItem()) {
1446 return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
1449 /* do it? */
1450 if (flags & DC_EXEC) {
1451 /* First normalise the sub types of the chain. */
1452 NormaliseSubtypes(new_head);
1454 if (v == first && v->IsEngine() && !sell_chain && new_head != NULL && new_head->IsFrontEngine()) {
1455 /* We are selling the front engine. In this case we want to
1456 * 'give' the order, unit number and such to the new head. */
1457 new_head->orders.list = first->orders.list;
1458 new_head->AddToShared(first);
1459 DeleteVehicleOrders(first);
1461 /* Copy other important data from the front engine */
1462 new_head->CopyVehicleConfigAndStatistics(first);
1463 GroupStatistics::CountVehicle(new_head, 1); // after copying over the profit
1464 } else if (v->IsPrimaryVehicle() && data & (MAKE_ORDER_BACKUP_FLAG >> 20)) {
1465 OrderBackup::Backup(v, user);
1468 /* We need to update the information about the train. */
1469 NormaliseTrainHead(new_head);
1471 /* We are undoubtedly changing something in the depot and train list. */
1472 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
1473 InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
1475 /* Actually delete the sold 'goods' */
1476 delete sell_head;
1477 } else {
1478 /* We don't want to execute what we're just tried. */
1479 RestoreTrainBackup(original);
1482 return cost;
1485 void Train::UpdateDeltaXY(Direction direction)
1487 /* Set common defaults. */
1488 this->x_offs = -1;
1489 this->y_offs = -1;
1490 this->x_extent = 3;
1491 this->y_extent = 3;
1492 this->z_extent = 6;
1493 this->x_bb_offs = 0;
1494 this->y_bb_offs = 0;
1496 if (!IsDiagonalDirection(direction)) {
1497 static const int _sign_table[] =
1499 // x, y
1500 -1, -1, // DIR_N
1501 -1, 1, // DIR_E
1502 1, 1, // DIR_S
1503 1, -1, // DIR_W
1506 int half_shorten = (VEHICLE_LENGTH - this->gcache.cached_veh_length) / 2;
1508 /* For all straight directions, move the bound box to the centre of the vehicle, but keep the size. */
1509 this->x_offs -= half_shorten * _sign_table[direction];
1510 this->y_offs -= half_shorten * _sign_table[direction + 1];
1511 this->x_extent += this->x_bb_offs = half_shorten * _sign_table[direction];
1512 this->y_extent += this->y_bb_offs = half_shorten * _sign_table[direction + 1];
1513 } else {
1514 switch (direction) {
1515 /* Shorten southern corner of the bounding box according the vehicle length
1516 * and center the bounding box on the vehicle. */
1517 case DIR_NE:
1518 this->x_offs = 1 - (this->gcache.cached_veh_length + 1) / 2;
1519 this->x_extent = this->gcache.cached_veh_length - 1;
1520 this->x_bb_offs = -1;
1521 break;
1523 case DIR_NW:
1524 this->y_offs = 1 - (this->gcache.cached_veh_length + 1) / 2;
1525 this->y_extent = this->gcache.cached_veh_length - 1;
1526 this->y_bb_offs = -1;
1527 break;
1529 /* Move northern corner of the bounding box down according to vehicle length
1530 * and center the bounding box on the vehicle. */
1531 case DIR_SW:
1532 this->x_offs = 1 + (this->gcache.cached_veh_length + 1) / 2 - VEHICLE_LENGTH;
1533 this->x_extent = VEHICLE_LENGTH - 1;
1534 this->x_bb_offs = VEHICLE_LENGTH - this->gcache.cached_veh_length - 1;
1535 break;
1537 case DIR_SE:
1538 this->y_offs = 1 + (this->gcache.cached_veh_length + 1) / 2 - VEHICLE_LENGTH;
1539 this->y_extent = VEHICLE_LENGTH - 1;
1540 this->y_bb_offs = VEHICLE_LENGTH - this->gcache.cached_veh_length - 1;
1541 break;
1543 default:
1544 NOT_REACHED();
1550 * Mark a train as stuck and stop it if it isn't stopped right now.
1551 * @param v %Train to mark as being stuck.
1553 static void MarkTrainAsStuck(Train *v)
1555 if (!HasBit(v->flags, VRF_TRAIN_STUCK)) {
1556 /* It is the first time the problem occurred, set the "train stuck" flag. */
1557 SetBit(v->flags, VRF_TRAIN_STUCK);
1559 v->wait_counter = 0;
1561 /* Stop train */
1562 v->cur_speed = 0;
1563 v->subspeed = 0;
1564 v->SetLastSpeed();
1566 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
1571 * Swap the two up/down flags in two ways:
1572 * - Swap values of \a swap_flag1 and \a swap_flag2, and
1573 * - If going up previously (#GVF_GOINGUP_BIT set), the #GVF_GOINGDOWN_BIT is set, and vice versa.
1574 * @param swap_flag1 [inout] First train flag.
1575 * @param swap_flag2 [inout] Second train flag.
1577 static void SwapTrainFlags(uint16 *swap_flag1, uint16 *swap_flag2)
1579 uint16 flag1 = *swap_flag1;
1580 uint16 flag2 = *swap_flag2;
1582 /* Clear the flags */
1583 ClrBit(*swap_flag1, GVF_GOINGUP_BIT);
1584 ClrBit(*swap_flag1, GVF_GOINGDOWN_BIT);
1585 ClrBit(*swap_flag2, GVF_GOINGUP_BIT);
1586 ClrBit(*swap_flag2, GVF_GOINGDOWN_BIT);
1588 /* Reverse the rail-flags (if needed) */
1589 if (HasBit(flag1, GVF_GOINGUP_BIT)) {
1590 SetBit(*swap_flag2, GVF_GOINGDOWN_BIT);
1591 } else if (HasBit(flag1, GVF_GOINGDOWN_BIT)) {
1592 SetBit(*swap_flag2, GVF_GOINGUP_BIT);
1594 if (HasBit(flag2, GVF_GOINGUP_BIT)) {
1595 SetBit(*swap_flag1, GVF_GOINGDOWN_BIT);
1596 } else if (HasBit(flag2, GVF_GOINGDOWN_BIT)) {
1597 SetBit(*swap_flag1, GVF_GOINGUP_BIT);
1602 * Updates some variables after swapping the vehicle.
1603 * @param v swapped vehicle
1605 static void UpdateStatusAfterSwap(Train *v)
1607 /* Reverse the direction. */
1608 if (v->trackdir != TRACKDIR_DEPOT) v->direction = ReverseDir(v->direction);
1610 if (v->trackdir < TRACKDIR_END) v->trackdir = ReverseTrackdir(v->trackdir);
1612 /* Call the proper EnterTile function unless we are in a wormhole. */
1613 if (v->trackdir != TRACKDIR_WORMHOLE) {
1614 TrainEnterTile(v, v->tile, v->x_pos, v->y_pos);
1615 } else {
1616 assert(v->direction == DiagDirToDir(GetTunnelBridgeDirection(v->tile)));
1617 v->tile = GetOtherTunnelBridgeEnd(v->tile);
1620 VehicleUpdatePosition(v);
1621 v->UpdateViewport(true, true);
1625 * Swap vehicles \a l and \a r in consist \a v, and reverse their direction.
1626 * @param v Consist to change.
1627 * @param l %Vehicle index in the consist of the first vehicle.
1628 * @param r %Vehicle index in the consist of the second vehicle.
1630 void ReverseTrainSwapVeh(Train *v, int l, int r)
1632 Train *a, *b;
1634 /* locate vehicles to swap */
1635 for (a = v; l != 0; l--) a = a->Next();
1636 for (b = v; r != 0; r--) b = b->Next();
1638 if (a != b) {
1639 /* swap the hidden bits */
1641 uint16 tmp = (a->vehstatus & ~VS_HIDDEN) | (b->vehstatus & VS_HIDDEN);
1642 b->vehstatus = (b->vehstatus & ~VS_HIDDEN) | (a->vehstatus & VS_HIDDEN);
1643 a->vehstatus = tmp;
1646 Swap(a->trackdir, b->trackdir);
1647 Swap(a->direction, b->direction);
1648 Swap(a->x_pos, b->x_pos);
1649 Swap(a->y_pos, b->y_pos);
1650 Swap(a->tile, b->tile);
1651 Swap(a->z_pos, b->z_pos);
1653 SwapTrainFlags(&a->gv_flags, &b->gv_flags);
1655 UpdateStatusAfterSwap(a);
1656 UpdateStatusAfterSwap(b);
1657 } else {
1658 /* Swap GVF_GOINGUP_BIT/GVF_GOINGDOWN_BIT.
1659 * This is a little bit redundant way, a->gv_flags will
1660 * be (re)set twice, but it reduces code duplication */
1661 SwapTrainFlags(&a->gv_flags, &a->gv_flags);
1662 UpdateStatusAfterSwap(a);
1668 * Check if there is a train on a tile
1669 * @param tile the tile to check
1670 * @return true if a train is on the tile
1672 static bool TrainOnTile (TileIndex tile)
1674 VehicleTileFinder iter (tile);
1675 while (!iter.finished()) {
1676 Vehicle *v = iter.next();
1677 if (v->type == VEH_TRAIN) iter.set_found();
1679 return iter.was_found();
1683 * Checks whether a train is approaching a rail-road crossing from a neighbour tile
1684 * @param tile the crossing tile
1685 * @param from the neighbour tile
1686 * @return true if a train is approaching the crossing
1688 static bool TrainApproachingCrossingFrom (TileIndex tile, TileIndex from)
1690 VehicleTileFinder iter (from);
1691 while (!iter.finished()) {
1692 Vehicle *v = iter.next();
1693 if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) continue;
1695 Train *t = Train::From(v);
1696 if (t->IsFrontEngine() && TrainApproachingCrossingTile(t) == tile) iter.set_found();
1698 return iter.was_found();
1702 * Finds a vehicle approaching rail-road crossing
1703 * @param tile tile to test
1704 * @return true if a vehicle is approaching the crossing
1705 * @pre tile is a rail-road crossing
1707 static bool TrainApproachingCrossing(TileIndex tile)
1709 assert(IsLevelCrossingTile(tile));
1711 TileIndexDiff delta = TileOffsByDiagDir(AxisToDiagDir(GetCrossingRailAxis(tile)));
1712 return TrainApproachingCrossingFrom (tile, tile + delta) ||
1713 TrainApproachingCrossingFrom (tile, tile - delta);
1718 * Sets correct crossing state
1719 * @param tile tile to update
1720 * @param sound should we play sound?
1721 * @pre tile is a rail-road crossing
1723 void UpdateLevelCrossing(TileIndex tile, bool sound)
1725 assert(IsLevelCrossingTile(tile));
1727 /* reserved || train on crossing || train approaching crossing */
1728 bool new_state = HasCrossingReservation(tile) || TrainOnTile(tile) || TrainApproachingCrossing(tile);
1730 if (new_state != IsCrossingBarred(tile)) {
1731 if (new_state && sound) {
1732 if (_settings_client.sound.ambient) SndPlayTileFx(SND_0E_LEVEL_CROSSING, tile);
1734 SetCrossingBarred(tile, new_state);
1735 MarkTileDirtyByTile(tile);
1741 * Bars crossing and plays ding-ding sound if not barred already
1742 * @param tile tile with crossing
1743 * @pre tile is a rail-road crossing
1745 static inline void MaybeBarCrossingWithSound(TileIndex tile)
1747 if (!IsCrossingBarred(tile)) {
1748 BarCrossing(tile);
1749 if (_settings_client.sound.ambient) SndPlayTileFx(SND_0E_LEVEL_CROSSING, tile);
1750 MarkTileDirtyByTile(tile);
1756 * Advances wagons for train reversing, needed for variable length wagons.
1757 * This one is called before the train is reversed.
1758 * @param v First vehicle in chain
1760 static void AdvanceWagonsBeforeSwap(Train *v)
1762 Train *base = v;
1763 Train *first = base; // first vehicle to move
1764 Train *last = v->Last(); // last vehicle to move
1765 uint length = CountVehiclesInChain(v);
1767 while (length > 2) {
1768 last = last->Previous();
1769 first = first->Next();
1771 int differential = base->CalcNextVehicleOffset() - last->CalcNextVehicleOffset();
1773 /* do not update images now
1774 * negative differential will be handled in AdvanceWagonsAfterSwap() */
1775 for (int i = 0; i < differential; i++) TrainController(first, last->Next());
1777 base = first; // == base->Next()
1778 length -= 2;
1784 * Advances wagons for train reversing, needed for variable length wagons.
1785 * This one is called after the train is reversed.
1786 * @param v First vehicle in chain
1788 static void AdvanceWagonsAfterSwap(Train *v)
1790 /* first of all, fix the situation when the train was entering a depot */
1791 Train *dep = v; // last vehicle in front of just left depot
1792 while (dep->Next() != NULL && (dep->trackdir == TRACKDIR_DEPOT || dep->Next()->trackdir != TRACKDIR_DEPOT)) {
1793 dep = dep->Next(); // find first vehicle outside of a depot, with next vehicle inside a depot
1796 Train *leave = dep->Next(); // first vehicle in a depot we are leaving now
1798 if (leave != NULL) {
1799 /* 'pull' next wagon out of the depot, so we won't miss it (it could stay in depot forever) */
1800 int d = TicksToLeaveDepot(dep);
1802 if (d <= 0) {
1803 leave->vehstatus &= ~VS_HIDDEN; // move it out of the depot
1804 leave->trackdir = DiagDirToDiagTrackdir(GetGroundDepotDirection(leave->tile));
1805 for (int i = 0; i >= d; i--) TrainController(leave, NULL); // maybe move it, and maybe let another wagon leave
1807 } else {
1808 dep = NULL; // no vehicle in a depot, so no vehicle leaving a depot
1811 Train *base = v;
1812 Train *first = base; // first vehicle to move
1813 Train *last = v->Last(); // last vehicle to move
1814 uint length = CountVehiclesInChain(v);
1816 /* We have to make sure all wagons that leave a depot because of train reversing are moved correctly
1817 * they have already correct spacing, so we have to make sure they are moved how they should */
1818 bool nomove = (dep == NULL); // If there is no vehicle leaving a depot, limit the number of wagons moved immediately.
1820 while (length > 2) {
1821 /* we reached vehicle (originally) in front of a depot, stop now
1822 * (we would move wagons that are already moved with new wagon length). */
1823 if (base == dep) break;
1825 /* the last wagon was that one leaving a depot, so do not move it anymore */
1826 if (last == dep) nomove = true;
1828 last = last->Previous();
1829 first = first->Next();
1831 int differential = last->CalcNextVehicleOffset() - base->CalcNextVehicleOffset();
1833 /* do not update images now */
1834 for (int i = 0; i < differential; i++) TrainController(first, (nomove ? last->Next() : NULL));
1836 base = first; // == base->Next()
1837 length -= 2;
1842 * Turn a train around.
1843 * @param v %Train to turn around.
1845 void ReverseTrainDirection(Train *v)
1847 if (IsRailDepotTile(v->tile)) {
1848 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
1851 /* Clear path reservation in front if train is not stuck. */
1852 if (!HasBit(v->flags, VRF_TRAIN_STUCK)) FreeTrainTrackReservation(v);
1854 /* Check if we were approaching a rail/road-crossing */
1855 TileIndex crossing = TrainApproachingCrossingTile(v);
1857 /* count number of vehicles */
1858 int r = CountVehiclesInChain(v) - 1; // number of vehicles - 1
1860 AdvanceWagonsBeforeSwap(v);
1862 /* swap start<>end, start+1<>end-1, ... */
1863 int l = 0;
1864 do {
1865 ReverseTrainSwapVeh(v, l++, r--);
1866 } while (l <= r);
1868 AdvanceWagonsAfterSwap(v);
1870 if (IsRailDepotTile(v->tile)) {
1871 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
1874 ToggleBit(v->flags, VRF_TOGGLE_REVERSE);
1876 ClrBit(v->flags, VRF_REVERSING);
1878 /* recalculate cached data */
1879 v->ConsistChanged(true);
1881 /* update all images */
1882 for (Train *u = v; u != NULL; u = u->Next()) u->UpdateViewport(false, false);
1884 /* update crossing we were approaching */
1885 if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
1887 /* maybe we are approaching crossing now, after reversal */
1888 crossing = TrainApproachingCrossingTile(v);
1889 if (crossing != INVALID_TILE) MaybeBarCrossingWithSound(crossing);
1891 /* If we are inside a depot after reversing, don't bother with path reserving. */
1892 if (v->trackdir == TRACKDIR_DEPOT) {
1893 /* Can't be stuck here as inside a depot is always a safe tile. */
1894 if (HasBit(v->flags, VRF_TRAIN_STUCK)) SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
1895 ClrBit(v->flags, VRF_TRAIN_STUCK);
1896 return;
1899 assert(IsSignalBufferEmpty());
1900 AddPosToSignalBuffer(v->GetPos(), v->owner);
1902 if (UpdateSignalsInBuffer() == SIGSEG_PBS || _settings_game.pf.reserve_paths) {
1903 RailPathPos pos = v->GetPos();
1905 /* If we are currently on a tile with conventional signals, we can't treat the
1906 * current tile as a safe tile or we would enter a PBS block without a reservation. */
1907 bool first_tile_okay = !(HasSignalAlongPos(pos) &&
1908 !IsPbsSignal(GetSignalType(pos)));
1910 /* If we are on a depot tile facing outwards, do not treat the current tile as safe. */
1911 if (!pos.in_wormhole() && IsRailDepotTile(pos.tile) && TrackdirToExitdir(pos.td) == GetGroundDepotDirection(pos.tile)) first_tile_okay = false;
1913 if (!pos.in_wormhole() && IsRailStationTile(pos.tile)) SetRailStationPlatformReservation(pos, true);
1914 if (TryPathReserve(v, false, first_tile_okay)) {
1915 /* Do a look-ahead now in case our current tile was already a safe tile. */
1916 CheckNextTrainTile(v);
1917 } else if (v->current_order.GetType() != OT_LOADING) {
1918 /* Do not wait for a way out when we're still loading */
1919 MarkTrainAsStuck(v);
1921 } else if (HasBit(v->flags, VRF_TRAIN_STUCK)) {
1922 /* A train not inside a PBS block can't be stuck. */
1923 ClrBit(v->flags, VRF_TRAIN_STUCK);
1924 v->wait_counter = 0;
1929 * Reverse train.
1930 * @param tile unused
1931 * @param flags type of operation
1932 * @param p1 train to reverse
1933 * @param p2 if true, reverse a unit in a train (needs to be in a depot)
1934 * @param text unused
1935 * @return the cost of this operation or an error
1937 CommandCost CmdReverseTrainDirection(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1939 Train *v = Train::GetIfValid(p1);
1940 if (v == NULL) return CMD_ERROR;
1942 CommandCost ret = CheckOwnership(v->owner);
1943 if (ret.Failed()) return ret;
1945 if (p2 != 0) {
1946 /* turn a single unit around */
1948 if (v->IsMultiheaded() || HasBit(EngInfo(v->engine_type)->callback_mask, CBM_VEHICLE_ARTIC_ENGINE)) {
1949 return_cmd_error(STR_ERROR_CAN_T_REVERSE_DIRECTION_RAIL_VEHICLE_MULTIPLE_UNITS);
1951 if (!HasBit(EngInfo(v->engine_type)->misc_flags, EF_RAIL_FLIPS)) return CMD_ERROR;
1953 Train *front = v->First();
1954 /* make sure the vehicle is stopped in the depot */
1955 if (!front->IsStoppedInDepot()) {
1956 return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
1959 if (flags & DC_EXEC) {
1960 ToggleBit(v->flags, VRF_REVERSE_DIRECTION);
1962 front->ConsistChanged(false);
1963 SetWindowDirty(WC_VEHICLE_DEPOT, front->tile);
1964 SetWindowDirty(WC_VEHICLE_DETAILS, front->index);
1965 SetWindowDirty(WC_VEHICLE_VIEW, front->index);
1966 SetWindowClassesDirty(WC_TRAINS_LIST);
1968 } else {
1969 /* turn the whole train around */
1970 if ((v->vehstatus & VS_CRASHED) || v->breakdown_ctr != 0) return CMD_ERROR;
1972 if (flags & DC_EXEC) {
1973 /* Properly leave the station if we are loading and won't be loading anymore */
1974 if (v->current_order.IsType(OT_LOADING)) {
1975 const Vehicle *last = v;
1976 while (last->Next() != NULL) last = last->Next();
1978 /* not a station || different station --> leave the station */
1979 if (!IsStationTile(last->tile) || GetStationIndex(last->tile) != GetStationIndex(v->tile)) {
1980 v->LeaveStation();
1984 /* We cancel any 'skip signal at dangers' here */
1985 v->force_proceed = TFP_NONE;
1986 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
1988 if (_settings_game.vehicle.train_acceleration_model != AM_ORIGINAL && v->cur_speed != 0) {
1989 ToggleBit(v->flags, VRF_REVERSING);
1990 } else {
1991 v->cur_speed = 0;
1992 v->SetLastSpeed();
1993 HideFillingPercent(&v->fill_percent_te_id);
1994 ReverseTrainDirection(v);
1998 return CommandCost();
2002 * Force a train through a red signal
2003 * @param tile unused
2004 * @param flags type of operation
2005 * @param p1 train to ignore the red signal
2006 * @param p2 unused
2007 * @param text unused
2008 * @return the cost of this operation or an error
2010 CommandCost CmdForceTrainProceed(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2012 Train *t = Train::GetIfValid(p1);
2013 if (t == NULL) return CMD_ERROR;
2015 if (!t->IsPrimaryVehicle()) return CMD_ERROR;
2017 CommandCost ret = CheckOwnership(t->owner);
2018 if (ret.Failed()) return ret;
2021 if (flags & DC_EXEC) {
2022 /* If we are forced to proceed, cancel that order.
2023 * If we are marked stuck we would want to force the train
2024 * to proceed to the next signal. In the other cases we
2025 * would like to pass the signal at danger and run till the
2026 * next signal we encounter. */
2027 t->force_proceed = t->force_proceed == TFP_SIGNAL ? TFP_NONE : HasBit(t->flags, VRF_TRAIN_STUCK) || t->IsChainInDepot() ? TFP_STUCK : TFP_SIGNAL;
2028 SetWindowDirty(WC_VEHICLE_VIEW, t->index);
2031 return CommandCost();
2035 * Try to find a depot.
2036 * @param v %Train that wants a depot.
2037 * @param nearby Only consider nearby depots.
2038 * @param res Pointer to store information where the closest train depot is located.
2039 * @return Whether a depot was found.
2040 * @pre The given vehicle must not be crashed!
2042 static bool FindClosestTrainDepot(Train *v, bool nearby, FindDepotData *res)
2044 assert(!(v->vehstatus & VS_CRASHED));
2046 if (IsRailDepotTile(v->tile) && v->trackdir == DiagDirToDiagTrackdir(ReverseDiagDir(GetGroundDepotDirection(v->tile)))) {
2047 *res = FindDepotData(v->tile);
2048 return true;
2051 RailPathPos origin;
2052 FollowTrainReservation(v, &origin);
2053 if (IsRailDepotTile(origin.tile) && origin.td == DiagDirToDiagTrackdir(ReverseDiagDir(GetGroundDepotDirection(origin.tile)))) {
2054 *res = FindDepotData(origin.tile);
2055 return true;
2058 return YapfTrainFindNearestDepot(v,
2059 nearby ? _settings_game.pf.yapf.maximum_go_to_depot_penalty : 0, res);
2063 * Locate the closest depot for this consist, and return the information to the caller.
2064 * @param location [out] If not \c NULL and a depot is found, store its location in the given address.
2065 * @param destination [out] If not \c NULL and a depot is found, store its index in the given address.
2066 * @param reverse [out] If not \c NULL and a depot is found, store reversal information in the given address.
2067 * @return A depot has been found.
2069 bool Train::FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
2071 FindDepotData tfdd;
2072 if (!FindClosestTrainDepot(this, false, &tfdd)) return false;
2074 if (location != NULL) *location = tfdd.tile;
2075 if (destination != NULL) *destination = GetDepotIndex(tfdd.tile);
2076 if (reverse != NULL) *reverse = tfdd.reverse;
2078 return true;
2081 /** Play a sound for a train leaving the station. */
2082 void Train::PlayLeaveStationSound() const
2084 static const SoundFx sfx[] = {
2085 SND_04_TRAIN,
2086 SND_0A_TRAIN_HORN,
2087 SND_0A_TRAIN_HORN,
2088 SND_47_MAGLEV_2,
2089 SND_41_MAGLEV
2092 if (PlayVehicleSound(this, VSE_START)) return;
2094 EngineID engtype = this->engine_type;
2095 SndPlayVehicleFx(sfx[RailVehInfo(engtype)->engclass], this);
2099 * Check if the train is on the last reserved tile and try to extend the path then.
2100 * @param v %Train that needs its path extended.
2102 static void CheckNextTrainTile(Train *v)
2104 /* Don't do any look-ahead if path_backoff_interval is 255. */
2105 if (_settings_game.pf.path_backoff_interval == 255) return;
2107 /* Exit if we are inside a depot. */
2108 if (v->trackdir == TRACKDIR_DEPOT) return;
2110 switch (v->current_order.GetType()) {
2111 /* Exit if we reached our destination depot. */
2112 case OT_GOTO_DEPOT:
2113 if (v->tile == v->dest_tile) return;
2114 break;
2116 case OT_GOTO_WAYPOINT:
2117 /* If we reached our waypoint, make sure we see that. */
2118 if (IsRailWaypointTile(v->tile) && GetStationIndex(v->tile) == v->current_order.GetDestination()) ProcessOrders(v);
2119 break;
2121 case OT_NOTHING:
2122 case OT_LEAVESTATION:
2123 case OT_LOADING:
2124 /* Exit if the current order doesn't have a destination, but the train has orders. */
2125 if (v->GetNumOrders() > 0) return;
2126 break;
2128 default:
2129 break;
2131 /* Exit if we are on a station tile and are going to stop. */
2132 if (IsRailStationTile(v->tile) && v->current_order.ShouldStopAtStation(v, GetStationIndex(v->tile))) return;
2134 RailPathPos pos = v->GetPos();
2136 /* On a tile with a red non-pbs signal, don't look ahead. */
2137 if (HasSignalAlongPos(pos) &&
2138 !IsPbsSignal(GetSignalType(pos)) &&
2139 GetSignalStateByPos(pos) == SIGNAL_STATE_RED) return;
2141 CFollowTrackRail ft(v, !_settings_game.pf.forbid_90_deg);
2142 if (!ft.Follow(pos)) return;
2144 if (ft.m_new.is_single()) {
2145 /* Next tile is not reserved. */
2146 if (!HasReservedPos(ft.m_new)) {
2147 if (HasPbsSignalAlongPos(ft.m_new)) {
2148 /* If the next tile is a PBS signal, try to make a reservation. */
2149 ChooseTrainTrack(v, pos, ft.m_new.tile, ft.m_new.trackdirs, false);
2156 * Will the train stay in the depot the next tick?
2157 * @param v %Train to check.
2158 * @return True if it stays in the depot, false otherwise.
2160 static bool CheckTrainStayInDepot(Train *v)
2162 /* bail out if not all wagons are in the same depot or not in a depot at all */
2163 for (const Train *u = v; u != NULL; u = u->Next()) {
2164 if (u->trackdir != TRACKDIR_DEPOT || u->tile != v->tile) return false;
2167 /* if the train got no power, then keep it in the depot */
2168 if (v->gcache.cached_power == 0) {
2169 v->vehstatus |= VS_STOPPED;
2170 SetWindowDirty(WC_VEHICLE_DEPOT, v->tile);
2171 return true;
2174 bool try_reserve;
2176 if (v->force_proceed == TFP_NONE) {
2177 /* force proceed was not pressed */
2178 if (++v->wait_counter < 37) {
2179 SetWindowClassesDirty(WC_TRAINS_LIST);
2180 return true;
2183 v->wait_counter = 0;
2185 if (HasDepotReservation(v->tile)) {
2186 /* Depot reserved, can't exit. */
2187 SetWindowClassesDirty(WC_TRAINS_LIST);
2188 return true;
2191 if (_settings_game.pf.reserve_paths) {
2192 try_reserve = true;
2193 } else {
2194 assert(IsSignalBufferEmpty());
2195 AddDepotToSignalBuffer(v->tile, v->owner);
2196 SigSegState seg_state = UpdateSignalsInBuffer();
2197 if (seg_state == SIGSEG_FULL) {
2198 /* Full and no PBS signal in block, can't exit. */
2199 SetWindowClassesDirty(WC_TRAINS_LIST);
2200 return true;
2202 try_reserve = seg_state == SIGSEG_PBS;
2204 } else if (_settings_game.pf.reserve_paths) {
2205 try_reserve = true;
2206 } else {
2207 assert(IsSignalBufferEmpty());
2208 AddDepotToSignalBuffer(v->tile, v->owner);
2209 try_reserve = UpdateSignalsInBuffer() == SIGSEG_PBS;
2212 /* We are leaving a depot, but have to go to the exact same one; re-enter */
2213 if (v->current_order.IsType(OT_GOTO_DEPOT) && v->tile == v->dest_tile) {
2214 /* We need to have a reservation for this to work. */
2215 if (HasDepotReservation(v->tile)) return true;
2216 SetDepotReservation(v->tile, true);
2217 VehicleEnterDepot(v);
2218 return true;
2221 /* Only leave when we can reserve a path to our destination. */
2222 if (try_reserve && !TryPathReserveFromDepot(v) && v->force_proceed == TFP_NONE) {
2223 /* No path and no force proceed. */
2224 SetWindowClassesDirty(WC_TRAINS_LIST);
2225 MarkTrainAsStuck(v);
2226 return true;
2229 SetDepotReservation(v->tile, true);
2230 if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(v->tile);
2232 VehicleServiceInDepot(v);
2233 SetWindowClassesDirty(WC_TRAINS_LIST);
2234 v->PlayLeaveStationSound();
2236 v->trackdir = DiagDirToDiagTrackdir(DirToDiagDir(v->direction));
2238 v->vehstatus &= ~VS_HIDDEN;
2239 v->cur_speed = 0;
2241 v->UpdateViewport(true, true);
2242 VehicleUpdatePosition(v);
2244 assert(IsSignalBufferEmpty());
2245 AddDepotToSignalBuffer(v->tile, v->owner);
2246 UpdateSignalsInBuffer();
2248 v->UpdateAcceleration();
2249 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
2251 return false;
2255 * Clear the reservation of \a tile that was just left by a wagon on \a track_dir.
2256 * @param v %Train owning the reservation.
2257 * @param pos position to clear.
2259 static void ClearPathReservation(const Train *v, const RailPathPos &pos)
2261 DiagDirection dir = TrackdirToExitdir(pos.td);
2263 if (pos.in_wormhole()) {
2264 UnreserveRailTrack(pos);
2265 } else if (IsRailStationTile(pos.tile)) {
2266 TileIndex new_tile = TileAddByDiagDir(pos.tile, dir);
2267 /* If the new tile is not a further tile of the same station, we
2268 * clear the reservation for the whole platform. */
2269 if (!IsCompatibleTrainStationTile(new_tile, pos.tile)) {
2270 SetRailStationPlatformReservation(pos.tile, ReverseDiagDir(dir), false);
2272 } else {
2273 /* Any other tile */
2274 UnreserveRailTrack(pos);
2279 * Free the reserved path in front of a vehicle.
2280 * @param v %Train owning the reserved path.
2282 void FreeTrainTrackReservation(const Train *v)
2284 assert(v->IsFrontEngine());
2286 RailPathPos pos = v->GetPos();
2287 bool first = true;
2289 /* Can't be holding a reservation if we enter a depot. */
2290 if (IsRailDepotTile(pos.tile) && TrackdirToExitdir(pos.td) != GetGroundDepotDirection(pos.tile)) return;
2291 if (v->trackdir == TRACKDIR_DEPOT) {
2292 /* Front engine is in a depot. We enter if some part is not in the depot. */
2293 for (const Train *u = v; u != NULL; u = u->Next()) {
2294 if (u->trackdir != TRACKDIR_DEPOT || u->tile != v->tile) return;
2297 /* Don't free reservation if it's not ours. */
2298 if (!pos.in_wormhole() && TracksOverlap(GetReservedTrackbits(pos.tile) | TrackToTrackBits(TrackdirToTrack(pos.td)))) return;
2300 CFollowTrackRail ft(v, true, v->railtype);
2301 ft.SetPos(pos);
2303 while (ft.FollowNext()) {
2304 if (!ft.m_new.in_wormhole()) {
2305 TrackdirBits trackdirs = ft.m_new.trackdirs & TrackBitsToTrackdirBits(GetReservedTrackbits(ft.m_new.tile));
2306 if (trackdirs == TRACKDIR_BIT_NONE) break;
2307 ft.m_new.set_trackdirs (trackdirs);
2308 assert(ft.m_new.is_single());
2311 if (HasSignalAlongPos(ft.m_new) && !IsPbsSignal(GetSignalType(ft.m_new))) {
2312 /* Conventional signal along trackdir: remove reservation and stop. */
2313 UnreserveRailTrack(ft.m_new);
2314 break;
2317 if (HasPbsSignalAlongPos(ft.m_new)) {
2318 if (GetSignalStateByPos(ft.m_new) == SIGNAL_STATE_RED) {
2319 /* Red PBS signal? Can't be our reservation, would be green then. */
2320 break;
2321 } else {
2322 /* Turn the signal back to red. */
2323 SetSignalState(ft.m_new.tile, ft.m_new.td, SIGNAL_STATE_RED);
2324 MarkTileDirtyByTile(ft.m_new.tile);
2326 } else if (HasSignalAgainstPos(ft.m_new) && IsOnewaySignal(GetSignalType(ft.m_new))) {
2327 break;
2330 if (first) {
2331 if (ft.m_flag == ft.TF_BRIDGE) {
2332 assert(IsRailBridgeTile(ft.m_old.in_wormhole() ? ft.m_old.wormhole : ft.m_old.tile));
2333 } else if (ft.m_flag == ft.TF_TUNNEL) {
2334 assert(IsTunnelTile(ft.m_old.in_wormhole() ? ft.m_old.wormhole : ft.m_old.tile));
2338 /* Don't free first station if we are on it. */
2339 if (!first || (ft.m_flag != ft.TF_STATION) ||
2340 !IsRailStationTile(ft.m_old.tile) || GetStationIndex(ft.m_new.tile) != GetStationIndex(ft.m_old.tile)) {
2341 ClearPathReservation(v, ft.m_new);
2344 first = false;
2348 static const byte _initial_tile_subcoord[TRACKDIR_END][3] = {
2349 {15, 8, 1}, // TRACKDIR_X_NE
2350 { 8, 0, 3}, // TRACKDIR_Y_SE
2351 { 7, 0, 2}, // TRACKDIR_UPPER_E
2352 {15, 8, 2}, // TRACKDIR_LOWER_E
2353 { 8, 0, 4}, // TRACKDIR_LEFT_S
2354 { 0, 8, 4}, // TRACKDIR_RIGHT_S
2355 { 0, 0, 0},
2356 { 0, 0, 0},
2357 { 0, 8, 5}, // TRACKDIR_X_SW
2358 { 8,15, 7}, // TRACKDIR_Y_NW
2359 { 0, 7, 6}, // TRACKDIR_UPPER_W
2360 { 8,15, 6}, // TRACKDIR_LOWER_W
2361 {15, 7, 0}, // TRACKDIR_LEFT_N
2362 { 7,15, 0}, // TRACKDIR_RIGHT_N
2366 * Perform pathfinding for a train.
2368 * @param v The train
2369 * @param origin The end of the current reservation
2370 * @param do_track_reservation Path reservation is requested
2371 * @param dest [out] State and destination of the requested path
2372 * @return The best trackdir the train should follow
2374 static Trackdir DoTrainPathfind(const Train *v, const RailPathPos &origin, bool do_track_reservation, PFResult *dest)
2376 return YapfTrainChooseTrack(v, origin, do_track_reservation, dest);
2380 * Return value type for ExtendTrainReservation
2382 enum ExtendReservationResult {
2383 EXTEND_RESERVATION_SAFE, ///< Reservation extended to a safe tile
2384 EXTEND_RESERVATION_UNSAFE, ///< Reservation extended to an unsafe tile
2385 EXTEND_RESERVATION_FAILED, ///< Reservation could not be extended
2389 * Extend a train path as far as possible. Stops on encountering a safe tile,
2390 * another reservation or a track choice.
2391 * @param v The train whose reservation to extend
2392 * @param origin The end of the current reservation, which will be updated
2393 * @return An ExtendReservationResult value, showing reservation extension outcome
2395 static ExtendReservationResult ExtendTrainReservation(const Train *v, RailPathPos *origin)
2397 CFollowTrackRail ft(v, !_settings_game.pf.forbid_90_deg);
2398 ft.SetPos(*origin);
2400 for (;;) {
2401 if (!ft.FollowNext()) {
2402 if (ft.m_err == CFollowTrackRail::EC_OWNER || ft.m_err == CFollowTrackRail::EC_NO_WAY) {
2403 /* End of line, path valid and okay. */
2404 *origin = ft.m_old;
2405 return EXTEND_RESERVATION_SAFE;
2407 break;
2410 /* A depot is always a safe waiting position. */
2411 if (!ft.m_new.in_wormhole() && IsRailDepotTile(ft.m_new.tile)) {
2412 /* Depot must be free for reservation to continue. */
2413 if (HasDepotReservation(ft.m_new.tile)) break;
2415 SetDepotReservation(ft.m_new.tile, true);
2416 *origin = ft.m_new;
2417 return EXTEND_RESERVATION_SAFE;
2420 /* Station and waypoints are possible targets. */
2421 if (ft.m_flag == ft.TF_STATION) {
2422 /* Possible target encountered.
2423 * On finding a possible target, we need to stop and let the pathfinder handle the
2424 * remaining path. This is because we don't know if this target is in one of our
2425 * orders, so we might cause pathfinding to fail later on if we find a choice.
2426 * This failure would cause a bogous call to TryReserveSafePath which might reserve
2427 * a wrong path not leading to our next destination. */
2428 if (!ft.MaskReservedTracks()) break;
2430 /* If we did skip some tiles, backtrack to the first skipped tile so the pathfinder
2431 * actually starts its search at the first unreserved tile. */
2432 ft.m_new.tile -= TileOffsByDiagDir(ft.m_exitdir) * ft.m_tiles_skipped;
2434 /* Possible target found, path valid but not okay. */
2435 *origin = ft.m_old;
2436 return EXTEND_RESERVATION_UNSAFE;
2439 if (!ft.m_new.is_single()) {
2440 /* Choice found. */
2441 if (HasReservedTracks(ft.m_new.tile, TrackdirBitsToTrackBits(ft.m_new.trackdirs))) break;
2443 assert(ft.m_tiles_skipped == 0);
2445 /* Choice found, path valid but not okay. Save info about the choice tile as well. */
2446 *origin = ft.m_old;
2447 return EXTEND_RESERVATION_UNSAFE;
2450 /* Possible signal tile. */
2451 if (HasOnewaySignalBlockingPos(ft.m_new)) break;
2453 PBSPositionState state = CheckWaitingPosition(v, ft.m_new, _settings_game.pf.forbid_90_deg);
2454 if (state == PBS_BUSY) break;
2456 if (!TryReserveRailTrack(ft.m_new)) break;
2458 if (state == PBS_FREE) {
2459 /* Safe position is all good, path valid and okay. */
2460 *origin = ft.m_new;
2461 return EXTEND_RESERVATION_SAFE;
2465 /* Sorry, can't reserve path, back out. */
2466 RailPathPos stopped = ft.m_old;
2467 ft.SetPos(*origin);
2468 while (ft.m_new != stopped) {
2469 if (!ft.FollowNext()) NOT_REACHED();
2471 assert(!ft.m_new.is_empty());
2472 assert(ft.m_new.is_single());
2474 UnreserveRailTrack(ft.m_new);
2477 /* Path invalid. */
2478 return EXTEND_RESERVATION_FAILED;
2482 * Try to reserve any path to a safe tile, ignoring the vehicle's destination.
2483 * Safe tiles are tiles in front of a signal, depots and station tiles at end of line.
2485 * @param v The vehicle.
2486 * @param pos The position the search should start from.
2487 * @param override_railtype Whether all physically compatible railtypes should be followed.
2488 * @return True if a path to a safe stopping tile could be reserved.
2490 static bool TryReserveSafeTrack(const Train *v, const RailPathPos &pos, bool override_tailtype)
2492 return YapfTrainFindNearestSafeTile(v, pos, override_tailtype);
2495 /** This class will save the current order of a vehicle and restore it on destruction. */
2496 class VehicleOrderSaver {
2497 private:
2498 Train *v;
2499 Order old_order;
2500 TileIndex old_dest_tile;
2501 StationID old_last_station_visited;
2502 VehicleOrderID index;
2503 bool suppress_implicit_orders;
2505 public:
2506 VehicleOrderSaver(Train *_v) :
2507 v(_v),
2508 old_order(_v->current_order),
2509 old_dest_tile(_v->dest_tile),
2510 old_last_station_visited(_v->last_station_visited),
2511 index(_v->cur_real_order_index),
2512 suppress_implicit_orders(HasBit(_v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS))
2516 ~VehicleOrderSaver()
2518 this->v->current_order = this->old_order;
2519 this->v->dest_tile = this->old_dest_tile;
2520 this->v->last_station_visited = this->old_last_station_visited;
2521 SB(this->v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS, 1, suppress_implicit_orders ? 1: 0);
2525 * Set the current vehicle order to the next order in the order list.
2526 * @param skip_first Shall the first (i.e. active) order be skipped?
2527 * @return True if a suitable next order could be found.
2529 bool SwitchToNextOrder(bool skip_first)
2531 if (this->v->GetNumOrders() == 0) return false;
2533 if (skip_first) ++this->index;
2535 int depth = 0;
2537 do {
2538 /* Wrap around. */
2539 if (this->index >= this->v->GetNumOrders()) this->index = 0;
2541 Order *order = this->v->GetOrder(this->index);
2542 assert(order != NULL);
2544 switch (order->GetType()) {
2545 case OT_GOTO_DEPOT:
2546 /* Skip service in depot orders when the train doesn't need service. */
2547 if ((order->GetDepotOrderType() & ODTFB_SERVICE) && !this->v->NeedsServicing()) break;
2548 case OT_GOTO_STATION:
2549 case OT_GOTO_WAYPOINT:
2550 this->v->current_order = *order;
2551 return UpdateOrderDest(this->v, order, 0, true);
2552 case OT_CONDITIONAL: {
2553 VehicleOrderID next = ProcessConditionalOrder(order, this->v);
2554 if (next != INVALID_VEH_ORDER_ID) {
2555 depth++;
2556 this->index = next;
2557 /* Don't increment next, so no break here. */
2558 continue;
2560 break;
2562 default:
2563 break;
2565 /* Don't increment inside the while because otherwise conditional
2566 * orders can lead to an infinite loop. */
2567 ++this->index;
2568 depth++;
2569 } while (this->index != this->v->cur_real_order_index && depth < this->v->GetNumOrders());
2571 return false;
2575 /* choose a track */
2576 static bool ChooseTrainTrack(Train *v, RailPathPos origin, TileIndex tile, TrackdirBits trackdirs, bool force_res, Trackdir *best_trackdir)
2578 bool do_track_reservation = _settings_game.pf.reserve_paths || force_res;
2579 bool change_signal = false;
2581 assert (trackdirs != TRACKDIR_BIT_NONE);
2583 /* Quick return in case only one possible trackdir is available */
2584 Trackdir single_trackdir = INVALID_TRACKDIR;
2585 if (HasAtMostOneBit(trackdirs)) {
2586 single_trackdir = FindFirstTrackdir(trackdirs);
2587 if (best_trackdir != NULL) *best_trackdir = single_trackdir;
2588 /* We need to check for signals only here, as a junction tile can't have signals. */
2589 if (HasPbsSignalOnTrackdir(tile, single_trackdir)) {
2590 do_track_reservation = true;
2591 change_signal = true;
2592 } else if (!do_track_reservation) {
2593 return true;
2597 if (do_track_reservation) {
2598 switch (ExtendTrainReservation(v, &origin)) {
2599 default: NOT_REACHED();
2600 case EXTEND_RESERVATION_FAILED:
2601 if (best_trackdir != NULL) *best_trackdir = FindFirstTrackdir(trackdirs);
2602 return false;
2603 case EXTEND_RESERVATION_SAFE:
2604 if (change_signal) {
2605 SetSignalState(tile, single_trackdir, SIGNAL_STATE_GREEN);
2606 MarkTileDirtyByTile(tile);
2608 TryReserveRailTrack(v->GetPos());
2609 assert (single_trackdir != INVALID_TRACKDIR);
2610 return true;
2611 case EXTEND_RESERVATION_UNSAFE:
2612 break;
2615 /* Check if the train needs service here, so it has a chance to always find a depot.
2616 * Also check if the current order is a service order so we don't reserve a path to
2617 * the destination but instead to the next one if service isn't needed. */
2618 CheckIfTrainNeedsService(v);
2619 if (v->current_order.IsType(OT_DUMMY) || v->current_order.IsType(OT_CONDITIONAL) || v->current_order.IsType(OT_GOTO_DEPOT)) ProcessOrders(v);
2622 /* Save the current train order. The destructor will restore the old order on function exit. */
2623 VehicleOrderSaver orders(v);
2625 /* If the current tile is the destination of the current order and
2626 * a reservation was requested, advance to the next order.
2627 * Don't advance on a depot order as depots are always safe end points
2628 * for a path and no look-ahead is necessary. This also avoids a
2629 * problem with depot orders not part of the order list when the
2630 * order list itself is empty. */
2631 if (v->current_order.IsType(OT_LEAVESTATION)) {
2632 orders.SwitchToNextOrder(false);
2633 } else if (v->current_order.IsType(OT_LOADING) || (!v->current_order.IsType(OT_GOTO_DEPOT) && (
2634 v->current_order.IsType(OT_GOTO_STATION) ?
2635 IsRailStationTile(v->tile) && v->current_order.GetDestination() == GetStationIndex(v->tile) :
2636 v->tile == v->dest_tile))) {
2637 orders.SwitchToNextOrder(true);
2640 /* Call the pathfinder... */
2641 PFResult res_dest;
2642 Trackdir next_trackdir = DoTrainPathfind(v, origin, do_track_reservation, &res_dest);
2643 v->HandlePathfindingResult(res_dest.found);
2644 /* ...but only use the result if we were at the original tile. */
2645 if (best_trackdir != NULL && single_trackdir == INVALID_TRACKDIR) {
2646 /* The initial tile had more than one available trackdir.
2647 * This means that ExtendTrainReservation cannot possibly
2648 * have extended the reservation, and we are pathfinding
2649 * at the original tile. */
2650 *best_trackdir = next_trackdir != INVALID_TRACKDIR ? next_trackdir : FindFirstTrackdir(trackdirs);
2651 /* If the initial tile only had one available trackdir, then
2652 * *best_trackdir was set along with single_trackdir. */
2655 /* No track reservation requested -> finished. */
2656 if (!do_track_reservation) {
2657 assert (!change_signal);
2658 return true;
2661 if (change_signal) SetSignalState(tile, single_trackdir, SIGNAL_STATE_GREEN);
2663 /* A path was found, but could not be reserved. */
2664 if (res_dest.pos.is_valid_tile() && !res_dest.okay) {
2665 FreeTrainTrackReservation(v);
2666 return false;
2669 /* No possible reservation target found, we are probably lost. */
2670 if (!res_dest.pos.is_valid_tile()) {
2671 /* Try to find any safe destination. */
2672 if (TryReserveSafeTrack(v, origin, false)) {
2673 if (best_trackdir != NULL && single_trackdir == INVALID_TRACKDIR) {
2674 TrackBits res = GetReservedTrackbits(tile);
2675 *best_trackdir = FindFirstTrackdir(TrackBitsToTrackdirBits(res) & trackdirs);
2677 TryReserveRailTrack(v->GetPos());
2678 if (change_signal) MarkTileDirtyByTile(tile);
2679 return true;
2680 } else {
2681 FreeTrainTrackReservation(v);
2682 return false;
2686 TryReserveRailTrack(v->GetPos());
2688 /* Extend reservation until we have found a safe position. */
2689 bool safe = false;
2690 for (;;) {
2691 origin = res_dest.pos;
2692 if (IsSafeWaitingPosition(v, origin, _settings_game.pf.forbid_90_deg)) {
2693 safe = true;
2694 break;
2697 /* Get next order with destination. */
2698 if (!orders.SwitchToNextOrder(true)) break;
2700 DoTrainPathfind(v, origin, true, &res_dest);
2701 /* Break if no safe position was found. */
2702 if (!res_dest.pos.is_valid_tile()) break;
2704 if (!res_dest.okay) {
2705 /* Path found, but could not be reserved. */
2706 FreeTrainTrackReservation(v);
2707 return false;
2711 /* No order or no safe position found, try any position. */
2712 if (!safe) safe = TryReserveSafeTrack(v, origin, true);
2714 if (!safe) {
2715 FreeTrainTrackReservation(v);
2716 } else if (change_signal) {
2717 MarkTileDirtyByTile(tile);
2720 return safe;
2724 * Try to reserve a path to a safe position.
2726 * @param v The vehicle
2727 * @param mark_as_stuck Should the train be marked as stuck on a failed reservation?
2728 * @param first_tile_okay True if no path should be reserved if the current tile is a safe position.
2729 * @return True if a path could be reserved.
2731 bool TryPathReserve(Train *v, bool mark_as_stuck, bool first_tile_okay)
2733 assert(v->IsFrontEngine());
2734 assert(v->trackdir != TRACKDIR_DEPOT);
2736 Vehicle *other_train = NULL;
2737 RailPathPos origin;
2738 FollowTrainReservation(v, &origin, &other_train);
2739 /* The path we are driving on is already blocked by some other train.
2740 * This can only happen in certain situations when mixing path and
2741 * block signals or when changing tracks and/or signals.
2742 * Exit here as doing any further reservations will probably just
2743 * make matters worse. */
2744 if (other_train != NULL && other_train->index != v->index) {
2745 if (mark_as_stuck) MarkTrainAsStuck(v);
2746 return false;
2749 /* If we have a reserved path and the path ends at a safe tile, we are finished already. */
2750 if ((v->tile != origin.tile || first_tile_okay) && IsSafeWaitingPosition(v, origin, _settings_game.pf.forbid_90_deg)) {
2751 /* Can't be stuck then. */
2752 if (HasBit(v->flags, VRF_TRAIN_STUCK)) SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
2753 ClrBit(v->flags, VRF_TRAIN_STUCK);
2754 return true;
2757 DiagDirection exitdir = TrackdirToExitdir(origin.td);
2758 TileIndex new_tile = TileAddByDiagDir(origin.tile, exitdir);
2759 TrackdirBits reachable = TrackStatusToTrackdirBits(GetTileRailwayStatus(new_tile)) & DiagdirReachesTrackdirs(exitdir);
2761 if (_settings_game.pf.forbid_90_deg) reachable &= ~TrackdirCrossesTrackdirs(origin.td);
2763 if (reachable != TRACKDIR_BIT_NONE && !ChooseTrainTrack(v, origin, new_tile, reachable, true)) {
2764 if (mark_as_stuck) MarkTrainAsStuck(v);
2765 return false;
2768 if (HasBit(v->flags, VRF_TRAIN_STUCK)) {
2769 v->wait_counter = 0;
2770 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
2772 ClrBit(v->flags, VRF_TRAIN_STUCK);
2773 return true;
2777 * Try to reserve a path to a safe position from a depot.
2779 * @param v The vehicle
2780 * @param mark_as_stuck Should the train be marked as stuck on a failed reservation?
2781 * @param first_tile_okay True if no path should be reserved if the current tile is a safe position.
2782 * @return True if a path could be reserved.
2784 static bool TryPathReserveFromDepot(Train *v)
2786 assert(v->IsFrontEngine());
2787 assert(v->trackdir == TRACKDIR_DEPOT);
2789 /* We have to handle depots specially as the track follower won't look
2790 * at the depot tile itself but starts from the next tile. If we are still
2791 * inside the depot, a depot reservation can never be ours. */
2792 if (HasDepotReservation(v->tile)) return false;
2794 /* Depot not reserved, but the next tile might be. */
2795 DiagDirection exitdir = GetGroundDepotDirection(v->tile);
2796 TileIndex new_tile = TileAddByDiagDir(v->tile, exitdir);
2797 if (HasReservedTracks(new_tile, DiagdirReachesTracks(exitdir))) return false;
2799 TrackdirBits reachable = TrackStatusToTrackdirBits(GetTileRailwayStatus(new_tile)) & DiagdirReachesTrackdirs(exitdir);
2801 if (reachable != TRACKDIR_BIT_NONE && !ChooseTrainTrack(v, v->GetPos(), new_tile, reachable, true)) {
2802 return false;
2805 SetDepotReservation(v->tile, true);
2806 if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(v->tile);
2808 if (HasBit(v->flags, VRF_TRAIN_STUCK)) {
2809 v->wait_counter = 0;
2810 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
2811 ClrBit(v->flags, VRF_TRAIN_STUCK);
2814 return true;
2818 static bool CheckReverseTrain(const Train *v)
2820 if (_settings_game.difficulty.line_reverse_mode != 0 ||
2821 v->trackdir == TRACKDIR_DEPOT || v->trackdir == TRACKDIR_WORMHOLE ||
2822 !(v->direction & 1)) {
2823 return false;
2826 assert(IsValidTrackdir(v->trackdir));
2828 return YapfTrainCheckReverse(v);
2832 * Get the location of the next station to visit.
2833 * @param station Next station to visit.
2834 * @return Location of the new station.
2836 TileIndex Train::GetOrderStationLocation(StationID station)
2838 if (station == this->last_station_visited) this->last_station_visited = INVALID_STATION;
2840 const Station *st = Station::Get(station);
2841 if (!(st->facilities & FACIL_TRAIN)) {
2842 /* The destination station has no trainstation tiles. */
2843 this->IncrementRealOrderIndex();
2844 return 0;
2847 return st->xy;
2850 /** Goods at the consist have changed, update the graphics, cargo, and acceleration. */
2851 void Train::MarkDirty()
2853 Train *v = this;
2854 do {
2855 v->colourmap = PAL_NONE;
2856 v->UpdateViewport(true, false);
2857 } while ((v = v->Next()) != NULL);
2859 /* need to update acceleration and cached values since the goods on the train changed. */
2860 this->CargoChanged();
2861 this->UpdateAcceleration();
2865 * This function looks at the vehicle and updates its speed (cur_speed
2866 * and subspeed) variables. Furthermore, it returns the distance that
2867 * the train can drive this tick. #Vehicle::GetAdvanceDistance() determines
2868 * the distance to drive before moving a step on the map.
2869 * @return distance to drive.
2871 int Train::UpdateSpeed()
2873 switch (_settings_game.vehicle.train_acceleration_model) {
2874 default: NOT_REACHED();
2875 case AM_ORIGINAL:
2876 return this->DoUpdateSpeed(this->acceleration * (this->GetAccelerationStatus() == AS_BRAKE ? -4 : 2), 0, this->GetCurrentMaxSpeed());
2878 case AM_REALISTIC:
2879 return this->DoUpdateSpeed(this->GetAcceleration(), this->GetAccelerationStatus() == AS_BRAKE ? 0 : 2, this->GetCurrentMaxSpeed());
2884 * Trains enters a station, send out a news item if it is the first train, and start loading.
2885 * @param v Train that entered the station.
2886 * @param station Station visited.
2888 static void TrainEnterStation(Train *v, StationID station)
2890 v->last_station_visited = station;
2892 /* check if a train ever visited this station before */
2893 Station *st = Station::Get(station);
2894 if (!(st->had_vehicle_of_type & HVOT_TRAIN)) {
2895 st->had_vehicle_of_type |= HVOT_TRAIN;
2896 SetDParam(0, st->index);
2897 AddVehicleNewsItem(
2898 STR_NEWS_FIRST_TRAIN_ARRIVAL,
2899 v->owner == _local_company ? NT_ARRIVAL_COMPANY : NT_ARRIVAL_OTHER,
2900 v->index,
2901 st->index
2903 AI::NewEvent(v->owner, new ScriptEventStationFirstVehicle(st->index, v->index));
2904 Game::NewEvent(new ScriptEventStationFirstVehicle(st->index, v->index));
2907 v->force_proceed = TFP_NONE;
2908 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
2910 v->BeginLoading();
2912 TriggerStationRandomisation(st, v->tile, SRT_TRAIN_ARRIVES);
2913 TriggerStationAnimation(st, v->tile, SAT_TRAIN_ARRIVES);
2916 /* Check if the vehicle is compatible with the specified tile */
2917 static inline bool CheckCompatibleRail(const Train *v, TileIndex tile, Track track = INVALID_TRACK)
2919 return IsTileOwner(tile, v->owner) &&
2920 (!v->IsFrontEngine() || HasBit(v->compatible_railtypes, GetRailType(tile, track)));
2923 /** Data structure for storing engine speed changes of an acceleration type. */
2924 struct AccelerationSlowdownParams {
2925 byte small_turn; ///< Speed change due to a small turn.
2926 byte large_turn; ///< Speed change due to a large turn.
2927 byte z_up; ///< Fraction to remove when moving up.
2928 byte z_down; ///< Fraction to add when moving down.
2931 /** Speed update fractions for each acceleration type. */
2932 static const AccelerationSlowdownParams _accel_slowdown[] = {
2933 /* normal accel */
2934 {256 / 4, 256 / 2, 256 / 4, 2}, ///< normal
2935 {256 / 4, 256 / 2, 256 / 4, 2}, ///< monorail
2936 {0, 256 / 2, 256 / 4, 2}, ///< maglev
2940 * Modify the speed of the vehicle due to a change in altitude.
2941 * @param v %Train to update.
2942 * @param old_z Previous height.
2944 static inline void AffectSpeedByZChange(Train *v, int old_z)
2946 if (old_z == v->z_pos || _settings_game.vehicle.train_acceleration_model != AM_ORIGINAL) return;
2948 const AccelerationSlowdownParams *asp = &_accel_slowdown[GetRailTypeInfo(v->railtype)->acceleration_type];
2950 if (old_z < v->z_pos) {
2951 v->cur_speed -= (v->cur_speed * asp->z_up >> 8);
2952 } else {
2953 uint16 spd = v->cur_speed + asp->z_down;
2954 if (spd <= v->gcache.cached_max_track_speed) v->cur_speed = spd;
2958 /** Tries to reserve track under whole train consist. */
2959 void Train::ReserveTrackUnderConsist() const
2961 for (const Train *u = this; u != NULL; u = u->Next()) {
2962 switch (u->trackdir) {
2963 case TRACKDIR_WORMHOLE:
2964 if (IsRailwayTile(u->tile)) {
2965 SetBridgeMiddleReservation(u->tile, true);
2966 SetBridgeMiddleReservation(GetOtherBridgeEnd(u->tile), true);
2967 } else {
2968 SetTunnelMiddleReservation(u->tile, true);
2969 SetTunnelMiddleReservation(GetOtherTunnelEnd(u->tile), true);
2971 break;
2972 case TRACKDIR_DEPOT:
2973 break;
2974 default:
2975 TryReserveRailTrack(u->tile, TrackdirToTrack(u->trackdir));
2976 break;
2982 * The train vehicle crashed!
2983 * Update its status and other parts around it.
2984 * @param flooded Crash was caused by flooding.
2985 * @return Number of people killed.
2987 uint Train::Crash(bool flooded)
2989 uint pass = 0;
2990 if (this->IsFrontEngine()) {
2991 pass += 2; // driver
2993 /* Remove the reserved path in front of the train if it is not stuck.
2994 * Also clear all reserved tracks the train is currently on. */
2995 if (!HasBit(this->flags, VRF_TRAIN_STUCK)) FreeTrainTrackReservation(this);
2996 for (const Train *v = this; v != NULL; v = v->Next()) {
2997 ClearPathReservation(v, v->GetPos());
3000 /* we may need to update crossing we were approaching,
3001 * but must be updated after the train has been marked crashed */
3002 TileIndex crossing = TrainApproachingCrossingTile(this);
3003 if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
3005 /* Remove the loading indicators (if any) */
3006 HideFillingPercent(&this->fill_percent_te_id);
3009 pass += this->GroundVehicleBase::Crash(flooded);
3011 this->crash_anim_pos = flooded ? 4000 : 1; // max 4440, disappear pretty fast when flooded
3012 return pass;
3016 * Marks train as crashed and creates an AI event.
3017 * Doesn't do anything if the train is crashed already.
3018 * @param v first vehicle of chain
3019 * @return number of victims (including 2 drivers; zero if train was already crashed)
3021 static uint TrainCrashed(Train *v)
3023 uint num = 0;
3025 /* do not crash train twice */
3026 if (!(v->vehstatus & VS_CRASHED)) {
3027 num = v->Crash();
3028 AI::NewEvent(v->owner, new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_TRAIN));
3029 Game::NewEvent(new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_TRAIN));
3032 /* Try to re-reserve track under already crashed train too.
3033 * Crash() clears the reservation! */
3034 v->ReserveTrackUnderConsist();
3036 return num;
3040 * Collision test function.
3041 * @param tcc %Train being examined.
3042 * @param v %Train vehicle to test collision with.
3043 * @return Total number of victims if train collided, else 0.
3045 static uint FindTrainCollision(Train *tcc, Vehicle *v)
3047 /* not a train or in depot */
3048 if (v->type != VEH_TRAIN || Train::From(v)->trackdir == TRACKDIR_DEPOT) return 0;
3050 /* do not crash into trains of another company. */
3051 if (v->owner != tcc->owner) return 0;
3053 /* get first vehicle now to make most usual checks faster */
3054 Train *coll = Train::From(v)->First();
3056 /* can't collide with own wagons */
3057 if (coll == tcc) return 0;
3059 int x_diff = v->x_pos - tcc->x_pos;
3060 int y_diff = v->y_pos - tcc->y_pos;
3062 /* Do fast calculation to check whether trains are not in close vicinity
3063 * and quickly reject trains distant enough for any collision.
3064 * Differences are shifted by 7, mapping range [-7 .. 8] into [0 .. 15]
3065 * Differences are then ORed and then we check for any higher bits */
3066 uint hash = (y_diff + 7) | (x_diff + 7);
3067 if (hash & ~15) return 0;
3069 /* Slower check using multiplication */
3070 int min_diff = (Train::From(v)->gcache.cached_veh_length + 1) / 2 + (tcc->gcache.cached_veh_length + 1) / 2 - 1;
3071 if (x_diff * x_diff + y_diff * y_diff > min_diff * min_diff) return 0;
3073 /* Happens when there is a train under bridge next to bridge head */
3074 if (abs(v->z_pos - tcc->z_pos) > 5) return 0;
3076 /* crash both trains */
3077 return TrainCrashed(tcc) + TrainCrashed(coll);
3080 /** Temporary data storage for testing collisions. */
3081 struct TrainCollideChecker {
3082 Train *v; ///< %Vehicle we are testing for collision.
3083 uint num; ///< Total number of victims if train collided.
3087 * Collision test function.
3088 * @param v %Train vehicle to test collision with.
3089 * @param data %Train being examined.
3090 * @return \c NULL (always continue search)
3092 static Vehicle *FindTrainCollideEnum(Vehicle *v, void *data)
3094 TrainCollideChecker *tcc = (TrainCollideChecker*)data;
3096 tcc->num += FindTrainCollision (tcc->v, v);
3098 return NULL;
3102 * Checks whether the specified train has a collision with another vehicle. If
3103 * so, destroys this vehicle, and the other vehicle if its subtype has TS_Front.
3104 * Reports the incident in a flashy news item, modifies station ratings and
3105 * plays a sound.
3106 * @param v %Train to test.
3108 static bool CheckTrainCollision(Train *v)
3110 /* can't collide in depot */
3111 if (v->trackdir == TRACKDIR_DEPOT) return false;
3113 assert(v->trackdir == TRACKDIR_WORMHOLE || TileVirtXY(v->x_pos, v->y_pos) == v->tile);
3115 TrainCollideChecker tcc;
3116 tcc.v = v;
3117 tcc.num = 0;
3119 /* find colliding vehicles */
3120 if (v->trackdir == TRACKDIR_WORMHOLE) {
3121 VehicleTileIterator iter1 (v->tile);
3122 while (!iter1.finished()) {
3123 tcc.num += FindTrainCollision (v, iter1.next());
3125 VehicleTileIterator iter2 (GetOtherTunnelBridgeEnd(v->tile));
3126 while (!iter2.finished()) {
3127 tcc.num += FindTrainCollision (v, iter2.next());
3129 } else {
3130 FindVehicleOnPosXY(v->x_pos, v->y_pos, &tcc, FindTrainCollideEnum);
3133 /* any dead -> no crash */
3134 if (tcc.num == 0) return false;
3136 SetDParam(0, tcc.num);
3137 AddVehicleNewsItem(STR_NEWS_TRAIN_CRASH, NT_ACCIDENT, v->index);
3139 ModifyStationRatingAround(v->tile, v->owner, -160, 30);
3140 if (_settings_client.sound.disaster) SndPlayVehicleFx(SND_13_BIG_CRASH, v);
3141 return true;
3146 * Tile callback routine when vehicle enters a track tile
3147 * @see vehicle_enter_tile_proc
3149 static void TrainEnter_Track(Train *v, TileIndex tile, int x, int y)
3151 if (IsTileSubtype(tile, TT_TRACK)) return;
3153 assert(abs((int)(GetSlopePixelZ(x, y) - v->z_pos)) < 3);
3155 /* modify speed of vehicle */
3156 uint16 spd = GetBridgeSpec(GetRailBridgeType(tile))->speed;
3157 Vehicle *first = v->First();
3158 first->cur_speed = min(first->cur_speed, spd);
3162 * Frame when the 'enter tunnel' sound should be played. This is the second
3163 * frame on a tile, so the sound is played shortly after entering the tunnel
3164 * tile, while the vehicle is still visible.
3166 static const byte TUNNEL_SOUND_FRAME = 1;
3168 extern const byte _tunnel_visibility_frame[DIAGDIR_END];
3171 * Compute number of ticks when next wagon will leave a depot.
3172 * Negative means next wagon should have left depot n ticks before.
3173 * @param v vehicle outside (leaving) the depot
3174 * @return number of ticks when the next wagon will leave
3176 int TicksToLeaveDepot(const Train *v)
3178 DiagDirection dir = GetGroundDepotDirection(v->tile);
3179 int length = v->CalcNextVehicleOffset();
3181 switch (dir) {
3182 case DIAGDIR_NE: return ((int)(v->x_pos & 0x0F) - (_vehicle_initial_x_fract[dir] - (length + 1)));
3183 case DIAGDIR_SE: return -((int)(v->y_pos & 0x0F) - (_vehicle_initial_y_fract[dir] + (length + 1)));
3184 case DIAGDIR_SW: return -((int)(v->x_pos & 0x0F) - (_vehicle_initial_x_fract[dir] + (length + 1)));
3185 default:
3186 case DIAGDIR_NW: return ((int)(v->y_pos & 0x0F) - (_vehicle_initial_y_fract[dir] - (length + 1)));
3189 return 0; // make compilers happy
3192 static void TrainEnter_Misc(Train *u, TileIndex tile, int x, int y)
3194 switch (GetTileSubtype(tile)) {
3195 default: break;
3197 case TT_MISC_TUNNEL: {
3198 assert(abs((int)GetSlopePixelZ(x, y) - u->z_pos) < 3);
3200 /* Direction into the wormhole */
3201 const DiagDirection dir = GetTunnelBridgeDirection(tile);
3203 if (u->direction == DiagDirToDir(dir)) {
3204 uint frame = DistanceFromTileEdge(ReverseDiagDir(dir), x & 0xF, y & 0xF);
3205 if (u->IsFrontEngine() && frame == TUNNEL_SOUND_FRAME) {
3206 if (!PlayVehicleSound(u, VSE_TUNNEL) && RailVehInfo(u->engine_type)->engclass == 0) {
3207 SndPlayVehicleFx(SND_05_TRAIN_THROUGH_TUNNEL, u);
3210 if (frame == _tunnel_visibility_frame[dir]) {
3211 u->vehstatus |= VS_HIDDEN;
3213 } else if (u->direction == ReverseDir(DiagDirToDir(dir))) {
3214 uint frame = DistanceFromTileEdge(dir, x & 0xF, y & 0xF);
3215 if (frame == TILE_SIZE - _tunnel_visibility_frame[dir]) {
3216 u->vehstatus &= ~VS_HIDDEN;
3220 break;
3223 case TT_MISC_DEPOT: {
3224 if (!IsRailDepot(tile)) break;
3226 /* depot direction */
3227 DiagDirection dir = GetGroundDepotDirection(tile);
3229 /* make sure a train is not entering the tile from behind */
3230 assert(DistanceFromTileEdge(ReverseDiagDir(dir), x & 0xF, y & 0xF) != 0);
3232 int fract_x = (int)(x & 0xF) - _vehicle_initial_x_fract[dir];
3233 int fract_y = (int)(y & 0xF) - _vehicle_initial_y_fract[dir];
3235 if (u->direction == DiagDirToDir(ReverseDiagDir(dir))) {
3236 if (fract_x == 0 && fract_y == 0) {
3237 /* enter the depot */
3238 u->trackdir = TRACKDIR_DEPOT,
3239 u->vehstatus |= VS_HIDDEN; // hide it
3240 u->direction = ReverseDir(u->direction);
3241 if (u->Next() == NULL) VehicleEnterDepot(u->First());
3242 u->tile = tile;
3244 InvalidateWindowData(WC_VEHICLE_DEPOT, u->tile);
3246 } else if (u->direction == DiagDirToDir(dir)) {
3247 static const int8 delta_x[4] = { -1, 0, 1, 0 };
3248 static const int8 delta_y[4] = { 0, 1, 0, -1 };
3250 /* Calculate the point where the following wagon should be activated. */
3251 int length = u->CalcNextVehicleOffset() + 1;
3253 if ((fract_x == length * delta_x[dir]) && (fract_y == length * delta_y[dir])) {
3254 /* leave the depot? */
3255 if ((u = u->Next()) != NULL) {
3256 u->vehstatus &= ~VS_HIDDEN;
3257 u->trackdir = DiagDirToDiagTrackdir(dir);
3262 break;
3267 static StationID TrainEnter_Station(Train *v, TileIndex tile, int x, int y)
3269 StationID station_id = GetStationIndex(tile);
3270 if (!v->current_order.ShouldStopAtStation(v, station_id)) return INVALID_STATION;
3271 if (!IsRailStation(tile) || !v->IsFrontEngine()) return INVALID_STATION;
3273 int station_ahead;
3274 int station_length;
3275 int stop = GetTrainStopLocation(station_id, tile, Train::From(v), &station_ahead, &station_length);
3277 /* Stop whenever that amount of station ahead + the distance from the
3278 * begin of the platform to the stop location is longer than the length
3279 * of the platform. Station ahead 'includes' the current tile where the
3280 * vehicle is on, so we need to subtract that. */
3281 if (stop + station_ahead - (int)TILE_SIZE >= station_length) return INVALID_STATION;
3283 DiagDirection dir = DirToDiagDir(v->direction);
3285 x &= 0xF;
3286 y &= 0xF;
3288 if (DiagDirToAxis(dir) != AXIS_X) Swap(x, y);
3289 if (y == TILE_SIZE / 2) {
3290 if (dir != DIAGDIR_SE && dir != DIAGDIR_SW) x = TILE_SIZE - 1 - x;
3291 stop &= TILE_SIZE - 1;
3293 if (x == stop) {
3294 return station_id; // enter station
3295 } else if (x < stop) {
3296 v->vehstatus |= VS_TRAIN_SLOWING;
3297 uint16 spd = max(0, (stop - x) * 20 - 15);
3298 if (spd < v->cur_speed) v->cur_speed = spd;
3302 return INVALID_STATION;
3306 * Call the tile callback function for a train entering a tile
3307 * @param v Train entering the tile
3308 * @param tile Tile entered
3309 * @param x X position
3310 * @param y Y position
3311 * @return Station ID of an entered station, or INVALID_STATION otherwise
3313 static StationID TrainEnterTile(Train *v, TileIndex tile, int x, int y)
3315 switch (GetTileType(tile)) {
3316 default: NOT_REACHED();
3318 case TT_RAILWAY:
3319 TrainEnter_Track(v, tile, x, y);
3320 break;
3322 case TT_MISC:
3323 TrainEnter_Misc(v, tile, x, y);
3324 break;
3326 case TT_STATION:
3327 return TrainEnter_Station(v, tile, x, y);
3330 return INVALID_STATION;
3334 * Choose the trackdir to follow when a train enters a new tile.
3335 * @param v The train that enters the tile
3336 * @param tile The tile entered
3337 * @param enterdir The direction the train is moving between tiles
3338 * @param tsdir The direction to use for GetTileRailwayStatus
3339 * @param check_90deg Check for 90-degree turns and disallow them
3340 * @param reverse Set to false to not execute the vehicle reversing. This does not change any other logic.
3341 * @return The trackdir to use, or INVALID_TRACKDIR if the train cannot go forward
3343 static Trackdir TrainControllerChooseTrackdir(Train *v, TileIndex tile, DiagDirection enterdir, DiagDirection tsdir, bool check_90deg, bool reverse)
3345 /* Get the status of the tracks in the new tile and mask
3346 * away the bits that aren't reachable. */
3347 TrackStatus ts = GetTileRailwayStatus(tile, tsdir);
3348 TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(enterdir);
3350 TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
3351 if (check_90deg) trackdirbits &= ~TrackdirCrossesTrackdirs(v->trackdir);
3353 TrackdirBits red_signals = TrackStatusToRedSignals(ts);
3355 /* Check if the new tile constrains tracks that are compatible
3356 * with the current train, if not, bail out. */
3357 if (trackdirbits == TRACKDIR_BIT_NONE || !CheckCompatibleRail(v, tile, TrackdirToTrack(FindFirstTrackdir(trackdirbits)))) {
3358 if (reverse) {
3359 v->wait_counter = 0;
3360 v->cur_speed = 0;
3361 v->subspeed = 0;
3362 ReverseTrainDirection(v);
3365 return INVALID_TRACKDIR;
3368 Trackdir chosen_trackdir;
3370 /* Don't use trackdirbits here as the setting to forbid 90 deg turns might have been switched between reservation and now. */
3371 TrackdirBits res_trackdirs = TrackBitsToTrackdirBits(GetReservedTrackbits(tile)) & reachable_trackdirs;
3372 /* Do we have a suitable reserved trackdir? */
3373 if (res_trackdirs != TRACKDIR_BIT_NONE) {
3374 chosen_trackdir = FindFirstTrackdir(res_trackdirs);
3375 } else {
3376 if (!ChooseTrainTrack(v, v->GetPos(), tile, trackdirbits, false, &chosen_trackdir)) {
3377 MarkTrainAsStuck(v);
3379 assert(chosen_trackdir != INVALID_TRACKDIR);
3380 assert(HasBit(trackdirbits, chosen_trackdir));
3383 /* Make sure chosen trackdir is a valid trackdir */
3384 assert(IsValidTrackdir(chosen_trackdir));
3386 if (v->force_proceed != TFP_NONE) {
3387 /* For each signal we find decrease the counter by one.
3388 * We start at two, so the first signal we pass decreases
3389 * this to one, then if we reach the next signal it is
3390 * decreased to zero and we won't pass that new signal. */
3391 bool at_signal;
3392 if (IsRailwayTile(tile)) {
3393 Track track = TrackdirToTrack(chosen_trackdir);
3394 /* However, we do not want to be stopped by PBS
3395 * signals entered via the back. */
3396 at_signal = HasSignalOnTrack(tile, track) &&
3397 (GetSignalType(tile, track) != SIGTYPE_PBS ||
3398 HasSignalOnTrackdir(tile, chosen_trackdir));
3399 } else if (maptile_is_rail_tunnel(tile)) {
3400 at_signal = maptile_has_tunnel_signals(tile);
3401 } else {
3402 at_signal = false;
3405 if (at_signal) {
3406 v->force_proceed = (v->force_proceed == TFP_SIGNAL) ? TFP_STUCK : TFP_NONE;
3407 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
3411 /* Check if it's a red signal and if force proceed is clicked. */
3412 if (!HasBit(red_signals, chosen_trackdir) || v->force_proceed != TFP_NONE) {
3413 /* Proceed */
3414 TryReserveRailTrack(tile, TrackdirToTrack(chosen_trackdir), false);
3415 return chosen_trackdir;
3418 /* In front of a red signal */
3419 assert(trackdirbits == TrackdirToTrackdirBits(chosen_trackdir));
3421 /* Don't handle stuck trains here. */
3422 if (HasBit(v->flags, VRF_TRAIN_STUCK)) return INVALID_TRACKDIR;
3424 if (!HasSignalOnTrackdir(tile, ReverseTrackdir(chosen_trackdir))) {
3425 v->cur_speed = 0;
3426 v->subspeed = 0;
3427 v->progress = 255 - 100;
3428 if (!_settings_game.pf.reverse_at_signals || ++v->wait_counter < _settings_game.pf.wait_oneway_signal * 20) return INVALID_TRACKDIR;
3429 } else if (HasSignalOnTrackdir(tile, chosen_trackdir)) {
3430 v->cur_speed = 0;
3431 v->subspeed = 0;
3432 v->progress = 255 - 10;
3433 if (!_settings_game.pf.reverse_at_signals || ++v->wait_counter < _settings_game.pf.wait_twoway_signal * 73) {
3434 DiagDirection exitdir = TrackdirToExitdir(chosen_trackdir);
3435 TileIndex o_tile = TileAddByDiagDir(tile, exitdir);
3437 exitdir = ReverseDiagDir(exitdir);
3439 /* check if a train is waiting on the other side */
3440 VehicleTileFinder iter (o_tile);
3441 while (!iter.finished()) {
3442 Vehicle *v = iter.next();
3443 if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) continue;
3445 Train *t = Train::From(v);
3446 if (t->IsFrontEngine() && (t->trackdir < TRACKDIR_END) && (t->cur_speed <= 5) && TrackdirToExitdir(t->trackdir) == exitdir) {
3447 iter.set_found();
3450 if (!iter.was_found()) return INVALID_TRACKDIR;
3454 /* If we would reverse but are currently in a PBS block and
3455 * reversing of stuck trains is disabled, don't reverse.
3456 * This does not apply if the reason for reversing is a one-way
3457 * signal blocking us, because a train would then be stuck forever. */
3458 if (!_settings_game.pf.reverse_at_signals && !HasOnewaySignalBlockingTrackdir(tile, chosen_trackdir)) {
3459 assert(IsSignalBufferEmpty());
3460 AddPosToSignalBuffer(v->GetPos(), v->owner);
3461 if (UpdateSignalsInBuffer() == SIGSEG_PBS) {
3462 v->wait_counter = 0;
3463 return INVALID_TRACKDIR;
3467 if (reverse) {
3468 v->wait_counter = 0;
3469 v->cur_speed = 0;
3470 v->subspeed = 0;
3471 ReverseTrainDirection(v);
3474 return INVALID_TRACKDIR;
3478 * Move a vehicle chain one movement stop forwards.
3479 * @param v First vehicle to move.
3480 * @param nomove Stop moving this and all following vehicles.
3481 * @param reverse Set to false to not execute the vehicle reversing. This does not change any other logic.
3482 * @return True if the vehicle could be moved forward, false otherwise.
3484 bool TrainController(Train *v, Vehicle *nomove, bool reverse)
3486 Train *first = v->First();
3487 Train *prev;
3488 bool direction_changed = false; // has direction of any part changed?
3490 /* For every vehicle after and including the given vehicle */
3491 for (prev = v->Previous(); v != nomove; prev = v, v = v->Next()) {
3492 TileIndex old_tile; // old virtual tile
3493 bool old_in_wormhole, new_in_wormhole; // old position was in wormhole, new position is in wormhole
3494 DiagDirection enterdir = INVALID_DIAGDIR; // direction into the new tile, or INVALID_DIAGDIR if we stay on the old tile
3495 DiagDirection tsdir = INVALID_DIAGDIR; // direction to use for GetTileRailwayStatus, only when moving into a new tile
3497 VehiclePos gp = GetNewVehiclePos(v);
3498 if (v->trackdir == TRACKDIR_WORMHOLE) {
3499 /* In a tunnel or on a bridge (middle part) */
3500 old_tile = TileVirtXY(v->x_pos, v->y_pos);
3501 old_in_wormhole = true;
3503 if (gp.new_tile != v->tile) {
3504 /* Still in the wormhole */
3505 new_in_wormhole = true;
3506 if (v->IsFrontEngine() && (v->vehstatus & VS_HIDDEN) && maptile_has_tunnel_signal(v->tile, false) && (FindTunnelPrevTrain(v) < TILE_SIZE)) {
3507 /* too close to train ahead, stop */
3508 return false;
3510 } else {
3511 new_in_wormhole = false;
3512 enterdir = ReverseDiagDir(GetTunnelBridgeDirection(gp.new_tile));
3513 tsdir = INVALID_DIAGDIR;
3515 } else if (v->trackdir == TRACKDIR_DEPOT) {
3516 /* Inside depot */
3517 assert(gp.new_tile == v->tile);
3518 continue;
3519 } else if (gp.new_tile == v->tile) {
3520 /* Not inside tunnel or depot, staying in the old tile */
3521 old_tile = v->tile;
3522 old_in_wormhole = false;
3523 new_in_wormhole = false;
3524 } else {
3525 /* Not inside tunnel or depot, about to enter a new tile */
3526 old_tile = v->tile;
3527 old_in_wormhole = false;
3529 /* Determine what direction we're entering the new tile from */
3530 enterdir = DiagdirBetweenTiles(v->tile, gp.new_tile);
3531 assert(IsValidDiagDirection(enterdir));
3533 if (IsTunnelTile(v->tile) && GetTunnelBridgeDirection(v->tile) == enterdir) {
3534 TileIndex end_tile = GetOtherTunnelEnd(v->tile);
3535 if (end_tile != gp.new_tile) {
3536 /* Entering a tunnel */
3537 new_in_wormhole = true;
3538 gp.new_tile = end_tile;
3539 } else {
3540 new_in_wormhole = false;
3541 tsdir = INVALID_DIAGDIR;
3543 } else if (IsRailBridgeTile(v->tile) && GetTunnelBridgeDirection(v->tile) == enterdir) {
3544 TileIndex end_tile = GetOtherBridgeEnd(v->tile);
3545 if (end_tile != gp.new_tile) {
3546 /* Entering a bridge */
3547 new_in_wormhole = true;
3548 gp.new_tile = end_tile;
3549 ClrBit(v->gv_flags, GVF_GOINGUP_BIT);
3550 ClrBit(v->gv_flags, GVF_GOINGDOWN_BIT);
3552 first->cur_speed = min(first->cur_speed, GetBridgeSpec(GetRailBridgeType(v->tile))->speed);
3553 } else {
3554 new_in_wormhole = false;
3555 tsdir = INVALID_DIAGDIR;
3557 } else {
3558 new_in_wormhole = false;
3559 tsdir = ReverseDiagDir(enterdir);
3563 if (enterdir == INVALID_DIAGDIR) {
3564 /* Staying on the same tile */
3566 /* Reverse when we are at the end of the track already, do not move to the new position */
3567 if (!new_in_wormhole && v->IsFrontEngine() && !TrainCheckIfLineEnds(v, reverse)) return false;
3568 } else {
3569 /* Entering a new tile */
3571 Trackdir chosen_trackdir;
3572 if (!new_in_wormhole) {
3573 if (prev == NULL) {
3574 /* Currently the locomotive is active. Determine which one of the
3575 * available tracks to choose */
3576 chosen_trackdir = TrainControllerChooseTrackdir(v, gp.new_tile, enterdir, tsdir, !old_in_wormhole && _settings_game.pf.forbid_90_deg, reverse);
3577 if (chosen_trackdir == INVALID_TRACKDIR) return false;
3579 if (HasPbsSignalOnTrackdir(gp.new_tile, chosen_trackdir)) {
3580 SetSignalState(gp.new_tile, chosen_trackdir, SIGNAL_STATE_RED);
3581 MarkTileDirtyByTile(gp.new_tile);
3583 } else {
3584 /* The wagon is active, simply follow the prev vehicle. */
3585 if (prev->tile == gp.new_tile) {
3586 /* Choose the same track as prev */
3587 assert(prev->trackdir != TRACKDIR_WORMHOLE);
3588 chosen_trackdir = prev->trackdir;
3589 } else {
3590 /* Choose the track that leads to the tile where prev is.
3591 * This case is active if 'prev' is already on the second next tile, when 'v' just enters the next tile.
3592 * I.e. when the tile between them has only space for a single vehicle like
3593 * 1) horizontal/vertical track tiles and
3594 * 2) some orientations of tunnel entries, where the vehicle is already inside the wormhole at 8/16 from the tile edge.
3595 * Is also the train just reversing, the wagon inside the tunnel is 'on' the tile of the opposite tunnel entry.
3597 DiagDirection exitdir = DiagdirBetweenTiles(gp.new_tile, prev->tile);
3598 assert(IsValidDiagDirection(exitdir));
3599 chosen_trackdir = EnterdirExitdirToTrackdir(enterdir, exitdir);
3600 assert(!IsReversingRoadTrackdir(chosen_trackdir));
3603 assert(CheckCompatibleRail(v, gp.new_tile, TrackdirToTrack(chosen_trackdir)));
3605 } else {
3606 /* new_in_wormhole */
3607 assert(!old_in_wormhole);
3608 if (prev == NULL) {
3609 if (IsRailwayTile(old_tile)) {
3610 SetBridgeMiddleReservation(old_tile, true);
3611 SetBridgeMiddleReservation(gp.new_tile, true);
3612 } else {
3613 SetTunnelMiddleReservation(old_tile, true);
3614 SetTunnelMiddleReservation(gp.new_tile, true);
3619 if (v->Next() == NULL) {
3620 /* Clear any track reservation when the last vehicle leaves the tile */
3621 ClearPathReservation(v, v->GetPos());
3623 RailPathPos rev = v->GetReversePos();
3624 if (HasSignalOnPos(rev)) {
3625 assert(IsSignalBufferEmpty());
3626 AddPosToSignalBuffer(rev, v->owner);
3627 /* Defer actual updating of signals until the train has moved */
3631 if (new_in_wormhole) {
3632 /* Just entered the wormhole */
3633 v->tile = gp.new_tile;
3634 v->trackdir = TRACKDIR_WORMHOLE;
3635 } else {
3636 RailType old_rt = v->GetTrackRailType();
3638 v->tile = gp.new_tile;
3639 v->trackdir = chosen_trackdir;
3641 if (GetRailType(gp.new_tile, TrackdirToTrack(chosen_trackdir)) != old_rt) {
3642 v->First()->ConsistChanged(true);
3646 Direction chosen_dir;
3647 if (new_in_wormhole) {
3648 chosen_dir = DiagDirToDir(enterdir);
3649 } else {
3650 /* Update XY to reflect the entrance to the new tile, and select the direction to use */
3651 const byte *b = _initial_tile_subcoord[chosen_trackdir];
3652 gp.x = (gp.x & ~0xF) | b[0];
3653 gp.y = (gp.y & ~0xF) | b[1];
3654 chosen_dir = (Direction)b[2];
3657 if (chosen_dir != v->direction) {
3658 if (prev == NULL && _settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) {
3659 const AccelerationSlowdownParams *asp = &_accel_slowdown[GetRailTypeInfo(v->railtype)->acceleration_type];
3660 DirDiff diff = DirDifference(v->direction, chosen_dir);
3661 v->cur_speed -= (diff == DIRDIFF_45RIGHT || diff == DIRDIFF_45LEFT ? asp->small_turn : asp->large_turn) * v->cur_speed >> 8;
3663 direction_changed = true;
3664 v->direction = chosen_dir;
3667 /* update image of train, as well as delta XY */
3668 v->UpdateDeltaXY(v->direction);
3671 if (!new_in_wormhole) {
3672 /* Call the landscape function and tell it that the vehicle entered the tile */
3673 StationID sid = TrainEnterTile(v, gp.new_tile, gp.x, gp.y);
3674 if (sid != INVALID_STATION) {
3675 /* The new position is the location where we want to stop */
3676 TrainEnterStation(v, sid);
3680 if (v->IsFrontEngine()) {
3681 v->wait_counter = 0;
3683 /* Always try to extend the reservation when entering a tile. */
3684 bool check_next_tile;
3685 if (!new_in_wormhole) {
3686 /* If we are approaching a crossing that is reserved, play the sound now. */
3687 TileIndex crossing = TrainApproachingCrossingTile(v);
3688 if (crossing != INVALID_TILE && HasCrossingReservation(crossing) && _settings_client.sound.ambient) SndPlayTileFx(SND_0E_LEVEL_CROSSING, crossing);
3690 check_next_tile = enterdir != INVALID_DIAGDIR;
3691 } else if (old_in_wormhole) {
3692 TileIndex last_wormhole_tile = TileAddByDiagDir(v->tile, GetTunnelBridgeDirection(v->tile));
3693 check_next_tile = (gp.new_tile == last_wormhole_tile) && (gp.new_tile != old_tile);
3694 } else {
3695 TileIndexDiff diff = TileOffsByDiagDir(GetTunnelBridgeDirection(v->tile));
3696 check_next_tile = (old_tile == TILE_ADD(v->tile, 2*diff));
3699 if (check_next_tile) CheckNextTrainTile(v);
3702 v->x_pos = gp.x;
3703 v->y_pos = gp.y;
3704 VehicleUpdatePosition(v);
3706 if (new_in_wormhole) {
3707 if ((v->vehstatus & VS_HIDDEN) == 0) VehicleUpdateViewport(v, true);
3708 } else {
3709 /* update the Z position of the vehicle */
3710 int old_z = v->UpdateInclination(enterdir != INVALID_DIAGDIR, false);
3712 if (prev == NULL) {
3713 /* This is the first vehicle in the train */
3714 AffectSpeedByZChange(v, old_z);
3718 if (enterdir != INVALID_DIAGDIR) {
3719 /* Update signals or crossing state if we changed tile */
3720 /* Signals can only change when the first or the last vehicle moves. */
3721 if (v->Next() == NULL) {
3722 /* Update the signal segment added before, if any */
3723 UpdateSignalsInBuffer();
3724 if (!old_in_wormhole && IsLevelCrossingTile(old_tile)) UpdateLevelCrossing(old_tile);
3727 if (v->IsFrontEngine()) {
3728 RailPathPos pos = v->GetPos();
3729 if (HasSignalOnPos(pos)) {
3730 assert(IsSignalBufferEmpty());
3731 AddPosToSignalBuffer(pos, v->owner);
3733 if (UpdateSignalsInBuffer() == SIGSEG_PBS &&
3734 HasSignalAlongPos(pos) &&
3735 /* A PBS block with a non-PBS signal facing us? */
3736 !IsPbsSignal(GetSignalType(pos))) {
3737 /* We are entering a block with PBS signals right now, but
3738 * not through a PBS signal. This means we don't have a
3739 * reservation right now. As a conventional signal will only
3740 * ever be green if no other train is in the block, getting
3741 * a path should always be possible. If the player built
3742 * such a strange network that it is not possible, the train
3743 * will be marked as stuck and the player has to deal with
3744 * the problem. */
3745 TryReserveRailTrack(pos);
3746 /* Signals cannot be built on junctions, so
3747 * a track on which there is a signal either
3748 * is already reserved or can be reserved. */
3749 assert (HasReservedPos(pos));
3750 if (!TryPathReserve(v)) {
3751 MarkTrainAsStuck(v);
3758 if (old_in_wormhole && old_tile != gp.new_tile && v->Next() == NULL && maptile_is_rail_tunnel(v->tile) && maptile_has_tunnel_signal(v->tile, false)
3759 && TileAddByDiagDir(old_tile, GetTunnelBridgeDirection(v->tile)) == GetOtherTunnelEnd(v->tile)) {
3760 AddTunnelToSignalBuffer(v->tile, v->owner);
3761 UpdateSignalsInBuffer();
3764 /* Do not check on every tick to save some computing time. */
3765 if (v->IsFrontEngine() && v->tick_counter % _settings_game.pf.path_backoff_interval == 0) {
3766 CheckNextTrainTile(v);
3770 if (direction_changed) first->tcache.cached_max_curve_speed = first->GetCurveSpeedLimit();
3772 return true;
3777 * Deletes/Clears the last wagon of a crashed train. It takes the engine of the
3778 * train, then goes to the last wagon and deletes that. Each call to this function
3779 * will remove the last wagon of a crashed train. If this wagon was on a crossing,
3780 * or inside a tunnel/bridge, recalculate the signals as they might need updating
3781 * @param v the Vehicle of which last wagon is to be removed
3783 static void DeleteLastWagon(Train *v)
3785 Train *first = v->First();
3787 /* Go to the last wagon and delete the link pointing there
3788 * *u is then the one-before-last wagon, and *v the last
3789 * one which will physically be removed */
3790 Train *u = v;
3791 for (; v->Next() != NULL; v = v->Next()) u = v;
3792 u->SetNext(NULL);
3794 if (first != v) {
3795 /* Recalculate cached train properties */
3796 first->ConsistChanged(false);
3797 /* Update the depot window if the first vehicle is in depot -
3798 * if v == first, then it is updated in PreDestructor() */
3799 if (first->trackdir == TRACKDIR_DEPOT) {
3800 SetWindowDirty(WC_VEHICLE_DEPOT, first->tile);
3802 v->last_station_visited = first->last_station_visited; // for PreDestructor
3805 /* 'v' shouldn't be accessed after it has been deleted */
3806 Trackdir trackdir = v->trackdir;
3807 TileIndex tile = v->tile;
3808 Owner owner = v->owner;
3810 delete v;
3811 v = NULL; // make sure nobody will try to read 'v' anymore
3813 if (trackdir == TRACKDIR_DEPOT) return;
3815 if (trackdir == TRACKDIR_WORMHOLE) {
3816 TileIndex endtile = GetOtherTunnelBridgeEnd(tile);
3817 if (EnsureNoTrainOnTunnelBridgeMiddle(tile, endtile).Succeeded()) {
3818 if (IsRailwayTile(tile)) {
3819 SetBridgeMiddleReservation(tile, false);
3820 SetBridgeMiddleReservation(endtile, false);
3821 } else {
3822 SetTunnelMiddleReservation(tile, false);
3823 SetTunnelMiddleReservation(endtile, false);
3827 assert(IsSignalBufferEmpty());
3828 if (IsRailwayTile(tile)) {
3829 AddBridgeToSignalBuffer(tile, owner);
3830 } else {
3831 AddTunnelToSignalBuffer(tile, owner);
3833 UpdateSignalsInBuffer();
3834 return;
3837 Track track = TrackdirToTrack(trackdir);
3838 if (HasReservedTrack(tile, track)) {
3839 UnreserveRailTrack(tile, track);
3841 /* If there are still crashed vehicles on the tile, give the track reservation to them */
3842 TrackBits remaining_trackbits = TRACK_BIT_NONE;
3843 VehicleTileIterator iter (tile);
3844 while (!iter.finished()) {
3845 Vehicle *v = iter.next();
3846 if (v->type == VEH_TRAIN && (v->vehstatus & VS_CRASHED) != 0) {
3847 Trackdir trackdir = Train::From(v)->trackdir;
3848 if (trackdir == TRACKDIR_WORMHOLE) {
3849 /* Vehicle is inside a wormhole, v->trackdir contains no useful value then. */
3850 remaining_trackbits |= DiagDirToDiagTrackBits(GetTunnelBridgeDirection(v->tile));
3851 } else if (trackdir != TRACKDIR_DEPOT) {
3852 remaining_trackbits |= TrackToTrackBits(TrackdirToTrack(trackdir));
3857 /* It is important that these two are the first in the loop, as reservation cannot deal with every trackbit combination */
3858 assert(TRACK_BEGIN == TRACK_X && TRACK_Y == TRACK_BEGIN + 1);
3859 Track t;
3860 FOR_EACH_SET_TRACK(t, remaining_trackbits) TryReserveRailTrack(tile, t);
3863 /* check if the wagon was on a road/rail-crossing */
3864 if (IsLevelCrossingTile(tile)) UpdateLevelCrossing(tile);
3866 /* Update signals */
3867 assert(IsSignalBufferEmpty());
3868 if (IsRailDepotTile(tile)) {
3869 AddDepotToSignalBuffer(tile, owner);
3870 } else if (IsTunnelTile(tile)) {
3871 AddTunnelToSignalBuffer(tile, owner);
3872 } else {
3873 AddTrackToSignalBuffer(tile, track, owner);
3875 UpdateSignalsInBuffer();
3879 * Rotate all vehicles of a (crashed) train chain randomly to animate the crash.
3880 * @param v First crashed vehicle.
3882 static void ChangeTrainDirRandomly(Train *v)
3884 static const DirDiff delta[] = {
3885 DIRDIFF_45LEFT, DIRDIFF_SAME, DIRDIFF_SAME, DIRDIFF_45RIGHT
3888 do {
3889 /* We don't need to twist around vehicles if they're not visible */
3890 if (!(v->vehstatus & VS_HIDDEN)) {
3891 v->direction = ChangeDir(v->direction, delta[GB(Random(), 0, 2)]);
3892 v->UpdateDeltaXY(v->direction);
3893 v->cur_image = v->GetImage(v->direction, EIT_ON_MAP);
3894 /* Refrain from updating the z position of the vehicle when on
3895 * a bridge, because UpdateInclination() will put the vehicle under
3896 * the bridge in that case */
3897 if (v->trackdir != TRACKDIR_WORMHOLE) {
3898 VehicleUpdatePosition(v);
3899 v->UpdateInclination(false, false);
3902 } while ((v = v->Next()) != NULL);
3906 * Handle a crashed train.
3907 * @param v First train vehicle.
3908 * @return %Vehicle chain still exists.
3910 static bool HandleCrashedTrain(Train *v)
3912 int state = ++v->crash_anim_pos;
3914 if (state == 4 && !(v->vehstatus & VS_HIDDEN)) {
3915 CreateEffectVehicleRel(v, 4, 4, 8, EV_EXPLOSION_LARGE);
3918 uint32 r;
3919 if (state <= 200 && Chance16R(1, 7, r)) {
3920 int index = (r * 10 >> 16);
3922 Vehicle *u = v;
3923 do {
3924 if (--index < 0) {
3925 r = Random();
3927 CreateEffectVehicleRel(u,
3928 GB(r, 8, 3) + 2,
3929 GB(r, 16, 3) + 2,
3930 GB(r, 0, 3) + 5,
3931 EV_EXPLOSION_SMALL);
3932 break;
3934 } while ((u = u->Next()) != NULL);
3937 if (state <= 240 && !(v->tick_counter & 3)) ChangeTrainDirRandomly(v);
3939 if (state >= 4440 && !(v->tick_counter & 0x1F)) {
3940 bool ret = v->Next() != NULL;
3941 DeleteLastWagon(v);
3942 return ret;
3945 return true;
3948 /** Maximum speeds for train that is broken down or approaching line end */
3949 static const uint16 _breakdown_speeds[16] = {
3950 225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, 15
3955 * Train is approaching line end, slow down and possibly reverse
3957 * @param v front train engine
3958 * @param signal not line end, just a red signal
3959 * @param reverse Set to false to not execute the vehicle reversing. This does not change any other logic.
3960 * @return true iff we did NOT have to reverse
3962 static bool TrainApproachingLineEnd(Train *v, bool signal, bool reverse)
3964 /* Calc position within the current tile */
3965 uint x = v->x_pos & 0xF;
3966 uint y = v->y_pos & 0xF;
3968 /* for diagonal directions, 'x' will be 0..15 -
3969 * for other directions, it will be 1, 3, 5, ..., 15 */
3970 switch (v->direction) {
3971 case DIR_N : x = ~x + ~y + 25; break;
3972 case DIR_NW: x = y; // FALL THROUGH
3973 case DIR_NE: x = ~x + 16; break;
3974 case DIR_E : x = ~x + y + 9; break;
3975 case DIR_SE: x = y; break;
3976 case DIR_S : x = x + y - 7; break;
3977 case DIR_W : x = ~y + x + 9; break;
3978 default: break;
3981 /* Do not reverse when approaching red signal. Make sure the vehicle's front
3982 * does not cross the tile boundary when we do reverse, but as the vehicle's
3983 * location is based on their center, use half a vehicle's length as offset.
3984 * Multiply the half-length by two for straight directions to compensate that
3985 * we only get odd x offsets there. */
3986 if (!signal && x + (v->gcache.cached_veh_length + 1) / 2 * (IsDiagonalDirection(v->direction) ? 1 : 2) >= TILE_SIZE) {
3987 /* we are too near the tile end, reverse now */
3988 v->cur_speed = 0;
3989 if (reverse) ReverseTrainDirection(v);
3990 return false;
3993 /* slow down */
3994 v->vehstatus |= VS_TRAIN_SLOWING;
3995 uint16 break_speed = _breakdown_speeds[x & 0xF];
3996 if (break_speed < v->cur_speed) v->cur_speed = break_speed;
3998 return true;
4003 * Determines whether a train is on the map and will stay on it after leaving the current tile
4004 * (as opposed to being in a wormhole or depot)
4005 * @param v train to test
4006 * @return true iff vehicle is NOT entering or inside a depot or tunnel/bridge
4008 static bool TrainStayOnMap(const Train *v)
4010 /* Exit if inside a tunnel/bridge or a depot */
4011 if (v->trackdir == TRACKDIR_WORMHOLE || v->trackdir == TRACKDIR_DEPOT) return false;
4013 TileIndex tile = v->tile;
4015 /* entering a tunnel/bridge? */
4016 if (IsRailBridgeTile(tile)) {
4017 if (TrackdirToExitdir(v->trackdir) == GetTunnelBridgeDirection(tile)) return false;
4020 if (IsTunnelTile(tile)) {
4021 DiagDirection dir = GetTunnelBridgeDirection(tile);
4022 if (DiagDirToDir(dir) == v->direction) return false;
4025 /* entering a depot? */
4026 if (IsRailDepotTile(tile)) {
4027 DiagDirection dir = ReverseDiagDir(GetGroundDepotDirection(tile));
4028 if (DiagDirToDir(dir) == v->direction) return false;
4031 return true;
4036 * Determines whether train is approaching a rail-road crossing
4037 * (thus making it barred)
4038 * @param v front engine of train
4039 * @return TileIndex of crossing the train is approaching, else INVALID_TILE
4040 * @pre v in non-crashed front engine
4042 static TileIndex TrainApproachingCrossingTile(const Train *v)
4044 assert(v->IsFrontEngine());
4045 assert(!(v->vehstatus & VS_CRASHED));
4047 if (!TrainStayOnMap(v)) return INVALID_TILE;
4049 DiagDirection dir = TrackdirToExitdir(v->trackdir);
4050 TileIndex tile = v->tile + TileOffsByDiagDir(dir);
4052 /* not a crossing || wrong axis || unusable rail (wrong type or owner) */
4053 if (!IsLevelCrossingTile(tile) || DiagDirToAxis(dir) == GetCrossingRoadAxis(tile) ||
4054 !CheckCompatibleRail(v, tile)) {
4055 return INVALID_TILE;
4058 return tile;
4063 * Checks for line end. Also, bars crossing at next tile if needed
4065 * @param v vehicle we are checking
4066 * @param reverse Set to false to not execute the vehicle reversing. This does not change any other logic.
4067 * @return true iff we did NOT have to reverse
4069 static bool TrainCheckIfLineEnds(Train *v, bool reverse)
4071 /* First, handle broken down train */
4073 int t = v->breakdown_ctr;
4074 if (t > 1) {
4075 v->vehstatus |= VS_TRAIN_SLOWING;
4077 uint16 break_speed = _breakdown_speeds[GB(~t, 4, 4)];
4078 if (break_speed < v->cur_speed) v->cur_speed = break_speed;
4079 } else {
4080 v->vehstatus &= ~VS_TRAIN_SLOWING;
4083 if (v->trackdir == TRACKDIR_WORMHOLE) {
4084 DiagDirection dir = GetTunnelBridgeDirection(v->tile);
4086 /* Only check when the train is on the last tile segment */
4087 if (TileVirtXY(v->x_pos, v->y_pos) != v->tile + TileOffsByDiagDir(dir)) return true;
4089 TrackStatus ts = GetTileRailwayStatus(v->tile, INVALID_DIAGDIR);
4090 TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(ReverseDiagDir(dir));
4092 TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
4093 TrackdirBits red_signals = TrackStatusToRedSignals(ts) & reachable_trackdirs;
4095 assert(trackdirbits != TRACKDIR_BIT_NONE);
4096 assert(CheckCompatibleRail(v, v->tile, TrackdirToTrack(FindFirstTrackdir(trackdirbits))));
4098 return (trackdirbits & red_signals) == 0 || TrainApproachingLineEnd(v, true, reverse);
4101 if (!TrainStayOnMap(v)) return true;
4103 /* Determine the non-diagonal direction in which we will exit this tile */
4104 DiagDirection dir = TrackdirToExitdir(v->trackdir);
4105 /* Calculate next tile */
4106 TileIndex tile = v->tile + TileOffsByDiagDir(dir);
4108 /* Determine the track status on the next tile */
4109 TrackStatus ts = GetTileRailwayStatus(tile, ReverseDiagDir(dir));
4110 TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(dir);
4112 TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
4113 TrackdirBits red_signals = TrackStatusToRedSignals(ts) & reachable_trackdirs;
4115 /* We are sure the train is not entering a depot, it is detected above */
4117 /* mask unreachable track bits if we are forbidden to do 90deg turns */
4118 if (_settings_game.pf.forbid_90_deg) {
4119 trackdirbits &= ~TrackdirCrossesTrackdirs(v->trackdir);
4122 /* no suitable trackbits at all || unusable rail (wrong type or owner) */
4123 if (trackdirbits == TRACKDIR_BIT_NONE || !CheckCompatibleRail(v, tile, TrackdirToTrack(FindFirstTrackdir(trackdirbits)))) {
4124 return TrainApproachingLineEnd(v, false, reverse);
4127 /* approaching red signal */
4128 if ((trackdirbits & red_signals) != 0) return TrainApproachingLineEnd(v, true, reverse);
4130 /* approaching a rail/road crossing? then make it red */
4131 if (IsLevelCrossingTile(tile)) MaybeBarCrossingWithSound(tile);
4133 return true;
4137 static bool TrainLocoHandler(Train *v, bool mode)
4139 /* train has crashed? */
4140 if (v->vehstatus & VS_CRASHED) {
4141 return mode ? true : HandleCrashedTrain(v); // 'this' can be deleted here
4144 if (v->force_proceed != TFP_NONE) {
4145 ClrBit(v->flags, VRF_TRAIN_STUCK);
4146 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
4149 /* train is broken down? */
4150 if (v->HandleBreakdown()) return true;
4152 if (HasBit(v->flags, VRF_REVERSING) && v->cur_speed == 0) {
4153 ReverseTrainDirection(v);
4156 /* exit if train is stopped */
4157 if ((v->vehstatus & VS_STOPPED) && v->cur_speed == 0) return true;
4159 bool valid_order = !v->current_order.IsType(OT_NOTHING) && v->current_order.GetType() != OT_CONDITIONAL;
4160 if (ProcessOrders(v) && CheckReverseTrain(v)) {
4161 v->wait_counter = 0;
4162 v->cur_speed = 0;
4163 v->subspeed = 0;
4164 ClrBit(v->flags, VRF_LEAVING_STATION);
4165 ReverseTrainDirection(v);
4166 return true;
4167 } else if (HasBit(v->flags, VRF_LEAVING_STATION)) {
4168 /* Try to reserve a path when leaving the station as we
4169 * might not be marked as wanting a reservation, e.g.
4170 * when an overlength train gets turned around in a station. */
4171 assert(IsSignalBufferEmpty());
4172 AddPosToSignalBuffer(v->GetPos(), v->owner);
4173 if (UpdateSignalsInBuffer() == SIGSEG_PBS || _settings_game.pf.reserve_paths) {
4174 TryPathReserve(v, true, true);
4176 ClrBit(v->flags, VRF_LEAVING_STATION);
4179 v->HandleLoading(mode);
4181 if (v->current_order.IsType(OT_LOADING)) return true;
4183 if (CheckTrainStayInDepot(v)) return true;
4185 if (!mode) v->ShowVisualEffect();
4187 /* We had no order but have an order now, do look ahead. */
4188 if (!valid_order && !v->current_order.IsType(OT_NOTHING)) {
4189 CheckNextTrainTile(v);
4192 /* Handle stuck trains. */
4193 if (!mode && HasBit(v->flags, VRF_TRAIN_STUCK)) {
4194 ++v->wait_counter;
4196 /* Should we try reversing this tick if still stuck? */
4197 bool turn_around = v->wait_counter % (_settings_game.pf.wait_for_pbs_path * DAY_TICKS) == 0 && _settings_game.pf.reverse_at_signals;
4199 if (!turn_around && v->wait_counter % _settings_game.pf.path_backoff_interval != 0 && v->force_proceed == TFP_NONE) return true;
4200 if (!TryPathReserve(v)) {
4201 /* Still stuck. */
4202 if (turn_around) ReverseTrainDirection(v);
4204 if (HasBit(v->flags, VRF_TRAIN_STUCK) && v->wait_counter > 2 * _settings_game.pf.wait_for_pbs_path * DAY_TICKS) {
4205 /* Show message to player. */
4206 if (_settings_client.gui.lost_vehicle_warn && v->owner == _local_company) {
4207 SetDParam(0, v->index);
4208 AddVehicleAdviceNewsItem(STR_NEWS_TRAIN_IS_STUCK, v->index);
4210 v->wait_counter = 0;
4212 /* Exit if force proceed not pressed, else reset stuck flag anyway. */
4213 if (v->force_proceed == TFP_NONE) return true;
4214 ClrBit(v->flags, VRF_TRAIN_STUCK);
4215 v->wait_counter = 0;
4216 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
4220 if (v->current_order.IsType(OT_LEAVESTATION)) {
4221 v->current_order.Free();
4222 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
4223 return true;
4226 int j = v->UpdateSpeed();
4228 /* we need to invalidate the widget if we are stopping from 'Stopping 0 km/h' to 'Stopped' */
4229 if (v->cur_speed == 0 && (v->vehstatus & VS_STOPPED)) {
4230 /* If we manually stopped, we're not force-proceeding anymore. */
4231 v->force_proceed = TFP_NONE;
4232 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
4235 int adv_spd = v->GetAdvanceDistance();
4236 if (j < adv_spd) {
4237 /* if the vehicle has speed 0, update the last_speed field. */
4238 if (v->cur_speed == 0) v->SetLastSpeed();
4239 } else {
4240 TrainCheckIfLineEnds(v);
4241 /* Loop until the train has finished moving. */
4242 for (;;) {
4243 j -= adv_spd;
4244 TrainController(v, NULL);
4245 /* Don't continue to move if the train crashed. */
4246 if (CheckTrainCollision(v)) break;
4247 /* Determine distance to next map position */
4248 adv_spd = v->GetAdvanceDistance();
4250 /* No more moving this tick */
4251 if (j < adv_spd || v->cur_speed == 0) break;
4253 OrderType order_type = v->current_order.GetType();
4254 /* Do not skip waypoints (incl. 'via' stations) when passing through at full speed. */
4255 if ((order_type == OT_GOTO_WAYPOINT || order_type == OT_GOTO_STATION) &&
4256 (v->current_order.GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION) &&
4257 IsStationTile(v->tile) &&
4258 v->current_order.GetDestination() == GetStationIndex(v->tile)) {
4259 ProcessOrders(v);
4262 v->SetLastSpeed();
4265 for (Train *u = v; u != NULL; u = u->Next()) {
4266 if ((u->vehstatus & VS_HIDDEN) != 0) continue;
4268 u->UpdateViewport(false, false);
4271 if (v->progress == 0) v->progress = j; // Save unused spd for next time, if TrainController didn't set progress
4273 return true;
4277 * Get running cost for the train consist.
4278 * @return Yearly running costs.
4280 Money Train::GetRunningCost() const
4282 Money cost = 0;
4283 const Train *v = this;
4285 do {
4286 const Engine *e = v->GetEngine();
4287 if (e->u.rail.running_cost_class == INVALID_PRICE) continue;
4289 uint cost_factor = GetVehicleProperty(v, PROP_TRAIN_RUNNING_COST_FACTOR, e->u.rail.running_cost);
4290 if (cost_factor == 0) continue;
4292 /* Halve running cost for multiheaded parts */
4293 if (v->IsMultiheaded()) cost_factor /= 2;
4295 cost += GetPrice(e->u.rail.running_cost_class, cost_factor, e->GetGRF());
4296 } while ((v = v->GetNextVehicle()) != NULL);
4298 return cost;
4302 * Update train vehicle data for a tick.
4303 * @return True if the vehicle still exists, false if it has ceased to exist (front of consists only).
4305 bool Train::Tick()
4307 this->tick_counter++;
4309 if (this->IsFrontEngine()) {
4310 if (!(this->vehstatus & VS_STOPPED) || this->cur_speed > 0) this->running_ticks++;
4312 this->current_order_time++;
4314 if (!TrainLocoHandler(this, false)) return false;
4316 return TrainLocoHandler(this, true);
4317 } else if (this->IsFreeWagon() && (this->vehstatus & VS_CRASHED)) {
4318 /* Delete flooded standalone wagon chain */
4319 if (++this->crash_anim_pos >= 4400) {
4320 delete this;
4321 return false;
4325 return true;
4329 * Check whether a train needs service, and if so, find a depot or service it.
4330 * @return v %Train to check.
4332 static void CheckIfTrainNeedsService(Train *v)
4334 if (Company::Get(v->owner)->settings.vehicle.servint_trains == 0 || !v->NeedsAutomaticServicing()) return;
4335 if (v->IsChainInDepot()) {
4336 VehicleServiceInDepot(v);
4337 return;
4340 FindDepotData tfdd;
4341 /* Only go to the depot if it is not too far out of our way. */
4342 if (!FindClosestTrainDepot(v, true, &tfdd)) {
4343 if (v->current_order.IsType(OT_GOTO_DEPOT)) {
4344 /* If we were already heading for a depot but it has
4345 * suddenly moved farther away, we continue our normal
4346 * schedule? */
4347 v->current_order.MakeDummy();
4348 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
4350 return;
4353 DepotID depot = GetDepotIndex(tfdd.tile);
4355 if (v->current_order.IsType(OT_GOTO_DEPOT) &&
4356 v->current_order.GetDestination() != depot &&
4357 !Chance16(3, 16)) {
4358 return;
4361 SetBit(v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS);
4362 v->current_order.MakeGoToDepot(depot, ODTFB_SERVICE);
4363 v->dest_tile = tfdd.tile;
4364 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
4367 /** Update day counters of the train vehicle. */
4368 void Train::OnNewDay()
4370 AgeVehicle(this);
4372 if ((++this->day_counter & 7) == 0) DecreaseVehicleValue(this);
4374 if (this->IsFrontEngine()) {
4375 CheckVehicleBreakdown(this);
4377 CheckIfTrainNeedsService(this);
4379 CheckOrders(this);
4381 /* update destination */
4382 if (this->current_order.IsType(OT_GOTO_STATION)) {
4383 TileIndex tile = Station::Get(this->current_order.GetDestination())->train_station.tile;
4384 if (tile != INVALID_TILE) this->dest_tile = tile;
4387 if (this->running_ticks != 0) {
4388 /* running costs */
4389 CommandCost cost(EXPENSES_TRAIN_RUN, this->GetRunningCost() * this->running_ticks / (DAYS_IN_YEAR * DAY_TICKS));
4391 this->profit_this_year -= cost.GetCost();
4392 this->running_ticks = 0;
4394 SubtractMoneyFromCompanyFract(this->owner, cost);
4396 SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
4397 SetWindowClassesDirty(WC_TRAINS_LIST);
4403 * Get the trackdir of the train vehicle.
4404 * @return Current trackdir of the vehicle.
4406 Trackdir Train::GetTrackdir() const
4408 assert(!(this->vehstatus & VS_CRASHED));
4409 assert(this->trackdir != TRACKDIR_WORMHOLE);
4411 if (this->trackdir == TRACKDIR_DEPOT) {
4412 /* We'll assume the train is facing outwards */
4413 return DiagDirToDiagTrackdir(GetGroundDepotDirection(this->tile)); // Train in depot
4416 return this->trackdir;
4419 RailPathPos Train::GetPos() const
4421 if (this->vehstatus & VS_CRASHED) return RailPathPos();
4423 if (this->trackdir == TRACKDIR_WORMHOLE) {
4424 DiagDirection rev = GetTunnelBridgeDirection(this->tile);
4425 assert(ReverseDiagDir(rev) == DirToDiagDir(this->direction));
4426 return RailPathPos(TILE_ADD(this->tile, TileOffsByDiagDir(rev)), DiagDirToDiagTrackdir(ReverseDiagDir(rev)), this->tile);
4429 return RailPathPos(this->tile, this->GetTrackdir());
4432 RailPathPos Train::GetReversePos() const
4434 if (this->vehstatus & VS_CRASHED) return RailPathPos();
4436 if (this->trackdir == TRACKDIR_WORMHOLE) {
4437 TileIndex other_end = GetOtherTunnelBridgeEnd(this->tile);
4438 DiagDirection dir = GetTunnelBridgeDirection(other_end);
4439 assert(dir == DirToDiagDir(this->direction));
4440 return RailPathPos(TILE_ADD(other_end, TileOffsByDiagDir(dir)), DiagDirToDiagTrackdir(ReverseDiagDir(dir)), other_end);
4443 return RailPathPos(this->tile, ReverseTrackdir(this->GetTrackdir()));