Translations update
[openttd/fttd.git] / src / train_cmd.cpp
blob37a92e51da4c11e5242866a48fd46a176582ea82
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 "signalbuffer.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, const PathMPos<RailPathPos> &pos, bool force_res, Trackdir *best_trackdir = NULL);
45 static bool TryPathExtend (Train *v, const RailPathPos &origin, bool mark_as_stuck = false);
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 allowed_changes Stuff that is allowed to change.
109 void Train::ConsistChanged(ConsistChangeFlags allowed_changes)
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 if (allowed_changes & CCF_CAPACITY) {
193 /* Update vehicle capacity. */
194 if (u->cargo_cap > new_cap) u->cargo.Truncate(new_cap);
195 u->refit_cap = min(new_cap, u->refit_cap);
196 u->cargo_cap = new_cap;
197 } else {
198 /* Verify capacity hasn't changed. */
199 if (new_cap != u->cargo_cap) ShowNewGrfVehicleError(u->engine_type, STR_NEWGRF_BROKEN, STR_NEWGRF_BROKEN_CAPACITY, GBUG_VEH_CAPACITY, true);
201 u->vcache.cached_cargo_age_period = GetVehicleProperty(u, PROP_TRAIN_CARGO_AGE_PERIOD, e_u->info.cargo_age_period);
203 /* check the vehicle length (callback) */
204 uint16 veh_len = CALLBACK_FAILED;
205 if (e_u->GetGRF() != NULL && e_u->GetGRF()->grf_version >= 8) {
206 /* Use callback 36 */
207 veh_len = GetVehicleProperty(u, PROP_TRAIN_SHORTEN_FACTOR, CALLBACK_FAILED);
209 if (veh_len != CALLBACK_FAILED && veh_len >= VEHICLE_LENGTH) {
210 ErrorUnknownCallbackResult(e_u->GetGRFID(), CBID_VEHICLE_LENGTH, veh_len);
212 } else if (HasBit(e_u->info.callback_mask, CBM_VEHICLE_LENGTH)) {
213 /* Use callback 11 */
214 veh_len = GetVehicleCallback(CBID_VEHICLE_LENGTH, 0, 0, u->engine_type, u);
216 if (veh_len == CALLBACK_FAILED) veh_len = rvi_u->shorten_factor;
217 veh_len = VEHICLE_LENGTH - Clamp(veh_len, 0, VEHICLE_LENGTH - 1);
219 if (allowed_changes & CCF_LENGTH) {
220 /* Update vehicle length. */
221 u->gcache.cached_veh_length = veh_len;
222 } else {
223 /* Verify length hasn't changed. */
224 if (veh_len != u->gcache.cached_veh_length) VehicleLengthChanged(u);
227 this->gcache.cached_total_length += u->gcache.cached_veh_length;
228 this->InvalidateNewGRFCache();
229 u->InvalidateNewGRFCache();
232 /* store consist weight/max speed in cache */
233 this->vcache.cached_max_speed = max_speed;
234 this->tcache.cached_tilt = train_can_tilt;
235 this->tcache.cached_max_curve_speed = this->GetCurveSpeedLimit();
237 /* 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) */
238 this->CargoChanged();
240 if (this->IsFrontEngine()) {
241 this->UpdateAcceleration();
242 SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
243 InvalidateWindowData(WC_VEHICLE_REFIT, this->index, VIWD_CONSIST_CHANGED);
244 InvalidateWindowData(WC_VEHICLE_ORDERS, this->index, VIWD_CONSIST_CHANGED);
245 InvalidateNewGRFInspectWindow(GSF_TRAINS, this->index);
250 * Get the stop location of (the center) of the front vehicle of a train at
251 * a platform of a station.
252 * @param station_id the ID of the station where we're stopping
253 * @param tile the tile where the vehicle currently is
254 * @param v the vehicle to get the stop location of
255 * @param station_ahead 'return' the amount of 1/16th tiles in front of the train
256 * @param station_length 'return' the station length in 1/16th tiles
257 * @return the location, calculated from the begin of the station to stop at.
259 int GetTrainStopLocation(StationID station_id, TileIndex tile, const Train *v, int *station_ahead, int *station_length)
261 const Station *st = Station::Get(station_id);
262 *station_ahead = st->GetPlatformLength(tile, DirToDiagDir(v->direction)) * TILE_SIZE;
263 *station_length = st->GetPlatformLength(tile) * TILE_SIZE;
265 /* Default to the middle of the station for stations stops that are not in
266 * the order list like intermediate stations when non-stop is disabled */
267 OrderStopLocation osl = OSL_PLATFORM_MIDDLE;
268 if (v->gcache.cached_total_length >= *station_length) {
269 /* The train is longer than the station, make it stop at the far end of the platform */
270 osl = OSL_PLATFORM_FAR_END;
271 } else if (v->current_order.IsType(OT_GOTO_STATION) && v->current_order.GetDestination() == station_id) {
272 osl = v->current_order.GetStopLocation();
275 /* The stop location of the FRONT! of the train */
276 int stop;
277 switch (osl) {
278 default: NOT_REACHED();
280 case OSL_PLATFORM_NEAR_END:
281 stop = v->gcache.cached_total_length;
282 break;
284 case OSL_PLATFORM_MIDDLE:
285 stop = *station_length - (*station_length - v->gcache.cached_total_length) / 2;
286 break;
288 case OSL_PLATFORM_FAR_END:
289 stop = *station_length;
290 break;
293 /* Subtract half the front vehicle length of the train so we get the real
294 * stop location of the train. */
295 return stop - (v->gcache.cached_veh_length + 1) / 2;
300 * Computes train speed limit caused by curves
301 * @return imposed speed limit
303 int Train::GetCurveSpeedLimit() const
305 assert(this->First() == this);
307 static const int absolute_max_speed = UINT16_MAX;
308 int max_speed = absolute_max_speed;
310 if (_settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) return max_speed;
312 int curvecount[2] = {0, 0};
314 /* first find the curve speed limit */
315 int numcurve = 0;
316 int sum = 0;
317 int pos = 0;
318 int lastpos = -1;
319 for (const Vehicle *u = this; u->Next() != NULL; u = u->Next(), pos++) {
320 Direction this_dir = u->direction;
321 Direction next_dir = u->Next()->direction;
323 DirDiff dirdiff = DirDifference(this_dir, next_dir);
324 if (dirdiff == DIRDIFF_SAME) continue;
326 if (dirdiff == DIRDIFF_45LEFT) curvecount[0]++;
327 if (dirdiff == DIRDIFF_45RIGHT) curvecount[1]++;
328 if (dirdiff == DIRDIFF_45LEFT || dirdiff == DIRDIFF_45RIGHT) {
329 if (lastpos != -1) {
330 numcurve++;
331 sum += pos - lastpos;
332 if (pos - lastpos == 1 && max_speed > 88) {
333 max_speed = 88;
336 lastpos = pos;
339 /* if we have a 90 degree turn, fix the speed limit to 60 */
340 if (dirdiff == DIRDIFF_90LEFT || dirdiff == DIRDIFF_90RIGHT) {
341 max_speed = 61;
345 if (numcurve > 0 && max_speed > 88) {
346 if (curvecount[0] == 1 && curvecount[1] == 1) {
347 max_speed = absolute_max_speed;
348 } else {
349 sum /= numcurve;
350 max_speed = 232 - (13 - Clamp(sum, 1, 12)) * (13 - Clamp(sum, 1, 12));
354 if (max_speed != absolute_max_speed) {
355 /* Apply the engine's rail type curve speed advantage, if it slowed by curves */
356 const RailtypeInfo *rti = GetRailTypeInfo(this->railtype);
357 max_speed += (max_speed / 2) * rti->curve_speed;
359 if (this->tcache.cached_tilt) {
360 /* Apply max_speed bonus of 20% for a tilting train */
361 max_speed += max_speed / 5;
365 return max_speed;
368 static uint FindTunnelPrevTrain(const Train *t, Vehicle **vv = NULL)
370 assert(maptile_is_rail_tunnel(t->tile));
371 assert(t->trackdir == TRACKDIR_WORMHOLE);
373 VehicleTileIterator iter (t->tile);
374 Vehicle *closest = NULL;
375 uint dist;
377 switch (GetTunnelBridgeDirection(t->tile)) {
378 default: NOT_REACHED();
380 case DIAGDIR_NE:
381 while (!iter.finished()) {
382 Vehicle *v = iter.next();
383 int pos = v->x_pos;
384 if (pos <= t->x_pos) continue; // v is behind
385 if (closest == NULL || pos < closest->x_pos) {
386 closest = v;
387 } else {
388 assert (pos != closest->x_pos);
391 dist = closest == NULL ? UINT_MAX : closest->x_pos - t->x_pos;
392 break;
394 case DIAGDIR_NW:
395 while (!iter.finished()) {
396 Vehicle *v = iter.next();
397 int pos = v->y_pos;
398 if (pos <= t->y_pos) continue; // v is behind
399 if (closest == NULL || pos < closest->y_pos) {
400 closest = v;
401 } else {
402 assert (pos != closest->y_pos);
405 dist = closest == NULL ? UINT_MAX : closest->y_pos - t->y_pos;
406 break;
408 case DIAGDIR_SW:
409 while (!iter.finished()) {
410 Vehicle *v = iter.next();
411 int pos = v->x_pos;
412 if (pos >= t->x_pos) continue; // v is behind
413 if (closest == NULL || pos > closest->x_pos) {
414 closest = v;
415 } else {
416 assert (pos != closest->x_pos);
419 dist = closest == NULL ? UINT_MAX : t->x_pos - closest->x_pos;
420 break;
422 case DIAGDIR_SE:
423 while (!iter.finished()) {
424 Vehicle *v = iter.next();
425 int pos = v->y_pos;
426 if (pos >= t->y_pos) continue; // v is behind
427 if (closest == NULL || pos > closest->y_pos) {
428 closest = v;
429 } else {
430 assert (pos != closest->y_pos);
433 dist = closest == NULL ? UINT_MAX : t->y_pos - closest->y_pos;
434 break;
437 if (vv != NULL) *vv = closest;
439 return dist;
443 * Calculates the maximum speed of the vehicle under its current conditions.
444 * @return Maximum speed of the vehicle.
446 int Train::GetCurrentMaxSpeed() const
448 int max_speed = _settings_game.vehicle.train_acceleration_model == AM_ORIGINAL ?
449 this->gcache.cached_max_track_speed :
450 this->tcache.cached_max_curve_speed;
452 if (_settings_game.vehicle.train_acceleration_model == AM_REALISTIC && IsRailStationTile(this->tile)) {
453 StationID sid = GetStationIndex(this->tile);
454 if (this->current_order.ShouldStopAtStation(this, sid)) {
455 int station_ahead;
456 int station_length;
457 int stop_at = GetTrainStopLocation(sid, this->tile, this, &station_ahead, &station_length);
459 /* The distance to go is whatever is still ahead of the train minus the
460 * distance from the train's stop location to the end of the platform */
461 int distance_to_go = station_ahead / TILE_SIZE - (station_length - stop_at) / TILE_SIZE;
463 if (distance_to_go > 0) {
464 int st_max_speed = 120;
466 int delta_v = this->cur_speed / (distance_to_go + 1);
467 if (max_speed > (this->cur_speed - delta_v)) {
468 st_max_speed = this->cur_speed - (delta_v / 10);
471 st_max_speed = max(st_max_speed, 25 * distance_to_go);
472 max_speed = min(max_speed, st_max_speed);
477 for (const Train *u = this; u != NULL; u = u->Next()) {
478 if (_settings_game.vehicle.train_acceleration_model == AM_REALISTIC && u->trackdir == TRACKDIR_DEPOT) {
479 max_speed = min(max_speed, 61);
480 break;
483 /* Vehicle is on the middle part of a bridge. */
484 if (u->trackdir == TRACKDIR_WORMHOLE && !(u->vehstatus & VS_HIDDEN)) {
485 max_speed = min(max_speed, GetBridgeSpec(GetRailBridgeType(u->tile))->speed);
489 if (this->trackdir == TRACKDIR_WORMHOLE && (this->vehstatus & VS_HIDDEN) && maptile_has_tunnel_signal(this->tile, false)) {
490 Vehicle *v;
491 uint dist = FindTunnelPrevTrain(this, &v);
493 if (dist <= TILE_SIZE) {
494 max_speed = 0;
495 } else if (v != NULL) {
496 max_speed = min(max_speed, (dist - TILE_SIZE) * this->GetAdvanceDistance() / 2);
497 if (dist < 2 * TILE_SIZE) max_speed = min(max_speed, v->cur_speed);
501 max_speed = min(max_speed, this->current_order.GetMaxSpeed());
502 return min(max_speed, this->gcache.cached_max_track_speed);
505 /** Update acceleration of the train from the cached power and weight. */
506 void Train::UpdateAcceleration()
508 assert(this->IsFrontEngine() || this->IsFreeWagon());
510 uint power = this->gcache.cached_power;
511 uint weight = this->gcache.cached_weight;
512 assert(weight != 0);
513 this->acceleration = Clamp(power / weight * 4, 1, 255);
517 * Get the width of a train vehicle image in the GUI.
518 * @param offset Additional offset for positioning the sprite; set to NULL if not needed
519 * @return Width in pixels
521 int Train::GetDisplayImageWidth(Point *offset) const
523 int reference_width = TRAININFO_DEFAULT_VEHICLE_WIDTH;
524 int vehicle_pitch = 0;
526 const Engine *e = this->GetEngine();
527 if (e->GetGRF() != NULL && is_custom_sprite(e->u.rail.image_index)) {
528 reference_width = e->GetGRF()->traininfo_vehicle_width;
529 vehicle_pitch = e->GetGRF()->traininfo_vehicle_pitch;
532 if (offset != NULL) {
533 offset->x = ScaleGUITrad(reference_width) / 2;
534 offset->y = ScaleGUITrad(vehicle_pitch);
536 return ScaleGUITrad(this->gcache.cached_veh_length * reference_width / VEHICLE_LENGTH);
539 static SpriteID GetDefaultTrainSprite(uint8 spritenum, Direction direction)
541 assert(IsValidImageIndex<VEH_TRAIN>(spritenum));
542 return ((direction + _engine_sprite_add[spritenum]) & _engine_sprite_and[spritenum]) + _engine_sprite_base[spritenum];
546 * Get the sprite to display the train.
547 * @param direction Direction of view/travel.
548 * @param image_type Visualisation context.
549 * @return Sprite to display.
551 void Train::GetImage(Direction direction, EngineImageType image_type, VehicleSpriteSeq *result) const
553 uint8 spritenum = this->spritenum;
555 if (HasBit(this->flags, VRF_REVERSE_DIRECTION)) direction = ReverseDir(direction);
557 if (is_custom_sprite(spritenum)) {
558 GetCustomVehicleSprite(this, (Direction)(direction + 4 * IS_CUSTOM_SECONDHEAD_SPRITE(spritenum)), image_type, result);
559 if (result->IsValid()) return;
561 spritenum = this->GetEngine()->original_image_index;
564 assert(IsValidImageIndex<VEH_TRAIN>(spritenum));
565 SpriteID sprite = GetDefaultTrainSprite(spritenum, direction);
567 if (this->cargo.StoredCount() >= this->cargo_cap / 2U) sprite += _wagon_full_adder[spritenum];
569 result->Set(sprite);
572 static void GetRailIcon(EngineID engine, bool rear_head, int &y, EngineImageType image_type, VehicleSpriteSeq *result)
574 const Engine *e = Engine::Get(engine);
575 Direction dir = rear_head ? DIR_E : DIR_W;
576 uint8 spritenum = e->u.rail.image_index;
578 if (is_custom_sprite(spritenum)) {
579 GetCustomVehicleIcon(engine, dir, image_type, result);
580 if (result->IsValid()) {
581 if (e->GetGRF() != NULL) {
582 y += ScaleGUITrad(e->GetGRF()->traininfo_vehicle_pitch);
584 return;
587 spritenum = Engine::Get(engine)->original_image_index;
590 if (rear_head) spritenum++;
592 result->Set(GetDefaultTrainSprite(spritenum, DIR_W));
595 void DrawTrainEngine (BlitArea *dpi, int left, int right, int preferred_x,
596 int y, EngineID engine, PaletteID pal, EngineImageType image_type)
598 if (RailVehInfo(engine)->railveh_type == RAILVEH_MULTIHEAD) {
599 int yf = y;
600 int yr = y;
602 VehicleSpriteSeq seqf, seqr;
603 GetRailIcon(engine, false, yf, image_type, &seqf);
604 GetRailIcon(engine, true, yr, image_type, &seqr);
606 Rect rectf, rectr;
607 seqf.GetBounds(&rectf);
608 seqr.GetBounds(&rectr);
610 preferred_x = Clamp(preferred_x,
611 left - UnScaleGUI(rectf.left) + ScaleGUITrad(14),
612 right - UnScaleGUI(rectr.right) - ScaleGUITrad(15));
614 seqf.Draw (dpi, preferred_x - ScaleGUITrad(14), yf, pal, pal == PALETTE_CRASH);
615 seqr.Draw (dpi, preferred_x + ScaleGUITrad(15), yr, pal, pal == PALETTE_CRASH);
616 } else {
617 VehicleSpriteSeq seq;
618 GetRailIcon(engine, false, y, image_type, &seq);
620 Rect rect;
621 seq.GetBounds(&rect);
622 preferred_x = Clamp(preferred_x,
623 left - UnScaleGUI(rect.left),
624 right - UnScaleGUI(rect.right));
626 seq.Draw (dpi, preferred_x, y, pal, pal == PALETTE_CRASH);
631 * Get the size of the sprite of a train sprite heading west, or both heads (used for lists).
632 * @param engine The engine to get the sprite from.
633 * @param[out] width The width of the sprite.
634 * @param[out] height The height of the sprite.
635 * @param[out] xoffs Number of pixels to shift the sprite to the right.
636 * @param[out] yoffs Number of pixels to shift the sprite downwards.
637 * @param image_type Context the sprite is used in.
639 void GetTrainSpriteSize(EngineID engine, uint &width, uint &height, int &xoffs, int &yoffs, EngineImageType image_type)
641 int y = 0;
643 VehicleSpriteSeq seq;
644 GetRailIcon(engine, false, y, image_type, &seq);
646 Rect rect;
647 seq.GetBounds(&rect);
649 width = UnScaleGUI(rect.right - rect.left + 1);
650 height = UnScaleGUI(rect.bottom - rect.top + 1);
651 xoffs = UnScaleGUI(rect.left);
652 yoffs = UnScaleGUI(rect.top);
654 if (RailVehInfo(engine)->railveh_type == RAILVEH_MULTIHEAD) {
655 GetRailIcon(engine, true, y, image_type, &seq);
656 seq.GetBounds(&rect);
658 /* Calculate values relative to an imaginary center between the two sprites. */
659 width = ScaleGUITrad(TRAININFO_DEFAULT_VEHICLE_WIDTH) + UnScaleGUI(rect.right) - xoffs;
660 height = max<uint>(height, UnScaleGUI(rect.bottom - rect.top + 1));
661 xoffs = xoffs - ScaleGUITrad(TRAININFO_DEFAULT_VEHICLE_WIDTH) / 2;
662 yoffs = min(yoffs, UnScaleGUI(rect.top));
667 * Build a railroad wagon.
668 * @param tile tile of the depot where rail-vehicle is built.
669 * @param flags type of operation.
670 * @param e the engine to build.
671 * @param ret[out] the vehicle that has been built.
672 * @return the cost of this operation or an error.
674 static CommandCost CmdBuildRailWagon(TileIndex tile, DoCommandFlag flags, const Engine *e, Vehicle **ret)
676 const RailVehicleInfo *rvi = &e->u.rail;
678 /* Check that the wagon can drive on the track in question */
679 if (!IsCompatibleRail(rvi->railtype, GetRailType(tile))) return CMD_ERROR;
681 if (flags & DC_EXEC) {
682 Train *v = new Train();
683 *ret = v;
684 v->spritenum = rvi->image_index;
686 v->engine_type = e->index;
687 v->gcache.first_engine = INVALID_ENGINE; // needs to be set before first callback
689 DiagDirection dir = GetGroundDepotDirection(tile);
691 v->direction = DiagDirToDir(dir);
692 v->tile = tile;
694 int x = TileX(tile) * TILE_SIZE | _vehicle_initial_x_fract[dir];
695 int y = TileY(tile) * TILE_SIZE | _vehicle_initial_y_fract[dir];
697 v->x_pos = x;
698 v->y_pos = y;
699 v->z_pos = GetSlopePixelZ(x, y);
700 v->owner = _current_company;
701 v->trackdir = TRACKDIR_DEPOT;
702 v->vehstatus = VS_HIDDEN | VS_DEFPAL;
704 v->SetWagon();
706 v->SetFreeWagon();
707 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
709 v->cargo_type = e->GetDefaultCargoType();
710 v->cargo_cap = rvi->capacity;
711 v->refit_cap = 0;
713 v->railtype = rvi->railtype;
715 v->date_of_last_service = _date;
716 v->build_year = _cur_year;
717 v->sprite_seq.Set(SPR_IMG_QUERY);
718 v->random_bits = VehicleRandomBits();
720 v->group_id = DEFAULT_GROUP;
722 AddArticulatedParts(v);
724 _new_vehicle_id = v->index;
726 v->UpdatePosition();
727 v->First()->ConsistChanged(CCF_ARRANGE);
728 UpdateTrainGroupID(v->First());
730 CheckConsistencyOfArticulatedVehicle(v);
732 /* Try to connect the vehicle to one of free chains of wagons. */
733 Train *w;
734 FOR_ALL_TRAINS(w) {
735 if (w->tile == tile && ///< Same depot
736 w->IsFreeWagon() && ///< A free wagon chain
737 w->engine_type == e->index && ///< Same type
738 w->First() != v && ///< Don't connect to ourself
739 !(w->vehstatus & VS_CRASHED)) { ///< Not crashed/flooded
740 DoCommand(0, v->index | 1 << 20, w->Last()->index, DC_EXEC, CMD_MOVE_RAIL_VEHICLE);
741 break;
746 return CommandCost();
749 /** Move all free vehicles in the depot to the train */
750 static void NormalizeTrainVehInDepot(const Train *u)
752 const Train *v;
753 FOR_ALL_TRAINS(v) {
754 if (v->IsFreeWagon() && v->tile == u->tile &&
755 v->trackdir == TRACKDIR_DEPOT) {
756 if (DoCommand(0, v->index | 1 << 20, u->index, DC_EXEC,
757 CMD_MOVE_RAIL_VEHICLE).Failed())
758 break;
763 static void AddRearEngineToMultiheadedTrain(Train *v)
765 Train *u = new Train();
766 v->value >>= 1;
767 u->value = v->value;
768 u->direction = v->direction;
769 u->owner = v->owner;
770 u->tile = v->tile;
771 u->x_pos = v->x_pos;
772 u->y_pos = v->y_pos;
773 u->z_pos = v->z_pos;
774 u->trackdir = TRACKDIR_DEPOT;
775 u->vehstatus = v->vehstatus & ~VS_STOPPED;
776 u->spritenum = v->spritenum + 1;
777 u->cargo_type = v->cargo_type;
778 u->cargo_subtype = v->cargo_subtype;
779 u->cargo_cap = v->cargo_cap;
780 u->refit_cap = v->refit_cap;
781 u->railtype = v->railtype;
782 u->engine_type = v->engine_type;
783 u->date_of_last_service = v->date_of_last_service;
784 u->build_year = v->build_year;
785 u->sprite_seq.Set(SPR_IMG_QUERY);
786 u->random_bits = VehicleRandomBits();
787 v->SetMultiheaded();
788 u->SetMultiheaded();
789 v->SetNext(u);
790 u->UpdatePosition();
792 /* Now we need to link the front and rear engines together */
793 v->other_multiheaded_part = u;
794 u->other_multiheaded_part = v;
798 * Build a railroad vehicle.
799 * @param tile tile of the depot where rail-vehicle is built.
800 * @param flags type of operation.
801 * @param e the engine to build.
802 * @param data bit 0 prevents any free cars from being added to the train.
803 * @param ret[out] the vehicle that has been built.
804 * @return the cost of this operation or an error.
806 CommandCost CmdBuildRailVehicle(TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **ret)
808 const RailVehicleInfo *rvi = &e->u.rail;
810 if (rvi->railveh_type == RAILVEH_WAGON) return CmdBuildRailWagon(tile, flags, e, ret);
812 /* Check if depot and new engine uses the same kind of tracks *
813 * We need to see if the engine got power on the tile to avoid electric engines in non-electric depots */
814 if (!HasPowerOnRail(rvi->railtype, GetRailType(tile))) return CMD_ERROR;
816 if (flags & DC_EXEC) {
817 DiagDirection dir = GetGroundDepotDirection(tile);
818 int x = TileX(tile) * TILE_SIZE + _vehicle_initial_x_fract[dir];
819 int y = TileY(tile) * TILE_SIZE + _vehicle_initial_y_fract[dir];
821 Train *v = new Train();
822 *ret = v;
823 v->direction = DiagDirToDir(dir);
824 v->tile = tile;
825 v->owner = _current_company;
826 v->x_pos = x;
827 v->y_pos = y;
828 v->z_pos = GetSlopePixelZ(x, y);
829 v->trackdir = TRACKDIR_DEPOT;
830 v->vehstatus = VS_HIDDEN | VS_STOPPED | VS_DEFPAL;
831 v->spritenum = rvi->image_index;
832 v->cargo_type = e->GetDefaultCargoType();
833 v->cargo_cap = rvi->capacity;
834 v->refit_cap = 0;
835 v->last_station_visited = INVALID_STATION;
836 v->last_loading_station = INVALID_STATION;
838 v->engine_type = e->index;
839 v->gcache.first_engine = INVALID_ENGINE; // needs to be set before first callback
841 v->reliability = e->reliability;
842 v->reliability_spd_dec = e->reliability_spd_dec;
843 v->max_age = e->GetLifeLengthInDays();
845 v->railtype = rvi->railtype;
846 _new_vehicle_id = v->index;
848 v->SetServiceInterval(Company::Get(_current_company)->settings.vehicle.servint_trains);
849 v->date_of_last_service = _date;
850 v->build_year = _cur_year;
851 v->sprite_seq.Set(SPR_IMG_QUERY);
852 v->random_bits = VehicleRandomBits();
854 if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) SetBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE);
855 v->SetServiceIntervalIsPercent(Company::Get(_current_company)->settings.vehicle.servint_ispercent);
857 v->group_id = DEFAULT_GROUP;
859 v->SetFrontEngine();
860 v->SetEngine();
862 v->UpdatePosition();
864 if (rvi->railveh_type == RAILVEH_MULTIHEAD) {
865 AddRearEngineToMultiheadedTrain(v);
866 } else {
867 AddArticulatedParts(v);
870 v->ConsistChanged(CCF_ARRANGE);
871 UpdateTrainGroupID(v);
873 if (!HasBit(data, 0) && !(flags & DC_AUTOREPLACE)) { // check if the cars should be added to the new vehicle
874 NormalizeTrainVehInDepot(v);
877 CheckConsistencyOfArticulatedVehicle(v);
880 return CommandCost();
883 static Train *FindGoodVehiclePos(const Train *src)
885 EngineID eng = src->engine_type;
886 TileIndex tile = src->tile;
888 Train *dst;
889 FOR_ALL_TRAINS(dst) {
890 if (dst->IsFreeWagon() && dst->tile == tile && !(dst->vehstatus & VS_CRASHED)) {
891 /* check so all vehicles in the line have the same engine. */
892 Train *t = dst;
893 while (t->engine_type == eng) {
894 t = t->Next();
895 if (t == NULL) return dst;
900 return NULL;
903 /** Helper type for lists/vectors of trains */
904 typedef SmallVector<Train *, 16> TrainList;
907 * Make a backup of a train into a train list.
908 * @param list to make the backup in
909 * @param t the train to make the backup of
911 static void MakeTrainBackup(TrainList &list, Train *t)
913 for (; t != NULL; t = t->Next()) *list.Append() = t;
917 * Restore the train from the backup list.
918 * @param list the train to restore.
920 static void RestoreTrainBackup(TrainList &list)
922 /* No train, nothing to do. */
923 if (list.Length() == 0) return;
925 Train *prev = NULL;
926 /* Iterate over the list and rebuild it. */
927 for (Train **iter = list.Begin(); iter != list.End(); iter++) {
928 Train *t = *iter;
929 if (prev != NULL) {
930 prev->SetNext(t);
931 } else if (t->Previous() != NULL) {
932 /* Make sure the head of the train is always the first in the chain. */
933 t->Previous()->SetNext(NULL);
935 prev = t;
940 * Remove the given wagon from its consist.
941 * @param part the part of the train to remove.
942 * @param chain whether to remove the whole chain.
944 static void RemoveFromConsist(Train *part, bool chain = false)
946 Train *tail = chain ? part->Last() : part->GetLastEnginePart();
948 /* Unlink at the front, but make it point to the next
949 * vehicle after the to be remove part. */
950 if (part->Previous() != NULL) part->Previous()->SetNext(tail->Next());
952 /* Unlink at the back */
953 tail->SetNext(NULL);
957 * Inserts a chain into the train at dst.
958 * @param dst the place where to append after.
959 * @param chain the chain to actually add.
961 static void InsertInConsist(Train *dst, Train *chain)
963 /* We do not want to add something in the middle of an articulated part. */
964 assert(dst->Next() == NULL || !dst->Next()->IsArticulatedPart());
966 chain->Last()->SetNext(dst->Next());
967 dst->SetNext(chain);
971 * Normalise the dual heads in the train, i.e. if one is
972 * missing move that one to this train.
973 * @param t the train to normalise.
975 static void NormaliseDualHeads(Train *t)
977 for (; t != NULL; t = t->GetNextVehicle()) {
978 if (!t->IsMultiheaded() || !t->IsEngine()) continue;
980 /* Make sure that there are no free cars before next engine */
981 Train *u;
982 for (u = t; u->Next() != NULL && !u->Next()->IsEngine(); u = u->Next()) {}
984 if (u == t->other_multiheaded_part) continue;
986 /* Remove the part from the 'wrong' train */
987 RemoveFromConsist(t->other_multiheaded_part);
988 /* And add it to the 'right' train */
989 InsertInConsist(u, t->other_multiheaded_part);
994 * Normalise the sub types of the parts in this chain.
995 * @param chain the chain to normalise.
997 static void NormaliseSubtypes(Train *chain)
999 /* Nothing to do */
1000 if (chain == NULL) return;
1002 /* We must be the first in the chain. */
1003 assert(chain->Previous() == NULL);
1005 /* Set the appropriate bits for the first in the chain. */
1006 if (chain->IsWagon()) {
1007 chain->SetFreeWagon();
1008 } else {
1009 assert(chain->IsEngine());
1010 chain->SetFrontEngine();
1013 /* Now clear the bits for the rest of the chain */
1014 for (Train *t = chain->Next(); t != NULL; t = t->Next()) {
1015 t->ClearFreeWagon();
1016 t->ClearFrontEngine();
1021 * Check/validate whether we may actually build a new train.
1022 * @note All vehicles are/were 'heads' of their chains.
1023 * @param original_dst The original destination chain.
1024 * @param dst The destination chain after constructing the train.
1025 * @param original_dst The original source chain.
1026 * @param dst The source chain after constructing the train.
1027 * @return possible error of this command.
1029 static CommandCost CheckNewTrain(Train *original_dst, Train *dst, Train *original_src, Train *src)
1031 /* Just add 'new' engines and subtract the original ones.
1032 * If that's less than or equal to 0 we can be sure we did
1033 * not add any engines (read: trains) along the way. */
1034 if ((src != NULL && src->IsEngine() ? 1 : 0) +
1035 (dst != NULL && dst->IsEngine() ? 1 : 0) -
1036 (original_src != NULL && original_src->IsEngine() ? 1 : 0) -
1037 (original_dst != NULL && original_dst->IsEngine() ? 1 : 0) <= 0) {
1038 return CommandCost();
1041 /* Get a free unit number and check whether it's within the bounds.
1042 * There will always be a maximum of one new train. */
1043 if (GetFreeUnitNumber(VEH_TRAIN) <= _settings_game.vehicle.max_trains) return CommandCost();
1045 return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
1049 * Check whether the train parts can be attached.
1050 * @param t the train to check
1051 * @return possible error of this command.
1053 static CommandCost CheckTrainAttachment(Train *t)
1055 /* No multi-part train, no need to check. */
1056 if (t == NULL || t->Next() == NULL || !t->IsEngine()) return CommandCost();
1058 /* The maximum length for a train. For each part we decrease this by one
1059 * and if the result is negative the train is simply too long. */
1060 int allowed_len = _settings_game.vehicle.max_train_length * TILE_SIZE - t->gcache.cached_veh_length;
1062 Train *head = t;
1063 Train *prev = t;
1065 /* Break the prev -> t link so it always holds within the loop. */
1066 t = t->Next();
1067 prev->SetNext(NULL);
1069 /* Make sure the cache is cleared. */
1070 head->InvalidateNewGRFCache();
1072 while (t != NULL) {
1073 allowed_len -= t->gcache.cached_veh_length;
1075 Train *next = t->Next();
1077 /* Unlink the to-be-added piece; it is already unlinked from the previous
1078 * part due to the fact that the prev -> t link is broken. */
1079 t->SetNext(NULL);
1081 /* Don't check callback for articulated or rear dual headed parts */
1082 if (!t->IsArticulatedPart() && !t->IsRearDualheaded()) {
1083 /* Back up and clear the first_engine data to avoid using wagon override group */
1084 EngineID first_engine = t->gcache.first_engine;
1085 t->gcache.first_engine = INVALID_ENGINE;
1087 /* We don't want the cache to interfere. head's cache is cleared before
1088 * the loop and after each callback does not need to be cleared here. */
1089 t->InvalidateNewGRFCache();
1091 uint16 callback = GetVehicleCallbackParent(CBID_TRAIN_ALLOW_WAGON_ATTACH, 0, 0, head->engine_type, t, head);
1093 /* Restore original first_engine data */
1094 t->gcache.first_engine = first_engine;
1096 /* We do not want to remember any cached variables from the test run */
1097 t->InvalidateNewGRFCache();
1098 head->InvalidateNewGRFCache();
1100 if (callback != CALLBACK_FAILED) {
1101 /* A failing callback means everything is okay */
1102 StringID error = STR_NULL;
1104 if (head->GetGRF()->grf_version < 8) {
1105 if (callback == 0xFD) error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
1106 if (callback < 0xFD) error = GetGRFStringID(head->GetGRFID(), 0xD000 + callback);
1107 if (callback >= 0x100) ErrorUnknownCallbackResult(head->GetGRFID(), CBID_TRAIN_ALLOW_WAGON_ATTACH, callback);
1108 } else {
1109 if (callback < 0x400) {
1110 error = GetGRFStringID(head->GetGRFID(), 0xD000 + callback);
1111 } else {
1112 switch (callback) {
1113 case 0x400: // allow if railtypes match (always the case for OpenTTD)
1114 case 0x401: // allow
1115 break;
1117 default: // unknown reason -> disallow
1118 case 0x402: // disallow attaching
1119 error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
1120 break;
1125 if (error != STR_NULL) return_cmd_error(error);
1129 /* And link it to the new part. */
1130 prev->SetNext(t);
1131 prev = t;
1132 t = next;
1135 if (allowed_len < 0) return_cmd_error(STR_ERROR_TRAIN_TOO_LONG);
1136 return CommandCost();
1140 * Validate whether we are going to create valid trains.
1141 * @note All vehicles are/were 'heads' of their chains.
1142 * @param original_dst The original destination chain.
1143 * @param dst The destination chain after constructing the train.
1144 * @param original_dst The original source chain.
1145 * @param dst The source chain after constructing the train.
1146 * @param check_limit Whether to check the vehicle limit.
1147 * @return possible error of this command.
1149 static CommandCost ValidateTrains(Train *original_dst, Train *dst, Train *original_src, Train *src, bool check_limit)
1151 /* Check whether we may actually construct the trains. */
1152 CommandCost ret = CheckTrainAttachment(src);
1153 if (ret.Failed()) return ret;
1154 ret = CheckTrainAttachment(dst);
1155 if (ret.Failed()) return ret;
1157 /* Check whether we need to build a new train. */
1158 return check_limit ? CheckNewTrain(original_dst, dst, original_src, src) : CommandCost();
1162 * Arrange the trains in the wanted way.
1163 * @param dst_head The destination chain of the to be moved vehicle.
1164 * @param dst The destination for the to be moved vehicle.
1165 * @param src_head The source chain of the to be moved vehicle.
1166 * @param src The to be moved vehicle.
1167 * @param move_chain Whether to move all vehicles after src or not.
1169 static void ArrangeTrains(Train **dst_head, Train *dst, Train **src_head, Train *src, bool move_chain)
1171 /* First determine the front of the two resulting trains */
1172 if (*src_head == *dst_head) {
1173 /* If we aren't moving part(s) to a new train, we are just moving the
1174 * front back and there is not destination head. */
1175 *dst_head = NULL;
1176 } else if (*dst_head == NULL) {
1177 /* If we are moving to a new train the head of the move train would become
1178 * the head of the new vehicle. */
1179 *dst_head = src;
1182 if (src == *src_head) {
1183 /* If we are moving the front of a train then we are, in effect, creating
1184 * a new head for the train. Point to that. Unless we are moving the whole
1185 * train in which case there is not 'source' train anymore.
1186 * In case we are a multiheaded part we want the complete thing to come
1187 * with us, so src->GetNextUnit(), however... when we are e.g. a wagon
1188 * that is followed by a rear multihead we do not want to include that. */
1189 *src_head = move_chain ? NULL :
1190 (src->IsMultiheaded() ? src->GetNextUnit() : src->GetNextVehicle());
1193 /* Now it's just simply removing the part that we are going to move from the
1194 * source train and *if* the destination is a not a new train add the chain
1195 * at the destination location. */
1196 RemoveFromConsist(src, move_chain);
1197 if (*dst_head != src) InsertInConsist(dst, src);
1199 /* Now normalise the dual heads, that is move the dual heads around in such
1200 * a way that the head and rear of a dual head are in the same train */
1201 NormaliseDualHeads(*src_head);
1202 NormaliseDualHeads(*dst_head);
1206 * Normalise the head of the train again, i.e. that is tell the world that
1207 * we have changed and update all kinds of variables.
1208 * @param head the train to update.
1210 static void NormaliseTrainHead(Train *head)
1212 /* Not much to do! */
1213 if (head == NULL) return;
1215 /* Tell the 'world' the train changed. */
1216 head->ConsistChanged(CCF_ARRANGE);
1217 UpdateTrainGroupID(head);
1219 /* Not a front engine, i.e. a free wagon chain. No need to do more. */
1220 if (!head->IsFrontEngine()) return;
1222 /* Update the refit button and window */
1223 InvalidateWindowData(WC_VEHICLE_REFIT, head->index, VIWD_CONSIST_CHANGED);
1224 SetWindowWidgetDirty(WC_VEHICLE_VIEW, head->index, WID_VV_REFIT);
1226 /* If we don't have a unit number yet, set one. */
1227 if (head->unitnumber != 0) return;
1228 head->unitnumber = GetFreeUnitNumber(VEH_TRAIN);
1232 * Move a rail vehicle around inside the depot.
1233 * @param tile unused
1234 * @param flags type of operation
1235 * Note: DC_AUTOREPLACE is set when autoreplace tries to undo its modifications or moves vehicles to temporary locations inside the depot.
1236 * @param p1 various bitstuffed elements
1237 * - p1 (bit 0 - 19) source vehicle index
1238 * - p1 (bit 20) move all vehicles following the source vehicle
1239 * - p1 (bit 31) do not show an error message on failure
1240 * @param p2 what wagon to put the source wagon AFTER, XXX - INVALID_VEHICLE to make a new line
1241 * @param text unused
1242 * @return the cost of this operation or an error
1244 CommandCost CmdMoveRailVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1246 VehicleID s = GB(p1, 0, 20);
1247 VehicleID d = GB(p2, 0, 20);
1248 bool move_chain = HasBit(p1, 20);
1250 Train *src = Train::GetIfValid(s);
1251 if (src == NULL) return CMD_ERROR;
1253 CommandCost ret = CheckOwnership(src->owner);
1254 if (ret.Failed()) return ret;
1256 /* Do not allow moving crashed vehicles inside the depot, it is likely to cause asserts later */
1257 if (src->vehstatus & VS_CRASHED) return CMD_ERROR;
1259 /* if nothing is selected as destination, try and find a matching vehicle to drag to. */
1260 Train *dst;
1261 if (d == INVALID_VEHICLE) {
1262 dst = src->IsEngine() ? NULL : FindGoodVehiclePos(src);
1263 } else {
1264 dst = Train::GetIfValid(d);
1265 if (dst == NULL) return CMD_ERROR;
1267 CommandCost ret = CheckOwnership(dst->owner);
1268 if (ret.Failed()) return ret;
1270 /* Do not allow appending to crashed vehicles, too */
1271 if (dst->vehstatus & VS_CRASHED) return CMD_ERROR;
1274 /* if an articulated part is being handled, deal with its parent vehicle */
1275 src = src->GetFirstEnginePart();
1276 if (dst != NULL) {
1277 dst = dst->GetFirstEnginePart();
1280 /* don't move the same vehicle.. */
1281 if (src == dst) return CommandCost();
1283 /* locate the head of the two chains */
1284 Train *src_head = src->First();
1285 Train *dst_head;
1286 if (dst != NULL) {
1287 dst_head = dst->First();
1288 if (dst_head->tile != src_head->tile) return CMD_ERROR;
1289 /* Now deal with articulated part of destination wagon */
1290 dst = dst->GetLastEnginePart();
1291 } else {
1292 dst_head = NULL;
1295 if (src->IsRearDualheaded()) return_cmd_error(STR_ERROR_REAR_ENGINE_FOLLOW_FRONT);
1297 /* When moving all wagons, we can't have the same src_head and dst_head */
1298 if (move_chain && src_head == dst_head) return CommandCost();
1300 /* When moving a multiheaded part to be place after itself, bail out. */
1301 if (!move_chain && dst != NULL && dst->IsRearDualheaded() && src == dst->other_multiheaded_part) return CommandCost();
1303 /* Check if all vehicles in the source train are stopped inside a depot. */
1304 if (!src_head->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
1306 /* Check if all vehicles in the destination train are stopped inside a depot. */
1307 if (dst_head != NULL && !dst_head->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
1309 /* First make a backup of the order of the trains. That way we can do
1310 * whatever we want with the order and later on easily revert. */
1311 TrainList original_src;
1312 TrainList original_dst;
1314 MakeTrainBackup(original_src, src_head);
1315 MakeTrainBackup(original_dst, dst_head);
1317 /* Also make backup of the original heads as ArrangeTrains can change them.
1318 * For the destination head we do not care if it is the same as the source
1319 * head because in that case it's just a copy. */
1320 Train *original_src_head = src_head;
1321 Train *original_dst_head = (dst_head == src_head ? NULL : dst_head);
1323 /* We want this information from before the rearrangement, but execute this after the validation.
1324 * original_src_head can't be NULL; src is by definition != NULL, so src_head can't be NULL as
1325 * src->GetFirst() always yields non-NULL, so eventually original_src_head != NULL as well. */
1326 bool original_src_head_front_engine = original_src_head->IsFrontEngine();
1327 bool original_dst_head_front_engine = original_dst_head != NULL && original_dst_head->IsFrontEngine();
1329 /* (Re)arrange the trains in the wanted arrangement. */
1330 ArrangeTrains(&dst_head, dst, &src_head, src, move_chain);
1332 if ((flags & DC_AUTOREPLACE) == 0) {
1333 /* If the autoreplace flag is set we do not need to test for the validity
1334 * because we are going to revert the train to its original state. As we
1335 * assume the original state was correct autoreplace can skip this. */
1336 CommandCost ret = ValidateTrains(original_dst_head, dst_head, original_src_head, src_head, true);
1337 if (ret.Failed()) {
1338 /* Restore the train we had. */
1339 RestoreTrainBackup(original_src);
1340 RestoreTrainBackup(original_dst);
1341 return ret;
1345 /* do it? */
1346 if (flags & DC_EXEC) {
1347 /* Remove old heads from the statistics */
1348 if (original_src_head_front_engine) GroupStatistics::CountVehicle(original_src_head, -1);
1349 if (original_dst_head_front_engine) GroupStatistics::CountVehicle(original_dst_head, -1);
1351 /* First normalise the sub types of the chains. */
1352 NormaliseSubtypes(src_head);
1353 NormaliseSubtypes(dst_head);
1355 /* There are 14 different cases:
1356 * 1) front engine gets moved to a new train, it stays a front engine.
1357 * a) the 'next' part is a wagon that becomes a free wagon chain.
1358 * b) the 'next' part is an engine that becomes a front engine.
1359 * c) there is no 'next' part, nothing else happens
1360 * 2) front engine gets moved to another train, it is not a front engine anymore
1361 * a) the 'next' part is a wagon that becomes a free wagon chain.
1362 * b) the 'next' part is an engine that becomes a front engine.
1363 * c) there is no 'next' part, nothing else happens
1364 * 3) front engine gets moved to later in the current train, it is not a front engine anymore.
1365 * a) the 'next' part is a wagon that becomes a free wagon chain.
1366 * b) the 'next' part is an engine that becomes a front engine.
1367 * 4) free wagon gets moved
1368 * a) the 'next' part is a wagon that becomes a free wagon chain.
1369 * b) the 'next' part is an engine that becomes a front engine.
1370 * c) there is no 'next' part, nothing else happens
1371 * 5) non front engine gets moved and becomes a new train, nothing else happens
1372 * 6) non front engine gets moved within a train / to another train, nothing hapens
1373 * 7) wagon gets moved, nothing happens
1375 if (src == original_src_head && src->IsEngine() && !src->IsFrontEngine()) {
1376 /* Cases #2 and #3: the front engine gets trashed. */
1377 DeleteWindowById(WC_VEHICLE_VIEW, src->index);
1378 DeleteWindowById(WC_VEHICLE_ORDERS, src->index);
1379 DeleteWindowById(WC_VEHICLE_REFIT, src->index);
1380 DeleteWindowById(WC_VEHICLE_DETAILS, src->index);
1381 DeleteWindowById(WC_VEHICLE_TIMETABLE, src->index);
1382 DeleteNewGRFInspectWindow(GSF_TRAINS, src->index);
1383 SetWindowDirty(WC_COMPANY, _current_company);
1385 /* Delete orders, group stuff and the unit number as we're not the
1386 * front of any vehicle anymore. */
1387 DeleteVehicleOrders(src);
1388 RemoveVehicleFromGroup(src);
1389 src->unitnumber = 0;
1392 /* We weren't a front engine but are becoming one. So
1393 * we should be put in the default group. */
1394 if (original_src_head != src && dst_head == src) {
1395 SetTrainGroupID(src, DEFAULT_GROUP);
1396 SetWindowDirty(WC_COMPANY, _current_company);
1399 /* Add new heads to statistics */
1400 if (src_head != NULL && src_head->IsFrontEngine()) GroupStatistics::CountVehicle(src_head, 1);
1401 if (dst_head != NULL && dst_head->IsFrontEngine()) GroupStatistics::CountVehicle(dst_head, 1);
1403 /* Handle 'new engine' part of cases #1b, #2b, #3b, #4b and #5 in NormaliseTrainHead. */
1404 NormaliseTrainHead(src_head);
1405 NormaliseTrainHead(dst_head);
1407 if ((flags & DC_NO_CARGO_CAP_CHECK) == 0) {
1408 CheckCargoCapacity(src_head);
1409 CheckCargoCapacity(dst_head);
1412 if (src_head != NULL) src_head->First()->MarkDirty();
1413 if (dst_head != NULL) dst_head->First()->MarkDirty();
1415 /* We are undoubtedly changing something in the depot and train list. */
1416 InvalidateWindowData(WC_VEHICLE_DEPOT, src->tile);
1417 InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
1418 } else {
1419 /* We don't want to execute what we're just tried. */
1420 RestoreTrainBackup(original_src);
1421 RestoreTrainBackup(original_dst);
1424 return CommandCost();
1428 * Sell a (single) train wagon/engine.
1429 * @param flags type of operation
1430 * @param t the train wagon to sell
1431 * @param data the selling mode
1432 * - data = 0: only sell the single dragged wagon/engine (and any belonging rear-engines)
1433 * - data = 1: sell the vehicle and all vehicles following it in the chain
1434 * if the wagon is dragged, don't delete the possibly belonging rear-engine to some front
1435 * @param user the user for the order backup.
1436 * @return the cost of this operation or an error
1438 CommandCost CmdSellRailWagon(DoCommandFlag flags, Vehicle *t, uint16 data, uint32 user)
1440 /* Sell a chain of vehicles or not? */
1441 bool sell_chain = HasBit(data, 0);
1443 Train *v = Train::From(t)->GetFirstEnginePart();
1444 Train *first = v->First();
1446 if (v->IsRearDualheaded()) return_cmd_error(STR_ERROR_REAR_ENGINE_FOLLOW_FRONT);
1448 /* First make a backup of the order of the train. That way we can do
1449 * whatever we want with the order and later on easily revert. */
1450 TrainList original;
1451 MakeTrainBackup(original, first);
1453 /* We need to keep track of the new head and the head of what we're going to sell. */
1454 Train *new_head = first;
1455 Train *sell_head = NULL;
1457 /* Split the train in the wanted way. */
1458 ArrangeTrains(&sell_head, NULL, &new_head, v, sell_chain);
1460 /* We don't need to validate the second train; it's going to be sold. */
1461 CommandCost ret = ValidateTrains(NULL, NULL, first, new_head, (flags & DC_AUTOREPLACE) == 0);
1462 if (ret.Failed()) {
1463 /* Restore the train we had. */
1464 RestoreTrainBackup(original);
1465 return ret;
1468 if (first->orders.list == NULL && !OrderList::CanAllocateItem()) {
1469 /* Restore the train we had. */
1470 RestoreTrainBackup(original);
1471 return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
1474 CommandCost cost(EXPENSES_NEW_VEHICLES);
1475 for (Train *t = sell_head; t != NULL; t = t->Next()) cost.AddCost(-t->value);
1477 /* do it? */
1478 if (flags & DC_EXEC) {
1479 /* First normalise the sub types of the chain. */
1480 NormaliseSubtypes(new_head);
1482 if (v == first && v->IsEngine() && !sell_chain && new_head != NULL && new_head->IsFrontEngine()) {
1483 /* We are selling the front engine. In this case we want to
1484 * 'give' the order, unit number and such to the new head. */
1485 new_head->orders.list = first->orders.list;
1486 new_head->AddToShared(first);
1487 DeleteVehicleOrders(first);
1489 /* Copy other important data from the front engine */
1490 new_head->CopyVehicleConfigAndStatistics(first);
1491 GroupStatistics::CountVehicle(new_head, 1); // after copying over the profit
1492 } else if (v->IsPrimaryVehicle() && data & (MAKE_ORDER_BACKUP_FLAG >> 20)) {
1493 OrderBackup::Backup(v, user);
1496 /* We need to update the information about the train. */
1497 NormaliseTrainHead(new_head);
1499 /* We are undoubtedly changing something in the depot and train list. */
1500 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
1501 InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
1503 /* Actually delete the sold 'goods' */
1504 delete sell_head;
1505 } else {
1506 /* We don't want to execute what we're just tried. */
1507 RestoreTrainBackup(original);
1510 return cost;
1513 void Train::UpdateDeltaXY(Direction direction)
1515 /* Set common defaults. */
1516 this->x_offs = -1;
1517 this->y_offs = -1;
1518 this->x_extent = 3;
1519 this->y_extent = 3;
1520 this->z_extent = 6;
1521 this->x_bb_offs = 0;
1522 this->y_bb_offs = 0;
1524 if (!IsDiagonalDirection(direction)) {
1525 static const int _sign_table[] =
1527 /* x, y */
1528 -1, -1, // DIR_N
1529 -1, 1, // DIR_E
1530 1, 1, // DIR_S
1531 1, -1, // DIR_W
1534 int half_shorten = (VEHICLE_LENGTH - this->gcache.cached_veh_length) / 2;
1536 /* For all straight directions, move the bound box to the centre of the vehicle, but keep the size. */
1537 this->x_offs -= half_shorten * _sign_table[direction];
1538 this->y_offs -= half_shorten * _sign_table[direction + 1];
1539 this->x_extent += this->x_bb_offs = half_shorten * _sign_table[direction];
1540 this->y_extent += this->y_bb_offs = half_shorten * _sign_table[direction + 1];
1541 } else {
1542 switch (direction) {
1543 /* Shorten southern corner of the bounding box according the vehicle length
1544 * and center the bounding box on the vehicle. */
1545 case DIR_NE:
1546 this->x_offs = 1 - (this->gcache.cached_veh_length + 1) / 2;
1547 this->x_extent = this->gcache.cached_veh_length - 1;
1548 this->x_bb_offs = -1;
1549 break;
1551 case DIR_NW:
1552 this->y_offs = 1 - (this->gcache.cached_veh_length + 1) / 2;
1553 this->y_extent = this->gcache.cached_veh_length - 1;
1554 this->y_bb_offs = -1;
1555 break;
1557 /* Move northern corner of the bounding box down according to vehicle length
1558 * and center the bounding box on the vehicle. */
1559 case DIR_SW:
1560 this->x_offs = 1 + (this->gcache.cached_veh_length + 1) / 2 - VEHICLE_LENGTH;
1561 this->x_extent = VEHICLE_LENGTH - 1;
1562 this->x_bb_offs = VEHICLE_LENGTH - this->gcache.cached_veh_length - 1;
1563 break;
1565 case DIR_SE:
1566 this->y_offs = 1 + (this->gcache.cached_veh_length + 1) / 2 - VEHICLE_LENGTH;
1567 this->y_extent = VEHICLE_LENGTH - 1;
1568 this->y_bb_offs = VEHICLE_LENGTH - this->gcache.cached_veh_length - 1;
1569 break;
1571 default:
1572 NOT_REACHED();
1578 * Mark a train as stuck and stop it if it isn't stopped right now.
1579 * @param v %Train to mark as being stuck.
1581 static void MarkTrainAsStuck(Train *v)
1583 if (!HasBit(v->flags, VRF_TRAIN_STUCK)) {
1584 /* It is the first time the problem occurred, set the "train stuck" flag. */
1585 SetBit(v->flags, VRF_TRAIN_STUCK);
1587 v->wait_counter = 0;
1589 /* Stop train */
1590 v->cur_speed = 0;
1591 v->subspeed = 0;
1592 v->SetLastSpeed();
1594 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
1599 * Swap the two up/down flags in two ways:
1600 * - Swap values of \a swap_flag1 and \a swap_flag2, and
1601 * - If going up previously (#GVF_GOINGUP_BIT set), the #GVF_GOINGDOWN_BIT is set, and vice versa.
1602 * @param swap_flag1 [inout] First train flag.
1603 * @param swap_flag2 [inout] Second train flag.
1605 static void SwapTrainFlags(uint16 *swap_flag1, uint16 *swap_flag2)
1607 uint16 flag1 = *swap_flag1;
1608 uint16 flag2 = *swap_flag2;
1610 /* Clear the flags */
1611 ClrBit(*swap_flag1, GVF_GOINGUP_BIT);
1612 ClrBit(*swap_flag1, GVF_GOINGDOWN_BIT);
1613 ClrBit(*swap_flag2, GVF_GOINGUP_BIT);
1614 ClrBit(*swap_flag2, GVF_GOINGDOWN_BIT);
1616 /* Reverse the rail-flags (if needed) */
1617 if (HasBit(flag1, GVF_GOINGUP_BIT)) {
1618 SetBit(*swap_flag2, GVF_GOINGDOWN_BIT);
1619 } else if (HasBit(flag1, GVF_GOINGDOWN_BIT)) {
1620 SetBit(*swap_flag2, GVF_GOINGUP_BIT);
1622 if (HasBit(flag2, GVF_GOINGUP_BIT)) {
1623 SetBit(*swap_flag1, GVF_GOINGDOWN_BIT);
1624 } else if (HasBit(flag2, GVF_GOINGDOWN_BIT)) {
1625 SetBit(*swap_flag1, GVF_GOINGUP_BIT);
1630 * Updates some variables after swapping the vehicle.
1631 * @param v swapped vehicle
1633 static void UpdateStatusAfterSwap(Train *v)
1635 /* Reverse the direction. */
1636 if (v->trackdir != TRACKDIR_DEPOT) v->direction = ReverseDir(v->direction);
1638 if (v->trackdir < TRACKDIR_END) v->trackdir = ReverseTrackdir(v->trackdir);
1640 /* Call the proper EnterTile function unless we are in a wormhole. */
1641 if (v->trackdir != TRACKDIR_WORMHOLE) {
1642 TrainEnterTile(v, v->tile, v->x_pos, v->y_pos);
1643 } else {
1644 assert(v->direction == DiagDirToDir(GetTunnelBridgeDirection(v->tile)));
1645 v->tile = GetOtherTunnelBridgeEnd(v->tile);
1648 v->UpdatePosition();
1649 v->UpdateViewport(true, true);
1653 * Swap vehicles \a l and \a r in consist \a v, and reverse their direction.
1654 * @param v Consist to change.
1655 * @param l %Vehicle index in the consist of the first vehicle.
1656 * @param r %Vehicle index in the consist of the second vehicle.
1658 void ReverseTrainSwapVeh(Train *v, int l, int r)
1660 Train *a, *b;
1662 /* locate vehicles to swap */
1663 for (a = v; l != 0; l--) a = a->Next();
1664 for (b = v; r != 0; r--) b = b->Next();
1666 if (a != b) {
1667 /* swap the hidden bits */
1669 uint16 tmp = (a->vehstatus & ~VS_HIDDEN) | (b->vehstatus & VS_HIDDEN);
1670 b->vehstatus = (b->vehstatus & ~VS_HIDDEN) | (a->vehstatus & VS_HIDDEN);
1671 a->vehstatus = tmp;
1674 Swap(a->trackdir, b->trackdir);
1675 Swap(a->direction, b->direction);
1676 Swap(a->x_pos, b->x_pos);
1677 Swap(a->y_pos, b->y_pos);
1678 Swap(a->tile, b->tile);
1679 Swap(a->z_pos, b->z_pos);
1681 SwapTrainFlags(&a->gv_flags, &b->gv_flags);
1683 UpdateStatusAfterSwap(a);
1684 UpdateStatusAfterSwap(b);
1685 } else {
1686 /* Swap GVF_GOINGUP_BIT/GVF_GOINGDOWN_BIT.
1687 * This is a little bit redundant way, a->gv_flags will
1688 * be (re)set twice, but it reduces code duplication */
1689 SwapTrainFlags(&a->gv_flags, &a->gv_flags);
1690 UpdateStatusAfterSwap(a);
1696 * Check if there is a train on a tile
1697 * @param tile the tile to check
1698 * @return true if a train is on the tile
1700 static bool TrainOnTile (TileIndex tile)
1702 VehicleTileFinder iter (tile);
1703 while (!iter.finished()) {
1704 Vehicle *v = iter.next();
1705 if (v->type == VEH_TRAIN) iter.set_found();
1707 return iter.was_found();
1711 * Checks whether a train is approaching a rail-road crossing from a neighbour tile
1712 * @param tile the crossing tile
1713 * @param from the neighbour tile
1714 * @return true if a train is approaching the crossing
1716 static bool TrainApproachingCrossingFrom (TileIndex tile, TileIndex from)
1718 VehicleTileFinder iter (from);
1719 while (!iter.finished()) {
1720 Vehicle *v = iter.next();
1721 if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) continue;
1723 Train *t = Train::From(v);
1724 if (t->IsFrontEngine() && TrainApproachingCrossingTile(t) == tile) iter.set_found();
1726 return iter.was_found();
1730 * Finds a vehicle approaching rail-road crossing
1731 * @param tile tile to test
1732 * @return true if a vehicle is approaching the crossing
1733 * @pre tile is a rail-road crossing
1735 static bool TrainApproachingCrossing(TileIndex tile)
1737 assert(IsLevelCrossingTile(tile));
1739 TileIndexDiff delta = TileOffsByDiagDir(AxisToDiagDir(GetCrossingRailAxis(tile)));
1740 return TrainApproachingCrossingFrom (tile, tile + delta) ||
1741 TrainApproachingCrossingFrom (tile, tile - delta);
1746 * Sets correct crossing state
1747 * @param tile tile to update
1748 * @param sound should we play sound?
1749 * @pre tile is a rail-road crossing
1751 void UpdateLevelCrossing(TileIndex tile, bool sound)
1753 assert(IsLevelCrossingTile(tile));
1755 /* reserved || train on crossing || train approaching crossing */
1756 bool new_state = HasCrossingReservation(tile) || TrainOnTile(tile) || TrainApproachingCrossing(tile);
1758 if (new_state != IsCrossingBarred(tile)) {
1759 if (new_state && sound) {
1760 if (_settings_client.sound.ambient) SndPlayTileFx(SND_0E_LEVEL_CROSSING, tile);
1762 SetCrossingBarred(tile, new_state);
1763 MarkTileDirtyByTile(tile);
1769 * Bars crossing and plays ding-ding sound if not barred already
1770 * @param tile tile with crossing
1771 * @pre tile is a rail-road crossing
1773 static inline void MaybeBarCrossingWithSound(TileIndex tile)
1775 if (!IsCrossingBarred(tile)) {
1776 BarCrossing(tile);
1777 if (_settings_client.sound.ambient) SndPlayTileFx(SND_0E_LEVEL_CROSSING, tile);
1778 MarkTileDirtyByTile(tile);
1784 * Advances wagons for train reversing, needed for variable length wagons.
1785 * This one is called before the train is reversed.
1786 * @param v First vehicle in chain
1788 static void AdvanceWagonsBeforeSwap(Train *v)
1790 Train *base = v;
1791 Train *first = base; // first vehicle to move
1792 Train *last = v->Last(); // last vehicle to move
1793 uint length = CountVehiclesInChain(v);
1795 while (length > 2) {
1796 last = last->Previous();
1797 first = first->Next();
1799 int differential = base->CalcNextVehicleOffset() - last->CalcNextVehicleOffset();
1801 /* do not update images now
1802 * negative differential will be handled in AdvanceWagonsAfterSwap() */
1803 for (int i = 0; i < differential; i++) TrainController(first, last->Next());
1805 base = first; // == base->Next()
1806 length -= 2;
1812 * Advances wagons for train reversing, needed for variable length wagons.
1813 * This one is called after the train is reversed.
1814 * @param v First vehicle in chain
1816 static void AdvanceWagonsAfterSwap(Train *v)
1818 /* first of all, fix the situation when the train was entering a depot */
1819 Train *dep = v; // last vehicle in front of just left depot
1820 while (dep->Next() != NULL && (dep->trackdir == TRACKDIR_DEPOT || dep->Next()->trackdir != TRACKDIR_DEPOT)) {
1821 dep = dep->Next(); // find first vehicle outside of a depot, with next vehicle inside a depot
1824 Train *leave = dep->Next(); // first vehicle in a depot we are leaving now
1826 if (leave != NULL) {
1827 /* 'pull' next wagon out of the depot, so we won't miss it (it could stay in depot forever) */
1828 int d = TicksToLeaveDepot(dep);
1830 if (d <= 0) {
1831 leave->vehstatus &= ~VS_HIDDEN; // move it out of the depot
1832 leave->trackdir = DiagDirToDiagTrackdir(GetGroundDepotDirection(leave->tile));
1833 for (int i = 0; i >= d; i--) TrainController(leave, NULL); // maybe move it, and maybe let another wagon leave
1835 } else {
1836 dep = NULL; // no vehicle in a depot, so no vehicle leaving a depot
1839 Train *base = v;
1840 Train *first = base; // first vehicle to move
1841 Train *last = v->Last(); // last vehicle to move
1842 uint length = CountVehiclesInChain(v);
1844 /* We have to make sure all wagons that leave a depot because of train reversing are moved correctly
1845 * they have already correct spacing, so we have to make sure they are moved how they should */
1846 bool nomove = (dep == NULL); // If there is no vehicle leaving a depot, limit the number of wagons moved immediately.
1848 while (length > 2) {
1849 /* we reached vehicle (originally) in front of a depot, stop now
1850 * (we would move wagons that are already moved with new wagon length). */
1851 if (base == dep) break;
1853 /* the last wagon was that one leaving a depot, so do not move it anymore */
1854 if (last == dep) nomove = true;
1856 last = last->Previous();
1857 first = first->Next();
1859 int differential = last->CalcNextVehicleOffset() - base->CalcNextVehicleOffset();
1861 /* do not update images now */
1862 for (int i = 0; i < differential; i++) TrainController(first, (nomove ? last->Next() : NULL));
1864 base = first; // == base->Next()
1865 length -= 2;
1870 * Turn a train around.
1871 * @param v %Train to turn around.
1873 void ReverseTrainDirection(Train *v)
1875 if (IsRailDepotTile(v->tile)) {
1876 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
1879 /* Clear path reservation in front if train is not stuck. */
1880 if (!HasBit(v->flags, VRF_TRAIN_STUCK)) FreeTrainTrackReservation(v);
1882 /* Check if we were approaching a rail/road-crossing */
1883 TileIndex crossing = TrainApproachingCrossingTile(v);
1885 /* count number of vehicles */
1886 int r = CountVehiclesInChain(v) - 1; // number of vehicles - 1
1888 AdvanceWagonsBeforeSwap(v);
1890 /* swap start<>end, start+1<>end-1, ... */
1891 int l = 0;
1892 do {
1893 ReverseTrainSwapVeh(v, l++, r--);
1894 } while (l <= r);
1896 AdvanceWagonsAfterSwap(v);
1898 if (IsRailDepotTile(v->tile)) {
1899 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
1902 ToggleBit(v->flags, VRF_TOGGLE_REVERSE);
1904 ClrBit(v->flags, VRF_REVERSING);
1906 /* recalculate cached data */
1907 v->ConsistChanged(CCF_TRACK);
1909 /* update all images */
1910 for (Train *u = v; u != NULL; u = u->Next()) u->UpdateViewport(false, false);
1912 /* update crossing we were approaching */
1913 if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
1915 /* maybe we are approaching crossing now, after reversal */
1916 crossing = TrainApproachingCrossingTile(v);
1917 if (crossing != INVALID_TILE) MaybeBarCrossingWithSound(crossing);
1919 /* If we are inside a depot after reversing, don't bother with path reserving. */
1920 if (v->trackdir == TRACKDIR_DEPOT) {
1921 /* Can't be stuck here as inside a depot is always a safe tile. */
1922 if (HasBit(v->flags, VRF_TRAIN_STUCK)) SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
1923 ClrBit(v->flags, VRF_TRAIN_STUCK);
1924 return;
1927 assert(IsSignalBufferEmpty());
1928 AddPosToSignalBuffer(v->GetPos(), v->owner);
1930 if (UpdateSignalsInBuffer() == SIGSEG_PBS || _settings_game.pf.reserve_paths) {
1931 RailPathPos pos = v->GetPos();
1933 /* If we are currently on a tile with conventional signals, we can't treat the
1934 * current tile as a safe tile or we would enter a PBS block without a reservation. */
1935 bool first_tile_okay = !(pos.has_signal_along() &&
1936 !IsPbsSignal(pos.get_signal_type()));
1938 /* If we are on a depot tile facing outwards, do not treat the current tile as safe. */
1939 if (!pos.in_wormhole() && IsRailDepotTile(pos.tile) && TrackdirToExitdir(pos.td) == GetGroundDepotDirection(pos.tile)) first_tile_okay = false;
1941 if (!pos.in_wormhole() && IsRailStationTile(pos.tile)) SetRailStationPlatformReservation(pos, true);
1942 if (TryPathReserve(v, false, first_tile_okay)) {
1943 /* Do a look-ahead now in case our current tile was already a safe tile. */
1944 CheckNextTrainTile(v);
1945 } else if (v->current_order.GetType() != OT_LOADING) {
1946 /* Do not wait for a way out when we're still loading */
1947 MarkTrainAsStuck(v);
1949 } else if (HasBit(v->flags, VRF_TRAIN_STUCK)) {
1950 /* A train not inside a PBS block can't be stuck. */
1951 ClrBit(v->flags, VRF_TRAIN_STUCK);
1952 v->wait_counter = 0;
1957 * Reverse train.
1958 * @param tile unused
1959 * @param flags type of operation
1960 * @param p1 train to reverse
1961 * @param p2 if true, reverse a unit in a train (needs to be in a depot)
1962 * @param text unused
1963 * @return the cost of this operation or an error
1965 CommandCost CmdReverseTrainDirection(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1967 Train *v = Train::GetIfValid(p1);
1968 if (v == NULL) return CMD_ERROR;
1970 CommandCost ret = CheckOwnership(v->owner);
1971 if (ret.Failed()) return ret;
1973 if (p2 != 0) {
1974 /* turn a single unit around */
1976 if (v->IsMultiheaded() || HasBit(EngInfo(v->engine_type)->callback_mask, CBM_VEHICLE_ARTIC_ENGINE)) {
1977 return_cmd_error(STR_ERROR_CAN_T_REVERSE_DIRECTION_RAIL_VEHICLE_MULTIPLE_UNITS);
1979 if (!HasBit(EngInfo(v->engine_type)->misc_flags, EF_RAIL_FLIPS)) return CMD_ERROR;
1981 Train *front = v->First();
1982 /* make sure the vehicle is stopped in the depot */
1983 if (!front->IsStoppedInDepot()) {
1984 return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
1987 if (flags & DC_EXEC) {
1988 ToggleBit(v->flags, VRF_REVERSE_DIRECTION);
1990 front->ConsistChanged(CCF_ARRANGE);
1991 SetWindowDirty(WC_VEHICLE_DEPOT, front->tile);
1992 SetWindowDirty(WC_VEHICLE_DETAILS, front->index);
1993 SetWindowDirty(WC_VEHICLE_VIEW, front->index);
1994 SetWindowClassesDirty(WC_TRAINS_LIST);
1996 } else {
1997 /* turn the whole train around */
1998 if ((v->vehstatus & VS_CRASHED) || v->breakdown_ctr != 0) return CMD_ERROR;
2000 if (flags & DC_EXEC) {
2001 /* Properly leave the station if we are loading and won't be loading anymore */
2002 if (v->current_order.IsType(OT_LOADING)) {
2003 const Vehicle *last = v;
2004 while (last->Next() != NULL) last = last->Next();
2006 /* not a station || different station --> leave the station */
2007 if (!IsStationTile(last->tile) || GetStationIndex(last->tile) != GetStationIndex(v->tile)) {
2008 v->LeaveStation();
2012 /* We cancel any 'skip signal at dangers' here */
2013 v->force_proceed = TFP_NONE;
2014 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
2016 if (_settings_game.vehicle.train_acceleration_model != AM_ORIGINAL && v->cur_speed != 0) {
2017 ToggleBit(v->flags, VRF_REVERSING);
2018 } else {
2019 v->cur_speed = 0;
2020 v->SetLastSpeed();
2021 HideFillingPercent(&v->fill_percent_te_id);
2022 ReverseTrainDirection(v);
2026 return CommandCost();
2030 * Force a train through a red signal
2031 * @param tile unused
2032 * @param flags type of operation
2033 * @param p1 train to ignore the red signal
2034 * @param p2 unused
2035 * @param text unused
2036 * @return the cost of this operation or an error
2038 CommandCost CmdForceTrainProceed(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2040 Train *t = Train::GetIfValid(p1);
2041 if (t == NULL) return CMD_ERROR;
2043 if (!t->IsPrimaryVehicle()) return CMD_ERROR;
2045 CommandCost ret = CheckOwnership(t->owner);
2046 if (ret.Failed()) return ret;
2049 if (flags & DC_EXEC) {
2050 /* If we are forced to proceed, cancel that order.
2051 * If we are marked stuck we would want to force the train
2052 * to proceed to the next signal. In the other cases we
2053 * would like to pass the signal at danger and run till the
2054 * next signal we encounter. */
2055 t->force_proceed = t->force_proceed == TFP_SIGNAL ? TFP_NONE : HasBit(t->flags, VRF_TRAIN_STUCK) || t->IsChainInDepot() ? TFP_STUCK : TFP_SIGNAL;
2056 SetWindowDirty(WC_VEHICLE_VIEW, t->index);
2059 return CommandCost();
2063 * Try to find a depot.
2064 * @param v %Train that wants a depot.
2065 * @param nearby Only consider nearby depots.
2066 * @param res Pointer to store information where the closest train depot is located.
2067 * @return Whether a depot was found.
2068 * @pre The given vehicle must not be crashed!
2070 static bool FindClosestTrainDepot(Train *v, bool nearby, FindDepotData *res)
2072 assert(!(v->vehstatus & VS_CRASHED));
2074 if (IsRailDepotTile(v->tile) && v->trackdir != DiagDirToDiagTrackdir(GetGroundDepotDirection(v->tile))) {
2075 *res = FindDepotData(v->tile);
2076 return true;
2079 RailPathPos origin;
2080 FollowTrainReservation(v, &origin);
2081 if (IsRailDepotTile(origin.tile) && origin.td != DiagDirToDiagTrackdir(GetGroundDepotDirection(origin.tile))) {
2082 *res = FindDepotData(origin.tile);
2083 return true;
2086 return YapfTrainFindNearestDepot (v, origin,
2087 nearby ? _settings_game.pf.yapf.maximum_go_to_depot_penalty : 0, res);
2091 * Locate the closest depot for this consist, and return the information to the caller.
2092 * @param location [out] If not \c NULL and a depot is found, store its location in the given address.
2093 * @param destination [out] If not \c NULL and a depot is found, store its index in the given address.
2094 * @param reverse [out] If not \c NULL and a depot is found, store reversal information in the given address.
2095 * @return A depot has been found.
2097 bool Train::FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
2099 FindDepotData tfdd;
2100 if (!FindClosestTrainDepot(this, false, &tfdd)) return false;
2102 if (location != NULL) *location = tfdd.tile;
2103 if (destination != NULL) *destination = GetDepotIndex(tfdd.tile);
2104 if (reverse != NULL) *reverse = tfdd.reverse;
2106 return true;
2109 /** Play a sound for a train leaving the station. */
2110 void Train::PlayLeaveStationSound() const
2112 static const SoundFx sfx[] = {
2113 SND_04_TRAIN,
2114 SND_0A_TRAIN_HORN,
2115 SND_0A_TRAIN_HORN,
2116 SND_47_MAGLEV_2,
2117 SND_41_MAGLEV
2120 if (PlayVehicleSound(this, VSE_START)) return;
2122 EngineID engtype = this->engine_type;
2123 SndPlayVehicleFx(sfx[RailVehInfo(engtype)->engclass], this);
2127 * Check if the train is on the last reserved tile and try to extend the path then.
2128 * @param v %Train that needs its path extended.
2130 static void CheckNextTrainTile(Train *v)
2132 /* Don't do any look-ahead if path_backoff_interval is 255. */
2133 if (_settings_game.pf.path_backoff_interval == 255) return;
2135 /* Exit if we are inside a depot. */
2136 if (v->trackdir == TRACKDIR_DEPOT) return;
2138 switch (v->current_order.GetType()) {
2139 /* Exit if we reached our destination depot. */
2140 case OT_GOTO_DEPOT:
2141 if (v->tile == v->dest_tile) return;
2142 break;
2144 case OT_GOTO_WAYPOINT:
2145 /* If we reached our waypoint, make sure we see that. */
2146 if (IsRailWaypointTile(v->tile) && GetStationIndex(v->tile) == v->current_order.GetDestination()) ProcessOrders(v);
2147 break;
2149 case OT_NOTHING:
2150 case OT_LEAVESTATION:
2151 case OT_LOADING:
2152 /* Exit if the current order doesn't have a destination, but the train has orders. */
2153 if (v->GetNumOrders() > 0) return;
2154 break;
2156 default:
2157 break;
2159 /* Exit if we are on a station tile and are going to stop. */
2160 if (IsRailStationTile(v->tile) && v->current_order.ShouldStopAtStation(v, GetStationIndex(v->tile))) return;
2162 RailPathPos pos = v->GetPos();
2164 /* On a tile with a red non-pbs signal, don't look ahead. */
2165 if (pos.has_signal_along() &&
2166 !IsPbsSignal(pos.get_signal_type()) &&
2167 pos.get_signal_state() == SIGNAL_STATE_RED) return;
2169 CFollowTrackRail ft(v, !_settings_game.pf.forbid_90_deg);
2170 if (ft.Follow (pos) != CFollowTrackRail::EC_NONE) return;
2172 if (ft.m_new.is_single() && ft.m_new.has_signal_along() &&
2173 IsPbsSignal(ft.m_new.get_signal_type()) &&
2174 !HasReservedPos(ft.m_new)) {
2175 /* If the next tile is a PBS signal, try to make a reservation. */
2176 ChooseTrainTrack (v, pos, ft.m_new, false);
2181 * Train entirely entered the depot, update its status, orders, vehicle windows, service it, etc.
2182 * @param v Train that entered a depot.
2184 static void TrainEnterDepot (Train *v)
2186 SetWindowClassesDirty (WC_TRAINS_LIST);
2187 /* Clear path reservation */
2188 SetDepotReservation (v->tile, false);
2189 if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile (v->tile);
2191 assert (IsSignalBufferEmpty());
2192 AddDepotToSignalBuffer (v->tile, v->owner);
2193 UpdateSignalsInBuffer();
2194 v->wait_counter = 0;
2195 v->force_proceed = TFP_NONE;
2196 ClrBit(v->flags, VRF_TOGGLE_REVERSE);
2197 v->ConsistChanged (CCF_ARRANGE);
2199 VehicleEnterDepot (v);
2203 * Will the train stay in the depot the next tick?
2204 * @param v %Train to check.
2205 * @return True if it stays in the depot, false otherwise.
2207 static bool CheckTrainStayInDepot(Train *v)
2209 /* bail out if not all wagons are in the same depot or not in a depot at all */
2210 for (const Train *u = v; u != NULL; u = u->Next()) {
2211 if (u->trackdir != TRACKDIR_DEPOT || u->tile != v->tile) return false;
2214 /* if the train got no power, then keep it in the depot */
2215 if (v->gcache.cached_power == 0) {
2216 v->vehstatus |= VS_STOPPED;
2217 SetWindowDirty(WC_VEHICLE_DEPOT, v->tile);
2218 return true;
2221 bool try_reserve;
2223 if (v->force_proceed == TFP_NONE) {
2224 /* force proceed was not pressed */
2225 if (++v->wait_counter < 37) {
2226 SetWindowClassesDirty(WC_TRAINS_LIST);
2227 return true;
2230 v->wait_counter = 0;
2232 if (HasDepotReservation(v->tile)) {
2233 /* Depot reserved, can't exit. */
2234 SetWindowClassesDirty(WC_TRAINS_LIST);
2235 return true;
2238 if (_settings_game.pf.reserve_paths) {
2239 try_reserve = true;
2240 } else {
2241 assert(IsSignalBufferEmpty());
2242 AddDepotToSignalBuffer(v->tile, v->owner);
2243 SigSegState seg_state = UpdateSignalsInBuffer();
2244 if (seg_state == SIGSEG_FULL) {
2245 /* Full and no PBS signal in block, can't exit. */
2246 SetWindowClassesDirty(WC_TRAINS_LIST);
2247 return true;
2249 try_reserve = seg_state == SIGSEG_PBS;
2251 } else if (_settings_game.pf.reserve_paths) {
2252 try_reserve = true;
2253 } else {
2254 assert(IsSignalBufferEmpty());
2255 AddDepotToSignalBuffer(v->tile, v->owner);
2256 try_reserve = UpdateSignalsInBuffer() == SIGSEG_PBS;
2259 /* We are leaving a depot, but have to go to the exact same one; re-enter */
2260 if (v->current_order.IsType(OT_GOTO_DEPOT) && v->tile == v->dest_tile) {
2261 /* We need to have a reservation for this to work. */
2262 if (HasDepotReservation(v->tile)) return true;
2263 SetDepotReservation(v->tile, true);
2264 TrainEnterDepot (v);
2265 return true;
2268 /* Only leave when we can reserve a path to our destination. */
2269 if (try_reserve) {
2270 if (HasDepotReservation (v->tile) || !TryPathExtend (v, v->GetPos())) {
2271 /* Failed to get a reservation. */
2272 if (v->force_proceed == TFP_NONE) {
2273 /* No path and no force proceed. */
2274 SetWindowClassesDirty(WC_TRAINS_LIST);
2275 MarkTrainAsStuck(v);
2276 return true;
2281 SetDepotReservation(v->tile, true);
2282 if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(v->tile);
2284 VehicleServiceInDepot(v);
2285 SetWindowClassesDirty(WC_TRAINS_LIST);
2286 v->PlayLeaveStationSound();
2288 v->trackdir = DiagDirToDiagTrackdir(DirToDiagDir(v->direction));
2290 v->vehstatus &= ~VS_HIDDEN;
2291 v->cur_speed = 0;
2293 v->UpdateViewport(true, true);
2294 v->UpdatePosition();
2296 assert(IsSignalBufferEmpty());
2297 AddDepotToSignalBuffer(v->tile, v->owner);
2298 UpdateSignalsInBuffer();
2300 v->UpdateAcceleration();
2301 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
2303 return false;
2307 * Clear the reservation of \a tile that was just left by a wagon on \a track_dir.
2308 * @param pos position to clear.
2310 static void ClearPathReservation (const RailPathPos &pos)
2312 DiagDirection dir = TrackdirToExitdir(pos.td);
2314 if (pos.in_wormhole()) {
2315 UnreserveRailTrack(pos);
2316 } else if (IsRailStationTile(pos.tile)) {
2317 TileIndex new_tile = TileAddByDiagDir(pos.tile, dir);
2318 /* If the new tile is not a further tile of the same station, we
2319 * clear the reservation for the whole platform. */
2320 if (!IsCompatibleTrainStationTile(new_tile, pos.tile)) {
2321 SetRailStationPlatformReservation(pos.tile, ReverseDiagDir(dir), false);
2323 } else {
2324 /* Any other tile */
2325 UnreserveRailTrack(pos);
2330 * Free the reserved path in front of a vehicle.
2331 * @param v %Train owning the reserved path.
2332 * @param end Position where the reservation ends
2334 static void FreeTrainTrackReservation (const Train *v, const RailPathPos *end)
2336 assert(v->IsFrontEngine());
2338 RailPathPos pos = v->GetPos();
2339 assert (!IsRailDepotTile(pos.tile) || TrackdirToExitdir(pos.td) == GetGroundDepotDirection(pos.tile));
2341 /* Don't free reservation if it's not ours. */
2342 if (!pos.in_wormhole() && TracksOverlap(GetReservedTrackbits(pos.tile) | TrackToTrackBits(TrackdirToTrack(pos.td)))) return;
2344 CFollowTrackRail ft(v, true, v->railtype);
2345 ft.SetPos(pos);
2347 bool first = true;
2348 for (;;) {
2349 if (end != NULL && ft.m_new == *end) return;
2351 if (ft.FollowNext() != CFollowTrackRail::EC_NONE) break;
2353 if (!ft.m_new.in_wormhole()) {
2354 TrackdirBits trackdirs = ft.m_new.trackdirs & TrackBitsToTrackdirBits(GetReservedTrackbits(ft.m_new.tile));
2355 if (trackdirs == TRACKDIR_BIT_NONE) break;
2356 ft.m_new.set_trackdirs (trackdirs);
2357 assert(ft.m_new.is_single());
2360 if (ft.m_new.has_signal_along()) {
2361 if (!IsPbsSignal(ft.m_new.get_signal_type())) {
2362 /* Conventional signal along trackdir: remove reservation and stop. */
2363 UnreserveRailTrack(ft.m_new);
2364 break;
2365 } else if (ft.m_new.get_signal_state() == SIGNAL_STATE_RED) {
2366 /* Red PBS signal? Can't be our reservation, would be green then. */
2367 break;
2368 } else {
2369 /* Turn the signal back to red. */
2370 ft.m_new.set_signal_state (SIGNAL_STATE_RED);
2371 MarkTileDirtyByTile(ft.m_new.tile);
2373 } else if (ft.m_new.has_signal_against() && IsOnewaySignal(ft.m_new.get_signal_type())) {
2374 break;
2377 if (first) {
2378 if (ft.m_flag == ft.TF_BRIDGE) {
2379 assert(IsRailBridgeTile(ft.m_old.in_wormhole() ? ft.m_old.wormhole : ft.m_old.tile));
2380 } else if (ft.m_flag == ft.TF_TUNNEL) {
2381 assert(IsTunnelTile(ft.m_old.in_wormhole() ? ft.m_old.wormhole : ft.m_old.tile));
2385 /* Don't free first station if we are on it. */
2386 if (!first || (ft.m_flag != ft.TF_STATION) ||
2387 !IsRailStationTile(ft.m_old.tile) || GetStationIndex(ft.m_new.tile) != GetStationIndex(ft.m_old.tile)) {
2388 ClearPathReservation (ft.m_new);
2391 first = false;
2394 /* If we were given an ending position but did not find it, then
2395 * something is wrong. */
2396 assert (end == NULL);
2400 * Free the reserved path in front of a vehicle, if any.
2401 * @param v %Train owning the reserved path.
2402 * @return Whether the train had a reservation (not in or entering a depot)
2404 bool FreeTrainTrackReservation (const Train *v)
2406 assert(v->IsFrontEngine());
2408 /* Can't be holding a reservation if we enter a depot. */
2409 if (v->trackdir == TRACKDIR_DEPOT) return false;
2410 if (IsRailDepotTile (v->tile) && v->trackdir != DiagDirToDiagTrackdir (GetGroundDepotDirection (v->tile))) return false;
2412 FreeTrainTrackReservation (v, NULL);
2413 return true;
2417 * Perform pathfinding for a train.
2419 * @param v The train
2420 * @param origin The end of the current reservation
2421 * @param do_track_reservation Path reservation is requested
2422 * @param dest [out] State and destination of the requested path
2423 * @return The best trackdir the train should follow
2425 static Trackdir DoTrainPathfind(const Train *v, const RailPathPos &origin, bool do_track_reservation, PFResult *dest)
2427 return YapfTrainChooseTrack(v, origin, do_track_reservation, dest);
2431 * Return value type for ExtendTrainReservation
2433 enum ExtendReservationResult {
2434 EXTEND_RESERVATION_SAFE, ///< Reservation extended to a safe tile
2435 EXTEND_RESERVATION_UNSAFE, ///< Reservation extended to an unsafe tile
2436 EXTEND_RESERVATION_FAILED, ///< Reservation could not be extended
2440 * Extend a train path as far as possible. Stops on encountering a safe tile,
2441 * another reservation or a track choice.
2442 * @param v The train whose reservation to extend
2443 * @param origin The end of the current reservation, which will be updated
2444 * @return An ExtendReservationResult value, showing reservation extension outcome
2446 static ExtendReservationResult ExtendTrainReservation(const Train *v, RailPathPos *origin)
2448 CFollowTrackRail ft(v, !_settings_game.pf.forbid_90_deg);
2449 ft.SetPos(*origin);
2451 for (;;) {
2452 CFollowTrackRail::ErrorCode err = ft.FollowNext();
2453 if (err == CFollowTrackRail::EC_NO_WAY) {
2454 /* End of line, path valid and okay. */
2455 *origin = ft.m_old;
2456 return EXTEND_RESERVATION_SAFE;
2457 } else if (err != CFollowTrackRail::EC_NONE) {
2458 break;
2461 /* A depot is always a safe waiting position. */
2462 if (!ft.m_new.in_wormhole() && IsRailDepotTile(ft.m_new.tile)) {
2463 /* Depot must be free for reservation to continue. */
2464 if (HasDepotReservation(ft.m_new.tile)) break;
2466 SetDepotReservation(ft.m_new.tile, true);
2467 *origin = ft.m_new;
2468 return EXTEND_RESERVATION_SAFE;
2471 /* Station and waypoints are possible targets. */
2472 if (ft.m_flag == ft.TF_STATION) {
2473 /* Possible target encountered.
2474 * On finding a possible target, we need to stop and let the pathfinder handle the
2475 * remaining path. This is because we don't know if this target is in one of our
2476 * orders, so we might cause pathfinding to fail later on if we find a choice.
2477 * This failure would cause a bogous call to TryReserveSafePath which might reserve
2478 * a wrong path not leading to our next destination. */
2479 if (!ft.MaskReservedTracks()) break;
2481 /* If we did skip some tiles, backtrack to the first skipped tile so the pathfinder
2482 * actually starts its search at the first unreserved tile. */
2483 ft.m_new.tile -= TileOffsByDiagDir(ft.m_exitdir) * ft.m_tiles_skipped;
2485 /* Possible target found, path valid but not okay. */
2486 *origin = ft.m_old;
2487 return EXTEND_RESERVATION_UNSAFE;
2490 if (!ft.m_new.is_single()) {
2491 /* Choice found. */
2492 if (HasReservedTracks(ft.m_new.tile, TrackdirBitsToTrackBits(ft.m_new.trackdirs))) break;
2494 assert(ft.m_tiles_skipped == 0);
2496 /* Choice found, path valid but not okay. Save info about the choice tile as well. */
2497 *origin = ft.m_old;
2498 return EXTEND_RESERVATION_UNSAFE;
2501 /* Possible signal tile. */
2502 if (ft.m_new.has_blocking_signal()) break;
2504 PBSPositionState state = CheckWaitingPosition(v, ft.m_new, _settings_game.pf.forbid_90_deg);
2505 if (state == PBS_BUSY) break;
2507 if (!TryReserveRailTrack(ft.m_new)) break;
2509 if (state == PBS_FREE) {
2510 /* Safe position is all good, path valid and okay. */
2511 *origin = ft.m_new;
2512 return EXTEND_RESERVATION_SAFE;
2516 /* Sorry, can't reserve path, back out. */
2517 RailPathPos stopped = ft.m_old;
2518 ft.SetPos(*origin);
2519 while (ft.m_new != stopped) {
2520 if (ft.FollowNext() != CFollowTrackRail::EC_NONE) NOT_REACHED();
2522 assert(!ft.m_new.is_empty());
2523 assert(ft.m_new.is_single());
2525 UnreserveRailTrack(ft.m_new);
2528 /* Path invalid. */
2529 return EXTEND_RESERVATION_FAILED;
2533 * Try to reserve any path to a safe tile, ignoring the vehicle's destination.
2534 * Safe tiles are tiles in front of a signal, depots and station tiles at end of line.
2536 * @param v The vehicle.
2537 * @param pos The position the search should start from.
2538 * @param override_railtype Whether all physically compatible railtypes should be followed.
2539 * @return True if a path to a safe stopping tile could be reserved.
2541 static bool TryReserveSafeTrack(const Train *v, const RailPathPos &pos, bool override_tailtype)
2543 return YapfTrainFindNearestSafeTile(v, pos, override_tailtype);
2546 /** This class will save the current order of a vehicle and restore it on destruction. */
2547 class VehicleOrderSaver {
2548 private:
2549 Train *v;
2550 BaseOrder old_order;
2551 TileIndex old_dest_tile;
2552 StationID old_last_station_visited;
2553 VehicleOrderID index;
2554 bool suppress_implicit_orders;
2556 public:
2557 VehicleOrderSaver(Train *_v) :
2558 v(_v),
2559 old_order(_v->current_order),
2560 old_dest_tile(_v->dest_tile),
2561 old_last_station_visited(_v->last_station_visited),
2562 index(_v->cur_real_order_index),
2563 suppress_implicit_orders(HasBit(_v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS))
2567 ~VehicleOrderSaver()
2569 this->v->current_order = this->old_order;
2570 this->v->dest_tile = this->old_dest_tile;
2571 this->v->last_station_visited = this->old_last_station_visited;
2572 SB(this->v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS, 1, suppress_implicit_orders ? 1: 0);
2576 * Set the current vehicle order to the next order in the order list.
2577 * @param skip_first Shall the first (i.e. active) order be skipped?
2578 * @return True if a suitable next order could be found.
2580 bool SwitchToNextOrder(bool skip_first)
2582 if (this->v->GetNumOrders() == 0) return false;
2584 if (skip_first) ++this->index;
2586 int depth = 0;
2588 do {
2589 /* Wrap around. */
2590 if (this->index >= this->v->GetNumOrders()) this->index = 0;
2592 Order *order = this->v->GetOrder(this->index);
2593 assert(order != NULL);
2595 switch (order->GetType()) {
2596 case OT_GOTO_DEPOT:
2597 /* Skip service in depot orders when the train doesn't need service. */
2598 if ((order->GetDepotOrderType() & ODTFB_SERVICE) && !this->v->NeedsServicing()) break;
2599 case OT_GOTO_STATION:
2600 case OT_GOTO_WAYPOINT:
2601 this->v->current_order = *order;
2602 return UpdateOrderDest(this->v, order, 0, true);
2603 case OT_CONDITIONAL: {
2604 VehicleOrderID next = ProcessConditionalOrder(order, this->v);
2605 if (next != INVALID_VEH_ORDER_ID) {
2606 depth++;
2607 this->index = next;
2608 /* Don't increment next, so no break here. */
2609 continue;
2611 break;
2613 default:
2614 break;
2616 /* Don't increment inside the while because otherwise conditional
2617 * orders can lead to an infinite loop. */
2618 ++this->index;
2619 depth++;
2620 } while (this->index != this->v->cur_real_order_index && depth < this->v->GetNumOrders());
2622 return false;
2626 /* choose a track */
2627 static bool ChooseTrainTrack (Train *v, RailPathPos origin,
2628 const PathMPos<RailPathPos> &pos, bool force_res,
2629 Trackdir *best_trackdir)
2631 bool do_track_reservation = _settings_game.pf.reserve_paths || force_res;
2632 bool change_signal = false;
2634 assert (!pos.is_empty());
2636 /* Quick return in case only one possible trackdir is available */
2637 if (pos.is_single()) {
2638 if (best_trackdir != NULL) *best_trackdir = pos.td;
2639 /* We need to check for signals only here, as a junction tile can't have signals. */
2640 if (pos.has_signal_along() && IsPbsSignal (pos.get_signal_type())) {
2641 do_track_reservation = true;
2642 change_signal = true;
2643 } else if (!do_track_reservation) {
2644 return true;
2648 if (do_track_reservation) {
2649 switch (ExtendTrainReservation(v, &origin)) {
2650 default: NOT_REACHED();
2651 case EXTEND_RESERVATION_FAILED:
2652 if (best_trackdir != NULL) *best_trackdir = FindFirstTrackdir (pos.trackdirs);
2653 return false;
2654 case EXTEND_RESERVATION_SAFE:
2655 assert (pos.is_single());
2656 if (change_signal) {
2657 pos.set_signal_state (SIGNAL_STATE_GREEN);
2658 MarkTileDirtyByTile (pos.tile);
2660 TryReserveRailTrack(v->GetPos());
2661 return true;
2662 case EXTEND_RESERVATION_UNSAFE:
2663 break;
2666 /* Check if the train needs service here, so it has a chance to always find a depot.
2667 * Also check if the current order is a service order so we don't reserve a path to
2668 * the destination but instead to the next one if service isn't needed. */
2669 CheckIfTrainNeedsService(v);
2670 if (v->current_order.IsType(OT_DUMMY) || v->current_order.IsType(OT_CONDITIONAL) || v->current_order.IsType(OT_GOTO_DEPOT)) ProcessOrders(v);
2673 /* Save the current train order. The destructor will restore the old order on function exit. */
2674 VehicleOrderSaver orders(v);
2676 /* If the current tile is the destination of the current order and
2677 * a reservation was requested, advance to the next order.
2678 * Don't advance on a depot order as depots are always safe end points
2679 * for a path and no look-ahead is necessary. This also avoids a
2680 * problem with depot orders not part of the order list when the
2681 * order list itself is empty. */
2682 if (v->current_order.IsType(OT_LEAVESTATION)) {
2683 orders.SwitchToNextOrder(false);
2684 } else if (v->current_order.IsType(OT_LOADING) || (!v->current_order.IsType(OT_GOTO_DEPOT) && (
2685 v->current_order.IsType(OT_GOTO_STATION) ?
2686 IsRailStationTile(v->tile) && v->current_order.GetDestination() == GetStationIndex(v->tile) :
2687 v->tile == v->dest_tile))) {
2688 orders.SwitchToNextOrder(true);
2691 /* Call the pathfinder... */
2692 PFResult res_dest;
2693 Trackdir next_trackdir = DoTrainPathfind(v, origin, do_track_reservation, &res_dest);
2694 v->HandlePathfindingResult(res_dest.found);
2695 /* ...but only use the result if we were at the original tile. */
2696 if (best_trackdir != NULL && !pos.is_single()) {
2697 /* The initial tile had more than one available trackdir.
2698 * This means that ExtendTrainReservation cannot possibly
2699 * have extended the reservation, and we are pathfinding
2700 * at the original tile. */
2701 *best_trackdir = next_trackdir != INVALID_TRACKDIR ? next_trackdir : FindFirstTrackdir (pos.trackdirs);
2702 /* If the initial tile only had one available trackdir, then
2703 * *best_trackdir was set along with single_trackdir. */
2706 /* No track reservation requested -> finished. */
2707 if (!do_track_reservation) {
2708 assert (!change_signal);
2709 return true;
2712 if (change_signal) pos.set_signal_state (SIGNAL_STATE_GREEN);
2714 /* A path was found, but could not be reserved. */
2715 if (res_dest.pos.is_valid_tile() && !res_dest.okay) {
2716 FreeTrainTrackReservation (v, &origin);
2717 return false;
2720 /* No possible reservation target found, we are probably lost. */
2721 if (!res_dest.pos.is_valid_tile()) {
2722 /* Try to find any safe destination. */
2723 if (TryReserveSafeTrack(v, origin, false)) {
2724 if (best_trackdir != NULL && !pos.is_single()) {
2725 TrackBits res = GetReservedTrackbits (pos.tile);
2726 *best_trackdir = FindFirstTrackdir (TrackBitsToTrackdirBits(res) & pos.trackdirs);
2728 TryReserveRailTrack(v->GetPos());
2729 if (change_signal) MarkTileDirtyByTile (pos.tile);
2730 return true;
2731 } else {
2732 FreeTrainTrackReservation (v, &origin);
2733 return false;
2737 /* Extend reservation until we have found a safe position. */
2738 bool safe = false;
2739 for (;;) {
2740 origin = res_dest.pos;
2741 if (IsSafeWaitingPosition(v, origin, _settings_game.pf.forbid_90_deg)) {
2742 safe = true;
2743 break;
2746 /* Get next order with destination. */
2747 if (!orders.SwitchToNextOrder(true)) break;
2749 DoTrainPathfind(v, origin, true, &res_dest);
2750 /* Break if no safe position was found. */
2751 if (!res_dest.pos.is_valid_tile()) break;
2753 if (!res_dest.okay) {
2754 /* Path found, but could not be reserved. */
2755 FreeTrainTrackReservation (v, &origin);
2756 return false;
2760 /* No order or no safe position found, try any position. */
2761 if (!safe) safe = TryReserveSafeTrack(v, origin, true);
2763 if (!safe) {
2764 FreeTrainTrackReservation (v, &origin);
2765 } else if (change_signal) {
2766 MarkTileDirtyByTile (pos.tile);
2769 return safe;
2773 * Try to extend a reserved path to a safe position.
2774 * @param v The vehicle.
2775 * @param origin Current end of the reservation.
2776 * @param mark_as_stuck Whether the train should be marked as stuck on a failed reservation.
2777 * @return Whether the reserved path could be extended.
2779 static bool TryPathExtend (Train *v, const RailPathPos &origin, bool mark_as_stuck)
2781 CFollowTrackRail ft (v, !_settings_game.pf.forbid_90_deg);
2783 if ((ft.Follow (origin) == CFollowTrackRail::EC_NONE)
2784 && !ChooseTrainTrack (v, origin, ft.m_new, true)) {
2785 if (mark_as_stuck) MarkTrainAsStuck(v);
2786 return false;
2789 if (HasBit (v->flags, VRF_TRAIN_STUCK)) {
2790 v->wait_counter = 0;
2791 SetWindowWidgetDirty (WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
2792 ClrBit (v->flags, VRF_TRAIN_STUCK);
2795 return true;
2799 * Try to reserve a path to a safe position.
2801 * @param v The vehicle
2802 * @param mark_as_stuck Should the train be marked as stuck on a failed reservation?
2803 * @param first_tile_okay True if no path should be reserved if the current tile is a safe position.
2804 * @return True if a path could be reserved.
2806 bool TryPathReserve(Train *v, bool mark_as_stuck, bool first_tile_okay)
2808 assert(v->IsFrontEngine());
2809 assert(v->trackdir != TRACKDIR_DEPOT);
2811 RailPathPos origin;
2812 /* The path we are driving on is already blocked by some other train.
2813 * This can only happen in certain situations when mixing path and
2814 * block signals or when changing tracks and/or signals.
2815 * Exit here as doing any further reservations will probably just
2816 * make matters worse. */
2817 if (!FollowTrainReservation (v, &origin, true)) {
2818 if (mark_as_stuck) MarkTrainAsStuck(v);
2819 return false;
2822 /* If we have a reserved path and the path ends at a safe tile, we are finished already. */
2823 if ((v->tile != origin.tile || first_tile_okay) && IsSafeWaitingPosition(v, origin, _settings_game.pf.forbid_90_deg)) {
2824 /* Can't be stuck then. */
2825 if (HasBit(v->flags, VRF_TRAIN_STUCK)) SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
2826 ClrBit(v->flags, VRF_TRAIN_STUCK);
2827 return true;
2830 return TryPathExtend (v, origin, mark_as_stuck);
2834 static bool CheckReverseTrain(const Train *v)
2836 if (_settings_game.difficulty.line_reverse_mode != 0 ||
2837 v->trackdir == TRACKDIR_DEPOT || v->trackdir == TRACKDIR_WORMHOLE ||
2838 !(v->direction & 1)) {
2839 return false;
2842 assert(IsValidTrackdir(v->trackdir));
2844 return YapfTrainCheckReverse(v);
2848 * Get the location of the next station to visit.
2849 * @param station Next station to visit.
2850 * @return Location of the new station.
2852 TileIndex Train::GetOrderStationLocation(StationID station)
2854 if (station == this->last_station_visited) this->last_station_visited = INVALID_STATION;
2856 const Station *st = Station::Get(station);
2857 if (!(st->facilities & FACIL_TRAIN)) {
2858 /* The destination station has no trainstation tiles. */
2859 this->IncrementRealOrderIndex();
2860 return 0;
2863 return st->xy;
2866 /** Goods at the consist have changed, update the graphics, cargo, and acceleration. */
2867 void Train::MarkDirty()
2869 Train *v = this;
2870 do {
2871 v->colourmap = PAL_NONE;
2872 v->UpdateViewport(true, false);
2873 } while ((v = v->Next()) != NULL);
2875 /* need to update acceleration and cached values since the goods on the train changed. */
2876 this->CargoChanged();
2877 this->UpdateAcceleration();
2881 * This function looks at the vehicle and updates its speed (cur_speed
2882 * and subspeed) variables. Furthermore, it returns the distance that
2883 * the train can drive this tick. #Vehicle::GetAdvanceDistance() determines
2884 * the distance to drive before moving a step on the map.
2885 * @return distance to drive.
2887 int Train::UpdateSpeed()
2889 switch (_settings_game.vehicle.train_acceleration_model) {
2890 default: NOT_REACHED();
2891 case AM_ORIGINAL:
2892 return this->DoUpdateSpeed(this->acceleration * (this->GetAccelerationStatus() == AS_BRAKE ? -4 : 2), 0, this->GetCurrentMaxSpeed());
2894 case AM_REALISTIC:
2895 return this->DoUpdateSpeed(this->GetAcceleration(), this->GetAccelerationStatus() == AS_BRAKE ? 0 : 2, this->GetCurrentMaxSpeed());
2900 * Trains enters a station, send out a news item if it is the first train, and start loading.
2901 * @param v Train that entered the station.
2902 * @param station Station visited.
2904 static void TrainEnterStation(Train *v, StationID station)
2906 v->last_station_visited = station;
2908 /* check if a train ever visited this station before */
2909 Station *st = Station::Get(station);
2910 if (!(st->had_vehicle_of_type & HVOT_TRAIN)) {
2911 st->had_vehicle_of_type |= HVOT_TRAIN;
2912 AddNewsItem<ArrivalNewsItem> (STR_NEWS_FIRST_TRAIN_ARRIVAL, v, st);
2913 AI::NewEvent(v->owner, new ScriptEventStationFirstVehicle(st->index, v->index));
2914 Game::NewEvent(new ScriptEventStationFirstVehicle(st->index, v->index));
2917 v->force_proceed = TFP_NONE;
2918 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
2920 v->BeginLoading();
2922 TriggerStationRandomisation(st, v->tile, SRT_TRAIN_ARRIVES);
2923 TriggerStationAnimation(st, v->tile, SAT_TRAIN_ARRIVES);
2926 /* Check if the vehicle is compatible with the specified tile */
2927 static inline bool CheckCompatibleRail(const Train *v, TileIndex tile, Track track = INVALID_TRACK)
2929 return IsTileOwner(tile, v->owner) &&
2930 (!v->IsFrontEngine() || HasBit(v->compatible_railtypes, GetRailType(tile, track)));
2933 /** Data structure for storing engine speed changes of an acceleration type. */
2934 struct AccelerationSlowdownParams {
2935 byte small_turn; ///< Speed change due to a small turn.
2936 byte large_turn; ///< Speed change due to a large turn.
2937 byte z_up; ///< Fraction to remove when moving up.
2938 byte z_down; ///< Fraction to add when moving down.
2941 /** Speed update fractions for each acceleration type. */
2942 static const AccelerationSlowdownParams _accel_slowdown[] = {
2943 /* normal accel */
2944 {256 / 4, 256 / 2, 256 / 4, 2}, ///< normal
2945 {256 / 4, 256 / 2, 256 / 4, 2}, ///< monorail
2946 {0, 256 / 2, 256 / 4, 2}, ///< maglev
2950 * Modify the speed of the vehicle due to a change in altitude.
2951 * @param v %Train to update.
2952 * @param old_z Previous height.
2954 static inline void AffectSpeedByZChange(Train *v, int old_z)
2956 if (old_z == v->z_pos || _settings_game.vehicle.train_acceleration_model != AM_ORIGINAL) return;
2958 const AccelerationSlowdownParams *asp = &_accel_slowdown[GetRailTypeInfo(v->railtype)->acceleration_type];
2960 if (old_z < v->z_pos) {
2961 v->cur_speed -= (v->cur_speed * asp->z_up >> 8);
2962 } else {
2963 uint16 spd = v->cur_speed + asp->z_down;
2964 if (spd <= v->gcache.cached_max_track_speed) v->cur_speed = spd;
2968 /** Tries to reserve track under whole train consist. */
2969 void Train::ReserveTrackUnderConsist() const
2971 for (const Train *u = this; u != NULL; u = u->Next()) {
2972 switch (u->trackdir) {
2973 case TRACKDIR_WORMHOLE:
2974 if (IsRailwayTile(u->tile)) {
2975 SetBridgeMiddleReservation(u->tile, true);
2976 SetBridgeMiddleReservation(GetOtherBridgeEnd(u->tile), true);
2977 } else {
2978 SetTunnelMiddleReservation(u->tile, true);
2979 SetTunnelMiddleReservation(GetOtherTunnelEnd(u->tile), true);
2981 break;
2982 case TRACKDIR_DEPOT:
2983 break;
2984 default:
2985 TryReserveRailTrack(u->tile, TrackdirToTrack(u->trackdir));
2986 break;
2992 * The train vehicle crashed!
2993 * Update its status and other parts around it.
2994 * @param flooded Crash was caused by flooding.
2995 * @return Number of people killed.
2997 uint Train::Crash(bool flooded)
2999 uint pass = 0;
3000 if (this->IsFrontEngine()) {
3001 pass += 2; // driver
3003 /* Remove the reserved path in front of the train if it is not stuck.
3004 * Also clear all reserved tracks the train is currently on. */
3005 if (!HasBit(this->flags, VRF_TRAIN_STUCK)) FreeTrainTrackReservation(this);
3006 for (const Train *v = this; v != NULL; v = v->Next()) {
3007 ClearPathReservation (v->GetPos());
3010 /* we may need to update crossing we were approaching,
3011 * but must be updated after the train has been marked crashed */
3012 TileIndex crossing = TrainApproachingCrossingTile(this);
3013 if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
3015 /* Remove the loading indicators (if any) */
3016 HideFillingPercent(&this->fill_percent_te_id);
3019 pass += this->GroundVehicleBase::Crash(flooded);
3021 this->crash_anim_pos = flooded ? 4000 : 1; // max 4440, disappear pretty fast when flooded
3022 return pass;
3026 * Marks train as crashed and creates an AI event.
3027 * Doesn't do anything if the train is crashed already.
3028 * @param v first vehicle of chain
3029 * @return number of victims (including 2 drivers; zero if train was already crashed)
3031 static uint TrainCrashed(Train *v)
3033 uint num = 0;
3035 /* do not crash train twice */
3036 if (!(v->vehstatus & VS_CRASHED)) {
3037 num = v->Crash();
3038 AI::NewEvent(v->owner, new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_TRAIN));
3039 Game::NewEvent(new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_TRAIN));
3042 /* Try to re-reserve track under already crashed train too.
3043 * Crash() clears the reservation! */
3044 v->ReserveTrackUnderConsist();
3046 return num;
3050 * Collision test function.
3051 * @param tcc %Train being examined.
3052 * @param v %Train vehicle to test collision with.
3053 * @return Total number of victims if train collided, else 0.
3055 static uint FindTrainCollision(Train *tcc, Vehicle *v)
3057 /* not a train or in depot */
3058 if (v->type != VEH_TRAIN || Train::From(v)->trackdir == TRACKDIR_DEPOT) return 0;
3060 /* do not crash into trains of another company. */
3061 if (v->owner != tcc->owner) return 0;
3063 /* get first vehicle now to make most usual checks faster */
3064 Train *coll = Train::From(v)->First();
3066 /* can't collide with own wagons */
3067 if (coll == tcc) return 0;
3069 int x_diff = v->x_pos - tcc->x_pos;
3070 int y_diff = v->y_pos - tcc->y_pos;
3072 /* Do fast calculation to check whether trains are not in close vicinity
3073 * and quickly reject trains distant enough for any collision.
3074 * Differences are shifted by 7, mapping range [-7 .. 8] into [0 .. 15]
3075 * Differences are then ORed and then we check for any higher bits */
3076 uint hash = (y_diff + 7) | (x_diff + 7);
3077 if (hash & ~15) return 0;
3079 /* Slower check using multiplication */
3080 int min_diff = (Train::From(v)->gcache.cached_veh_length + 1) / 2 + (tcc->gcache.cached_veh_length + 1) / 2 - 1;
3081 if (x_diff * x_diff + y_diff * y_diff > min_diff * min_diff) return 0;
3083 /* Happens when there is a train under bridge next to bridge head */
3084 if (abs(v->z_pos - tcc->z_pos) > 5) return 0;
3086 /* crash both trains */
3087 return TrainCrashed(tcc) + TrainCrashed(coll);
3090 /** Temporary data storage for testing collisions. */
3091 struct TrainCollideChecker {
3092 Train *v; ///< %Vehicle we are testing for collision.
3093 uint num; ///< Total number of victims if train collided.
3097 * Collision test function.
3098 * @param v %Train vehicle to test collision with.
3099 * @param data %Train being examined.
3100 * @return \c NULL (always continue search)
3102 static Vehicle *FindTrainCollideEnum(Vehicle *v, void *data)
3104 TrainCollideChecker *tcc = (TrainCollideChecker*)data;
3106 tcc->num += FindTrainCollision (tcc->v, v);
3108 return NULL;
3112 * Checks whether the specified train has a collision with another vehicle. If
3113 * so, destroys this vehicle, and the other vehicle if its subtype has TS_Front.
3114 * Reports the incident in a flashy news item, modifies station ratings and
3115 * plays a sound.
3116 * @param v %Train to test.
3118 static bool CheckTrainCollision(Train *v)
3120 /* can't collide in depot */
3121 if (v->trackdir == TRACKDIR_DEPOT) return false;
3123 assert(v->trackdir == TRACKDIR_WORMHOLE || TileVirtXY(v->x_pos, v->y_pos) == v->tile);
3125 TrainCollideChecker tcc;
3126 tcc.v = v;
3127 tcc.num = 0;
3129 /* find colliding vehicles */
3130 if (v->trackdir == TRACKDIR_WORMHOLE) {
3131 VehicleTileIterator iter1 (v->tile);
3132 while (!iter1.finished()) {
3133 tcc.num += FindTrainCollision (v, iter1.next());
3135 VehicleTileIterator iter2 (GetOtherTunnelBridgeEnd(v->tile));
3136 while (!iter2.finished()) {
3137 tcc.num += FindTrainCollision (v, iter2.next());
3139 } else {
3140 FindVehicleOnPosXY(v->x_pos, v->y_pos, &tcc, FindTrainCollideEnum);
3143 /* any dead -> no crash */
3144 if (tcc.num == 0) return false;
3146 AddNewsItem<VehicleNewsItem> (STR_NEWS_TRAIN_CRASH, NT_ACCIDENT,
3147 v->index, tcc.num);
3149 ModifyStationRatingAround(v->tile, v->owner, -160, 30);
3150 if (_settings_client.sound.disaster) SndPlayVehicleFx(SND_13_BIG_CRASH, v);
3151 return true;
3156 * Tile callback routine when vehicle enters a track tile
3157 * @see vehicle_enter_tile_proc
3159 static void TrainEnter_Track(Train *v, TileIndex tile, int x, int y)
3161 if (IsTileSubtype(tile, TT_TRACK)) return;
3163 assert(abs((int)(GetSlopePixelZ(x, y) - v->z_pos)) < 3);
3165 /* modify speed of vehicle */
3166 uint16 spd = GetBridgeSpec(GetRailBridgeType(tile))->speed;
3167 Vehicle *first = v->First();
3168 first->cur_speed = min(first->cur_speed, spd);
3172 * Frame when the 'enter tunnel' sound should be played. This is the second
3173 * frame on a tile, so the sound is played shortly after entering the tunnel
3174 * tile, while the vehicle is still visible.
3176 static const byte TUNNEL_SOUND_FRAME = 1;
3178 extern const byte _tunnel_visibility_frame[DIAGDIR_END];
3181 * Compute number of ticks when next wagon will leave a depot.
3182 * Negative means next wagon should have left depot n ticks before.
3183 * @param v vehicle outside (leaving) the depot
3184 * @return number of ticks when the next wagon will leave
3186 int TicksToLeaveDepot(const Train *v)
3188 DiagDirection dir = GetGroundDepotDirection(v->tile);
3189 int length = v->CalcNextVehicleOffset();
3191 switch (dir) {
3192 case DIAGDIR_NE: return ((int)(v->x_pos & 0x0F) - (_vehicle_initial_x_fract[dir] - (length + 1)));
3193 case DIAGDIR_SE: return -((int)(v->y_pos & 0x0F) - (_vehicle_initial_y_fract[dir] + (length + 1)));
3194 case DIAGDIR_SW: return -((int)(v->x_pos & 0x0F) - (_vehicle_initial_x_fract[dir] + (length + 1)));
3195 default:
3196 case DIAGDIR_NW: return ((int)(v->y_pos & 0x0F) - (_vehicle_initial_y_fract[dir] - (length + 1)));
3199 return 0; // make compilers happy
3202 static void TrainEnter_Misc(Train *u, TileIndex tile, int x, int y)
3204 switch (GetTileSubtype(tile)) {
3205 default: break;
3207 case TT_MISC_TUNNEL: {
3208 assert(abs((int)GetSlopePixelZ(x, y) - u->z_pos) < 3);
3210 /* Direction into the wormhole */
3211 const DiagDirection dir = GetTunnelBridgeDirection(tile);
3213 if (u->direction == DiagDirToDir(dir)) {
3214 uint frame = DistanceFromTileEdge(ReverseDiagDir(dir), x & 0xF, y & 0xF);
3215 if (u->IsFrontEngine() && frame == TUNNEL_SOUND_FRAME) {
3216 if (!PlayVehicleSound(u, VSE_TUNNEL) && RailVehInfo(u->engine_type)->engclass == 0) {
3217 SndPlayVehicleFx(SND_05_TRAIN_THROUGH_TUNNEL, u);
3220 if (frame == _tunnel_visibility_frame[dir]) {
3221 u->vehstatus |= VS_HIDDEN;
3223 } else if (u->direction == ReverseDir(DiagDirToDir(dir))) {
3224 uint frame = DistanceFromTileEdge(dir, x & 0xF, y & 0xF);
3225 if (frame == TILE_SIZE - _tunnel_visibility_frame[dir]) {
3226 u->vehstatus &= ~VS_HIDDEN;
3230 break;
3233 case TT_MISC_DEPOT: {
3234 if (!IsRailDepot(tile)) break;
3236 /* depot direction */
3237 DiagDirection dir = GetGroundDepotDirection(tile);
3239 /* make sure a train is not entering the tile from behind */
3240 assert(DistanceFromTileEdge(ReverseDiagDir(dir), x & 0xF, y & 0xF) != 0);
3242 int fract_x = (int)(x & 0xF) - _vehicle_initial_x_fract[dir];
3243 int fract_y = (int)(y & 0xF) - _vehicle_initial_y_fract[dir];
3245 if (u->direction == DiagDirToDir(ReverseDiagDir(dir))) {
3246 if (fract_x == 0 && fract_y == 0) {
3247 /* enter the depot */
3248 u->trackdir = TRACKDIR_DEPOT,
3249 u->vehstatus |= VS_HIDDEN; // hide it
3250 u->direction = ReverseDir(u->direction);
3251 if (u->Next() == NULL) TrainEnterDepot (u->First());
3252 u->tile = tile;
3254 InvalidateWindowData(WC_VEHICLE_DEPOT, u->tile);
3256 } else if (u->direction == DiagDirToDir(dir)) {
3257 static const int8 delta_x[4] = { -1, 0, 1, 0 };
3258 static const int8 delta_y[4] = { 0, 1, 0, -1 };
3260 /* Calculate the point where the following wagon should be activated. */
3261 int length = u->CalcNextVehicleOffset() + 1;
3263 if ((fract_x == length * delta_x[dir]) && (fract_y == length * delta_y[dir])) {
3264 /* leave the depot? */
3265 if ((u = u->Next()) != NULL) {
3266 u->vehstatus &= ~VS_HIDDEN;
3267 u->trackdir = DiagDirToDiagTrackdir(dir);
3272 break;
3277 static StationID TrainEnter_Station(Train *v, TileIndex tile, int x, int y)
3279 StationID station_id = GetStationIndex(tile);
3280 if (!v->current_order.ShouldStopAtStation(v, station_id)) return INVALID_STATION;
3281 if (!IsRailStation(tile) || !v->IsFrontEngine()) return INVALID_STATION;
3283 int station_ahead;
3284 int station_length;
3285 int stop = GetTrainStopLocation(station_id, tile, Train::From(v), &station_ahead, &station_length);
3287 /* Stop whenever that amount of station ahead + the distance from the
3288 * begin of the platform to the stop location is longer than the length
3289 * of the platform. Station ahead 'includes' the current tile where the
3290 * vehicle is on, so we need to subtract that. */
3291 if (stop + station_ahead - (int)TILE_SIZE >= station_length) return INVALID_STATION;
3293 DiagDirection dir = DirToDiagDir(v->direction);
3295 x &= 0xF;
3296 y &= 0xF;
3298 if (DiagDirToAxis(dir) != AXIS_X) Swap(x, y);
3299 if (y == TILE_SIZE / 2) {
3300 if (dir != DIAGDIR_SE && dir != DIAGDIR_SW) x = TILE_SIZE - 1 - x;
3301 stop &= TILE_SIZE - 1;
3303 if (x == stop) {
3304 return station_id; // enter station
3305 } else if (x < stop) {
3306 v->vehstatus |= VS_TRAIN_SLOWING;
3307 uint16 spd = max(0, (stop - x) * 20 - 15);
3308 if (spd < v->cur_speed) v->cur_speed = spd;
3312 return INVALID_STATION;
3316 * Call the tile callback function for a train entering a tile
3317 * @param v Train entering the tile
3318 * @param tile Tile entered
3319 * @param x X position
3320 * @param y Y position
3321 * @return Station ID of an entered station, or INVALID_STATION otherwise
3323 static StationID TrainEnterTile(Train *v, TileIndex tile, int x, int y)
3325 switch (GetTileType(tile)) {
3326 default: NOT_REACHED();
3328 case TT_RAILWAY:
3329 TrainEnter_Track(v, tile, x, y);
3330 break;
3332 case TT_MISC:
3333 TrainEnter_Misc(v, tile, x, y);
3334 break;
3336 case TT_STATION:
3337 return TrainEnter_Station(v, tile, x, y);
3340 return INVALID_STATION;
3344 * Choose the trackdir to follow when a train enters a new tile.
3345 * @param v The train that enters the tile
3346 * @param tile The tile entered
3347 * @param enterdir The direction the train is moving between tiles
3348 * @param tsdir The direction to use for GetTileRailwayStatus
3349 * @param check_90deg Check for 90-degree turns and disallow them
3350 * @param reverse Set to false to not execute the vehicle reversing. This does not change any other logic.
3351 * @return The trackdir to use, or INVALID_TRACKDIR if the train cannot go forward
3353 static Trackdir TrainControllerChooseTrackdir(Train *v, TileIndex tile, DiagDirection enterdir, DiagDirection tsdir, bool check_90deg, bool reverse)
3355 /* Get the status of the tracks in the new tile and mask
3356 * away the bits that aren't reachable. */
3357 TrackStatus ts = GetTileRailwayStatus(tile, tsdir);
3358 TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(enterdir);
3360 TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
3361 if (check_90deg) trackdirbits &= ~TrackdirCrossesTrackdirs(v->trackdir);
3363 TrackdirBits red_signals = TrackStatusToRedSignals(ts);
3365 /* Check if the new tile constrains tracks that are compatible
3366 * with the current train, if not, bail out. */
3367 if (trackdirbits == TRACKDIR_BIT_NONE || !CheckCompatibleRail(v, tile, TrackdirToTrack(FindFirstTrackdir(trackdirbits)))) {
3368 if (reverse) {
3369 v->wait_counter = 0;
3370 v->cur_speed = 0;
3371 v->subspeed = 0;
3372 ReverseTrainDirection(v);
3375 return INVALID_TRACKDIR;
3378 Trackdir chosen_trackdir;
3380 /* Don't use trackdirbits here as the setting to forbid 90 deg turns might have been switched between reservation and now. */
3381 TrackdirBits res_trackdirs = TrackBitsToTrackdirBits(GetReservedTrackbits(tile)) & reachable_trackdirs;
3382 /* Do we have a suitable reserved trackdir? */
3383 if (res_trackdirs != TRACKDIR_BIT_NONE) {
3384 chosen_trackdir = FindFirstTrackdir(res_trackdirs);
3385 } else {
3386 if (!ChooseTrainTrack (v, v->GetPos(),
3387 PathMPos<RailPathPos> (tile, trackdirbits),
3388 false, &chosen_trackdir)) {
3389 MarkTrainAsStuck(v);
3391 assert(chosen_trackdir != INVALID_TRACKDIR);
3392 assert(HasBit(trackdirbits, chosen_trackdir));
3395 /* Make sure chosen trackdir is a valid trackdir */
3396 assert(IsValidTrackdir(chosen_trackdir));
3398 if (v->force_proceed != TFP_NONE) {
3399 /* For each signal we find decrease the counter by one.
3400 * We start at two, so the first signal we pass decreases
3401 * this to one, then if we reach the next signal it is
3402 * decreased to zero and we won't pass that new signal. */
3403 bool at_signal;
3404 if (IsRailwayTile(tile)) {
3405 Track track = TrackdirToTrack(chosen_trackdir);
3406 /* However, we do not want to be stopped by PBS
3407 * signals entered via the back. */
3408 at_signal = HasSignalOnTrack(tile, track) &&
3409 (GetSignalType(tile, track) != SIGTYPE_PBS ||
3410 HasSignalOnTrackdir(tile, chosen_trackdir));
3411 } else if (maptile_is_rail_tunnel(tile)) {
3412 at_signal = maptile_has_tunnel_signals(tile);
3413 } else {
3414 at_signal = false;
3417 if (at_signal) {
3418 v->force_proceed = (v->force_proceed == TFP_SIGNAL) ? TFP_STUCK : TFP_NONE;
3419 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
3423 /* Check if it's a red signal and if force proceed is clicked. */
3424 if (!HasBit(red_signals, chosen_trackdir) || v->force_proceed != TFP_NONE) {
3425 /* Proceed */
3426 TryReserveRailTrack(tile, TrackdirToTrack(chosen_trackdir), false);
3427 return chosen_trackdir;
3430 /* In front of a red signal */
3431 assert(trackdirbits == TrackdirToTrackdirBits(chosen_trackdir));
3433 /* Don't handle stuck trains here. */
3434 if (HasBit(v->flags, VRF_TRAIN_STUCK)) return INVALID_TRACKDIR;
3436 bool is_track = IsRailwayTile (tile);
3438 SignalPair sp;
3439 bool is_along;
3440 if (is_track) {
3441 sp = *maptile_signalpair (tile, TrackdirToTrack (chosen_trackdir));
3442 is_along = trackdir_is_signal_along (chosen_trackdir);
3443 } else {
3444 assert (maptile_is_rail_tunnel (tile));
3445 assert (IsDiagonalTrackdir (chosen_trackdir));
3446 sp = *maptile_tunnel_signalpair (tile);
3447 /* For tunnels, along means inwards. */
3448 is_along = (chosen_trackdir == DiagDirToDiagTrackdir (GetTunnelBridgeDirection (tile)));
3451 assert (signalpair_has_signals (&sp));
3453 /* Is the train stuck at the wrong side of a one-way signal? */
3454 bool blocked;
3456 if (!signalpair_has_signal (&sp, !is_along)) {
3457 /* No signal against; wait here for the signal to clear. */
3458 v->cur_speed = 0;
3459 v->subspeed = 0;
3460 v->progress = 255 - 100;
3461 if (!_settings_game.pf.reverse_at_signals || ++v->wait_counter < _settings_game.pf.wait_oneway_signal * 20) return INVALID_TRACKDIR;
3462 blocked = false;
3463 } else if (signalpair_has_signal (&sp, is_along)) {
3464 /* Signals both along and against. */
3465 v->cur_speed = 0;
3466 v->subspeed = 0;
3467 v->progress = 255 - 10;
3468 if ((!_settings_game.pf.reverse_at_signals || ++v->wait_counter < _settings_game.pf.wait_twoway_signal * 73)
3469 && (is_track || !is_along)) {
3470 DiagDirection exitdir = TrackdirToExitdir(chosen_trackdir);
3471 TileIndex o_tile = TileAddByDiagDir(tile, exitdir);
3473 exitdir = ReverseDiagDir(exitdir);
3475 /* check if a train is waiting on the other side */
3476 VehicleTileFinder iter (o_tile);
3477 while (!iter.finished()) {
3478 Vehicle *v = iter.next();
3479 if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) continue;
3481 Train *t = Train::From(v);
3482 if (t->IsFrontEngine() && (t->trackdir < TRACKDIR_END) && (t->cur_speed <= 5) && TrackdirToExitdir(t->trackdir) == exitdir) {
3483 iter.set_found();
3486 if (!iter.was_found()) return INVALID_TRACKDIR;
3488 blocked = false;
3489 } else {
3490 /* Signal against, but not along; reverse immediately. */
3491 assert (IsOnewaySignal (signalpair_get_type (&sp)));
3492 blocked = true;
3495 /* If we would reverse but are currently in a PBS block and
3496 * reversing of stuck trains is disabled, don't reverse.
3497 * This does not apply if the reason for reversing is a one-way
3498 * signal blocking us, because a train would then be stuck forever. */
3499 if (!blocked && !_settings_game.pf.reverse_at_signals) {
3500 assert(IsSignalBufferEmpty());
3501 AddPosToSignalBuffer(v->GetPos(), v->owner);
3502 if (UpdateSignalsInBuffer() == SIGSEG_PBS) {
3503 v->wait_counter = 0;
3504 return INVALID_TRACKDIR;
3508 if (reverse) {
3509 v->wait_counter = 0;
3510 v->cur_speed = 0;
3511 v->subspeed = 0;
3512 ReverseTrainDirection(v);
3515 return INVALID_TRACKDIR;
3519 * Move a vehicle chain one movement stop forwards.
3520 * @param v First vehicle to move.
3521 * @param nomove Stop moving this and all following vehicles.
3522 * @param reverse Set to false to not execute the vehicle reversing. This does not change any other logic.
3523 * @return True if the vehicle could be moved forward, false otherwise.
3525 bool TrainController(Train *v, Vehicle *nomove, bool reverse)
3527 Train *first = v->First();
3528 Train *prev;
3529 bool direction_changed = false; // has direction of any part changed?
3531 /* For every vehicle after and including the given vehicle */
3532 for (prev = v->Previous(); v != nomove; prev = v, v = v->Next()) {
3533 TileIndex old_tile; // old virtual tile
3534 bool old_in_wormhole; // whether old position was in wormhole
3535 enum {
3536 WORMHOLE_NONE,
3537 WORMHOLE_BRIDGE,
3538 WORMHOLE_TUNNEL,
3539 } new_in_wormhole; // whether new position is in a wormhole, and of which kind
3540 DiagDirection enterdir = INVALID_DIAGDIR; // direction into the new tile, or INVALID_DIAGDIR if we stay on the old tile
3541 DiagDirection tsdir = INVALID_DIAGDIR; // direction to use for GetTileRailwayStatus, only when moving into a new tile
3543 FullPosTile gp = GetNewVehiclePos(v);
3544 if (v->trackdir == TRACKDIR_WORMHOLE) {
3545 /* In a tunnel or on a bridge (middle part) */
3546 old_tile = TileVirtXY(v->x_pos, v->y_pos);
3547 old_in_wormhole = true;
3549 if (gp.tile == v->tile) {
3550 new_in_wormhole = WORMHOLE_NONE;
3551 enterdir = ReverseDiagDir(GetTunnelBridgeDirection(gp.tile));
3552 tsdir = INVALID_DIAGDIR;
3553 } else if (!(v->vehstatus & VS_HIDDEN)) {
3554 /* Still on the bridge. */
3555 new_in_wormhole = WORMHOLE_BRIDGE;
3556 } else {
3557 /* Still in the tunnel. */
3558 if (v->IsFrontEngine() && maptile_has_tunnel_signal (v->tile, false) && (FindTunnelPrevTrain(v) < TILE_SIZE)) {
3559 /* too close to train ahead, stop */
3560 return false;
3562 new_in_wormhole = WORMHOLE_TUNNEL;
3564 } else if (v->trackdir == TRACKDIR_DEPOT) {
3565 /* Inside depot */
3566 assert(gp.tile == v->tile);
3567 continue;
3568 } else if (gp.tile == v->tile) {
3569 /* Not inside tunnel or depot, staying in the old tile */
3570 old_tile = v->tile;
3571 old_in_wormhole = false;
3572 new_in_wormhole = WORMHOLE_NONE;
3573 } else {
3574 /* Not inside tunnel or depot, about to enter a new tile */
3575 old_tile = v->tile;
3576 old_in_wormhole = false;
3578 /* Determine what direction we're entering the new tile from */
3579 enterdir = DiagdirBetweenTiles(v->tile, gp.tile);
3580 assert(IsValidDiagDirection(enterdir));
3582 if (IsTunnelTile(v->tile) && GetTunnelBridgeDirection(v->tile) == enterdir) {
3583 TileIndex end_tile = GetOtherTunnelEnd(v->tile);
3584 if (end_tile != gp.tile) {
3585 /* Entering a tunnel */
3586 new_in_wormhole = WORMHOLE_TUNNEL;
3587 gp.tile = end_tile;
3588 } else {
3589 new_in_wormhole = WORMHOLE_NONE;
3590 tsdir = INVALID_DIAGDIR;
3592 } else if (IsRailBridgeTile(v->tile) && GetTunnelBridgeDirection(v->tile) == enterdir) {
3593 TileIndex end_tile = GetOtherBridgeEnd(v->tile);
3594 if (end_tile != gp.tile) {
3595 /* Entering a bridge */
3596 new_in_wormhole = WORMHOLE_BRIDGE;
3597 gp.tile = end_tile;
3598 ClrBit(v->gv_flags, GVF_GOINGUP_BIT);
3599 ClrBit(v->gv_flags, GVF_GOINGDOWN_BIT);
3601 first->cur_speed = min(first->cur_speed, GetBridgeSpec(GetRailBridgeType(v->tile))->speed);
3602 } else {
3603 new_in_wormhole = WORMHOLE_NONE;
3604 tsdir = INVALID_DIAGDIR;
3606 } else {
3607 new_in_wormhole = WORMHOLE_NONE;
3608 tsdir = ReverseDiagDir(enterdir);
3612 if (enterdir == INVALID_DIAGDIR) {
3613 /* Staying on the same tile */
3615 /* Reverse when we are at the end of the track already, do not move to the new position */
3616 if ((new_in_wormhole == WORMHOLE_NONE) && v->IsFrontEngine() && !TrainCheckIfLineEnds(v, reverse)) return false;
3617 } else {
3618 /* Entering a new tile */
3620 Trackdir chosen_trackdir;
3621 if (new_in_wormhole == WORMHOLE_BRIDGE) {
3622 /* entering a bridge */
3623 assert(!old_in_wormhole);
3624 if (prev == NULL) {
3625 SetBridgeMiddleReservation (old_tile, true);
3626 SetBridgeMiddleReservation (gp.tile, true);
3628 } else if (new_in_wormhole == WORMHOLE_TUNNEL) {
3629 /* entering a tunnel */
3630 assert(!old_in_wormhole);
3631 if (prev == NULL) {
3632 SetTunnelMiddleReservation (old_tile, true);
3633 SetTunnelMiddleReservation (gp.tile, true);
3635 } else if (prev == NULL) {
3636 /* locomotive entering a new tile, so choose a track */
3637 chosen_trackdir = TrainControllerChooseTrackdir(v, gp.tile, enterdir, tsdir, !old_in_wormhole && _settings_game.pf.forbid_90_deg, reverse);
3638 if (chosen_trackdir == INVALID_TRACKDIR) return false;
3640 bool mark_dirty = false;
3641 if (IsRailwayTile (gp.tile)) {
3642 if (HasSignalOnTrackdir (gp.tile, chosen_trackdir) && IsPbsSignal (GetSignalType (gp.tile, TrackdirToTrack (chosen_trackdir)))) {
3643 SetSignalStateByTrackdir (gp.tile, chosen_trackdir, SIGNAL_STATE_RED);
3644 mark_dirty = true;
3646 } else if (old_in_wormhole) {
3647 assert (maptile_is_rail_tunnel (gp.tile));
3648 assert (TrackdirToExitdir (chosen_trackdir) != GetTunnelBridgeDirection (gp.tile));
3649 if (maptile_has_tunnel_signal (gp.tile, false) && IsPbsSignal (maptile_get_tunnel_signal_type (gp.tile))) {
3650 maptile_set_tunnel_signal_state (gp.tile, false, SIGNAL_STATE_RED);
3651 mark_dirty = true;
3654 if (mark_dirty) MarkTileDirtyByTile (gp.tile);
3655 } else {
3656 /* wagon entering a new tile, just follow the previous vehicle */
3657 if (prev->tile == gp.tile) {
3658 /* Choose the same track as prev */
3659 assert(prev->trackdir != TRACKDIR_WORMHOLE);
3660 chosen_trackdir = prev->trackdir;
3661 } else {
3662 /* Choose the track that leads to the tile where prev is.
3663 * This case is active if 'prev' is already on the second next tile, when 'v' just enters the next tile.
3664 * I.e. when the tile between them has only space for a single vehicle like
3665 * 1) horizontal/vertical track tiles and
3666 * 2) some orientations of tunnel entries, where the vehicle is already inside the wormhole at 8/16 from the tile edge.
3667 * Is also the train just reversing, the wagon inside the tunnel is 'on' the tile of the opposite tunnel entry.
3669 DiagDirection exitdir = DiagdirBetweenTiles(gp.tile, prev->tile);
3670 assert(IsValidDiagDirection(exitdir));
3671 chosen_trackdir = EnterdirExitdirToTrackdir(enterdir, exitdir);
3672 assert(!IsReversingRoadTrackdir(chosen_trackdir));
3675 assert(CheckCompatibleRail(v, gp.tile, TrackdirToTrack(chosen_trackdir)));
3678 if (v->Next() == NULL) {
3679 /* Clear any track reservation when the last vehicle leaves the tile */
3680 ClearPathReservation (v->GetPos());
3682 RailPathPos rev = v->GetReversePos();
3683 if (rev.has_signals()) {
3684 assert(IsSignalBufferEmpty());
3685 AddPosToSignalBuffer(rev, v->owner);
3686 /* Defer actual updating of signals until the train has moved */
3690 Direction chosen_dir;
3691 if (new_in_wormhole != WORMHOLE_NONE) {
3692 /* Just entered the wormhole */
3693 v->tile = gp.tile;
3694 v->trackdir = TRACKDIR_WORMHOLE;
3695 chosen_dir = DiagDirToDir(enterdir);
3696 } else {
3697 bool track_changed = !old_in_wormhole &&
3698 (GetRailType (v->tile, TrackdirToTrack(v->trackdir)) !=
3699 GetRailType (gp.tile, TrackdirToTrack(chosen_trackdir)));
3701 v->tile = gp.tile;
3702 v->trackdir = chosen_trackdir;
3704 if (track_changed) {
3705 v->First()->ConsistChanged(CCF_TRACK);
3708 /* Update XY to reflect the entrance to the new tile, and select the direction to use */
3709 const InitialSubcoords *b = get_initial_subcoords (chosen_trackdir);
3710 gp.adjust_subcoords (b);
3711 chosen_dir = b->dir;
3714 if (chosen_dir != v->direction) {
3715 if (prev == NULL && _settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) {
3716 const AccelerationSlowdownParams *asp = &_accel_slowdown[GetRailTypeInfo(v->railtype)->acceleration_type];
3717 DirDiff diff = DirDifference(v->direction, chosen_dir);
3718 v->cur_speed -= (diff == DIRDIFF_45RIGHT || diff == DIRDIFF_45LEFT ? asp->small_turn : asp->large_turn) * v->cur_speed >> 8;
3720 direction_changed = true;
3721 v->direction = chosen_dir;
3724 /* update image of train, as well as delta XY */
3725 v->UpdateDeltaXY(v->direction);
3728 if (new_in_wormhole == WORMHOLE_NONE) {
3729 /* Call the landscape function and tell it that the vehicle entered the tile */
3730 StationID sid = TrainEnterTile(v, gp.tile, gp.xx, gp.yy);
3731 if (sid != INVALID_STATION) {
3732 /* The new position is the location where we want to stop */
3733 TrainEnterStation(v, sid);
3737 if (v->IsFrontEngine()) {
3738 v->wait_counter = 0;
3740 /* Always try to extend the reservation when entering a tile. */
3741 bool check_next_tile;
3742 if (new_in_wormhole == WORMHOLE_NONE) {
3743 /* If we are approaching a crossing that is reserved, play the sound now. */
3744 TileIndex crossing = TrainApproachingCrossingTile(v);
3745 if (crossing != INVALID_TILE && HasCrossingReservation(crossing) && _settings_client.sound.ambient) SndPlayTileFx(SND_0E_LEVEL_CROSSING, crossing);
3747 check_next_tile = enterdir != INVALID_DIAGDIR;
3748 } else {
3749 check_next_tile = (gp.tile != old_tile) &&
3750 DistanceAlongAxis (old_tile, v->tile) == 2;
3753 if (check_next_tile) CheckNextTrainTile(v);
3756 v->x_pos = gp.xx;
3757 v->y_pos = gp.yy;
3758 v->UpdatePosition();
3760 if (new_in_wormhole == WORMHOLE_BRIDGE) {
3761 v->Vehicle::UpdateViewport (true);
3762 } else if (new_in_wormhole == WORMHOLE_NONE) {
3763 /* update the Z position of the vehicle */
3764 int old_z = v->z_pos;
3766 if (enterdir != INVALID_DIAGDIR) {
3767 v->ResetZPosition();
3769 /* Only rail tiles can be sloped, and only
3770 * if they have a single trackbit and it is
3771 * along an axis. */
3772 if (IsRailwayTile (v->tile)) {
3773 assert_compile (TRACK_BIT_X == 1);
3774 assert_compile (TRACK_BIT_Y == 2);
3775 if (GetTrackBits (v->tile) < 3) {
3776 v->UpdateInclination();
3779 } else {
3780 if (HasBit(v->gv_flags, GVF_GOINGUP_BIT) || HasBit(v->gv_flags, GVF_GOINGDOWN_BIT)) {
3781 v->UpdateZPosition();
3783 assert (v->z_pos == GetSlopePixelZ (v->x_pos, v->y_pos));
3786 v->UpdateViewport (true, false);
3788 if (prev == NULL) {
3789 /* This is the first vehicle in the train */
3790 AffectSpeedByZChange(v, old_z);
3794 if (enterdir != INVALID_DIAGDIR) {
3795 /* Update signals or crossing state if we changed tile */
3796 /* Signals can only change when the first or the last vehicle moves. */
3797 if (v->Next() == NULL) {
3798 /* Update the signal segment added before, if any */
3799 UpdateSignalsInBuffer();
3800 if (!old_in_wormhole && IsLevelCrossingTile(old_tile)) UpdateLevelCrossing(old_tile);
3803 if (v->IsFrontEngine()) {
3804 RailPathPos pos = v->GetPos();
3805 if (pos.has_signals()) {
3806 assert(IsSignalBufferEmpty());
3807 AddPosToSignalBuffer(pos, v->owner);
3809 if (UpdateSignalsInBuffer() == SIGSEG_PBS &&
3810 pos.has_signal_along() &&
3811 /* A PBS block with a non-PBS signal facing us? */
3812 !IsPbsSignal(pos.get_signal_type())) {
3813 /* We are entering a block with PBS signals right now, but
3814 * not through a PBS signal. This means we don't have a
3815 * reservation right now. As a conventional signal will only
3816 * ever be green if no other train is in the block, getting
3817 * a path should always be possible. If the player built
3818 * such a strange network that it is not possible, the train
3819 * will be marked as stuck and the player has to deal with
3820 * the problem. */
3821 TryReserveRailTrack(pos);
3822 /* Signals cannot be built on junctions, so
3823 * a track on which there is a signal either
3824 * is already reserved or can be reserved. */
3825 assert (HasReservedPos(pos));
3826 if (!TryPathReserve(v)) {
3827 MarkTrainAsStuck(v);
3834 if (old_in_wormhole && old_tile != gp.tile && v->Next() == NULL && maptile_is_rail_tunnel(v->tile) && maptile_has_tunnel_signal(v->tile, false)
3835 && TileAddByDiagDir(old_tile, GetTunnelBridgeDirection(v->tile)) == GetOtherTunnelEnd(v->tile)) {
3836 AddTunnelToSignalBuffer(v->tile, v->owner);
3837 UpdateSignalsInBuffer();
3840 /* Do not check on every tick to save some computing time. */
3841 if (v->IsFrontEngine() && v->tick_counter % _settings_game.pf.path_backoff_interval == 0
3842 && (!old_in_wormhole || (DistanceAlongAxis (old_tile, v->tile) == 1))) {
3843 CheckNextTrainTile(v);
3847 if (direction_changed) first->tcache.cached_max_curve_speed = first->GetCurveSpeedLimit();
3849 return true;
3854 * Deletes/Clears the last wagon of a crashed train. It takes the engine of the
3855 * train, then goes to the last wagon and deletes that. Each call to this function
3856 * will remove the last wagon of a crashed train. If this wagon was on a crossing,
3857 * or inside a tunnel/bridge, recalculate the signals as they might need updating
3858 * @param v the Vehicle of which last wagon is to be removed
3860 static void DeleteLastWagon(Train *v)
3862 Train *first = v->First();
3864 /* Go to the last wagon and delete the link pointing there
3865 * *u is then the one-before-last wagon, and *v the last
3866 * one which will physically be removed */
3867 Train *u = v;
3868 for (; v->Next() != NULL; v = v->Next()) u = v;
3869 u->SetNext(NULL);
3871 if (first != v) {
3872 /* Recalculate cached train properties */
3873 first->ConsistChanged(CCF_ARRANGE);
3874 /* Update the depot window if the first vehicle is in depot -
3875 * if v == first, then it is updated in PreDestructor() */
3876 if (first->trackdir == TRACKDIR_DEPOT) {
3877 SetWindowDirty(WC_VEHICLE_DEPOT, first->tile);
3879 v->last_station_visited = first->last_station_visited; // for PreDestructor
3882 /* 'v' shouldn't be accessed after it has been deleted */
3883 Trackdir trackdir = v->trackdir;
3884 TileIndex tile = v->tile;
3885 Owner owner = v->owner;
3887 delete v;
3888 v = NULL; // make sure nobody will try to read 'v' anymore
3890 if (trackdir == TRACKDIR_DEPOT) return;
3892 if (trackdir == TRACKDIR_WORMHOLE) {
3893 TileIndex endtile = GetOtherTunnelBridgeEnd(tile);
3894 if (CheckTunnelBridgeMiddleFree (tile, endtile)) {
3895 if (IsRailwayTile(tile)) {
3896 SetBridgeMiddleReservation(tile, false);
3897 SetBridgeMiddleReservation(endtile, false);
3898 } else {
3899 SetTunnelMiddleReservation(tile, false);
3900 SetTunnelMiddleReservation(endtile, false);
3904 assert(IsSignalBufferEmpty());
3905 if (IsRailwayTile(tile)) {
3906 AddBridgeToSignalBuffer(tile, owner);
3907 } else {
3908 AddTunnelToSignalBuffer(tile, owner);
3910 UpdateSignalsInBuffer();
3911 return;
3914 Track track = TrackdirToTrack(trackdir);
3915 if (HasReservedTrack(tile, track)) {
3916 UnreserveRailTrack(tile, track);
3918 /* If there are still crashed vehicles on the tile, give the track reservation to them */
3919 TrackBits remaining_trackbits = TRACK_BIT_NONE;
3920 VehicleTileIterator iter (tile);
3921 while (!iter.finished()) {
3922 Vehicle *v = iter.next();
3923 if (v->type == VEH_TRAIN && (v->vehstatus & VS_CRASHED) != 0) {
3924 Trackdir trackdir = Train::From(v)->trackdir;
3925 if (IsValidTrackdir (trackdir)) {
3926 remaining_trackbits |= TrackToTrackBits(TrackdirToTrack(trackdir));
3931 /* It is important that these two are the first in the loop, as reservation cannot deal with every trackbit combination */
3932 assert_compile (TRACK_X == TRACK_BEGIN);
3933 assert_compile (TRACK_Y == TRACK_BEGIN + 1);
3934 Track t;
3935 FOR_EACH_SET_TRACK(t, remaining_trackbits) TryReserveRailTrack(tile, t);
3938 /* check if the wagon was on a road/rail-crossing */
3939 if (IsLevelCrossingTile(tile)) UpdateLevelCrossing(tile);
3941 /* Update signals */
3942 assert(IsSignalBufferEmpty());
3943 if (IsRailDepotTile(tile)) {
3944 AddDepotToSignalBuffer(tile, owner);
3945 } else if (IsTunnelTile(tile)) {
3946 AddTunnelToSignalBuffer(tile, owner);
3947 } else {
3948 AddTrackToSignalBuffer(tile, track, owner);
3950 UpdateSignalsInBuffer();
3954 * Rotate all vehicles of a (crashed) train chain randomly to animate the crash.
3955 * @param v First crashed vehicle.
3957 static void ChangeTrainDirRandomly(Train *v)
3959 static const DirDiff delta[] = {
3960 DIRDIFF_45LEFT, DIRDIFF_SAME, DIRDIFF_SAME, DIRDIFF_45RIGHT
3963 do {
3964 /* We don't need to twist around vehicles if they're not visible */
3965 if (!(v->vehstatus & VS_HIDDEN)) {
3966 v->direction = ChangeDir(v->direction, delta[GB(Random(), 0, 2)]);
3967 v->UpdateDeltaXY(v->direction);
3968 v->GetImage(v->direction, EIT_ON_MAP, &v->sprite_seq);
3969 if (v->trackdir != TRACKDIR_WORMHOLE) {
3970 v->UpdatePosition();
3971 v->UpdateViewport (true, false);
3974 } while ((v = v->Next()) != NULL);
3978 * Handle a crashed train.
3979 * @param v First train vehicle.
3980 * @return %Vehicle chain still exists.
3982 static bool HandleCrashedTrain(Train *v)
3984 int state = ++v->crash_anim_pos;
3986 if (state == 4 && !(v->vehstatus & VS_HIDDEN)) {
3987 CreateEffectVehicleRel(v, 4, 4, 8, EV_EXPLOSION_LARGE);
3990 uint32 r;
3991 if (state <= 200 && Chance16R(1, 7, r)) {
3992 int index = (r * 10 >> 16);
3994 Vehicle *u = v;
3995 do {
3996 if (--index < 0) {
3997 r = Random();
3999 CreateEffectVehicleRel(u,
4000 GB(r, 8, 3) + 2,
4001 GB(r, 16, 3) + 2,
4002 GB(r, 0, 3) + 5,
4003 EV_EXPLOSION_SMALL);
4004 break;
4006 } while ((u = u->Next()) != NULL);
4009 if (state <= 240 && !(v->tick_counter & 3)) ChangeTrainDirRandomly(v);
4011 if (state >= 4440 && !(v->tick_counter & 0x1F)) {
4012 bool ret = v->Next() != NULL;
4013 DeleteLastWagon(v);
4014 return ret;
4017 return true;
4020 /** Maximum speeds for train that is broken down or approaching line end */
4021 static const uint16 _breakdown_speeds[16] = {
4022 225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, 15
4027 * Train is approaching line end, slow down and possibly reverse
4029 * @param v front train engine
4030 * @param signal not line end, just a red signal
4031 * @param reverse Set to false to not execute the vehicle reversing. This does not change any other logic.
4032 * @return true iff we did NOT have to reverse
4034 static bool TrainApproachingLineEnd(Train *v, bool signal, bool reverse)
4036 /* Calc position within the current tile */
4037 uint x = v->x_pos & 0xF;
4038 uint y = v->y_pos & 0xF;
4040 /* for diagonal directions, 'x' will be 0..15 -
4041 * for other directions, it will be 1, 3, 5, ..., 15 */
4042 switch (v->direction) {
4043 case DIR_N : x = ~x + ~y + 25; break;
4044 case DIR_NW: x = y; // FALL THROUGH
4045 case DIR_NE: x = ~x + 16; break;
4046 case DIR_E : x = ~x + y + 9; break;
4047 case DIR_SE: x = y; break;
4048 case DIR_S : x = x + y - 7; break;
4049 case DIR_W : x = ~y + x + 9; break;
4050 default: break;
4053 /* Do not reverse when approaching red signal. Make sure the vehicle's front
4054 * does not cross the tile boundary when we do reverse, but as the vehicle's
4055 * location is based on their center, use half a vehicle's length as offset.
4056 * Multiply the half-length by two for straight directions to compensate that
4057 * we only get odd x offsets there. */
4058 if (!signal && x + (v->gcache.cached_veh_length + 1) / 2 * (IsDiagonalDirection(v->direction) ? 1 : 2) >= TILE_SIZE) {
4059 /* we are too near the tile end, reverse now */
4060 v->cur_speed = 0;
4061 if (reverse) ReverseTrainDirection(v);
4062 return false;
4065 /* slow down */
4066 v->vehstatus |= VS_TRAIN_SLOWING;
4067 uint16 break_speed = _breakdown_speeds[x & 0xF];
4068 if (break_speed < v->cur_speed) v->cur_speed = break_speed;
4070 return true;
4075 * Determines whether a train is on the map and will stay on it after leaving the current tile
4076 * (as opposed to being in a wormhole or depot)
4077 * @param v train to test
4078 * @return true iff vehicle is NOT entering or inside a depot or tunnel/bridge
4080 static bool TrainStayOnMap(const Train *v)
4082 /* Exit if inside a tunnel/bridge or a depot */
4083 if (v->trackdir == TRACKDIR_WORMHOLE || v->trackdir == TRACKDIR_DEPOT) return false;
4085 TileIndex tile = v->tile;
4087 /* entering a tunnel/bridge? */
4088 if (IsRailBridgeTile(tile)) {
4089 if (TrackdirToExitdir(v->trackdir) == GetTunnelBridgeDirection(tile)) return false;
4092 if (IsTunnelTile(tile)) {
4093 DiagDirection dir = GetTunnelBridgeDirection(tile);
4094 if (DiagDirToDir(dir) == v->direction) return false;
4097 /* entering a depot? */
4098 if (IsRailDepotTile(tile)) {
4099 DiagDirection dir = ReverseDiagDir(GetGroundDepotDirection(tile));
4100 if (DiagDirToDir(dir) == v->direction) return false;
4103 return true;
4108 * Determines whether train is approaching a rail-road crossing
4109 * (thus making it barred)
4110 * @param v front engine of train
4111 * @return TileIndex of crossing the train is approaching, else INVALID_TILE
4112 * @pre v in non-crashed front engine
4114 static TileIndex TrainApproachingCrossingTile(const Train *v)
4116 assert(v->IsFrontEngine());
4117 assert(!(v->vehstatus & VS_CRASHED));
4119 if (!TrainStayOnMap(v)) return INVALID_TILE;
4121 DiagDirection dir = TrackdirToExitdir(v->trackdir);
4122 TileIndex tile = v->tile + TileOffsByDiagDir(dir);
4124 /* not a crossing || wrong axis || unusable rail (wrong type or owner) */
4125 if (!IsLevelCrossingTile(tile) || DiagDirToAxis(dir) == GetCrossingRoadAxis(tile) ||
4126 !CheckCompatibleRail(v, tile)) {
4127 return INVALID_TILE;
4130 return tile;
4135 * Checks for line end. Also, bars crossing at next tile if needed
4137 * @param v vehicle we are checking
4138 * @param reverse Set to false to not execute the vehicle reversing. This does not change any other logic.
4139 * @return true iff we did NOT have to reverse
4141 static bool TrainCheckIfLineEnds(Train *v, bool reverse)
4143 /* First, handle broken down train */
4145 int t = v->breakdown_ctr;
4146 if (t > 1) {
4147 v->vehstatus |= VS_TRAIN_SLOWING;
4149 uint16 break_speed = _breakdown_speeds[GB(~t, 4, 4)];
4150 if (break_speed < v->cur_speed) v->cur_speed = break_speed;
4151 } else {
4152 v->vehstatus &= ~VS_TRAIN_SLOWING;
4155 if (v->trackdir == TRACKDIR_WORMHOLE) {
4156 DiagDirection dir = GetTunnelBridgeDirection(v->tile);
4158 /* Only check when the train is on the last tile segment */
4159 if (TileVirtXY(v->x_pos, v->y_pos) != v->tile + TileOffsByDiagDir(dir)) return true;
4161 TrackStatus ts = GetTileRailwayStatus(v->tile, INVALID_DIAGDIR);
4162 TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(ReverseDiagDir(dir));
4164 TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
4165 TrackdirBits red_signals = TrackStatusToRedSignals(ts) & reachable_trackdirs;
4167 assert(trackdirbits != TRACKDIR_BIT_NONE);
4168 assert(CheckCompatibleRail(v, v->tile, TrackdirToTrack(FindFirstTrackdir(trackdirbits))));
4170 return (trackdirbits & red_signals) == 0 || TrainApproachingLineEnd(v, true, reverse);
4173 if (!TrainStayOnMap(v)) return true;
4175 /* Determine the non-diagonal direction in which we will exit this tile */
4176 DiagDirection dir = TrackdirToExitdir(v->trackdir);
4177 /* Calculate next tile */
4178 TileIndex tile = v->tile + TileOffsByDiagDir(dir);
4180 /* Determine the track status on the next tile */
4181 TrackStatus ts = GetTileRailwayStatus(tile, ReverseDiagDir(dir));
4182 TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(dir);
4184 TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
4185 TrackdirBits red_signals = TrackStatusToRedSignals(ts) & reachable_trackdirs;
4187 /* We are sure the train is not entering a depot, it is detected above */
4189 /* mask unreachable track bits if we are forbidden to do 90deg turns */
4190 if (_settings_game.pf.forbid_90_deg) {
4191 trackdirbits &= ~TrackdirCrossesTrackdirs(v->trackdir);
4194 /* no suitable trackbits at all || unusable rail (wrong type or owner) */
4195 if (trackdirbits == TRACKDIR_BIT_NONE || !CheckCompatibleRail(v, tile, TrackdirToTrack(FindFirstTrackdir(trackdirbits)))) {
4196 return TrainApproachingLineEnd(v, false, reverse);
4199 /* approaching red signal */
4200 if ((trackdirbits & red_signals) != 0) return TrainApproachingLineEnd(v, true, reverse);
4202 /* approaching a rail/road crossing? then make it red */
4203 if (IsLevelCrossingTile(tile)) MaybeBarCrossingWithSound(tile);
4205 return true;
4209 static bool TrainLocoHandler(Train *v, bool mode)
4211 /* train has crashed? */
4212 if (v->vehstatus & VS_CRASHED) {
4213 return mode ? true : HandleCrashedTrain(v); // 'this' can be deleted here
4216 if (v->force_proceed != TFP_NONE) {
4217 ClrBit(v->flags, VRF_TRAIN_STUCK);
4218 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
4221 /* train is broken down? */
4222 if (v->HandleBreakdown()) return true;
4224 if (HasBit(v->flags, VRF_REVERSING) && v->cur_speed == 0) {
4225 ReverseTrainDirection(v);
4228 /* exit if train is stopped */
4229 if ((v->vehstatus & VS_STOPPED) && v->cur_speed == 0) return true;
4231 bool valid_order = !v->current_order.IsType(OT_NOTHING) && v->current_order.GetType() != OT_CONDITIONAL;
4232 if (ProcessOrders(v) && CheckReverseTrain(v)) {
4233 v->wait_counter = 0;
4234 v->cur_speed = 0;
4235 v->subspeed = 0;
4236 ClrBit(v->flags, VRF_LEAVING_STATION);
4237 ReverseTrainDirection(v);
4238 return true;
4239 } else if (HasBit(v->flags, VRF_LEAVING_STATION)) {
4240 /* Try to reserve a path when leaving the station as we
4241 * might not be marked as wanting a reservation, e.g.
4242 * when an overlength train gets turned around in a station. */
4243 if (v->trackdir != TRACKDIR_DEPOT) {
4244 assert(IsSignalBufferEmpty());
4245 AddPosToSignalBuffer(v->GetPos(), v->owner);
4246 if (UpdateSignalsInBuffer() == SIGSEG_PBS || _settings_game.pf.reserve_paths) {
4247 TryPathReserve(v, true, true);
4250 ClrBit(v->flags, VRF_LEAVING_STATION);
4253 v->HandleLoading(mode);
4255 if (v->current_order.IsType(OT_LOADING)) return true;
4257 if (CheckTrainStayInDepot(v)) return true;
4259 if (!mode) v->ShowVisualEffect();
4261 /* We had no order but have an order now, do look ahead. */
4262 if (!valid_order && !v->current_order.IsType(OT_NOTHING)) {
4263 CheckNextTrainTile(v);
4266 /* Handle stuck trains. */
4267 if (!mode && HasBit(v->flags, VRF_TRAIN_STUCK)) {
4268 ++v->wait_counter;
4270 /* Should we try reversing this tick if still stuck? */
4271 bool turn_around = v->wait_counter % (_settings_game.pf.wait_for_pbs_path * DAY_TICKS) == 0 && _settings_game.pf.reverse_at_signals;
4273 if (!turn_around && v->wait_counter % _settings_game.pf.path_backoff_interval != 0 && v->force_proceed == TFP_NONE) return true;
4274 if (!TryPathReserve(v)) {
4275 /* Still stuck. */
4276 if (turn_around) ReverseTrainDirection(v);
4278 if (HasBit(v->flags, VRF_TRAIN_STUCK) && v->wait_counter > 2 * _settings_game.pf.wait_for_pbs_path * DAY_TICKS) {
4279 /* Show message to player. */
4280 if (_settings_client.gui.lost_vehicle_warn && v->owner == _local_company) {
4281 AddNewsItem<VehicleAdviceNewsItem> (STR_NEWS_TRAIN_IS_STUCK, v->index);
4283 v->wait_counter = 0;
4285 /* Exit if force proceed not pressed, else reset stuck flag anyway. */
4286 if (v->force_proceed == TFP_NONE) return true;
4287 ClrBit(v->flags, VRF_TRAIN_STUCK);
4288 v->wait_counter = 0;
4289 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
4293 if (v->current_order.IsType(OT_LEAVESTATION)) {
4294 v->current_order.Clear();
4295 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
4296 return true;
4299 int j = v->UpdateSpeed();
4301 /* we need to invalidate the widget if we are stopping from 'Stopping 0 km/h' to 'Stopped' */
4302 if (v->cur_speed == 0 && (v->vehstatus & VS_STOPPED)) {
4303 /* If we manually stopped, we're not force-proceeding anymore. */
4304 v->force_proceed = TFP_NONE;
4305 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
4308 int adv_spd = v->GetAdvanceDistance();
4309 if (j < adv_spd) {
4310 /* if the vehicle has speed 0, update the last_speed field. */
4311 if (v->cur_speed == 0) v->SetLastSpeed();
4312 } else {
4313 TrainCheckIfLineEnds(v);
4314 /* Loop until the train has finished moving. */
4315 for (;;) {
4316 j -= adv_spd;
4317 TrainController(v, NULL);
4318 /* Don't continue to move if the train crashed. */
4319 if (CheckTrainCollision(v)) break;
4320 /* Determine distance to next map position */
4321 adv_spd = v->GetAdvanceDistance();
4323 /* No more moving this tick */
4324 if (j < adv_spd || v->cur_speed == 0) break;
4326 OrderType order_type = v->current_order.GetType();
4327 /* Do not skip waypoints (incl. 'via' stations) when passing through at full speed. */
4328 if ((order_type == OT_GOTO_WAYPOINT || order_type == OT_GOTO_STATION) &&
4329 (v->current_order.GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION) &&
4330 IsStationTile(v->tile) &&
4331 v->current_order.GetDestination() == GetStationIndex(v->tile)) {
4332 ProcessOrders(v);
4335 v->SetLastSpeed();
4338 for (Train *u = v; u != NULL; u = u->Next()) {
4339 if ((u->vehstatus & VS_HIDDEN) != 0) continue;
4341 u->UpdateViewport(false, false);
4344 if (v->progress == 0) v->progress = j; // Save unused spd for next time, if TrainController didn't set progress
4346 return true;
4350 * Get running cost for the train consist.
4351 * @return Yearly running costs.
4353 Money Train::GetRunningCost() const
4355 Money cost = 0;
4356 const Train *v = this;
4358 do {
4359 const Engine *e = v->GetEngine();
4360 if (e->u.rail.running_cost_class == INVALID_PRICE) continue;
4362 uint cost_factor = GetVehicleProperty(v, PROP_TRAIN_RUNNING_COST_FACTOR, e->u.rail.running_cost);
4363 if (cost_factor == 0) continue;
4365 /* Halve running cost for multiheaded parts */
4366 if (v->IsMultiheaded()) cost_factor /= 2;
4368 cost += GetPrice(e->u.rail.running_cost_class, cost_factor, e->GetGRF());
4369 } while ((v = v->GetNextVehicle()) != NULL);
4371 return cost;
4375 * Update train vehicle data for a tick.
4376 * @return True if the vehicle still exists, false if it has ceased to exist (front of consists only).
4378 bool Train::Tick()
4380 this->tick_counter++;
4382 if (this->IsFrontEngine()) {
4383 if (!(this->vehstatus & VS_STOPPED) || this->cur_speed > 0) this->running_ticks++;
4385 this->current_order_time++;
4387 if (!TrainLocoHandler(this, false)) return false;
4389 return TrainLocoHandler(this, true);
4390 } else if (this->IsFreeWagon() && (this->vehstatus & VS_CRASHED)) {
4391 /* Delete flooded standalone wagon chain */
4392 if (++this->crash_anim_pos >= 4400) {
4393 delete this;
4394 return false;
4398 return true;
4402 * Check whether a train needs service, and if so, find a depot or service it.
4403 * @return v %Train to check.
4405 static void CheckIfTrainNeedsService(Train *v)
4407 if (Company::Get(v->owner)->settings.vehicle.servint_trains == 0 || !v->NeedsAutomaticServicing()) return;
4408 if (v->IsChainInDepot()) {
4409 VehicleServiceInDepot(v);
4410 return;
4413 FindDepotData tfdd;
4414 /* Only go to the depot if it is not too far out of our way. */
4415 if (!FindClosestTrainDepot(v, true, &tfdd)) {
4416 if (v->current_order.IsType(OT_GOTO_DEPOT)) {
4417 /* If we were already heading for a depot but it has
4418 * suddenly moved farther away, we continue our normal
4419 * schedule? */
4420 v->current_order.MakeDummy();
4421 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
4423 return;
4426 DepotID depot = GetDepotIndex(tfdd.tile);
4428 if (v->current_order.IsType(OT_GOTO_DEPOT) &&
4429 v->current_order.GetDestination() != depot &&
4430 !Chance16(3, 16)) {
4431 return;
4434 SetBit(v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS);
4435 v->current_order.MakeGoToDepot(depot, ODTFB_SERVICE);
4436 v->dest_tile = tfdd.tile;
4437 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
4440 /** Update day counters of the train vehicle. */
4441 void Train::OnNewDay()
4443 AgeVehicle(this);
4445 if ((++this->day_counter & 7) == 0) DecreaseVehicleValue(this);
4447 if (this->IsFrontEngine()) {
4448 CheckVehicleBreakdown(this);
4450 CheckIfTrainNeedsService(this);
4452 CheckOrders(this);
4454 /* update destination */
4455 if (this->current_order.IsType(OT_GOTO_STATION)) {
4456 TileIndex tile = Station::Get(this->current_order.GetDestination())->train_station.tile;
4457 if (tile != INVALID_TILE) this->dest_tile = tile;
4460 if (this->running_ticks != 0) {
4461 /* running costs */
4462 CommandCost cost(EXPENSES_TRAIN_RUN, this->GetRunningCost() * this->running_ticks / (DAYS_IN_YEAR * DAY_TICKS));
4464 this->profit_this_year -= cost.GetCost();
4465 this->running_ticks = 0;
4467 SubtractMoneyFromCompanyFract(this->owner, cost);
4469 SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
4470 SetWindowClassesDirty(WC_TRAINS_LIST);
4476 * Get the trackdir of the train vehicle.
4477 * @return Current trackdir of the vehicle.
4479 Trackdir Train::GetTrackdir() const
4481 assert(!(this->vehstatus & VS_CRASHED));
4482 assert(this->trackdir != TRACKDIR_WORMHOLE);
4484 if (this->trackdir == TRACKDIR_DEPOT) {
4485 /* We'll assume the train is facing outwards */
4486 return DiagDirToDiagTrackdir(GetGroundDepotDirection(this->tile)); // Train in depot
4489 return this->trackdir;
4492 RailPathPos Train::GetPos() const
4494 if (this->vehstatus & VS_CRASHED) return RailPathPos();
4496 if (this->trackdir == TRACKDIR_WORMHOLE) {
4497 DiagDirection rev = GetTunnelBridgeDirection(this->tile);
4498 assert(ReverseDiagDir(rev) == DirToDiagDir(this->direction));
4499 return RailPathPos(TILE_ADD(this->tile, TileOffsByDiagDir(rev)), DiagDirToDiagTrackdir(ReverseDiagDir(rev)), this->tile);
4502 return RailPathPos(this->tile, this->GetTrackdir());
4505 RailPathPos Train::GetReversePos() const
4507 if (this->vehstatus & VS_CRASHED) return RailPathPos();
4509 if (this->trackdir == TRACKDIR_WORMHOLE) {
4510 TileIndex other_end = GetOtherTunnelBridgeEnd(this->tile);
4511 DiagDirection dir = GetTunnelBridgeDirection(other_end);
4512 assert(dir == DirToDiagDir(this->direction));
4513 return RailPathPos(TILE_ADD(other_end, TileOffsByDiagDir(dir)), DiagDirToDiagTrackdir(ReverseDiagDir(dir)), other_end);
4516 return RailPathPos(this->tile, ReverseTrackdir(this->GetTrackdir()));