Add support for deleted functions
[openttd/fttd.git] / src / train_cmd.cpp
blob5ac876f6d565fe3d32764a6ce6b724b2c7f01286
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8 */
10 /** @file train_cmd.cpp Handling of trains. */
12 #include "stdafx.h"
13 #include "error.h"
14 #include "articulated_vehicles.h"
15 #include "command_func.h"
16 #include "pathfinder/yapf/yapf.hpp"
17 #include "news_func.h"
18 #include "company_func.h"
19 #include "newgrf_sound.h"
20 #include "newgrf_text.h"
21 #include "strings_func.h"
22 #include "viewport_func.h"
23 #include "vehicle_func.h"
24 #include "sound_func.h"
25 #include "ai/ai.hpp"
26 #include "game/game.hpp"
27 #include "newgrf_station.h"
28 #include "effectvehicle_func.h"
29 #include "network/network.h"
30 #include "spritecache.h"
31 #include "core/random_func.hpp"
32 #include "company_base.h"
33 #include "newgrf.h"
34 #include "order_backup.h"
35 #include "zoom_func.h"
36 #include "signal_func.h"
37 #include "station_func.h"
38 #include "newgrf_debug.h"
39 #include "date_func.h"
41 #include "table/strings.h"
42 #include "table/train_cmd.h"
44 static bool ChooseTrainTrack(Train *v, RailPathPos origin, TileIndex tile, TrackdirBits trackdirs, bool force_res, Trackdir *best_trackdir = NULL);
45 static bool TryPathReserveFromDepot(Train *v);
46 static bool TrainCheckIfLineEnds(Train *v, bool reverse = true);
47 static StationID TrainEnterTile(Train *v, TileIndex tile, int x, int y);
48 bool TrainController(Train *v, Vehicle *nomove, bool reverse = true); // Also used in vehicle_sl.cpp.
49 static TileIndex TrainApproachingCrossingTile(const Train *v);
50 static void CheckIfTrainNeedsService(Train *v);
51 static void CheckNextTrainTile(Train *v);
53 static const byte _vehicle_initial_x_fract[4] = {10, 8, 4, 8};
54 static const byte _vehicle_initial_y_fract[4] = { 8, 4, 8, 10};
56 template <>
57 bool IsValidImageIndex<VEH_TRAIN>(uint8 image_index)
59 return image_index < lengthof(_engine_sprite_base);
62 /**
63 * Return the cargo weight multiplier to use for a rail vehicle
64 * @param cargo Cargo type to get multiplier for
65 * @return Cargo weight multiplier
67 byte FreightWagonMult(CargoID cargo)
69 if (!CargoSpec::Get(cargo)->is_freight) return 1;
70 return _settings_game.vehicle.freight_trains;
73 /** Checks if lengths of all rail vehicles are valid. If not, shows an error message. */
74 void CheckTrainsLengths()
76 const Train *v;
77 bool first = true;
79 FOR_ALL_TRAINS(v) {
80 if (v->First() == v && !(v->vehstatus & VS_CRASHED)) {
81 for (const Train *u = v, *w = v->Next(); w != NULL; u = w, w = w->Next()) {
82 if (u->trackdir != TRACKDIR_DEPOT) {
83 if ((w->trackdir != TRACKDIR_DEPOT &&
84 max(abs(u->x_pos - w->x_pos), abs(u->y_pos - w->y_pos)) != u->CalcNextVehicleOffset()) ||
85 (w->trackdir == TRACKDIR_DEPOT && TicksToLeaveDepot(u) <= 0)) {
86 SetDParam(0, v->index);
87 SetDParam(1, v->owner);
88 ShowErrorMessage(STR_BROKEN_VEHICLE_LENGTH, INVALID_STRING_ID, WL_CRITICAL);
90 if (!_networking && first) {
91 first = false;
92 DoCommandP(0, PM_PAUSED_ERROR, 1, CMD_PAUSE);
94 /* Break so we warn only once for each train. */
95 break;
104 * Recalculates the cached stuff of a train. Should be called each time a vehicle is added
105 * to/removed from the chain, and when the game is loaded.
106 * Note: this needs to be called too for 'wagon chains' (in the depot, without an engine)
107 * @param 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.max_speed);
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 = reference_width / 2;
534 offset->y = vehicle_pitch;
536 return 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 SpriteID Train::GetImage(Direction direction, EngineImageType image_type) const
553 uint8 spritenum = this->spritenum;
554 SpriteID sprite;
556 if (HasBit(this->flags, VRF_REVERSE_DIRECTION)) direction = ReverseDir(direction);
558 if (is_custom_sprite(spritenum)) {
559 sprite = GetCustomVehicleSprite(this, (Direction)(direction + 4 * IS_CUSTOM_SECONDHEAD_SPRITE(spritenum)), image_type);
560 if (sprite != 0) return sprite;
562 spritenum = this->GetEngine()->original_image_index;
565 assert(IsValidImageIndex<VEH_TRAIN>(spritenum));
566 sprite = GetDefaultTrainSprite(spritenum, direction);
568 if (this->cargo.StoredCount() >= this->cargo_cap / 2U) sprite += _wagon_full_adder[spritenum];
570 return sprite;
573 static SpriteID GetRailIcon(EngineID engine, bool rear_head, int &y, EngineImageType image_type)
575 const Engine *e = Engine::Get(engine);
576 Direction dir = rear_head ? DIR_E : DIR_W;
577 uint8 spritenum = e->u.rail.image_index;
579 if (is_custom_sprite(spritenum)) {
580 SpriteID sprite = GetCustomVehicleIcon(engine, dir, image_type);
581 if (sprite != 0) {
582 if (e->GetGRF() != NULL) {
583 y += e->GetGRF()->traininfo_vehicle_pitch;
585 return sprite;
588 spritenum = Engine::Get(engine)->original_image_index;
591 if (rear_head) spritenum++;
593 return GetDefaultTrainSprite(spritenum, DIR_W);
596 void DrawTrainEngine(int left, int right, int preferred_x, 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 SpriteID spritef = GetRailIcon(engine, false, yf, image_type);
603 SpriteID spriter = GetRailIcon(engine, true, yr, image_type);
604 const Sprite *real_spritef = GetSprite(spritef, ST_NORMAL);
605 const Sprite *real_spriter = GetSprite(spriter, ST_NORMAL);
607 preferred_x = Clamp(preferred_x, left - UnScaleByZoom(real_spritef->x_offs, ZOOM_LVL_GUI) + 14, right - UnScaleByZoom(real_spriter->width, ZOOM_LVL_GUI) - UnScaleByZoom(real_spriter->x_offs, ZOOM_LVL_GUI) - 15);
609 DrawSprite(spritef, pal, preferred_x - 14, yf);
610 DrawSprite(spriter, pal, preferred_x + 15, yr);
611 } else {
612 SpriteID sprite = GetRailIcon(engine, false, y, image_type);
613 const Sprite *real_sprite = GetSprite(sprite, ST_NORMAL);
614 preferred_x = Clamp(preferred_x, left - UnScaleByZoom(real_sprite->x_offs, ZOOM_LVL_GUI), right - UnScaleByZoom(real_sprite->width, ZOOM_LVL_GUI) - UnScaleByZoom(real_sprite->x_offs, ZOOM_LVL_GUI));
615 DrawSprite(sprite, pal, preferred_x, y);
620 * Get the size of the sprite of a train sprite heading west, or both heads (used for lists).
621 * @param engine The engine to get the sprite from.
622 * @param[out] width The width of the sprite.
623 * @param[out] height The height of the sprite.
624 * @param[out] xoffs Number of pixels to shift the sprite to the right.
625 * @param[out] yoffs Number of pixels to shift the sprite downwards.
626 * @param image_type Context the sprite is used in.
628 void GetTrainSpriteSize(EngineID engine, uint &width, uint &height, int &xoffs, int &yoffs, EngineImageType image_type)
630 int y = 0;
632 SpriteID sprite = GetRailIcon(engine, false, y, image_type);
633 const Sprite *real_sprite = GetSprite(sprite, ST_NORMAL);
635 width = UnScaleByZoom(real_sprite->width, ZOOM_LVL_GUI);
636 height = UnScaleByZoom(real_sprite->height, ZOOM_LVL_GUI);
637 xoffs = UnScaleByZoom(real_sprite->x_offs, ZOOM_LVL_GUI);
638 yoffs = UnScaleByZoom(real_sprite->y_offs, ZOOM_LVL_GUI);
640 if (RailVehInfo(engine)->railveh_type == RAILVEH_MULTIHEAD) {
641 sprite = GetRailIcon(engine, true, y, image_type);
642 real_sprite = GetSprite(sprite, ST_NORMAL);
644 /* Calculate values relative to an imaginary center between the two sprites. */
645 width = TRAININFO_DEFAULT_VEHICLE_WIDTH + UnScaleByZoom(real_sprite->width, ZOOM_LVL_GUI) + UnScaleByZoom(real_sprite->x_offs, ZOOM_LVL_GUI) - xoffs;
646 height = max<uint>(height, UnScaleByZoom(real_sprite->height, ZOOM_LVL_GUI));
647 xoffs = xoffs - TRAININFO_DEFAULT_VEHICLE_WIDTH / 2;
648 yoffs = min(yoffs, UnScaleByZoom(real_sprite->y_offs, ZOOM_LVL_GUI));
653 * Build a railroad wagon.
654 * @param tile tile of the depot where rail-vehicle is built.
655 * @param flags type of operation.
656 * @param e the engine to build.
657 * @param ret[out] the vehicle that has been built.
658 * @return the cost of this operation or an error.
660 static CommandCost CmdBuildRailWagon(TileIndex tile, DoCommandFlag flags, const Engine *e, Vehicle **ret)
662 const RailVehicleInfo *rvi = &e->u.rail;
664 /* Check that the wagon can drive on the track in question */
665 if (!IsCompatibleRail(rvi->railtype, GetRailType(tile))) return CMD_ERROR;
667 if (flags & DC_EXEC) {
668 Train *v = new Train();
669 *ret = v;
670 v->spritenum = rvi->image_index;
672 v->engine_type = e->index;
673 v->gcache.first_engine = INVALID_ENGINE; // needs to be set before first callback
675 DiagDirection dir = GetGroundDepotDirection(tile);
677 v->direction = DiagDirToDir(dir);
678 v->tile = tile;
680 int x = TileX(tile) * TILE_SIZE | _vehicle_initial_x_fract[dir];
681 int y = TileY(tile) * TILE_SIZE | _vehicle_initial_y_fract[dir];
683 v->x_pos = x;
684 v->y_pos = y;
685 v->z_pos = GetSlopePixelZ(x, y);
686 v->owner = _current_company;
687 v->trackdir = TRACKDIR_DEPOT;
688 v->vehstatus = VS_HIDDEN | VS_DEFPAL;
690 v->SetWagon();
692 v->SetFreeWagon();
693 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
695 v->cargo_type = e->GetDefaultCargoType();
696 v->cargo_cap = rvi->capacity;
697 v->refit_cap = 0;
699 v->railtype = rvi->railtype;
701 v->build_year = _cur_year;
702 v->cur_image = SPR_IMG_QUERY;
703 v->random_bits = VehicleRandomBits();
705 v->group_id = DEFAULT_GROUP;
707 AddArticulatedParts(v);
709 _new_vehicle_id = v->index;
711 VehicleUpdatePosition(v);
712 v->First()->ConsistChanged(CCF_ARRANGE);
713 UpdateTrainGroupID(v->First());
715 CheckConsistencyOfArticulatedVehicle(v);
717 /* Try to connect the vehicle to one of free chains of wagons. */
718 Train *w;
719 FOR_ALL_TRAINS(w) {
720 if (w->tile == tile && ///< Same depot
721 w->IsFreeWagon() && ///< A free wagon chain
722 w->engine_type == e->index && ///< Same type
723 w->First() != v && ///< Don't connect to ourself
724 !(w->vehstatus & VS_CRASHED)) { ///< Not crashed/flooded
725 DoCommand(0, v->index | 1 << 20, w->Last()->index, DC_EXEC, CMD_MOVE_RAIL_VEHICLE);
726 break;
731 return CommandCost();
734 /** Move all free vehicles in the depot to the train */
735 static void NormalizeTrainVehInDepot(const Train *u)
737 const Train *v;
738 FOR_ALL_TRAINS(v) {
739 if (v->IsFreeWagon() && v->tile == u->tile &&
740 v->trackdir == TRACKDIR_DEPOT) {
741 if (DoCommand(0, v->index | 1 << 20, u->index, DC_EXEC,
742 CMD_MOVE_RAIL_VEHICLE).Failed())
743 break;
748 static void AddRearEngineToMultiheadedTrain(Train *v)
750 Train *u = new Train();
751 v->value >>= 1;
752 u->value = v->value;
753 u->direction = v->direction;
754 u->owner = v->owner;
755 u->tile = v->tile;
756 u->x_pos = v->x_pos;
757 u->y_pos = v->y_pos;
758 u->z_pos = v->z_pos;
759 u->trackdir = TRACKDIR_DEPOT;
760 u->vehstatus = v->vehstatus & ~VS_STOPPED;
761 u->spritenum = v->spritenum + 1;
762 u->cargo_type = v->cargo_type;
763 u->cargo_subtype = v->cargo_subtype;
764 u->cargo_cap = v->cargo_cap;
765 u->refit_cap = v->refit_cap;
766 u->railtype = v->railtype;
767 u->engine_type = v->engine_type;
768 u->build_year = v->build_year;
769 u->cur_image = SPR_IMG_QUERY;
770 u->random_bits = VehicleRandomBits();
771 v->SetMultiheaded();
772 u->SetMultiheaded();
773 v->SetNext(u);
774 VehicleUpdatePosition(u);
776 /* Now we need to link the front and rear engines together */
777 v->other_multiheaded_part = u;
778 u->other_multiheaded_part = v;
782 * Build a railroad vehicle.
783 * @param tile tile of the depot where rail-vehicle is built.
784 * @param flags type of operation.
785 * @param e the engine to build.
786 * @param data bit 0 prevents any free cars from being added to the train.
787 * @param ret[out] the vehicle that has been built.
788 * @return the cost of this operation or an error.
790 CommandCost CmdBuildRailVehicle(TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **ret)
792 const RailVehicleInfo *rvi = &e->u.rail;
794 if (rvi->railveh_type == RAILVEH_WAGON) return CmdBuildRailWagon(tile, flags, e, ret);
796 /* Check if depot and new engine uses the same kind of tracks *
797 * We need to see if the engine got power on the tile to avoid electric engines in non-electric depots */
798 if (!HasPowerOnRail(rvi->railtype, GetRailType(tile))) return CMD_ERROR;
800 if (flags & DC_EXEC) {
801 DiagDirection dir = GetGroundDepotDirection(tile);
802 int x = TileX(tile) * TILE_SIZE + _vehicle_initial_x_fract[dir];
803 int y = TileY(tile) * TILE_SIZE + _vehicle_initial_y_fract[dir];
805 Train *v = new Train();
806 *ret = v;
807 v->direction = DiagDirToDir(dir);
808 v->tile = tile;
809 v->owner = _current_company;
810 v->x_pos = x;
811 v->y_pos = y;
812 v->z_pos = GetSlopePixelZ(x, y);
813 v->trackdir = TRACKDIR_DEPOT;
814 v->vehstatus = VS_HIDDEN | VS_STOPPED | VS_DEFPAL;
815 v->spritenum = rvi->image_index;
816 v->cargo_type = e->GetDefaultCargoType();
817 v->cargo_cap = rvi->capacity;
818 v->refit_cap = 0;
819 v->last_station_visited = INVALID_STATION;
820 v->last_loading_station = INVALID_STATION;
822 v->engine_type = e->index;
823 v->gcache.first_engine = INVALID_ENGINE; // needs to be set before first callback
825 v->reliability = e->reliability;
826 v->reliability_spd_dec = e->reliability_spd_dec;
827 v->max_age = e->GetLifeLengthInDays();
829 v->railtype = rvi->railtype;
830 _new_vehicle_id = v->index;
832 v->SetServiceInterval(Company::Get(_current_company)->settings.vehicle.servint_trains);
833 v->date_of_last_service = _date;
834 v->build_year = _cur_year;
835 v->cur_image = SPR_IMG_QUERY;
836 v->random_bits = VehicleRandomBits();
838 if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) SetBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE);
839 v->SetServiceIntervalIsPercent(Company::Get(_current_company)->settings.vehicle.servint_ispercent);
841 v->group_id = DEFAULT_GROUP;
843 v->SetFrontEngine();
844 v->SetEngine();
846 VehicleUpdatePosition(v);
848 if (rvi->railveh_type == RAILVEH_MULTIHEAD) {
849 AddRearEngineToMultiheadedTrain(v);
850 } else {
851 AddArticulatedParts(v);
854 v->ConsistChanged(CCF_ARRANGE);
855 UpdateTrainGroupID(v);
857 if (!HasBit(data, 0) && !(flags & DC_AUTOREPLACE)) { // check if the cars should be added to the new vehicle
858 NormalizeTrainVehInDepot(v);
861 CheckConsistencyOfArticulatedVehicle(v);
864 return CommandCost();
867 static Train *FindGoodVehiclePos(const Train *src)
869 EngineID eng = src->engine_type;
870 TileIndex tile = src->tile;
872 Train *dst;
873 FOR_ALL_TRAINS(dst) {
874 if (dst->IsFreeWagon() && dst->tile == tile && !(dst->vehstatus & VS_CRASHED)) {
875 /* check so all vehicles in the line have the same engine. */
876 Train *t = dst;
877 while (t->engine_type == eng) {
878 t = t->Next();
879 if (t == NULL) return dst;
884 return NULL;
887 /** Helper type for lists/vectors of trains */
888 typedef SmallVector<Train *, 16> TrainList;
891 * Make a backup of a train into a train list.
892 * @param list to make the backup in
893 * @param t the train to make the backup of
895 static void MakeTrainBackup(TrainList &list, Train *t)
897 for (; t != NULL; t = t->Next()) *list.Append() = t;
901 * Restore the train from the backup list.
902 * @param list the train to restore.
904 static void RestoreTrainBackup(TrainList &list)
906 /* No train, nothing to do. */
907 if (list.Length() == 0) return;
909 Train *prev = NULL;
910 /* Iterate over the list and rebuild it. */
911 for (Train **iter = list.Begin(); iter != list.End(); iter++) {
912 Train *t = *iter;
913 if (prev != NULL) {
914 prev->SetNext(t);
915 } else if (t->Previous() != NULL) {
916 /* Make sure the head of the train is always the first in the chain. */
917 t->Previous()->SetNext(NULL);
919 prev = t;
924 * Remove the given wagon from its consist.
925 * @param part the part of the train to remove.
926 * @param chain whether to remove the whole chain.
928 static void RemoveFromConsist(Train *part, bool chain = false)
930 Train *tail = chain ? part->Last() : part->GetLastEnginePart();
932 /* Unlink at the front, but make it point to the next
933 * vehicle after the to be remove part. */
934 if (part->Previous() != NULL) part->Previous()->SetNext(tail->Next());
936 /* Unlink at the back */
937 tail->SetNext(NULL);
941 * Inserts a chain into the train at dst.
942 * @param dst the place where to append after.
943 * @param chain the chain to actually add.
945 static void InsertInConsist(Train *dst, Train *chain)
947 /* We do not want to add something in the middle of an articulated part. */
948 assert(dst->Next() == NULL || !dst->Next()->IsArticulatedPart());
950 chain->Last()->SetNext(dst->Next());
951 dst->SetNext(chain);
955 * Normalise the dual heads in the train, i.e. if one is
956 * missing move that one to this train.
957 * @param t the train to normalise.
959 static void NormaliseDualHeads(Train *t)
961 for (; t != NULL; t = t->GetNextVehicle()) {
962 if (!t->IsMultiheaded() || !t->IsEngine()) continue;
964 /* Make sure that there are no free cars before next engine */
965 Train *u;
966 for (u = t; u->Next() != NULL && !u->Next()->IsEngine(); u = u->Next()) {}
968 if (u == t->other_multiheaded_part) continue;
970 /* Remove the part from the 'wrong' train */
971 RemoveFromConsist(t->other_multiheaded_part);
972 /* And add it to the 'right' train */
973 InsertInConsist(u, t->other_multiheaded_part);
978 * Normalise the sub types of the parts in this chain.
979 * @param chain the chain to normalise.
981 static void NormaliseSubtypes(Train *chain)
983 /* Nothing to do */
984 if (chain == NULL) return;
986 /* We must be the first in the chain. */
987 assert(chain->Previous() == NULL);
989 /* Set the appropriate bits for the first in the chain. */
990 if (chain->IsWagon()) {
991 chain->SetFreeWagon();
992 } else {
993 assert(chain->IsEngine());
994 chain->SetFrontEngine();
997 /* Now clear the bits for the rest of the chain */
998 for (Train *t = chain->Next(); t != NULL; t = t->Next()) {
999 t->ClearFreeWagon();
1000 t->ClearFrontEngine();
1005 * Check/validate whether we may actually build a new train.
1006 * @note All vehicles are/were 'heads' of their chains.
1007 * @param original_dst The original destination chain.
1008 * @param dst The destination chain after constructing the train.
1009 * @param original_dst The original source chain.
1010 * @param dst The source chain after constructing the train.
1011 * @return possible error of this command.
1013 static CommandCost CheckNewTrain(Train *original_dst, Train *dst, Train *original_src, Train *src)
1015 /* Just add 'new' engines and subtract the original ones.
1016 * If that's less than or equal to 0 we can be sure we did
1017 * not add any engines (read: trains) along the way. */
1018 if ((src != NULL && src->IsEngine() ? 1 : 0) +
1019 (dst != NULL && dst->IsEngine() ? 1 : 0) -
1020 (original_src != NULL && original_src->IsEngine() ? 1 : 0) -
1021 (original_dst != NULL && original_dst->IsEngine() ? 1 : 0) <= 0) {
1022 return CommandCost();
1025 /* Get a free unit number and check whether it's within the bounds.
1026 * There will always be a maximum of one new train. */
1027 if (GetFreeUnitNumber(VEH_TRAIN) <= _settings_game.vehicle.max_trains) return CommandCost();
1029 return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
1033 * Check whether the train parts can be attached.
1034 * @param t the train to check
1035 * @return possible error of this command.
1037 static CommandCost CheckTrainAttachment(Train *t)
1039 /* No multi-part train, no need to check. */
1040 if (t == NULL || t->Next() == NULL || !t->IsEngine()) return CommandCost();
1042 /* The maximum length for a train. For each part we decrease this by one
1043 * and if the result is negative the train is simply too long. */
1044 int allowed_len = _settings_game.vehicle.max_train_length * TILE_SIZE - t->gcache.cached_veh_length;
1046 Train *head = t;
1047 Train *prev = t;
1049 /* Break the prev -> t link so it always holds within the loop. */
1050 t = t->Next();
1051 prev->SetNext(NULL);
1053 /* Make sure the cache is cleared. */
1054 head->InvalidateNewGRFCache();
1056 while (t != NULL) {
1057 allowed_len -= t->gcache.cached_veh_length;
1059 Train *next = t->Next();
1061 /* Unlink the to-be-added piece; it is already unlinked from the previous
1062 * part due to the fact that the prev -> t link is broken. */
1063 t->SetNext(NULL);
1065 /* Don't check callback for articulated or rear dual headed parts */
1066 if (!t->IsArticulatedPart() && !t->IsRearDualheaded()) {
1067 /* Back up and clear the first_engine data to avoid using wagon override group */
1068 EngineID first_engine = t->gcache.first_engine;
1069 t->gcache.first_engine = INVALID_ENGINE;
1071 /* We don't want the cache to interfere. head's cache is cleared before
1072 * the loop and after each callback does not need to be cleared here. */
1073 t->InvalidateNewGRFCache();
1075 uint16 callback = GetVehicleCallbackParent(CBID_TRAIN_ALLOW_WAGON_ATTACH, 0, 0, head->engine_type, t, head);
1077 /* Restore original first_engine data */
1078 t->gcache.first_engine = first_engine;
1080 /* We do not want to remember any cached variables from the test run */
1081 t->InvalidateNewGRFCache();
1082 head->InvalidateNewGRFCache();
1084 if (callback != CALLBACK_FAILED) {
1085 /* A failing callback means everything is okay */
1086 StringID error = STR_NULL;
1088 if (head->GetGRF()->grf_version < 8) {
1089 if (callback == 0xFD) error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
1090 if (callback < 0xFD) error = GetGRFStringID(head->GetGRFID(), 0xD000 + callback);
1091 if (callback >= 0x100) ErrorUnknownCallbackResult(head->GetGRFID(), CBID_TRAIN_ALLOW_WAGON_ATTACH, callback);
1092 } else {
1093 if (callback < 0x400) {
1094 error = GetGRFStringID(head->GetGRFID(), 0xD000 + callback);
1095 } else {
1096 switch (callback) {
1097 case 0x400: // allow if railtypes match (always the case for OpenTTD)
1098 case 0x401: // allow
1099 break;
1101 default: // unknown reason -> disallow
1102 case 0x402: // disallow attaching
1103 error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
1104 break;
1109 if (error != STR_NULL) return_cmd_error(error);
1113 /* And link it to the new part. */
1114 prev->SetNext(t);
1115 prev = t;
1116 t = next;
1119 if (allowed_len < 0) return_cmd_error(STR_ERROR_TRAIN_TOO_LONG);
1120 return CommandCost();
1124 * Validate whether we are going to create valid trains.
1125 * @note All vehicles are/were 'heads' of their chains.
1126 * @param original_dst The original destination chain.
1127 * @param dst The destination chain after constructing the train.
1128 * @param original_dst The original source chain.
1129 * @param dst The source chain after constructing the train.
1130 * @param check_limit Whether to check the vehicle limit.
1131 * @return possible error of this command.
1133 static CommandCost ValidateTrains(Train *original_dst, Train *dst, Train *original_src, Train *src, bool check_limit)
1135 /* Check whether we may actually construct the trains. */
1136 CommandCost ret = CheckTrainAttachment(src);
1137 if (ret.Failed()) return ret;
1138 ret = CheckTrainAttachment(dst);
1139 if (ret.Failed()) return ret;
1141 /* Check whether we need to build a new train. */
1142 return check_limit ? CheckNewTrain(original_dst, dst, original_src, src) : CommandCost();
1146 * Arrange the trains in the wanted way.
1147 * @param dst_head The destination chain of the to be moved vehicle.
1148 * @param dst The destination for the to be moved vehicle.
1149 * @param src_head The source chain of the to be moved vehicle.
1150 * @param src The to be moved vehicle.
1151 * @param move_chain Whether to move all vehicles after src or not.
1153 static void ArrangeTrains(Train **dst_head, Train *dst, Train **src_head, Train *src, bool move_chain)
1155 /* First determine the front of the two resulting trains */
1156 if (*src_head == *dst_head) {
1157 /* If we aren't moving part(s) to a new train, we are just moving the
1158 * front back and there is not destination head. */
1159 *dst_head = NULL;
1160 } else if (*dst_head == NULL) {
1161 /* If we are moving to a new train the head of the move train would become
1162 * the head of the new vehicle. */
1163 *dst_head = src;
1166 if (src == *src_head) {
1167 /* If we are moving the front of a train then we are, in effect, creating
1168 * a new head for the train. Point to that. Unless we are moving the whole
1169 * train in which case there is not 'source' train anymore.
1170 * In case we are a multiheaded part we want the complete thing to come
1171 * with us, so src->GetNextUnit(), however... when we are e.g. a wagon
1172 * that is followed by a rear multihead we do not want to include that. */
1173 *src_head = move_chain ? NULL :
1174 (src->IsMultiheaded() ? src->GetNextUnit() : src->GetNextVehicle());
1177 /* Now it's just simply removing the part that we are going to move from the
1178 * source train and *if* the destination is a not a new train add the chain
1179 * at the destination location. */
1180 RemoveFromConsist(src, move_chain);
1181 if (*dst_head != src) InsertInConsist(dst, src);
1183 /* Now normalise the dual heads, that is move the dual heads around in such
1184 * a way that the head and rear of a dual head are in the same train */
1185 NormaliseDualHeads(*src_head);
1186 NormaliseDualHeads(*dst_head);
1190 * Normalise the head of the train again, i.e. that is tell the world that
1191 * we have changed and update all kinds of variables.
1192 * @param head the train to update.
1194 static void NormaliseTrainHead(Train *head)
1196 /* Not much to do! */
1197 if (head == NULL) return;
1199 /* Tell the 'world' the train changed. */
1200 head->ConsistChanged(CCF_ARRANGE);
1201 UpdateTrainGroupID(head);
1203 /* Not a front engine, i.e. a free wagon chain. No need to do more. */
1204 if (!head->IsFrontEngine()) return;
1206 /* Update the refit button and window */
1207 InvalidateWindowData(WC_VEHICLE_REFIT, head->index, VIWD_CONSIST_CHANGED);
1208 SetWindowWidgetDirty(WC_VEHICLE_VIEW, head->index, WID_VV_REFIT);
1210 /* If we don't have a unit number yet, set one. */
1211 if (head->unitnumber != 0) return;
1212 head->unitnumber = GetFreeUnitNumber(VEH_TRAIN);
1216 * Move a rail vehicle around inside the depot.
1217 * @param tile unused
1218 * @param flags type of operation
1219 * Note: DC_AUTOREPLACE is set when autoreplace tries to undo its modifications or moves vehicles to temporary locations inside the depot.
1220 * @param p1 various bitstuffed elements
1221 * - p1 (bit 0 - 19) source vehicle index
1222 * - p1 (bit 20) move all vehicles following the source vehicle
1223 * @param p2 what wagon to put the source wagon AFTER, XXX - INVALID_VEHICLE to make a new line
1224 * @param text unused
1225 * @return the cost of this operation or an error
1227 CommandCost CmdMoveRailVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1229 VehicleID s = GB(p1, 0, 20);
1230 VehicleID d = GB(p2, 0, 20);
1231 bool move_chain = HasBit(p1, 20);
1233 Train *src = Train::GetIfValid(s);
1234 if (src == NULL) return CMD_ERROR;
1236 CommandCost ret = CheckOwnership(src->owner);
1237 if (ret.Failed()) return ret;
1239 /* Do not allow moving crashed vehicles inside the depot, it is likely to cause asserts later */
1240 if (src->vehstatus & VS_CRASHED) return CMD_ERROR;
1242 /* if nothing is selected as destination, try and find a matching vehicle to drag to. */
1243 Train *dst;
1244 if (d == INVALID_VEHICLE) {
1245 dst = src->IsEngine() ? NULL : FindGoodVehiclePos(src);
1246 } else {
1247 dst = Train::GetIfValid(d);
1248 if (dst == NULL) return CMD_ERROR;
1250 CommandCost ret = CheckOwnership(dst->owner);
1251 if (ret.Failed()) return ret;
1253 /* Do not allow appending to crashed vehicles, too */
1254 if (dst->vehstatus & VS_CRASHED) return CMD_ERROR;
1257 /* if an articulated part is being handled, deal with its parent vehicle */
1258 src = src->GetFirstEnginePart();
1259 if (dst != NULL) {
1260 dst = dst->GetFirstEnginePart();
1263 /* don't move the same vehicle.. */
1264 if (src == dst) return CommandCost();
1266 /* locate the head of the two chains */
1267 Train *src_head = src->First();
1268 Train *dst_head;
1269 if (dst != NULL) {
1270 dst_head = dst->First();
1271 if (dst_head->tile != src_head->tile) return CMD_ERROR;
1272 /* Now deal with articulated part of destination wagon */
1273 dst = dst->GetLastEnginePart();
1274 } else {
1275 dst_head = NULL;
1278 if (src->IsRearDualheaded()) return_cmd_error(STR_ERROR_REAR_ENGINE_FOLLOW_FRONT);
1280 /* When moving all wagons, we can't have the same src_head and dst_head */
1281 if (move_chain && src_head == dst_head) return CommandCost();
1283 /* When moving a multiheaded part to be place after itself, bail out. */
1284 if (!move_chain && dst != NULL && dst->IsRearDualheaded() && src == dst->other_multiheaded_part) return CommandCost();
1286 /* Check if all vehicles in the source train are stopped inside a depot. */
1287 if (!src_head->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
1289 /* Check if all vehicles in the destination train are stopped inside a depot. */
1290 if (dst_head != NULL && !dst_head->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
1292 /* First make a backup of the order of the trains. That way we can do
1293 * whatever we want with the order and later on easily revert. */
1294 TrainList original_src;
1295 TrainList original_dst;
1297 MakeTrainBackup(original_src, src_head);
1298 MakeTrainBackup(original_dst, dst_head);
1300 /* Also make backup of the original heads as ArrangeTrains can change them.
1301 * For the destination head we do not care if it is the same as the source
1302 * head because in that case it's just a copy. */
1303 Train *original_src_head = src_head;
1304 Train *original_dst_head = (dst_head == src_head ? NULL : dst_head);
1306 /* We want this information from before the rearrangement, but execute this after the validation.
1307 * original_src_head can't be NULL; src is by definition != NULL, so src_head can't be NULL as
1308 * src->GetFirst() always yields non-NULL, so eventually original_src_head != NULL as well. */
1309 bool original_src_head_front_engine = original_src_head->IsFrontEngine();
1310 bool original_dst_head_front_engine = original_dst_head != NULL && original_dst_head->IsFrontEngine();
1312 /* (Re)arrange the trains in the wanted arrangement. */
1313 ArrangeTrains(&dst_head, dst, &src_head, src, move_chain);
1315 if ((flags & DC_AUTOREPLACE) == 0) {
1316 /* If the autoreplace flag is set we do not need to test for the validity
1317 * because we are going to revert the train to its original state. As we
1318 * assume the original state was correct autoreplace can skip this. */
1319 CommandCost ret = ValidateTrains(original_dst_head, dst_head, original_src_head, src_head, true);
1320 if (ret.Failed()) {
1321 /* Restore the train we had. */
1322 RestoreTrainBackup(original_src);
1323 RestoreTrainBackup(original_dst);
1324 return ret;
1328 /* do it? */
1329 if (flags & DC_EXEC) {
1330 /* Remove old heads from the statistics */
1331 if (original_src_head_front_engine) GroupStatistics::CountVehicle(original_src_head, -1);
1332 if (original_dst_head_front_engine) GroupStatistics::CountVehicle(original_dst_head, -1);
1334 /* First normalise the sub types of the chains. */
1335 NormaliseSubtypes(src_head);
1336 NormaliseSubtypes(dst_head);
1338 /* There are 14 different cases:
1339 * 1) front engine gets moved to a new train, it stays a front engine.
1340 * a) the 'next' part is a wagon that becomes a free wagon chain.
1341 * b) the 'next' part is an engine that becomes a front engine.
1342 * c) there is no 'next' part, nothing else happens
1343 * 2) front engine gets moved to another train, it is not a front engine anymore
1344 * a) the 'next' part is a wagon that becomes a free wagon chain.
1345 * b) the 'next' part is an engine that becomes a front engine.
1346 * c) there is no 'next' part, nothing else happens
1347 * 3) front engine gets moved to later in the current train, it is not a front engine anymore.
1348 * a) the 'next' part is a wagon that becomes a free wagon chain.
1349 * b) the 'next' part is an engine that becomes a front engine.
1350 * 4) free wagon gets moved
1351 * a) the 'next' part is a wagon that becomes a free wagon chain.
1352 * b) the 'next' part is an engine that becomes a front engine.
1353 * c) there is no 'next' part, nothing else happens
1354 * 5) non front engine gets moved and becomes a new train, nothing else happens
1355 * 6) non front engine gets moved within a train / to another train, nothing hapens
1356 * 7) wagon gets moved, nothing happens
1358 if (src == original_src_head && src->IsEngine() && !src->IsFrontEngine()) {
1359 /* Cases #2 and #3: the front engine gets trashed. */
1360 DeleteWindowById(WC_VEHICLE_VIEW, src->index);
1361 DeleteWindowById(WC_VEHICLE_ORDERS, src->index);
1362 DeleteWindowById(WC_VEHICLE_REFIT, src->index);
1363 DeleteWindowById(WC_VEHICLE_DETAILS, src->index);
1364 DeleteWindowById(WC_VEHICLE_TIMETABLE, src->index);
1365 DeleteNewGRFInspectWindow(GSF_TRAINS, src->index);
1366 SetWindowDirty(WC_COMPANY, _current_company);
1368 /* Delete orders, group stuff and the unit number as we're not the
1369 * front of any vehicle anymore. */
1370 DeleteVehicleOrders(src);
1371 RemoveVehicleFromGroup(src);
1372 src->unitnumber = 0;
1375 /* We weren't a front engine but are becoming one. So
1376 * we should be put in the default group. */
1377 if (original_src_head != src && dst_head == src) {
1378 SetTrainGroupID(src, DEFAULT_GROUP);
1379 SetWindowDirty(WC_COMPANY, _current_company);
1382 /* Add new heads to statistics */
1383 if (src_head != NULL && src_head->IsFrontEngine()) GroupStatistics::CountVehicle(src_head, 1);
1384 if (dst_head != NULL && dst_head->IsFrontEngine()) GroupStatistics::CountVehicle(dst_head, 1);
1386 /* Handle 'new engine' part of cases #1b, #2b, #3b, #4b and #5 in NormaliseTrainHead. */
1387 NormaliseTrainHead(src_head);
1388 NormaliseTrainHead(dst_head);
1390 if ((flags & DC_NO_CARGO_CAP_CHECK) == 0) {
1391 CheckCargoCapacity(src_head);
1392 CheckCargoCapacity(dst_head);
1395 if (src_head != NULL) src_head->First()->MarkDirty();
1396 if (dst_head != NULL) dst_head->First()->MarkDirty();
1398 /* We are undoubtedly changing something in the depot and train list. */
1399 InvalidateWindowData(WC_VEHICLE_DEPOT, src->tile);
1400 InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
1401 } else {
1402 /* We don't want to execute what we're just tried. */
1403 RestoreTrainBackup(original_src);
1404 RestoreTrainBackup(original_dst);
1407 return CommandCost();
1411 * Sell a (single) train wagon/engine.
1412 * @param flags type of operation
1413 * @param t the train wagon to sell
1414 * @param data the selling mode
1415 * - data = 0: only sell the single dragged wagon/engine (and any belonging rear-engines)
1416 * - data = 1: sell the vehicle and all vehicles following it in the chain
1417 * if the wagon is dragged, don't delete the possibly belonging rear-engine to some front
1418 * @param user the user for the order backup.
1419 * @return the cost of this operation or an error
1421 CommandCost CmdSellRailWagon(DoCommandFlag flags, Vehicle *t, uint16 data, uint32 user)
1423 /* Sell a chain of vehicles or not? */
1424 bool sell_chain = HasBit(data, 0);
1426 Train *v = Train::From(t)->GetFirstEnginePart();
1427 Train *first = v->First();
1429 if (v->IsRearDualheaded()) return_cmd_error(STR_ERROR_REAR_ENGINE_FOLLOW_FRONT);
1431 /* First make a backup of the order of the train. That way we can do
1432 * whatever we want with the order and later on easily revert. */
1433 TrainList original;
1434 MakeTrainBackup(original, first);
1436 /* We need to keep track of the new head and the head of what we're going to sell. */
1437 Train *new_head = first;
1438 Train *sell_head = NULL;
1440 /* Split the train in the wanted way. */
1441 ArrangeTrains(&sell_head, NULL, &new_head, v, sell_chain);
1443 /* We don't need to validate the second train; it's going to be sold. */
1444 CommandCost ret = ValidateTrains(NULL, NULL, first, new_head, (flags & DC_AUTOREPLACE) == 0);
1445 if (ret.Failed()) {
1446 /* Restore the train we had. */
1447 RestoreTrainBackup(original);
1448 return ret;
1451 CommandCost cost(EXPENSES_NEW_VEHICLES);
1452 for (Train *t = sell_head; t != NULL; t = t->Next()) cost.AddCost(-t->value);
1454 if (first->orders.list == NULL && !OrderList::CanAllocateItem()) {
1455 return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
1458 /* do it? */
1459 if (flags & DC_EXEC) {
1460 /* First normalise the sub types of the chain. */
1461 NormaliseSubtypes(new_head);
1463 if (v == first && v->IsEngine() && !sell_chain && new_head != NULL && new_head->IsFrontEngine()) {
1464 /* We are selling the front engine. In this case we want to
1465 * 'give' the order, unit number and such to the new head. */
1466 new_head->orders.list = first->orders.list;
1467 new_head->AddToShared(first);
1468 DeleteVehicleOrders(first);
1470 /* Copy other important data from the front engine */
1471 new_head->CopyVehicleConfigAndStatistics(first);
1472 GroupStatistics::CountVehicle(new_head, 1); // after copying over the profit
1473 } else if (v->IsPrimaryVehicle() && data & (MAKE_ORDER_BACKUP_FLAG >> 20)) {
1474 OrderBackup::Backup(v, user);
1477 /* We need to update the information about the train. */
1478 NormaliseTrainHead(new_head);
1480 /* We are undoubtedly changing something in the depot and train list. */
1481 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
1482 InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
1484 /* Actually delete the sold 'goods' */
1485 delete sell_head;
1486 } else {
1487 /* We don't want to execute what we're just tried. */
1488 RestoreTrainBackup(original);
1491 return cost;
1494 void Train::UpdateDeltaXY(Direction direction)
1496 /* Set common defaults. */
1497 this->x_offs = -1;
1498 this->y_offs = -1;
1499 this->x_extent = 3;
1500 this->y_extent = 3;
1501 this->z_extent = 6;
1502 this->x_bb_offs = 0;
1503 this->y_bb_offs = 0;
1505 if (!IsDiagonalDirection(direction)) {
1506 static const int _sign_table[] =
1508 // x, y
1509 -1, -1, // DIR_N
1510 -1, 1, // DIR_E
1511 1, 1, // DIR_S
1512 1, -1, // DIR_W
1515 int half_shorten = (VEHICLE_LENGTH - this->gcache.cached_veh_length) / 2;
1517 /* For all straight directions, move the bound box to the centre of the vehicle, but keep the size. */
1518 this->x_offs -= half_shorten * _sign_table[direction];
1519 this->y_offs -= half_shorten * _sign_table[direction + 1];
1520 this->x_extent += this->x_bb_offs = half_shorten * _sign_table[direction];
1521 this->y_extent += this->y_bb_offs = half_shorten * _sign_table[direction + 1];
1522 } else {
1523 switch (direction) {
1524 /* Shorten southern corner of the bounding box according the vehicle length
1525 * and center the bounding box on the vehicle. */
1526 case DIR_NE:
1527 this->x_offs = 1 - (this->gcache.cached_veh_length + 1) / 2;
1528 this->x_extent = this->gcache.cached_veh_length - 1;
1529 this->x_bb_offs = -1;
1530 break;
1532 case DIR_NW:
1533 this->y_offs = 1 - (this->gcache.cached_veh_length + 1) / 2;
1534 this->y_extent = this->gcache.cached_veh_length - 1;
1535 this->y_bb_offs = -1;
1536 break;
1538 /* Move northern corner of the bounding box down according to vehicle length
1539 * and center the bounding box on the vehicle. */
1540 case DIR_SW:
1541 this->x_offs = 1 + (this->gcache.cached_veh_length + 1) / 2 - VEHICLE_LENGTH;
1542 this->x_extent = VEHICLE_LENGTH - 1;
1543 this->x_bb_offs = VEHICLE_LENGTH - this->gcache.cached_veh_length - 1;
1544 break;
1546 case DIR_SE:
1547 this->y_offs = 1 + (this->gcache.cached_veh_length + 1) / 2 - VEHICLE_LENGTH;
1548 this->y_extent = VEHICLE_LENGTH - 1;
1549 this->y_bb_offs = VEHICLE_LENGTH - this->gcache.cached_veh_length - 1;
1550 break;
1552 default:
1553 NOT_REACHED();
1559 * Mark a train as stuck and stop it if it isn't stopped right now.
1560 * @param v %Train to mark as being stuck.
1562 static void MarkTrainAsStuck(Train *v)
1564 if (!HasBit(v->flags, VRF_TRAIN_STUCK)) {
1565 /* It is the first time the problem occurred, set the "train stuck" flag. */
1566 SetBit(v->flags, VRF_TRAIN_STUCK);
1568 v->wait_counter = 0;
1570 /* Stop train */
1571 v->cur_speed = 0;
1572 v->subspeed = 0;
1573 v->SetLastSpeed();
1575 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
1580 * Swap the two up/down flags in two ways:
1581 * - Swap values of \a swap_flag1 and \a swap_flag2, and
1582 * - If going up previously (#GVF_GOINGUP_BIT set), the #GVF_GOINGDOWN_BIT is set, and vice versa.
1583 * @param swap_flag1 [inout] First train flag.
1584 * @param swap_flag2 [inout] Second train flag.
1586 static void SwapTrainFlags(uint16 *swap_flag1, uint16 *swap_flag2)
1588 uint16 flag1 = *swap_flag1;
1589 uint16 flag2 = *swap_flag2;
1591 /* Clear the flags */
1592 ClrBit(*swap_flag1, GVF_GOINGUP_BIT);
1593 ClrBit(*swap_flag1, GVF_GOINGDOWN_BIT);
1594 ClrBit(*swap_flag2, GVF_GOINGUP_BIT);
1595 ClrBit(*swap_flag2, GVF_GOINGDOWN_BIT);
1597 /* Reverse the rail-flags (if needed) */
1598 if (HasBit(flag1, GVF_GOINGUP_BIT)) {
1599 SetBit(*swap_flag2, GVF_GOINGDOWN_BIT);
1600 } else if (HasBit(flag1, GVF_GOINGDOWN_BIT)) {
1601 SetBit(*swap_flag2, GVF_GOINGUP_BIT);
1603 if (HasBit(flag2, GVF_GOINGUP_BIT)) {
1604 SetBit(*swap_flag1, GVF_GOINGDOWN_BIT);
1605 } else if (HasBit(flag2, GVF_GOINGDOWN_BIT)) {
1606 SetBit(*swap_flag1, GVF_GOINGUP_BIT);
1611 * Updates some variables after swapping the vehicle.
1612 * @param v swapped vehicle
1614 static void UpdateStatusAfterSwap(Train *v)
1616 /* Reverse the direction. */
1617 if (v->trackdir != TRACKDIR_DEPOT) v->direction = ReverseDir(v->direction);
1619 if (v->trackdir < TRACKDIR_END) v->trackdir = ReverseTrackdir(v->trackdir);
1621 /* Call the proper EnterTile function unless we are in a wormhole. */
1622 if (v->trackdir != TRACKDIR_WORMHOLE) {
1623 TrainEnterTile(v, v->tile, v->x_pos, v->y_pos);
1624 } else {
1625 assert(v->direction == DiagDirToDir(GetTunnelBridgeDirection(v->tile)));
1626 v->tile = GetOtherTunnelBridgeEnd(v->tile);
1629 VehicleUpdatePosition(v);
1630 v->UpdateViewport(true, true);
1634 * Swap vehicles \a l and \a r in consist \a v, and reverse their direction.
1635 * @param v Consist to change.
1636 * @param l %Vehicle index in the consist of the first vehicle.
1637 * @param r %Vehicle index in the consist of the second vehicle.
1639 void ReverseTrainSwapVeh(Train *v, int l, int r)
1641 Train *a, *b;
1643 /* locate vehicles to swap */
1644 for (a = v; l != 0; l--) a = a->Next();
1645 for (b = v; r != 0; r--) b = b->Next();
1647 if (a != b) {
1648 /* swap the hidden bits */
1650 uint16 tmp = (a->vehstatus & ~VS_HIDDEN) | (b->vehstatus & VS_HIDDEN);
1651 b->vehstatus = (b->vehstatus & ~VS_HIDDEN) | (a->vehstatus & VS_HIDDEN);
1652 a->vehstatus = tmp;
1655 Swap(a->trackdir, b->trackdir);
1656 Swap(a->direction, b->direction);
1657 Swap(a->x_pos, b->x_pos);
1658 Swap(a->y_pos, b->y_pos);
1659 Swap(a->tile, b->tile);
1660 Swap(a->z_pos, b->z_pos);
1662 SwapTrainFlags(&a->gv_flags, &b->gv_flags);
1664 UpdateStatusAfterSwap(a);
1665 UpdateStatusAfterSwap(b);
1666 } else {
1667 /* Swap GVF_GOINGUP_BIT/GVF_GOINGDOWN_BIT.
1668 * This is a little bit redundant way, a->gv_flags will
1669 * be (re)set twice, but it reduces code duplication */
1670 SwapTrainFlags(&a->gv_flags, &a->gv_flags);
1671 UpdateStatusAfterSwap(a);
1677 * Check if there is a train on a tile
1678 * @param tile the tile to check
1679 * @return true if a train is on the tile
1681 static bool TrainOnTile (TileIndex tile)
1683 VehicleTileFinder iter (tile);
1684 while (!iter.finished()) {
1685 Vehicle *v = iter.next();
1686 if (v->type == VEH_TRAIN) iter.set_found();
1688 return iter.was_found();
1692 * Checks whether a train is approaching a rail-road crossing from a neighbour tile
1693 * @param tile the crossing tile
1694 * @param from the neighbour tile
1695 * @return true if a train is approaching the crossing
1697 static bool TrainApproachingCrossingFrom (TileIndex tile, TileIndex from)
1699 VehicleTileFinder iter (from);
1700 while (!iter.finished()) {
1701 Vehicle *v = iter.next();
1702 if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) continue;
1704 Train *t = Train::From(v);
1705 if (t->IsFrontEngine() && TrainApproachingCrossingTile(t) == tile) iter.set_found();
1707 return iter.was_found();
1711 * Finds a vehicle approaching rail-road crossing
1712 * @param tile tile to test
1713 * @return true if a vehicle is approaching the crossing
1714 * @pre tile is a rail-road crossing
1716 static bool TrainApproachingCrossing(TileIndex tile)
1718 assert(IsLevelCrossingTile(tile));
1720 TileIndexDiff delta = TileOffsByDiagDir(AxisToDiagDir(GetCrossingRailAxis(tile)));
1721 return TrainApproachingCrossingFrom (tile, tile + delta) ||
1722 TrainApproachingCrossingFrom (tile, tile - delta);
1727 * Sets correct crossing state
1728 * @param tile tile to update
1729 * @param sound should we play sound?
1730 * @pre tile is a rail-road crossing
1732 void UpdateLevelCrossing(TileIndex tile, bool sound)
1734 assert(IsLevelCrossingTile(tile));
1736 /* reserved || train on crossing || train approaching crossing */
1737 bool new_state = HasCrossingReservation(tile) || TrainOnTile(tile) || TrainApproachingCrossing(tile);
1739 if (new_state != IsCrossingBarred(tile)) {
1740 if (new_state && sound) {
1741 if (_settings_client.sound.ambient) SndPlayTileFx(SND_0E_LEVEL_CROSSING, tile);
1743 SetCrossingBarred(tile, new_state);
1744 MarkTileDirtyByTile(tile);
1750 * Bars crossing and plays ding-ding sound if not barred already
1751 * @param tile tile with crossing
1752 * @pre tile is a rail-road crossing
1754 static inline void MaybeBarCrossingWithSound(TileIndex tile)
1756 if (!IsCrossingBarred(tile)) {
1757 BarCrossing(tile);
1758 if (_settings_client.sound.ambient) SndPlayTileFx(SND_0E_LEVEL_CROSSING, tile);
1759 MarkTileDirtyByTile(tile);
1765 * Advances wagons for train reversing, needed for variable length wagons.
1766 * This one is called before the train is reversed.
1767 * @param v First vehicle in chain
1769 static void AdvanceWagonsBeforeSwap(Train *v)
1771 Train *base = v;
1772 Train *first = base; // first vehicle to move
1773 Train *last = v->Last(); // last vehicle to move
1774 uint length = CountVehiclesInChain(v);
1776 while (length > 2) {
1777 last = last->Previous();
1778 first = first->Next();
1780 int differential = base->CalcNextVehicleOffset() - last->CalcNextVehicleOffset();
1782 /* do not update images now
1783 * negative differential will be handled in AdvanceWagonsAfterSwap() */
1784 for (int i = 0; i < differential; i++) TrainController(first, last->Next());
1786 base = first; // == base->Next()
1787 length -= 2;
1793 * Advances wagons for train reversing, needed for variable length wagons.
1794 * This one is called after the train is reversed.
1795 * @param v First vehicle in chain
1797 static void AdvanceWagonsAfterSwap(Train *v)
1799 /* first of all, fix the situation when the train was entering a depot */
1800 Train *dep = v; // last vehicle in front of just left depot
1801 while (dep->Next() != NULL && (dep->trackdir == TRACKDIR_DEPOT || dep->Next()->trackdir != TRACKDIR_DEPOT)) {
1802 dep = dep->Next(); // find first vehicle outside of a depot, with next vehicle inside a depot
1805 Train *leave = dep->Next(); // first vehicle in a depot we are leaving now
1807 if (leave != NULL) {
1808 /* 'pull' next wagon out of the depot, so we won't miss it (it could stay in depot forever) */
1809 int d = TicksToLeaveDepot(dep);
1811 if (d <= 0) {
1812 leave->vehstatus &= ~VS_HIDDEN; // move it out of the depot
1813 leave->trackdir = DiagDirToDiagTrackdir(GetGroundDepotDirection(leave->tile));
1814 for (int i = 0; i >= d; i--) TrainController(leave, NULL); // maybe move it, and maybe let another wagon leave
1816 } else {
1817 dep = NULL; // no vehicle in a depot, so no vehicle leaving a depot
1820 Train *base = v;
1821 Train *first = base; // first vehicle to move
1822 Train *last = v->Last(); // last vehicle to move
1823 uint length = CountVehiclesInChain(v);
1825 /* We have to make sure all wagons that leave a depot because of train reversing are moved correctly
1826 * they have already correct spacing, so we have to make sure they are moved how they should */
1827 bool nomove = (dep == NULL); // If there is no vehicle leaving a depot, limit the number of wagons moved immediately.
1829 while (length > 2) {
1830 /* we reached vehicle (originally) in front of a depot, stop now
1831 * (we would move wagons that are already moved with new wagon length). */
1832 if (base == dep) break;
1834 /* the last wagon was that one leaving a depot, so do not move it anymore */
1835 if (last == dep) nomove = true;
1837 last = last->Previous();
1838 first = first->Next();
1840 int differential = last->CalcNextVehicleOffset() - base->CalcNextVehicleOffset();
1842 /* do not update images now */
1843 for (int i = 0; i < differential; i++) TrainController(first, (nomove ? last->Next() : NULL));
1845 base = first; // == base->Next()
1846 length -= 2;
1851 * Turn a train around.
1852 * @param v %Train to turn around.
1854 void ReverseTrainDirection(Train *v)
1856 if (IsRailDepotTile(v->tile)) {
1857 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
1860 /* Clear path reservation in front if train is not stuck. */
1861 if (!HasBit(v->flags, VRF_TRAIN_STUCK)) FreeTrainTrackReservation(v);
1863 /* Check if we were approaching a rail/road-crossing */
1864 TileIndex crossing = TrainApproachingCrossingTile(v);
1866 /* count number of vehicles */
1867 int r = CountVehiclesInChain(v) - 1; // number of vehicles - 1
1869 AdvanceWagonsBeforeSwap(v);
1871 /* swap start<>end, start+1<>end-1, ... */
1872 int l = 0;
1873 do {
1874 ReverseTrainSwapVeh(v, l++, r--);
1875 } while (l <= r);
1877 AdvanceWagonsAfterSwap(v);
1879 if (IsRailDepotTile(v->tile)) {
1880 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
1883 ToggleBit(v->flags, VRF_TOGGLE_REVERSE);
1885 ClrBit(v->flags, VRF_REVERSING);
1887 /* recalculate cached data */
1888 v->ConsistChanged(CCF_TRACK);
1890 /* update all images */
1891 for (Train *u = v; u != NULL; u = u->Next()) u->UpdateViewport(false, false);
1893 /* update crossing we were approaching */
1894 if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
1896 /* maybe we are approaching crossing now, after reversal */
1897 crossing = TrainApproachingCrossingTile(v);
1898 if (crossing != INVALID_TILE) MaybeBarCrossingWithSound(crossing);
1900 /* If we are inside a depot after reversing, don't bother with path reserving. */
1901 if (v->trackdir == TRACKDIR_DEPOT) {
1902 /* Can't be stuck here as inside a depot is always a safe tile. */
1903 if (HasBit(v->flags, VRF_TRAIN_STUCK)) SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
1904 ClrBit(v->flags, VRF_TRAIN_STUCK);
1905 return;
1908 assert(IsSignalBufferEmpty());
1909 AddPosToSignalBuffer(v->GetPos(), v->owner);
1911 if (UpdateSignalsInBuffer() == SIGSEG_PBS || _settings_game.pf.reserve_paths) {
1912 RailPathPos pos = v->GetPos();
1914 /* If we are currently on a tile with conventional signals, we can't treat the
1915 * current tile as a safe tile or we would enter a PBS block without a reservation. */
1916 bool first_tile_okay = !(HasSignalAlongPos(pos) &&
1917 !IsPbsSignal(GetSignalType(pos)));
1919 /* If we are on a depot tile facing outwards, do not treat the current tile as safe. */
1920 if (!pos.in_wormhole() && IsRailDepotTile(pos.tile) && TrackdirToExitdir(pos.td) == GetGroundDepotDirection(pos.tile)) first_tile_okay = false;
1922 if (!pos.in_wormhole() && IsRailStationTile(pos.tile)) SetRailStationPlatformReservation(pos, true);
1923 if (TryPathReserve(v, false, first_tile_okay)) {
1924 /* Do a look-ahead now in case our current tile was already a safe tile. */
1925 CheckNextTrainTile(v);
1926 } else if (v->current_order.GetType() != OT_LOADING) {
1927 /* Do not wait for a way out when we're still loading */
1928 MarkTrainAsStuck(v);
1930 } else if (HasBit(v->flags, VRF_TRAIN_STUCK)) {
1931 /* A train not inside a PBS block can't be stuck. */
1932 ClrBit(v->flags, VRF_TRAIN_STUCK);
1933 v->wait_counter = 0;
1938 * Reverse train.
1939 * @param tile unused
1940 * @param flags type of operation
1941 * @param p1 train to reverse
1942 * @param p2 if true, reverse a unit in a train (needs to be in a depot)
1943 * @param text unused
1944 * @return the cost of this operation or an error
1946 CommandCost CmdReverseTrainDirection(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1948 Train *v = Train::GetIfValid(p1);
1949 if (v == NULL) return CMD_ERROR;
1951 CommandCost ret = CheckOwnership(v->owner);
1952 if (ret.Failed()) return ret;
1954 if (p2 != 0) {
1955 /* turn a single unit around */
1957 if (v->IsMultiheaded() || HasBit(EngInfo(v->engine_type)->callback_mask, CBM_VEHICLE_ARTIC_ENGINE)) {
1958 return_cmd_error(STR_ERROR_CAN_T_REVERSE_DIRECTION_RAIL_VEHICLE_MULTIPLE_UNITS);
1960 if (!HasBit(EngInfo(v->engine_type)->misc_flags, EF_RAIL_FLIPS)) return CMD_ERROR;
1962 Train *front = v->First();
1963 /* make sure the vehicle is stopped in the depot */
1964 if (!front->IsStoppedInDepot()) {
1965 return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
1968 if (flags & DC_EXEC) {
1969 ToggleBit(v->flags, VRF_REVERSE_DIRECTION);
1971 front->ConsistChanged(CCF_ARRANGE);
1972 SetWindowDirty(WC_VEHICLE_DEPOT, front->tile);
1973 SetWindowDirty(WC_VEHICLE_DETAILS, front->index);
1974 SetWindowDirty(WC_VEHICLE_VIEW, front->index);
1975 SetWindowClassesDirty(WC_TRAINS_LIST);
1977 } else {
1978 /* turn the whole train around */
1979 if ((v->vehstatus & VS_CRASHED) || v->breakdown_ctr != 0) return CMD_ERROR;
1981 if (flags & DC_EXEC) {
1982 /* Properly leave the station if we are loading and won't be loading anymore */
1983 if (v->current_order.IsType(OT_LOADING)) {
1984 const Vehicle *last = v;
1985 while (last->Next() != NULL) last = last->Next();
1987 /* not a station || different station --> leave the station */
1988 if (!IsStationTile(last->tile) || GetStationIndex(last->tile) != GetStationIndex(v->tile)) {
1989 v->LeaveStation();
1993 /* We cancel any 'skip signal at dangers' here */
1994 v->force_proceed = TFP_NONE;
1995 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
1997 if (_settings_game.vehicle.train_acceleration_model != AM_ORIGINAL && v->cur_speed != 0) {
1998 ToggleBit(v->flags, VRF_REVERSING);
1999 } else {
2000 v->cur_speed = 0;
2001 v->SetLastSpeed();
2002 HideFillingPercent(&v->fill_percent_te_id);
2003 ReverseTrainDirection(v);
2007 return CommandCost();
2011 * Force a train through a red signal
2012 * @param tile unused
2013 * @param flags type of operation
2014 * @param p1 train to ignore the red signal
2015 * @param p2 unused
2016 * @param text unused
2017 * @return the cost of this operation or an error
2019 CommandCost CmdForceTrainProceed(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2021 Train *t = Train::GetIfValid(p1);
2022 if (t == NULL) return CMD_ERROR;
2024 if (!t->IsPrimaryVehicle()) return CMD_ERROR;
2026 CommandCost ret = CheckOwnership(t->owner);
2027 if (ret.Failed()) return ret;
2030 if (flags & DC_EXEC) {
2031 /* If we are forced to proceed, cancel that order.
2032 * If we are marked stuck we would want to force the train
2033 * to proceed to the next signal. In the other cases we
2034 * would like to pass the signal at danger and run till the
2035 * next signal we encounter. */
2036 t->force_proceed = t->force_proceed == TFP_SIGNAL ? TFP_NONE : HasBit(t->flags, VRF_TRAIN_STUCK) || t->IsChainInDepot() ? TFP_STUCK : TFP_SIGNAL;
2037 SetWindowDirty(WC_VEHICLE_VIEW, t->index);
2040 return CommandCost();
2044 * Try to find a depot.
2045 * @param v %Train that wants a depot.
2046 * @param nearby Only consider nearby depots.
2047 * @param res Pointer to store information where the closest train depot is located.
2048 * @return Whether a depot was found.
2049 * @pre The given vehicle must not be crashed!
2051 static bool FindClosestTrainDepot(Train *v, bool nearby, FindDepotData *res)
2053 assert(!(v->vehstatus & VS_CRASHED));
2055 if (IsRailDepotTile(v->tile) && v->trackdir == DiagDirToDiagTrackdir(ReverseDiagDir(GetGroundDepotDirection(v->tile)))) {
2056 *res = FindDepotData(v->tile);
2057 return true;
2060 RailPathPos origin;
2061 FollowTrainReservation(v, &origin);
2062 if (IsRailDepotTile(origin.tile) && origin.td == DiagDirToDiagTrackdir(ReverseDiagDir(GetGroundDepotDirection(origin.tile)))) {
2063 *res = FindDepotData(origin.tile);
2064 return true;
2067 return YapfTrainFindNearestDepot(v,
2068 nearby ? _settings_game.pf.yapf.maximum_go_to_depot_penalty : 0, res);
2072 * Locate the closest depot for this consist, and return the information to the caller.
2073 * @param location [out] If not \c NULL and a depot is found, store its location in the given address.
2074 * @param destination [out] If not \c NULL and a depot is found, store its index in the given address.
2075 * @param reverse [out] If not \c NULL and a depot is found, store reversal information in the given address.
2076 * @return A depot has been found.
2078 bool Train::FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
2080 FindDepotData tfdd;
2081 if (!FindClosestTrainDepot(this, false, &tfdd)) return false;
2083 if (location != NULL) *location = tfdd.tile;
2084 if (destination != NULL) *destination = GetDepotIndex(tfdd.tile);
2085 if (reverse != NULL) *reverse = tfdd.reverse;
2087 return true;
2090 /** Play a sound for a train leaving the station. */
2091 void Train::PlayLeaveStationSound() const
2093 static const SoundFx sfx[] = {
2094 SND_04_TRAIN,
2095 SND_0A_TRAIN_HORN,
2096 SND_0A_TRAIN_HORN,
2097 SND_47_MAGLEV_2,
2098 SND_41_MAGLEV
2101 if (PlayVehicleSound(this, VSE_START)) return;
2103 EngineID engtype = this->engine_type;
2104 SndPlayVehicleFx(sfx[RailVehInfo(engtype)->engclass], this);
2108 * Check if the train is on the last reserved tile and try to extend the path then.
2109 * @param v %Train that needs its path extended.
2111 static void CheckNextTrainTile(Train *v)
2113 /* Don't do any look-ahead if path_backoff_interval is 255. */
2114 if (_settings_game.pf.path_backoff_interval == 255) return;
2116 /* Exit if we are inside a depot. */
2117 if (v->trackdir == TRACKDIR_DEPOT) return;
2119 switch (v->current_order.GetType()) {
2120 /* Exit if we reached our destination depot. */
2121 case OT_GOTO_DEPOT:
2122 if (v->tile == v->dest_tile) return;
2123 break;
2125 case OT_GOTO_WAYPOINT:
2126 /* If we reached our waypoint, make sure we see that. */
2127 if (IsRailWaypointTile(v->tile) && GetStationIndex(v->tile) == v->current_order.GetDestination()) ProcessOrders(v);
2128 break;
2130 case OT_NOTHING:
2131 case OT_LEAVESTATION:
2132 case OT_LOADING:
2133 /* Exit if the current order doesn't have a destination, but the train has orders. */
2134 if (v->GetNumOrders() > 0) return;
2135 break;
2137 default:
2138 break;
2140 /* Exit if we are on a station tile and are going to stop. */
2141 if (IsRailStationTile(v->tile) && v->current_order.ShouldStopAtStation(v, GetStationIndex(v->tile))) return;
2143 RailPathPos pos = v->GetPos();
2145 /* On a tile with a red non-pbs signal, don't look ahead. */
2146 if (HasSignalAlongPos(pos) &&
2147 !IsPbsSignal(GetSignalType(pos)) &&
2148 GetSignalStateByPos(pos) == SIGNAL_STATE_RED) return;
2150 CFollowTrackRail ft(v, !_settings_game.pf.forbid_90_deg);
2151 if (!ft.Follow(pos)) return;
2153 if (ft.m_new.is_single()) {
2154 /* Next tile is not reserved. */
2155 if (!HasReservedPos(ft.m_new)) {
2156 if (HasPbsSignalAlongPos(ft.m_new)) {
2157 /* If the next tile is a PBS signal, try to make a reservation. */
2158 ChooseTrainTrack(v, pos, ft.m_new.tile, ft.m_new.trackdirs, false);
2165 * Will the train stay in the depot the next tick?
2166 * @param v %Train to check.
2167 * @return True if it stays in the depot, false otherwise.
2169 static bool CheckTrainStayInDepot(Train *v)
2171 /* bail out if not all wagons are in the same depot or not in a depot at all */
2172 for (const Train *u = v; u != NULL; u = u->Next()) {
2173 if (u->trackdir != TRACKDIR_DEPOT || u->tile != v->tile) return false;
2176 /* if the train got no power, then keep it in the depot */
2177 if (v->gcache.cached_power == 0) {
2178 v->vehstatus |= VS_STOPPED;
2179 SetWindowDirty(WC_VEHICLE_DEPOT, v->tile);
2180 return true;
2183 bool try_reserve;
2185 if (v->force_proceed == TFP_NONE) {
2186 /* force proceed was not pressed */
2187 if (++v->wait_counter < 37) {
2188 SetWindowClassesDirty(WC_TRAINS_LIST);
2189 return true;
2192 v->wait_counter = 0;
2194 if (HasDepotReservation(v->tile)) {
2195 /* Depot reserved, can't exit. */
2196 SetWindowClassesDirty(WC_TRAINS_LIST);
2197 return true;
2200 if (_settings_game.pf.reserve_paths) {
2201 try_reserve = true;
2202 } else {
2203 assert(IsSignalBufferEmpty());
2204 AddDepotToSignalBuffer(v->tile, v->owner);
2205 SigSegState seg_state = UpdateSignalsInBuffer();
2206 if (seg_state == SIGSEG_FULL) {
2207 /* Full and no PBS signal in block, can't exit. */
2208 SetWindowClassesDirty(WC_TRAINS_LIST);
2209 return true;
2211 try_reserve = seg_state == SIGSEG_PBS;
2213 } else if (_settings_game.pf.reserve_paths) {
2214 try_reserve = true;
2215 } else {
2216 assert(IsSignalBufferEmpty());
2217 AddDepotToSignalBuffer(v->tile, v->owner);
2218 try_reserve = UpdateSignalsInBuffer() == SIGSEG_PBS;
2221 /* We are leaving a depot, but have to go to the exact same one; re-enter */
2222 if (v->current_order.IsType(OT_GOTO_DEPOT) && v->tile == v->dest_tile) {
2223 /* We need to have a reservation for this to work. */
2224 if (HasDepotReservation(v->tile)) return true;
2225 SetDepotReservation(v->tile, true);
2226 VehicleEnterDepot(v);
2227 return true;
2230 /* Only leave when we can reserve a path to our destination. */
2231 if (try_reserve && !TryPathReserveFromDepot(v) && v->force_proceed == TFP_NONE) {
2232 /* No path and no force proceed. */
2233 SetWindowClassesDirty(WC_TRAINS_LIST);
2234 MarkTrainAsStuck(v);
2235 return true;
2238 SetDepotReservation(v->tile, true);
2239 if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(v->tile);
2241 VehicleServiceInDepot(v);
2242 SetWindowClassesDirty(WC_TRAINS_LIST);
2243 v->PlayLeaveStationSound();
2245 v->trackdir = DiagDirToDiagTrackdir(DirToDiagDir(v->direction));
2247 v->vehstatus &= ~VS_HIDDEN;
2248 v->cur_speed = 0;
2250 v->UpdateViewport(true, true);
2251 VehicleUpdatePosition(v);
2253 assert(IsSignalBufferEmpty());
2254 AddDepotToSignalBuffer(v->tile, v->owner);
2255 UpdateSignalsInBuffer();
2257 v->UpdateAcceleration();
2258 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
2260 return false;
2264 * Clear the reservation of \a tile that was just left by a wagon on \a track_dir.
2265 * @param v %Train owning the reservation.
2266 * @param pos position to clear.
2268 static void ClearPathReservation(const Train *v, const RailPathPos &pos)
2270 DiagDirection dir = TrackdirToExitdir(pos.td);
2272 if (pos.in_wormhole()) {
2273 UnreserveRailTrack(pos);
2274 } else if (IsRailStationTile(pos.tile)) {
2275 TileIndex new_tile = TileAddByDiagDir(pos.tile, dir);
2276 /* If the new tile is not a further tile of the same station, we
2277 * clear the reservation for the whole platform. */
2278 if (!IsCompatibleTrainStationTile(new_tile, pos.tile)) {
2279 SetRailStationPlatformReservation(pos.tile, ReverseDiagDir(dir), false);
2281 } else {
2282 /* Any other tile */
2283 UnreserveRailTrack(pos);
2288 * Free the reserved path in front of a vehicle.
2289 * @param v %Train owning the reserved path.
2291 void FreeTrainTrackReservation(const Train *v)
2293 assert(v->IsFrontEngine());
2295 RailPathPos pos = v->GetPos();
2296 bool first = true;
2298 /* Can't be holding a reservation if we enter a depot. */
2299 if (IsRailDepotTile(pos.tile) && TrackdirToExitdir(pos.td) != GetGroundDepotDirection(pos.tile)) return;
2300 if (v->trackdir == TRACKDIR_DEPOT) {
2301 /* Front engine is in a depot. We enter if some part is not in the depot. */
2302 for (const Train *u = v; u != NULL; u = u->Next()) {
2303 if (u->trackdir != TRACKDIR_DEPOT || u->tile != v->tile) return;
2306 /* Don't free reservation if it's not ours. */
2307 if (!pos.in_wormhole() && TracksOverlap(GetReservedTrackbits(pos.tile) | TrackToTrackBits(TrackdirToTrack(pos.td)))) return;
2309 CFollowTrackRail ft(v, true, v->railtype);
2310 ft.SetPos(pos);
2312 while (ft.FollowNext()) {
2313 if (!ft.m_new.in_wormhole()) {
2314 TrackdirBits trackdirs = ft.m_new.trackdirs & TrackBitsToTrackdirBits(GetReservedTrackbits(ft.m_new.tile));
2315 if (trackdirs == TRACKDIR_BIT_NONE) break;
2316 ft.m_new.set_trackdirs (trackdirs);
2317 assert(ft.m_new.is_single());
2320 if (HasSignalAlongPos(ft.m_new) && !IsPbsSignal(GetSignalType(ft.m_new))) {
2321 /* Conventional signal along trackdir: remove reservation and stop. */
2322 UnreserveRailTrack(ft.m_new);
2323 break;
2326 if (HasPbsSignalAlongPos(ft.m_new)) {
2327 if (GetSignalStateByPos(ft.m_new) == SIGNAL_STATE_RED) {
2328 /* Red PBS signal? Can't be our reservation, would be green then. */
2329 break;
2330 } else {
2331 /* Turn the signal back to red. */
2332 SetSignalState(ft.m_new.tile, ft.m_new.td, SIGNAL_STATE_RED);
2333 MarkTileDirtyByTile(ft.m_new.tile);
2335 } else if (HasSignalAgainstPos(ft.m_new) && IsOnewaySignal(GetSignalType(ft.m_new))) {
2336 break;
2339 if (first) {
2340 if (ft.m_flag == ft.TF_BRIDGE) {
2341 assert(IsRailBridgeTile(ft.m_old.in_wormhole() ? ft.m_old.wormhole : ft.m_old.tile));
2342 } else if (ft.m_flag == ft.TF_TUNNEL) {
2343 assert(IsTunnelTile(ft.m_old.in_wormhole() ? ft.m_old.wormhole : ft.m_old.tile));
2347 /* Don't free first station if we are on it. */
2348 if (!first || (ft.m_flag != ft.TF_STATION) ||
2349 !IsRailStationTile(ft.m_old.tile) || GetStationIndex(ft.m_new.tile) != GetStationIndex(ft.m_old.tile)) {
2350 ClearPathReservation(v, ft.m_new);
2353 first = false;
2357 static const byte _initial_tile_subcoord[TRACKDIR_END][3] = {
2358 {15, 8, 1}, // TRACKDIR_X_NE
2359 { 8, 0, 3}, // TRACKDIR_Y_SE
2360 { 7, 0, 2}, // TRACKDIR_UPPER_E
2361 {15, 8, 2}, // TRACKDIR_LOWER_E
2362 { 8, 0, 4}, // TRACKDIR_LEFT_S
2363 { 0, 8, 4}, // TRACKDIR_RIGHT_S
2364 { 0, 0, 0},
2365 { 0, 0, 0},
2366 { 0, 8, 5}, // TRACKDIR_X_SW
2367 { 8,15, 7}, // TRACKDIR_Y_NW
2368 { 0, 7, 6}, // TRACKDIR_UPPER_W
2369 { 8,15, 6}, // TRACKDIR_LOWER_W
2370 {15, 7, 0}, // TRACKDIR_LEFT_N
2371 { 7,15, 0}, // TRACKDIR_RIGHT_N
2375 * Perform pathfinding for a train.
2377 * @param v The train
2378 * @param origin The end of the current reservation
2379 * @param do_track_reservation Path reservation is requested
2380 * @param dest [out] State and destination of the requested path
2381 * @return The best trackdir the train should follow
2383 static Trackdir DoTrainPathfind(const Train *v, const RailPathPos &origin, bool do_track_reservation, PFResult *dest)
2385 return YapfTrainChooseTrack(v, origin, do_track_reservation, dest);
2389 * Return value type for ExtendTrainReservation
2391 enum ExtendReservationResult {
2392 EXTEND_RESERVATION_SAFE, ///< Reservation extended to a safe tile
2393 EXTEND_RESERVATION_UNSAFE, ///< Reservation extended to an unsafe tile
2394 EXTEND_RESERVATION_FAILED, ///< Reservation could not be extended
2398 * Extend a train path as far as possible. Stops on encountering a safe tile,
2399 * another reservation or a track choice.
2400 * @param v The train whose reservation to extend
2401 * @param origin The end of the current reservation, which will be updated
2402 * @return An ExtendReservationResult value, showing reservation extension outcome
2404 static ExtendReservationResult ExtendTrainReservation(const Train *v, RailPathPos *origin)
2406 CFollowTrackRail ft(v, !_settings_game.pf.forbid_90_deg);
2407 ft.SetPos(*origin);
2409 for (;;) {
2410 if (!ft.FollowNext()) {
2411 if (ft.m_err == CFollowTrackRail::EC_OWNER || ft.m_err == CFollowTrackRail::EC_NO_WAY) {
2412 /* End of line, path valid and okay. */
2413 *origin = ft.m_old;
2414 return EXTEND_RESERVATION_SAFE;
2416 break;
2419 /* A depot is always a safe waiting position. */
2420 if (!ft.m_new.in_wormhole() && IsRailDepotTile(ft.m_new.tile)) {
2421 /* Depot must be free for reservation to continue. */
2422 if (HasDepotReservation(ft.m_new.tile)) break;
2424 SetDepotReservation(ft.m_new.tile, true);
2425 *origin = ft.m_new;
2426 return EXTEND_RESERVATION_SAFE;
2429 /* Station and waypoints are possible targets. */
2430 if (ft.m_flag == ft.TF_STATION) {
2431 /* Possible target encountered.
2432 * On finding a possible target, we need to stop and let the pathfinder handle the
2433 * remaining path. This is because we don't know if this target is in one of our
2434 * orders, so we might cause pathfinding to fail later on if we find a choice.
2435 * This failure would cause a bogous call to TryReserveSafePath which might reserve
2436 * a wrong path not leading to our next destination. */
2437 if (!ft.MaskReservedTracks()) break;
2439 /* If we did skip some tiles, backtrack to the first skipped tile so the pathfinder
2440 * actually starts its search at the first unreserved tile. */
2441 ft.m_new.tile -= TileOffsByDiagDir(ft.m_exitdir) * ft.m_tiles_skipped;
2443 /* Possible target found, path valid but not okay. */
2444 *origin = ft.m_old;
2445 return EXTEND_RESERVATION_UNSAFE;
2448 if (!ft.m_new.is_single()) {
2449 /* Choice found. */
2450 if (HasReservedTracks(ft.m_new.tile, TrackdirBitsToTrackBits(ft.m_new.trackdirs))) break;
2452 assert(ft.m_tiles_skipped == 0);
2454 /* Choice found, path valid but not okay. Save info about the choice tile as well. */
2455 *origin = ft.m_old;
2456 return EXTEND_RESERVATION_UNSAFE;
2459 /* Possible signal tile. */
2460 if (HasOnewaySignalBlockingPos(ft.m_new)) break;
2462 PBSPositionState state = CheckWaitingPosition(v, ft.m_new, _settings_game.pf.forbid_90_deg);
2463 if (state == PBS_BUSY) break;
2465 if (!TryReserveRailTrack(ft.m_new)) break;
2467 if (state == PBS_FREE) {
2468 /* Safe position is all good, path valid and okay. */
2469 *origin = ft.m_new;
2470 return EXTEND_RESERVATION_SAFE;
2474 /* Sorry, can't reserve path, back out. */
2475 RailPathPos stopped = ft.m_old;
2476 ft.SetPos(*origin);
2477 while (ft.m_new != stopped) {
2478 if (!ft.FollowNext()) NOT_REACHED();
2480 assert(!ft.m_new.is_empty());
2481 assert(ft.m_new.is_single());
2483 UnreserveRailTrack(ft.m_new);
2486 /* Path invalid. */
2487 return EXTEND_RESERVATION_FAILED;
2491 * Try to reserve any path to a safe tile, ignoring the vehicle's destination.
2492 * Safe tiles are tiles in front of a signal, depots and station tiles at end of line.
2494 * @param v The vehicle.
2495 * @param pos The position the search should start from.
2496 * @param override_railtype Whether all physically compatible railtypes should be followed.
2497 * @return True if a path to a safe stopping tile could be reserved.
2499 static bool TryReserveSafeTrack(const Train *v, const RailPathPos &pos, bool override_tailtype)
2501 return YapfTrainFindNearestSafeTile(v, pos, override_tailtype);
2504 /** This class will save the current order of a vehicle and restore it on destruction. */
2505 class VehicleOrderSaver {
2506 private:
2507 Train *v;
2508 Order old_order;
2509 TileIndex old_dest_tile;
2510 StationID old_last_station_visited;
2511 VehicleOrderID index;
2512 bool suppress_implicit_orders;
2514 public:
2515 VehicleOrderSaver(Train *_v) :
2516 v(_v),
2517 old_order(_v->current_order),
2518 old_dest_tile(_v->dest_tile),
2519 old_last_station_visited(_v->last_station_visited),
2520 index(_v->cur_real_order_index),
2521 suppress_implicit_orders(HasBit(_v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS))
2525 ~VehicleOrderSaver()
2527 this->v->current_order = this->old_order;
2528 this->v->dest_tile = this->old_dest_tile;
2529 this->v->last_station_visited = this->old_last_station_visited;
2530 SB(this->v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS, 1, suppress_implicit_orders ? 1: 0);
2534 * Set the current vehicle order to the next order in the order list.
2535 * @param skip_first Shall the first (i.e. active) order be skipped?
2536 * @return True if a suitable next order could be found.
2538 bool SwitchToNextOrder(bool skip_first)
2540 if (this->v->GetNumOrders() == 0) return false;
2542 if (skip_first) ++this->index;
2544 int depth = 0;
2546 do {
2547 /* Wrap around. */
2548 if (this->index >= this->v->GetNumOrders()) this->index = 0;
2550 Order *order = this->v->GetOrder(this->index);
2551 assert(order != NULL);
2553 switch (order->GetType()) {
2554 case OT_GOTO_DEPOT:
2555 /* Skip service in depot orders when the train doesn't need service. */
2556 if ((order->GetDepotOrderType() & ODTFB_SERVICE) && !this->v->NeedsServicing()) break;
2557 case OT_GOTO_STATION:
2558 case OT_GOTO_WAYPOINT:
2559 this->v->current_order = *order;
2560 return UpdateOrderDest(this->v, order, 0, true);
2561 case OT_CONDITIONAL: {
2562 VehicleOrderID next = ProcessConditionalOrder(order, this->v);
2563 if (next != INVALID_VEH_ORDER_ID) {
2564 depth++;
2565 this->index = next;
2566 /* Don't increment next, so no break here. */
2567 continue;
2569 break;
2571 default:
2572 break;
2574 /* Don't increment inside the while because otherwise conditional
2575 * orders can lead to an infinite loop. */
2576 ++this->index;
2577 depth++;
2578 } while (this->index != this->v->cur_real_order_index && depth < this->v->GetNumOrders());
2580 return false;
2584 /* choose a track */
2585 static bool ChooseTrainTrack(Train *v, RailPathPos origin, TileIndex tile, TrackdirBits trackdirs, bool force_res, Trackdir *best_trackdir)
2587 bool do_track_reservation = _settings_game.pf.reserve_paths || force_res;
2588 bool change_signal = false;
2590 assert (trackdirs != TRACKDIR_BIT_NONE);
2592 /* Quick return in case only one possible trackdir is available */
2593 Trackdir single_trackdir = INVALID_TRACKDIR;
2594 if (HasAtMostOneBit(trackdirs)) {
2595 single_trackdir = FindFirstTrackdir(trackdirs);
2596 if (best_trackdir != NULL) *best_trackdir = single_trackdir;
2597 /* We need to check for signals only here, as a junction tile can't have signals. */
2598 if (HasPbsSignalOnTrackdir(tile, single_trackdir)) {
2599 do_track_reservation = true;
2600 change_signal = true;
2601 } else if (!do_track_reservation) {
2602 return true;
2606 if (do_track_reservation) {
2607 switch (ExtendTrainReservation(v, &origin)) {
2608 default: NOT_REACHED();
2609 case EXTEND_RESERVATION_FAILED:
2610 if (best_trackdir != NULL) *best_trackdir = FindFirstTrackdir(trackdirs);
2611 return false;
2612 case EXTEND_RESERVATION_SAFE:
2613 if (change_signal) {
2614 SetSignalState(tile, single_trackdir, SIGNAL_STATE_GREEN);
2615 MarkTileDirtyByTile(tile);
2617 TryReserveRailTrack(v->GetPos());
2618 assert (single_trackdir != INVALID_TRACKDIR);
2619 return true;
2620 case EXTEND_RESERVATION_UNSAFE:
2621 break;
2624 /* Check if the train needs service here, so it has a chance to always find a depot.
2625 * Also check if the current order is a service order so we don't reserve a path to
2626 * the destination but instead to the next one if service isn't needed. */
2627 CheckIfTrainNeedsService(v);
2628 if (v->current_order.IsType(OT_DUMMY) || v->current_order.IsType(OT_CONDITIONAL) || v->current_order.IsType(OT_GOTO_DEPOT)) ProcessOrders(v);
2631 /* Save the current train order. The destructor will restore the old order on function exit. */
2632 VehicleOrderSaver orders(v);
2634 /* If the current tile is the destination of the current order and
2635 * a reservation was requested, advance to the next order.
2636 * Don't advance on a depot order as depots are always safe end points
2637 * for a path and no look-ahead is necessary. This also avoids a
2638 * problem with depot orders not part of the order list when the
2639 * order list itself is empty. */
2640 if (v->current_order.IsType(OT_LEAVESTATION)) {
2641 orders.SwitchToNextOrder(false);
2642 } else if (v->current_order.IsType(OT_LOADING) || (!v->current_order.IsType(OT_GOTO_DEPOT) && (
2643 v->current_order.IsType(OT_GOTO_STATION) ?
2644 IsRailStationTile(v->tile) && v->current_order.GetDestination() == GetStationIndex(v->tile) :
2645 v->tile == v->dest_tile))) {
2646 orders.SwitchToNextOrder(true);
2649 /* Call the pathfinder... */
2650 PFResult res_dest;
2651 Trackdir next_trackdir = DoTrainPathfind(v, origin, do_track_reservation, &res_dest);
2652 v->HandlePathfindingResult(res_dest.found);
2653 /* ...but only use the result if we were at the original tile. */
2654 if (best_trackdir != NULL && single_trackdir == INVALID_TRACKDIR) {
2655 /* The initial tile had more than one available trackdir.
2656 * This means that ExtendTrainReservation cannot possibly
2657 * have extended the reservation, and we are pathfinding
2658 * at the original tile. */
2659 *best_trackdir = next_trackdir != INVALID_TRACKDIR ? next_trackdir : FindFirstTrackdir(trackdirs);
2660 /* If the initial tile only had one available trackdir, then
2661 * *best_trackdir was set along with single_trackdir. */
2664 /* No track reservation requested -> finished. */
2665 if (!do_track_reservation) {
2666 assert (!change_signal);
2667 return true;
2670 if (change_signal) SetSignalState(tile, single_trackdir, SIGNAL_STATE_GREEN);
2672 /* A path was found, but could not be reserved. */
2673 if (res_dest.pos.is_valid_tile() && !res_dest.okay) {
2674 FreeTrainTrackReservation(v);
2675 return false;
2678 /* No possible reservation target found, we are probably lost. */
2679 if (!res_dest.pos.is_valid_tile()) {
2680 /* Try to find any safe destination. */
2681 if (TryReserveSafeTrack(v, origin, false)) {
2682 if (best_trackdir != NULL && single_trackdir == INVALID_TRACKDIR) {
2683 TrackBits res = GetReservedTrackbits(tile);
2684 *best_trackdir = FindFirstTrackdir(TrackBitsToTrackdirBits(res) & trackdirs);
2686 TryReserveRailTrack(v->GetPos());
2687 if (change_signal) MarkTileDirtyByTile(tile);
2688 return true;
2689 } else {
2690 FreeTrainTrackReservation(v);
2691 return false;
2695 TryReserveRailTrack(v->GetPos());
2697 /* Extend reservation until we have found a safe position. */
2698 bool safe = false;
2699 for (;;) {
2700 origin = res_dest.pos;
2701 if (IsSafeWaitingPosition(v, origin, _settings_game.pf.forbid_90_deg)) {
2702 safe = true;
2703 break;
2706 /* Get next order with destination. */
2707 if (!orders.SwitchToNextOrder(true)) break;
2709 DoTrainPathfind(v, origin, true, &res_dest);
2710 /* Break if no safe position was found. */
2711 if (!res_dest.pos.is_valid_tile()) break;
2713 if (!res_dest.okay) {
2714 /* Path found, but could not be reserved. */
2715 FreeTrainTrackReservation(v);
2716 return false;
2720 /* No order or no safe position found, try any position. */
2721 if (!safe) safe = TryReserveSafeTrack(v, origin, true);
2723 if (!safe) {
2724 FreeTrainTrackReservation(v);
2725 } else if (change_signal) {
2726 MarkTileDirtyByTile(tile);
2729 return safe;
2733 * Try to reserve a path to a safe position.
2735 * @param v The vehicle
2736 * @param mark_as_stuck Should the train be marked as stuck on a failed reservation?
2737 * @param first_tile_okay True if no path should be reserved if the current tile is a safe position.
2738 * @return True if a path could be reserved.
2740 bool TryPathReserve(Train *v, bool mark_as_stuck, bool first_tile_okay)
2742 assert(v->IsFrontEngine());
2743 assert(v->trackdir != TRACKDIR_DEPOT);
2745 Vehicle *other_train = NULL;
2746 RailPathPos origin;
2747 FollowTrainReservation(v, &origin, &other_train);
2748 /* The path we are driving on is already blocked by some other train.
2749 * This can only happen in certain situations when mixing path and
2750 * block signals or when changing tracks and/or signals.
2751 * Exit here as doing any further reservations will probably just
2752 * make matters worse. */
2753 if (other_train != NULL && other_train->index != v->index) {
2754 if (mark_as_stuck) MarkTrainAsStuck(v);
2755 return false;
2758 /* If we have a reserved path and the path ends at a safe tile, we are finished already. */
2759 if ((v->tile != origin.tile || first_tile_okay) && IsSafeWaitingPosition(v, origin, _settings_game.pf.forbid_90_deg)) {
2760 /* Can't be stuck then. */
2761 if (HasBit(v->flags, VRF_TRAIN_STUCK)) SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
2762 ClrBit(v->flags, VRF_TRAIN_STUCK);
2763 return true;
2766 DiagDirection exitdir = TrackdirToExitdir(origin.td);
2767 TileIndex new_tile = TileAddByDiagDir(origin.tile, exitdir);
2768 TrackdirBits reachable = TrackStatusToTrackdirBits(GetTileRailwayStatus(new_tile)) & DiagdirReachesTrackdirs(exitdir);
2770 if (_settings_game.pf.forbid_90_deg) reachable &= ~TrackdirCrossesTrackdirs(origin.td);
2772 if (reachable != TRACKDIR_BIT_NONE && !ChooseTrainTrack(v, origin, new_tile, reachable, true)) {
2773 if (mark_as_stuck) MarkTrainAsStuck(v);
2774 return false;
2777 if (HasBit(v->flags, VRF_TRAIN_STUCK)) {
2778 v->wait_counter = 0;
2779 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
2781 ClrBit(v->flags, VRF_TRAIN_STUCK);
2782 return true;
2786 * Try to reserve a path to a safe position from a depot.
2788 * @param v The vehicle
2789 * @param mark_as_stuck Should the train be marked as stuck on a failed reservation?
2790 * @param first_tile_okay True if no path should be reserved if the current tile is a safe position.
2791 * @return True if a path could be reserved.
2793 static bool TryPathReserveFromDepot(Train *v)
2795 assert(v->IsFrontEngine());
2796 assert(v->trackdir == TRACKDIR_DEPOT);
2798 /* We have to handle depots specially as the track follower won't look
2799 * at the depot tile itself but starts from the next tile. If we are still
2800 * inside the depot, a depot reservation can never be ours. */
2801 if (HasDepotReservation(v->tile)) return false;
2803 /* Depot not reserved, but the next tile might be. */
2804 DiagDirection exitdir = GetGroundDepotDirection(v->tile);
2805 TileIndex new_tile = TileAddByDiagDir(v->tile, exitdir);
2806 if (HasReservedTracks(new_tile, DiagdirReachesTracks(exitdir))) return false;
2808 TrackdirBits reachable = TrackStatusToTrackdirBits(GetTileRailwayStatus(new_tile)) & DiagdirReachesTrackdirs(exitdir);
2810 if (reachable != TRACKDIR_BIT_NONE && !ChooseTrainTrack(v, v->GetPos(), new_tile, reachable, true)) {
2811 return false;
2814 SetDepotReservation(v->tile, true);
2815 if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(v->tile);
2817 if (HasBit(v->flags, VRF_TRAIN_STUCK)) {
2818 v->wait_counter = 0;
2819 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
2820 ClrBit(v->flags, VRF_TRAIN_STUCK);
2823 return true;
2827 static bool CheckReverseTrain(const Train *v)
2829 if (_settings_game.difficulty.line_reverse_mode != 0 ||
2830 v->trackdir == TRACKDIR_DEPOT || v->trackdir == TRACKDIR_WORMHOLE ||
2831 !(v->direction & 1)) {
2832 return false;
2835 assert(IsValidTrackdir(v->trackdir));
2837 return YapfTrainCheckReverse(v);
2841 * Get the location of the next station to visit.
2842 * @param station Next station to visit.
2843 * @return Location of the new station.
2845 TileIndex Train::GetOrderStationLocation(StationID station)
2847 if (station == this->last_station_visited) this->last_station_visited = INVALID_STATION;
2849 const Station *st = Station::Get(station);
2850 if (!(st->facilities & FACIL_TRAIN)) {
2851 /* The destination station has no trainstation tiles. */
2852 this->IncrementRealOrderIndex();
2853 return 0;
2856 return st->xy;
2859 /** Goods at the consist have changed, update the graphics, cargo, and acceleration. */
2860 void Train::MarkDirty()
2862 Train *v = this;
2863 do {
2864 v->colourmap = PAL_NONE;
2865 v->UpdateViewport(true, false);
2866 } while ((v = v->Next()) != NULL);
2868 /* need to update acceleration and cached values since the goods on the train changed. */
2869 this->CargoChanged();
2870 this->UpdateAcceleration();
2874 * This function looks at the vehicle and updates its speed (cur_speed
2875 * and subspeed) variables. Furthermore, it returns the distance that
2876 * the train can drive this tick. #Vehicle::GetAdvanceDistance() determines
2877 * the distance to drive before moving a step on the map.
2878 * @return distance to drive.
2880 int Train::UpdateSpeed()
2882 switch (_settings_game.vehicle.train_acceleration_model) {
2883 default: NOT_REACHED();
2884 case AM_ORIGINAL:
2885 return this->DoUpdateSpeed(this->acceleration * (this->GetAccelerationStatus() == AS_BRAKE ? -4 : 2), 0, this->GetCurrentMaxSpeed());
2887 case AM_REALISTIC:
2888 return this->DoUpdateSpeed(this->GetAcceleration(), this->GetAccelerationStatus() == AS_BRAKE ? 0 : 2, this->GetCurrentMaxSpeed());
2893 * Trains enters a station, send out a news item if it is the first train, and start loading.
2894 * @param v Train that entered the station.
2895 * @param station Station visited.
2897 static void TrainEnterStation(Train *v, StationID station)
2899 v->last_station_visited = station;
2901 /* check if a train ever visited this station before */
2902 Station *st = Station::Get(station);
2903 if (!(st->had_vehicle_of_type & HVOT_TRAIN)) {
2904 st->had_vehicle_of_type |= HVOT_TRAIN;
2905 SetDParam(0, st->index);
2906 AddVehicleNewsItem(
2907 STR_NEWS_FIRST_TRAIN_ARRIVAL,
2908 v->owner == _local_company ? NT_ARRIVAL_COMPANY : NT_ARRIVAL_OTHER,
2909 v->index,
2910 st->index
2912 AI::NewEvent(v->owner, new ScriptEventStationFirstVehicle(st->index, v->index));
2913 Game::NewEvent(new ScriptEventStationFirstVehicle(st->index, v->index));
2916 v->force_proceed = TFP_NONE;
2917 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
2919 v->BeginLoading();
2921 TriggerStationRandomisation(st, v->tile, SRT_TRAIN_ARRIVES);
2922 TriggerStationAnimation(st, v->tile, SAT_TRAIN_ARRIVES);
2925 /* Check if the vehicle is compatible with the specified tile */
2926 static inline bool CheckCompatibleRail(const Train *v, TileIndex tile, Track track = INVALID_TRACK)
2928 return IsTileOwner(tile, v->owner) &&
2929 (!v->IsFrontEngine() || HasBit(v->compatible_railtypes, GetRailType(tile, track)));
2932 /** Data structure for storing engine speed changes of an acceleration type. */
2933 struct AccelerationSlowdownParams {
2934 byte small_turn; ///< Speed change due to a small turn.
2935 byte large_turn; ///< Speed change due to a large turn.
2936 byte z_up; ///< Fraction to remove when moving up.
2937 byte z_down; ///< Fraction to add when moving down.
2940 /** Speed update fractions for each acceleration type. */
2941 static const AccelerationSlowdownParams _accel_slowdown[] = {
2942 /* normal accel */
2943 {256 / 4, 256 / 2, 256 / 4, 2}, ///< normal
2944 {256 / 4, 256 / 2, 256 / 4, 2}, ///< monorail
2945 {0, 256 / 2, 256 / 4, 2}, ///< maglev
2949 * Modify the speed of the vehicle due to a change in altitude.
2950 * @param v %Train to update.
2951 * @param old_z Previous height.
2953 static inline void AffectSpeedByZChange(Train *v, int old_z)
2955 if (old_z == v->z_pos || _settings_game.vehicle.train_acceleration_model != AM_ORIGINAL) return;
2957 const AccelerationSlowdownParams *asp = &_accel_slowdown[GetRailTypeInfo(v->railtype)->acceleration_type];
2959 if (old_z < v->z_pos) {
2960 v->cur_speed -= (v->cur_speed * asp->z_up >> 8);
2961 } else {
2962 uint16 spd = v->cur_speed + asp->z_down;
2963 if (spd <= v->gcache.cached_max_track_speed) v->cur_speed = spd;
2967 /** Tries to reserve track under whole train consist. */
2968 void Train::ReserveTrackUnderConsist() const
2970 for (const Train *u = this; u != NULL; u = u->Next()) {
2971 switch (u->trackdir) {
2972 case TRACKDIR_WORMHOLE:
2973 if (IsRailwayTile(u->tile)) {
2974 SetBridgeMiddleReservation(u->tile, true);
2975 SetBridgeMiddleReservation(GetOtherBridgeEnd(u->tile), true);
2976 } else {
2977 SetTunnelMiddleReservation(u->tile, true);
2978 SetTunnelMiddleReservation(GetOtherTunnelEnd(u->tile), true);
2980 break;
2981 case TRACKDIR_DEPOT:
2982 break;
2983 default:
2984 TryReserveRailTrack(u->tile, TrackdirToTrack(u->trackdir));
2985 break;
2991 * The train vehicle crashed!
2992 * Update its status and other parts around it.
2993 * @param flooded Crash was caused by flooding.
2994 * @return Number of people killed.
2996 uint Train::Crash(bool flooded)
2998 uint pass = 0;
2999 if (this->IsFrontEngine()) {
3000 pass += 2; // driver
3002 /* Remove the reserved path in front of the train if it is not stuck.
3003 * Also clear all reserved tracks the train is currently on. */
3004 if (!HasBit(this->flags, VRF_TRAIN_STUCK)) FreeTrainTrackReservation(this);
3005 for (const Train *v = this; v != NULL; v = v->Next()) {
3006 ClearPathReservation(v, v->GetPos());
3009 /* we may need to update crossing we were approaching,
3010 * but must be updated after the train has been marked crashed */
3011 TileIndex crossing = TrainApproachingCrossingTile(this);
3012 if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
3014 /* Remove the loading indicators (if any) */
3015 HideFillingPercent(&this->fill_percent_te_id);
3018 pass += this->GroundVehicleBase::Crash(flooded);
3020 this->crash_anim_pos = flooded ? 4000 : 1; // max 4440, disappear pretty fast when flooded
3021 return pass;
3025 * Marks train as crashed and creates an AI event.
3026 * Doesn't do anything if the train is crashed already.
3027 * @param v first vehicle of chain
3028 * @return number of victims (including 2 drivers; zero if train was already crashed)
3030 static uint TrainCrashed(Train *v)
3032 uint num = 0;
3034 /* do not crash train twice */
3035 if (!(v->vehstatus & VS_CRASHED)) {
3036 num = v->Crash();
3037 AI::NewEvent(v->owner, new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_TRAIN));
3038 Game::NewEvent(new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_TRAIN));
3041 /* Try to re-reserve track under already crashed train too.
3042 * Crash() clears the reservation! */
3043 v->ReserveTrackUnderConsist();
3045 return num;
3049 * Collision test function.
3050 * @param tcc %Train being examined.
3051 * @param v %Train vehicle to test collision with.
3052 * @return Total number of victims if train collided, else 0.
3054 static uint FindTrainCollision(Train *tcc, Vehicle *v)
3056 /* not a train or in depot */
3057 if (v->type != VEH_TRAIN || Train::From(v)->trackdir == TRACKDIR_DEPOT) return 0;
3059 /* do not crash into trains of another company. */
3060 if (v->owner != tcc->owner) return 0;
3062 /* get first vehicle now to make most usual checks faster */
3063 Train *coll = Train::From(v)->First();
3065 /* can't collide with own wagons */
3066 if (coll == tcc) return 0;
3068 int x_diff = v->x_pos - tcc->x_pos;
3069 int y_diff = v->y_pos - tcc->y_pos;
3071 /* Do fast calculation to check whether trains are not in close vicinity
3072 * and quickly reject trains distant enough for any collision.
3073 * Differences are shifted by 7, mapping range [-7 .. 8] into [0 .. 15]
3074 * Differences are then ORed and then we check for any higher bits */
3075 uint hash = (y_diff + 7) | (x_diff + 7);
3076 if (hash & ~15) return 0;
3078 /* Slower check using multiplication */
3079 int min_diff = (Train::From(v)->gcache.cached_veh_length + 1) / 2 + (tcc->gcache.cached_veh_length + 1) / 2 - 1;
3080 if (x_diff * x_diff + y_diff * y_diff > min_diff * min_diff) return 0;
3082 /* Happens when there is a train under bridge next to bridge head */
3083 if (abs(v->z_pos - tcc->z_pos) > 5) return 0;
3085 /* crash both trains */
3086 return TrainCrashed(tcc) + TrainCrashed(coll);
3089 /** Temporary data storage for testing collisions. */
3090 struct TrainCollideChecker {
3091 Train *v; ///< %Vehicle we are testing for collision.
3092 uint num; ///< Total number of victims if train collided.
3096 * Collision test function.
3097 * @param v %Train vehicle to test collision with.
3098 * @param data %Train being examined.
3099 * @return \c NULL (always continue search)
3101 static Vehicle *FindTrainCollideEnum(Vehicle *v, void *data)
3103 TrainCollideChecker *tcc = (TrainCollideChecker*)data;
3105 tcc->num += FindTrainCollision (tcc->v, v);
3107 return NULL;
3111 * Checks whether the specified train has a collision with another vehicle. If
3112 * so, destroys this vehicle, and the other vehicle if its subtype has TS_Front.
3113 * Reports the incident in a flashy news item, modifies station ratings and
3114 * plays a sound.
3115 * @param v %Train to test.
3117 static bool CheckTrainCollision(Train *v)
3119 /* can't collide in depot */
3120 if (v->trackdir == TRACKDIR_DEPOT) return false;
3122 assert(v->trackdir == TRACKDIR_WORMHOLE || TileVirtXY(v->x_pos, v->y_pos) == v->tile);
3124 TrainCollideChecker tcc;
3125 tcc.v = v;
3126 tcc.num = 0;
3128 /* find colliding vehicles */
3129 if (v->trackdir == TRACKDIR_WORMHOLE) {
3130 VehicleTileIterator iter1 (v->tile);
3131 while (!iter1.finished()) {
3132 tcc.num += FindTrainCollision (v, iter1.next());
3134 VehicleTileIterator iter2 (GetOtherTunnelBridgeEnd(v->tile));
3135 while (!iter2.finished()) {
3136 tcc.num += FindTrainCollision (v, iter2.next());
3138 } else {
3139 FindVehicleOnPosXY(v->x_pos, v->y_pos, &tcc, FindTrainCollideEnum);
3142 /* any dead -> no crash */
3143 if (tcc.num == 0) return false;
3145 SetDParam(0, tcc.num);
3146 AddVehicleNewsItem(STR_NEWS_TRAIN_CRASH, NT_ACCIDENT, v->index);
3148 ModifyStationRatingAround(v->tile, v->owner, -160, 30);
3149 if (_settings_client.sound.disaster) SndPlayVehicleFx(SND_13_BIG_CRASH, v);
3150 return true;
3155 * Tile callback routine when vehicle enters a track tile
3156 * @see vehicle_enter_tile_proc
3158 static void TrainEnter_Track(Train *v, TileIndex tile, int x, int y)
3160 if (IsTileSubtype(tile, TT_TRACK)) return;
3162 assert(abs((int)(GetSlopePixelZ(x, y) - v->z_pos)) < 3);
3164 /* modify speed of vehicle */
3165 uint16 spd = GetBridgeSpec(GetRailBridgeType(tile))->speed;
3166 Vehicle *first = v->First();
3167 first->cur_speed = min(first->cur_speed, spd);
3171 * Frame when the 'enter tunnel' sound should be played. This is the second
3172 * frame on a tile, so the sound is played shortly after entering the tunnel
3173 * tile, while the vehicle is still visible.
3175 static const byte TUNNEL_SOUND_FRAME = 1;
3177 extern const byte _tunnel_visibility_frame[DIAGDIR_END];
3180 * Compute number of ticks when next wagon will leave a depot.
3181 * Negative means next wagon should have left depot n ticks before.
3182 * @param v vehicle outside (leaving) the depot
3183 * @return number of ticks when the next wagon will leave
3185 int TicksToLeaveDepot(const Train *v)
3187 DiagDirection dir = GetGroundDepotDirection(v->tile);
3188 int length = v->CalcNextVehicleOffset();
3190 switch (dir) {
3191 case DIAGDIR_NE: return ((int)(v->x_pos & 0x0F) - (_vehicle_initial_x_fract[dir] - (length + 1)));
3192 case DIAGDIR_SE: return -((int)(v->y_pos & 0x0F) - (_vehicle_initial_y_fract[dir] + (length + 1)));
3193 case DIAGDIR_SW: return -((int)(v->x_pos & 0x0F) - (_vehicle_initial_x_fract[dir] + (length + 1)));
3194 default:
3195 case DIAGDIR_NW: return ((int)(v->y_pos & 0x0F) - (_vehicle_initial_y_fract[dir] - (length + 1)));
3198 return 0; // make compilers happy
3201 static void TrainEnter_Misc(Train *u, TileIndex tile, int x, int y)
3203 switch (GetTileSubtype(tile)) {
3204 default: break;
3206 case TT_MISC_TUNNEL: {
3207 assert(abs((int)GetSlopePixelZ(x, y) - u->z_pos) < 3);
3209 /* Direction into the wormhole */
3210 const DiagDirection dir = GetTunnelBridgeDirection(tile);
3212 if (u->direction == DiagDirToDir(dir)) {
3213 uint frame = DistanceFromTileEdge(ReverseDiagDir(dir), x & 0xF, y & 0xF);
3214 if (u->IsFrontEngine() && frame == TUNNEL_SOUND_FRAME) {
3215 if (!PlayVehicleSound(u, VSE_TUNNEL) && RailVehInfo(u->engine_type)->engclass == 0) {
3216 SndPlayVehicleFx(SND_05_TRAIN_THROUGH_TUNNEL, u);
3219 if (frame == _tunnel_visibility_frame[dir]) {
3220 u->vehstatus |= VS_HIDDEN;
3222 } else if (u->direction == ReverseDir(DiagDirToDir(dir))) {
3223 uint frame = DistanceFromTileEdge(dir, x & 0xF, y & 0xF);
3224 if (frame == TILE_SIZE - _tunnel_visibility_frame[dir]) {
3225 u->vehstatus &= ~VS_HIDDEN;
3229 break;
3232 case TT_MISC_DEPOT: {
3233 if (!IsRailDepot(tile)) break;
3235 /* depot direction */
3236 DiagDirection dir = GetGroundDepotDirection(tile);
3238 /* make sure a train is not entering the tile from behind */
3239 assert(DistanceFromTileEdge(ReverseDiagDir(dir), x & 0xF, y & 0xF) != 0);
3241 int fract_x = (int)(x & 0xF) - _vehicle_initial_x_fract[dir];
3242 int fract_y = (int)(y & 0xF) - _vehicle_initial_y_fract[dir];
3244 if (u->direction == DiagDirToDir(ReverseDiagDir(dir))) {
3245 if (fract_x == 0 && fract_y == 0) {
3246 /* enter the depot */
3247 u->trackdir = TRACKDIR_DEPOT,
3248 u->vehstatus |= VS_HIDDEN; // hide it
3249 u->direction = ReverseDir(u->direction);
3250 if (u->Next() == NULL) VehicleEnterDepot(u->First());
3251 u->tile = tile;
3253 InvalidateWindowData(WC_VEHICLE_DEPOT, u->tile);
3255 } else if (u->direction == DiagDirToDir(dir)) {
3256 static const int8 delta_x[4] = { -1, 0, 1, 0 };
3257 static const int8 delta_y[4] = { 0, 1, 0, -1 };
3259 /* Calculate the point where the following wagon should be activated. */
3260 int length = u->CalcNextVehicleOffset() + 1;
3262 if ((fract_x == length * delta_x[dir]) && (fract_y == length * delta_y[dir])) {
3263 /* leave the depot? */
3264 if ((u = u->Next()) != NULL) {
3265 u->vehstatus &= ~VS_HIDDEN;
3266 u->trackdir = DiagDirToDiagTrackdir(dir);
3271 break;
3276 static StationID TrainEnter_Station(Train *v, TileIndex tile, int x, int y)
3278 StationID station_id = GetStationIndex(tile);
3279 if (!v->current_order.ShouldStopAtStation(v, station_id)) return INVALID_STATION;
3280 if (!IsRailStation(tile) || !v->IsFrontEngine()) return INVALID_STATION;
3282 int station_ahead;
3283 int station_length;
3284 int stop = GetTrainStopLocation(station_id, tile, Train::From(v), &station_ahead, &station_length);
3286 /* Stop whenever that amount of station ahead + the distance from the
3287 * begin of the platform to the stop location is longer than the length
3288 * of the platform. Station ahead 'includes' the current tile where the
3289 * vehicle is on, so we need to subtract that. */
3290 if (stop + station_ahead - (int)TILE_SIZE >= station_length) return INVALID_STATION;
3292 DiagDirection dir = DirToDiagDir(v->direction);
3294 x &= 0xF;
3295 y &= 0xF;
3297 if (DiagDirToAxis(dir) != AXIS_X) Swap(x, y);
3298 if (y == TILE_SIZE / 2) {
3299 if (dir != DIAGDIR_SE && dir != DIAGDIR_SW) x = TILE_SIZE - 1 - x;
3300 stop &= TILE_SIZE - 1;
3302 if (x == stop) {
3303 return station_id; // enter station
3304 } else if (x < stop) {
3305 v->vehstatus |= VS_TRAIN_SLOWING;
3306 uint16 spd = max(0, (stop - x) * 20 - 15);
3307 if (spd < v->cur_speed) v->cur_speed = spd;
3311 return INVALID_STATION;
3315 * Call the tile callback function for a train entering a tile
3316 * @param v Train entering the tile
3317 * @param tile Tile entered
3318 * @param x X position
3319 * @param y Y position
3320 * @return Station ID of an entered station, or INVALID_STATION otherwise
3322 static StationID TrainEnterTile(Train *v, TileIndex tile, int x, int y)
3324 switch (GetTileType(tile)) {
3325 default: NOT_REACHED();
3327 case TT_RAILWAY:
3328 TrainEnter_Track(v, tile, x, y);
3329 break;
3331 case TT_MISC:
3332 TrainEnter_Misc(v, tile, x, y);
3333 break;
3335 case TT_STATION:
3336 return TrainEnter_Station(v, tile, x, y);
3339 return INVALID_STATION;
3343 * Choose the trackdir to follow when a train enters a new tile.
3344 * @param v The train that enters the tile
3345 * @param tile The tile entered
3346 * @param enterdir The direction the train is moving between tiles
3347 * @param tsdir The direction to use for GetTileRailwayStatus
3348 * @param check_90deg Check for 90-degree turns and disallow them
3349 * @param reverse Set to false to not execute the vehicle reversing. This does not change any other logic.
3350 * @return The trackdir to use, or INVALID_TRACKDIR if the train cannot go forward
3352 static Trackdir TrainControllerChooseTrackdir(Train *v, TileIndex tile, DiagDirection enterdir, DiagDirection tsdir, bool check_90deg, bool reverse)
3354 /* Get the status of the tracks in the new tile and mask
3355 * away the bits that aren't reachable. */
3356 TrackStatus ts = GetTileRailwayStatus(tile, tsdir);
3357 TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(enterdir);
3359 TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
3360 if (check_90deg) trackdirbits &= ~TrackdirCrossesTrackdirs(v->trackdir);
3362 TrackdirBits red_signals = TrackStatusToRedSignals(ts);
3364 /* Check if the new tile constrains tracks that are compatible
3365 * with the current train, if not, bail out. */
3366 if (trackdirbits == TRACKDIR_BIT_NONE || !CheckCompatibleRail(v, tile, TrackdirToTrack(FindFirstTrackdir(trackdirbits)))) {
3367 if (reverse) {
3368 v->wait_counter = 0;
3369 v->cur_speed = 0;
3370 v->subspeed = 0;
3371 ReverseTrainDirection(v);
3374 return INVALID_TRACKDIR;
3377 Trackdir chosen_trackdir;
3379 /* Don't use trackdirbits here as the setting to forbid 90 deg turns might have been switched between reservation and now. */
3380 TrackdirBits res_trackdirs = TrackBitsToTrackdirBits(GetReservedTrackbits(tile)) & reachable_trackdirs;
3381 /* Do we have a suitable reserved trackdir? */
3382 if (res_trackdirs != TRACKDIR_BIT_NONE) {
3383 chosen_trackdir = FindFirstTrackdir(res_trackdirs);
3384 } else {
3385 if (!ChooseTrainTrack(v, v->GetPos(), tile, trackdirbits, false, &chosen_trackdir)) {
3386 MarkTrainAsStuck(v);
3388 assert(chosen_trackdir != INVALID_TRACKDIR);
3389 assert(HasBit(trackdirbits, chosen_trackdir));
3392 /* Make sure chosen trackdir is a valid trackdir */
3393 assert(IsValidTrackdir(chosen_trackdir));
3395 if (v->force_proceed != TFP_NONE) {
3396 /* For each signal we find decrease the counter by one.
3397 * We start at two, so the first signal we pass decreases
3398 * this to one, then if we reach the next signal it is
3399 * decreased to zero and we won't pass that new signal. */
3400 bool at_signal;
3401 if (IsRailwayTile(tile)) {
3402 Track track = TrackdirToTrack(chosen_trackdir);
3403 /* However, we do not want to be stopped by PBS
3404 * signals entered via the back. */
3405 at_signal = HasSignalOnTrack(tile, track) &&
3406 (GetSignalType(tile, track) != SIGTYPE_PBS ||
3407 HasSignalOnTrackdir(tile, chosen_trackdir));
3408 } else if (maptile_is_rail_tunnel(tile)) {
3409 at_signal = maptile_has_tunnel_signals(tile);
3410 } else {
3411 at_signal = false;
3414 if (at_signal) {
3415 v->force_proceed = (v->force_proceed == TFP_SIGNAL) ? TFP_STUCK : TFP_NONE;
3416 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
3420 /* Check if it's a red signal and if force proceed is clicked. */
3421 if (!HasBit(red_signals, chosen_trackdir) || v->force_proceed != TFP_NONE) {
3422 /* Proceed */
3423 TryReserveRailTrack(tile, TrackdirToTrack(chosen_trackdir), false);
3424 return chosen_trackdir;
3427 /* In front of a red signal */
3428 assert(trackdirbits == TrackdirToTrackdirBits(chosen_trackdir));
3430 /* Don't handle stuck trains here. */
3431 if (HasBit(v->flags, VRF_TRAIN_STUCK)) return INVALID_TRACKDIR;
3433 if (!HasSignalOnTrackdir(tile, ReverseTrackdir(chosen_trackdir))) {
3434 v->cur_speed = 0;
3435 v->subspeed = 0;
3436 v->progress = 255 - 100;
3437 if (!_settings_game.pf.reverse_at_signals || ++v->wait_counter < _settings_game.pf.wait_oneway_signal * 20) return INVALID_TRACKDIR;
3438 } else if (HasSignalOnTrackdir(tile, chosen_trackdir)) {
3439 v->cur_speed = 0;
3440 v->subspeed = 0;
3441 v->progress = 255 - 10;
3442 if (!_settings_game.pf.reverse_at_signals || ++v->wait_counter < _settings_game.pf.wait_twoway_signal * 73) {
3443 DiagDirection exitdir = TrackdirToExitdir(chosen_trackdir);
3444 TileIndex o_tile = TileAddByDiagDir(tile, exitdir);
3446 exitdir = ReverseDiagDir(exitdir);
3448 /* check if a train is waiting on the other side */
3449 VehicleTileFinder iter (o_tile);
3450 while (!iter.finished()) {
3451 Vehicle *v = iter.next();
3452 if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) continue;
3454 Train *t = Train::From(v);
3455 if (t->IsFrontEngine() && (t->trackdir < TRACKDIR_END) && (t->cur_speed <= 5) && TrackdirToExitdir(t->trackdir) == exitdir) {
3456 iter.set_found();
3459 if (!iter.was_found()) return INVALID_TRACKDIR;
3463 /* If we would reverse but are currently in a PBS block and
3464 * reversing of stuck trains is disabled, don't reverse.
3465 * This does not apply if the reason for reversing is a one-way
3466 * signal blocking us, because a train would then be stuck forever. */
3467 if (!_settings_game.pf.reverse_at_signals && !HasOnewaySignalBlockingTrackdir(tile, chosen_trackdir)) {
3468 assert(IsSignalBufferEmpty());
3469 AddPosToSignalBuffer(v->GetPos(), v->owner);
3470 if (UpdateSignalsInBuffer() == SIGSEG_PBS) {
3471 v->wait_counter = 0;
3472 return INVALID_TRACKDIR;
3476 if (reverse) {
3477 v->wait_counter = 0;
3478 v->cur_speed = 0;
3479 v->subspeed = 0;
3480 ReverseTrainDirection(v);
3483 return INVALID_TRACKDIR;
3487 * Move a vehicle chain one movement stop forwards.
3488 * @param v First vehicle to move.
3489 * @param nomove Stop moving this and all following vehicles.
3490 * @param reverse Set to false to not execute the vehicle reversing. This does not change any other logic.
3491 * @return True if the vehicle could be moved forward, false otherwise.
3493 bool TrainController(Train *v, Vehicle *nomove, bool reverse)
3495 Train *first = v->First();
3496 Train *prev;
3497 bool direction_changed = false; // has direction of any part changed?
3499 /* For every vehicle after and including the given vehicle */
3500 for (prev = v->Previous(); v != nomove; prev = v, v = v->Next()) {
3501 TileIndex old_tile; // old virtual tile
3502 bool old_in_wormhole, new_in_wormhole; // old position was in wormhole, new position is in wormhole
3503 DiagDirection enterdir = INVALID_DIAGDIR; // direction into the new tile, or INVALID_DIAGDIR if we stay on the old tile
3504 DiagDirection tsdir = INVALID_DIAGDIR; // direction to use for GetTileRailwayStatus, only when moving into a new tile
3506 VehiclePos gp = GetNewVehiclePos(v);
3507 if (v->trackdir == TRACKDIR_WORMHOLE) {
3508 /* In a tunnel or on a bridge (middle part) */
3509 old_tile = TileVirtXY(v->x_pos, v->y_pos);
3510 old_in_wormhole = true;
3512 if (gp.new_tile != v->tile) {
3513 /* Still in the wormhole */
3514 new_in_wormhole = true;
3515 if (v->IsFrontEngine() && (v->vehstatus & VS_HIDDEN) && maptile_has_tunnel_signal(v->tile, false) && (FindTunnelPrevTrain(v) < TILE_SIZE)) {
3516 /* too close to train ahead, stop */
3517 return false;
3519 } else {
3520 new_in_wormhole = false;
3521 enterdir = ReverseDiagDir(GetTunnelBridgeDirection(gp.new_tile));
3522 tsdir = INVALID_DIAGDIR;
3524 } else if (v->trackdir == TRACKDIR_DEPOT) {
3525 /* Inside depot */
3526 assert(gp.new_tile == v->tile);
3527 continue;
3528 } else if (gp.new_tile == v->tile) {
3529 /* Not inside tunnel or depot, staying in the old tile */
3530 old_tile = v->tile;
3531 old_in_wormhole = false;
3532 new_in_wormhole = false;
3533 } else {
3534 /* Not inside tunnel or depot, about to enter a new tile */
3535 old_tile = v->tile;
3536 old_in_wormhole = false;
3538 /* Determine what direction we're entering the new tile from */
3539 enterdir = DiagdirBetweenTiles(v->tile, gp.new_tile);
3540 assert(IsValidDiagDirection(enterdir));
3542 if (IsTunnelTile(v->tile) && GetTunnelBridgeDirection(v->tile) == enterdir) {
3543 TileIndex end_tile = GetOtherTunnelEnd(v->tile);
3544 if (end_tile != gp.new_tile) {
3545 /* Entering a tunnel */
3546 new_in_wormhole = true;
3547 gp.new_tile = end_tile;
3548 } else {
3549 new_in_wormhole = false;
3550 tsdir = INVALID_DIAGDIR;
3552 } else if (IsRailBridgeTile(v->tile) && GetTunnelBridgeDirection(v->tile) == enterdir) {
3553 TileIndex end_tile = GetOtherBridgeEnd(v->tile);
3554 if (end_tile != gp.new_tile) {
3555 /* Entering a bridge */
3556 new_in_wormhole = true;
3557 gp.new_tile = end_tile;
3558 ClrBit(v->gv_flags, GVF_GOINGUP_BIT);
3559 ClrBit(v->gv_flags, GVF_GOINGDOWN_BIT);
3561 first->cur_speed = min(first->cur_speed, GetBridgeSpec(GetRailBridgeType(v->tile))->speed);
3562 } else {
3563 new_in_wormhole = false;
3564 tsdir = INVALID_DIAGDIR;
3566 } else {
3567 new_in_wormhole = false;
3568 tsdir = ReverseDiagDir(enterdir);
3572 if (enterdir == INVALID_DIAGDIR) {
3573 /* Staying on the same tile */
3575 /* Reverse when we are at the end of the track already, do not move to the new position */
3576 if (!new_in_wormhole && v->IsFrontEngine() && !TrainCheckIfLineEnds(v, reverse)) return false;
3577 } else {
3578 /* Entering a new tile */
3580 Trackdir chosen_trackdir;
3581 if (!new_in_wormhole) {
3582 if (prev == NULL) {
3583 /* Currently the locomotive is active. Determine which one of the
3584 * available tracks to choose */
3585 chosen_trackdir = TrainControllerChooseTrackdir(v, gp.new_tile, enterdir, tsdir, !old_in_wormhole && _settings_game.pf.forbid_90_deg, reverse);
3586 if (chosen_trackdir == INVALID_TRACKDIR) return false;
3588 if (HasPbsSignalOnTrackdir(gp.new_tile, chosen_trackdir)) {
3589 SetSignalState(gp.new_tile, chosen_trackdir, SIGNAL_STATE_RED);
3590 MarkTileDirtyByTile(gp.new_tile);
3592 } else {
3593 /* The wagon is active, simply follow the prev vehicle. */
3594 if (prev->tile == gp.new_tile) {
3595 /* Choose the same track as prev */
3596 assert(prev->trackdir != TRACKDIR_WORMHOLE);
3597 chosen_trackdir = prev->trackdir;
3598 } else {
3599 /* Choose the track that leads to the tile where prev is.
3600 * This case is active if 'prev' is already on the second next tile, when 'v' just enters the next tile.
3601 * I.e. when the tile between them has only space for a single vehicle like
3602 * 1) horizontal/vertical track tiles and
3603 * 2) some orientations of tunnel entries, where the vehicle is already inside the wormhole at 8/16 from the tile edge.
3604 * Is also the train just reversing, the wagon inside the tunnel is 'on' the tile of the opposite tunnel entry.
3606 DiagDirection exitdir = DiagdirBetweenTiles(gp.new_tile, prev->tile);
3607 assert(IsValidDiagDirection(exitdir));
3608 chosen_trackdir = EnterdirExitdirToTrackdir(enterdir, exitdir);
3609 assert(!IsReversingRoadTrackdir(chosen_trackdir));
3612 assert(CheckCompatibleRail(v, gp.new_tile, TrackdirToTrack(chosen_trackdir)));
3614 } else {
3615 /* new_in_wormhole */
3616 assert(!old_in_wormhole);
3617 if (prev == NULL) {
3618 if (IsRailwayTile(old_tile)) {
3619 SetBridgeMiddleReservation(old_tile, true);
3620 SetBridgeMiddleReservation(gp.new_tile, true);
3621 } else {
3622 SetTunnelMiddleReservation(old_tile, true);
3623 SetTunnelMiddleReservation(gp.new_tile, true);
3628 if (v->Next() == NULL) {
3629 /* Clear any track reservation when the last vehicle leaves the tile */
3630 ClearPathReservation(v, v->GetPos());
3632 RailPathPos rev = v->GetReversePos();
3633 if (HasSignalOnPos(rev)) {
3634 assert(IsSignalBufferEmpty());
3635 AddPosToSignalBuffer(rev, v->owner);
3636 /* Defer actual updating of signals until the train has moved */
3640 if (new_in_wormhole) {
3641 /* Just entered the wormhole */
3642 v->tile = gp.new_tile;
3643 v->trackdir = TRACKDIR_WORMHOLE;
3644 } else {
3645 RailType old_rt = v->GetTrackRailType();
3647 v->tile = gp.new_tile;
3648 v->trackdir = chosen_trackdir;
3650 if (GetRailType(gp.new_tile, TrackdirToTrack(chosen_trackdir)) != old_rt) {
3651 v->First()->ConsistChanged(CCF_TRACK);
3655 Direction chosen_dir;
3656 if (new_in_wormhole) {
3657 chosen_dir = DiagDirToDir(enterdir);
3658 } else {
3659 /* Update XY to reflect the entrance to the new tile, and select the direction to use */
3660 const byte *b = _initial_tile_subcoord[chosen_trackdir];
3661 gp.x = (gp.x & ~0xF) | b[0];
3662 gp.y = (gp.y & ~0xF) | b[1];
3663 chosen_dir = (Direction)b[2];
3666 if (chosen_dir != v->direction) {
3667 if (prev == NULL && _settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) {
3668 const AccelerationSlowdownParams *asp = &_accel_slowdown[GetRailTypeInfo(v->railtype)->acceleration_type];
3669 DirDiff diff = DirDifference(v->direction, chosen_dir);
3670 v->cur_speed -= (diff == DIRDIFF_45RIGHT || diff == DIRDIFF_45LEFT ? asp->small_turn : asp->large_turn) * v->cur_speed >> 8;
3672 direction_changed = true;
3673 v->direction = chosen_dir;
3676 /* update image of train, as well as delta XY */
3677 v->UpdateDeltaXY(v->direction);
3680 if (!new_in_wormhole) {
3681 /* Call the landscape function and tell it that the vehicle entered the tile */
3682 StationID sid = TrainEnterTile(v, gp.new_tile, gp.x, gp.y);
3683 if (sid != INVALID_STATION) {
3684 /* The new position is the location where we want to stop */
3685 TrainEnterStation(v, sid);
3689 if (v->IsFrontEngine()) {
3690 v->wait_counter = 0;
3692 /* Always try to extend the reservation when entering a tile. */
3693 bool check_next_tile;
3694 if (!new_in_wormhole) {
3695 /* If we are approaching a crossing that is reserved, play the sound now. */
3696 TileIndex crossing = TrainApproachingCrossingTile(v);
3697 if (crossing != INVALID_TILE && HasCrossingReservation(crossing) && _settings_client.sound.ambient) SndPlayTileFx(SND_0E_LEVEL_CROSSING, crossing);
3699 check_next_tile = enterdir != INVALID_DIAGDIR;
3700 } else if (old_in_wormhole) {
3701 TileIndex last_wormhole_tile = TileAddByDiagDir(v->tile, GetTunnelBridgeDirection(v->tile));
3702 check_next_tile = (gp.new_tile == last_wormhole_tile) && (gp.new_tile != old_tile);
3703 } else {
3704 TileIndexDiff diff = TileOffsByDiagDir(GetTunnelBridgeDirection(v->tile));
3705 check_next_tile = (old_tile == TILE_ADD(v->tile, 2*diff));
3708 if (check_next_tile) CheckNextTrainTile(v);
3711 v->x_pos = gp.x;
3712 v->y_pos = gp.y;
3713 VehicleUpdatePosition(v);
3715 if (new_in_wormhole) {
3716 if ((v->vehstatus & VS_HIDDEN) == 0) VehicleUpdateViewport(v, true);
3717 } else {
3718 /* update the Z position of the vehicle */
3719 int old_z = v->UpdateInclination(enterdir != INVALID_DIAGDIR, false);
3721 if (prev == NULL) {
3722 /* This is the first vehicle in the train */
3723 AffectSpeedByZChange(v, old_z);
3727 if (enterdir != INVALID_DIAGDIR) {
3728 /* Update signals or crossing state if we changed tile */
3729 /* Signals can only change when the first or the last vehicle moves. */
3730 if (v->Next() == NULL) {
3731 /* Update the signal segment added before, if any */
3732 UpdateSignalsInBuffer();
3733 if (!old_in_wormhole && IsLevelCrossingTile(old_tile)) UpdateLevelCrossing(old_tile);
3736 if (v->IsFrontEngine()) {
3737 RailPathPos pos = v->GetPos();
3738 if (HasSignalOnPos(pos)) {
3739 assert(IsSignalBufferEmpty());
3740 AddPosToSignalBuffer(pos, v->owner);
3742 if (UpdateSignalsInBuffer() == SIGSEG_PBS &&
3743 HasSignalAlongPos(pos) &&
3744 /* A PBS block with a non-PBS signal facing us? */
3745 !IsPbsSignal(GetSignalType(pos))) {
3746 /* We are entering a block with PBS signals right now, but
3747 * not through a PBS signal. This means we don't have a
3748 * reservation right now. As a conventional signal will only
3749 * ever be green if no other train is in the block, getting
3750 * a path should always be possible. If the player built
3751 * such a strange network that it is not possible, the train
3752 * will be marked as stuck and the player has to deal with
3753 * the problem. */
3754 TryReserveRailTrack(pos);
3755 /* Signals cannot be built on junctions, so
3756 * a track on which there is a signal either
3757 * is already reserved or can be reserved. */
3758 assert (HasReservedPos(pos));
3759 if (!TryPathReserve(v)) {
3760 MarkTrainAsStuck(v);
3767 if (old_in_wormhole && old_tile != gp.new_tile && v->Next() == NULL && maptile_is_rail_tunnel(v->tile) && maptile_has_tunnel_signal(v->tile, false)
3768 && TileAddByDiagDir(old_tile, GetTunnelBridgeDirection(v->tile)) == GetOtherTunnelEnd(v->tile)) {
3769 AddTunnelToSignalBuffer(v->tile, v->owner);
3770 UpdateSignalsInBuffer();
3773 /* Do not check on every tick to save some computing time. */
3774 if (v->IsFrontEngine() && v->tick_counter % _settings_game.pf.path_backoff_interval == 0) {
3775 CheckNextTrainTile(v);
3779 if (direction_changed) first->tcache.cached_max_curve_speed = first->GetCurveSpeedLimit();
3781 return true;
3786 * Deletes/Clears the last wagon of a crashed train. It takes the engine of the
3787 * train, then goes to the last wagon and deletes that. Each call to this function
3788 * will remove the last wagon of a crashed train. If this wagon was on a crossing,
3789 * or inside a tunnel/bridge, recalculate the signals as they might need updating
3790 * @param v the Vehicle of which last wagon is to be removed
3792 static void DeleteLastWagon(Train *v)
3794 Train *first = v->First();
3796 /* Go to the last wagon and delete the link pointing there
3797 * *u is then the one-before-last wagon, and *v the last
3798 * one which will physically be removed */
3799 Train *u = v;
3800 for (; v->Next() != NULL; v = v->Next()) u = v;
3801 u->SetNext(NULL);
3803 if (first != v) {
3804 /* Recalculate cached train properties */
3805 first->ConsistChanged(CCF_ARRANGE);
3806 /* Update the depot window if the first vehicle is in depot -
3807 * if v == first, then it is updated in PreDestructor() */
3808 if (first->trackdir == TRACKDIR_DEPOT) {
3809 SetWindowDirty(WC_VEHICLE_DEPOT, first->tile);
3811 v->last_station_visited = first->last_station_visited; // for PreDestructor
3814 /* 'v' shouldn't be accessed after it has been deleted */
3815 Trackdir trackdir = v->trackdir;
3816 TileIndex tile = v->tile;
3817 Owner owner = v->owner;
3819 delete v;
3820 v = NULL; // make sure nobody will try to read 'v' anymore
3822 if (trackdir == TRACKDIR_DEPOT) return;
3824 if (trackdir == TRACKDIR_WORMHOLE) {
3825 TileIndex endtile = GetOtherTunnelBridgeEnd(tile);
3826 if (EnsureNoTrainOnTunnelBridgeMiddle(tile, endtile).Succeeded()) {
3827 if (IsRailwayTile(tile)) {
3828 SetBridgeMiddleReservation(tile, false);
3829 SetBridgeMiddleReservation(endtile, false);
3830 } else {
3831 SetTunnelMiddleReservation(tile, false);
3832 SetTunnelMiddleReservation(endtile, false);
3836 assert(IsSignalBufferEmpty());
3837 if (IsRailwayTile(tile)) {
3838 AddBridgeToSignalBuffer(tile, owner);
3839 } else {
3840 AddTunnelToSignalBuffer(tile, owner);
3842 UpdateSignalsInBuffer();
3843 return;
3846 Track track = TrackdirToTrack(trackdir);
3847 if (HasReservedTrack(tile, track)) {
3848 UnreserveRailTrack(tile, track);
3850 /* If there are still crashed vehicles on the tile, give the track reservation to them */
3851 TrackBits remaining_trackbits = TRACK_BIT_NONE;
3852 VehicleTileIterator iter (tile);
3853 while (!iter.finished()) {
3854 Vehicle *v = iter.next();
3855 if (v->type == VEH_TRAIN && (v->vehstatus & VS_CRASHED) != 0) {
3856 Trackdir trackdir = Train::From(v)->trackdir;
3857 if (trackdir == TRACKDIR_WORMHOLE) {
3858 /* Vehicle is inside a wormhole, v->trackdir contains no useful value then. */
3859 remaining_trackbits |= DiagDirToDiagTrackBits(GetTunnelBridgeDirection(v->tile));
3860 } else if (trackdir != TRACKDIR_DEPOT) {
3861 remaining_trackbits |= TrackToTrackBits(TrackdirToTrack(trackdir));
3866 /* It is important that these two are the first in the loop, as reservation cannot deal with every trackbit combination */
3867 assert(TRACK_BEGIN == TRACK_X && TRACK_Y == TRACK_BEGIN + 1);
3868 Track t;
3869 FOR_EACH_SET_TRACK(t, remaining_trackbits) TryReserveRailTrack(tile, t);
3872 /* check if the wagon was on a road/rail-crossing */
3873 if (IsLevelCrossingTile(tile)) UpdateLevelCrossing(tile);
3875 /* Update signals */
3876 assert(IsSignalBufferEmpty());
3877 if (IsRailDepotTile(tile)) {
3878 AddDepotToSignalBuffer(tile, owner);
3879 } else if (IsTunnelTile(tile)) {
3880 AddTunnelToSignalBuffer(tile, owner);
3881 } else {
3882 AddTrackToSignalBuffer(tile, track, owner);
3884 UpdateSignalsInBuffer();
3888 * Rotate all vehicles of a (crashed) train chain randomly to animate the crash.
3889 * @param v First crashed vehicle.
3891 static void ChangeTrainDirRandomly(Train *v)
3893 static const DirDiff delta[] = {
3894 DIRDIFF_45LEFT, DIRDIFF_SAME, DIRDIFF_SAME, DIRDIFF_45RIGHT
3897 do {
3898 /* We don't need to twist around vehicles if they're not visible */
3899 if (!(v->vehstatus & VS_HIDDEN)) {
3900 v->direction = ChangeDir(v->direction, delta[GB(Random(), 0, 2)]);
3901 v->UpdateDeltaXY(v->direction);
3902 v->cur_image = v->GetImage(v->direction, EIT_ON_MAP);
3903 /* Refrain from updating the z position of the vehicle when on
3904 * a bridge, because UpdateInclination() will put the vehicle under
3905 * the bridge in that case */
3906 if (v->trackdir != TRACKDIR_WORMHOLE) {
3907 VehicleUpdatePosition(v);
3908 v->UpdateInclination(false, false);
3911 } while ((v = v->Next()) != NULL);
3915 * Handle a crashed train.
3916 * @param v First train vehicle.
3917 * @return %Vehicle chain still exists.
3919 static bool HandleCrashedTrain(Train *v)
3921 int state = ++v->crash_anim_pos;
3923 if (state == 4 && !(v->vehstatus & VS_HIDDEN)) {
3924 CreateEffectVehicleRel(v, 4, 4, 8, EV_EXPLOSION_LARGE);
3927 uint32 r;
3928 if (state <= 200 && Chance16R(1, 7, r)) {
3929 int index = (r * 10 >> 16);
3931 Vehicle *u = v;
3932 do {
3933 if (--index < 0) {
3934 r = Random();
3936 CreateEffectVehicleRel(u,
3937 GB(r, 8, 3) + 2,
3938 GB(r, 16, 3) + 2,
3939 GB(r, 0, 3) + 5,
3940 EV_EXPLOSION_SMALL);
3941 break;
3943 } while ((u = u->Next()) != NULL);
3946 if (state <= 240 && !(v->tick_counter & 3)) ChangeTrainDirRandomly(v);
3948 if (state >= 4440 && !(v->tick_counter & 0x1F)) {
3949 bool ret = v->Next() != NULL;
3950 DeleteLastWagon(v);
3951 return ret;
3954 return true;
3957 /** Maximum speeds for train that is broken down or approaching line end */
3958 static const uint16 _breakdown_speeds[16] = {
3959 225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, 15
3964 * Train is approaching line end, slow down and possibly reverse
3966 * @param v front train engine
3967 * @param signal not line end, just a red signal
3968 * @param reverse Set to false to not execute the vehicle reversing. This does not change any other logic.
3969 * @return true iff we did NOT have to reverse
3971 static bool TrainApproachingLineEnd(Train *v, bool signal, bool reverse)
3973 /* Calc position within the current tile */
3974 uint x = v->x_pos & 0xF;
3975 uint y = v->y_pos & 0xF;
3977 /* for diagonal directions, 'x' will be 0..15 -
3978 * for other directions, it will be 1, 3, 5, ..., 15 */
3979 switch (v->direction) {
3980 case DIR_N : x = ~x + ~y + 25; break;
3981 case DIR_NW: x = y; // FALL THROUGH
3982 case DIR_NE: x = ~x + 16; break;
3983 case DIR_E : x = ~x + y + 9; break;
3984 case DIR_SE: x = y; break;
3985 case DIR_S : x = x + y - 7; break;
3986 case DIR_W : x = ~y + x + 9; break;
3987 default: break;
3990 /* Do not reverse when approaching red signal. Make sure the vehicle's front
3991 * does not cross the tile boundary when we do reverse, but as the vehicle's
3992 * location is based on their center, use half a vehicle's length as offset.
3993 * Multiply the half-length by two for straight directions to compensate that
3994 * we only get odd x offsets there. */
3995 if (!signal && x + (v->gcache.cached_veh_length + 1) / 2 * (IsDiagonalDirection(v->direction) ? 1 : 2) >= TILE_SIZE) {
3996 /* we are too near the tile end, reverse now */
3997 v->cur_speed = 0;
3998 if (reverse) ReverseTrainDirection(v);
3999 return false;
4002 /* slow down */
4003 v->vehstatus |= VS_TRAIN_SLOWING;
4004 uint16 break_speed = _breakdown_speeds[x & 0xF];
4005 if (break_speed < v->cur_speed) v->cur_speed = break_speed;
4007 return true;
4012 * Determines whether a train is on the map and will stay on it after leaving the current tile
4013 * (as opposed to being in a wormhole or depot)
4014 * @param v train to test
4015 * @return true iff vehicle is NOT entering or inside a depot or tunnel/bridge
4017 static bool TrainStayOnMap(const Train *v)
4019 /* Exit if inside a tunnel/bridge or a depot */
4020 if (v->trackdir == TRACKDIR_WORMHOLE || v->trackdir == TRACKDIR_DEPOT) return false;
4022 TileIndex tile = v->tile;
4024 /* entering a tunnel/bridge? */
4025 if (IsRailBridgeTile(tile)) {
4026 if (TrackdirToExitdir(v->trackdir) == GetTunnelBridgeDirection(tile)) return false;
4029 if (IsTunnelTile(tile)) {
4030 DiagDirection dir = GetTunnelBridgeDirection(tile);
4031 if (DiagDirToDir(dir) == v->direction) return false;
4034 /* entering a depot? */
4035 if (IsRailDepotTile(tile)) {
4036 DiagDirection dir = ReverseDiagDir(GetGroundDepotDirection(tile));
4037 if (DiagDirToDir(dir) == v->direction) return false;
4040 return true;
4045 * Determines whether train is approaching a rail-road crossing
4046 * (thus making it barred)
4047 * @param v front engine of train
4048 * @return TileIndex of crossing the train is approaching, else INVALID_TILE
4049 * @pre v in non-crashed front engine
4051 static TileIndex TrainApproachingCrossingTile(const Train *v)
4053 assert(v->IsFrontEngine());
4054 assert(!(v->vehstatus & VS_CRASHED));
4056 if (!TrainStayOnMap(v)) return INVALID_TILE;
4058 DiagDirection dir = TrackdirToExitdir(v->trackdir);
4059 TileIndex tile = v->tile + TileOffsByDiagDir(dir);
4061 /* not a crossing || wrong axis || unusable rail (wrong type or owner) */
4062 if (!IsLevelCrossingTile(tile) || DiagDirToAxis(dir) == GetCrossingRoadAxis(tile) ||
4063 !CheckCompatibleRail(v, tile)) {
4064 return INVALID_TILE;
4067 return tile;
4072 * Checks for line end. Also, bars crossing at next tile if needed
4074 * @param v vehicle we are checking
4075 * @param reverse Set to false to not execute the vehicle reversing. This does not change any other logic.
4076 * @return true iff we did NOT have to reverse
4078 static bool TrainCheckIfLineEnds(Train *v, bool reverse)
4080 /* First, handle broken down train */
4082 int t = v->breakdown_ctr;
4083 if (t > 1) {
4084 v->vehstatus |= VS_TRAIN_SLOWING;
4086 uint16 break_speed = _breakdown_speeds[GB(~t, 4, 4)];
4087 if (break_speed < v->cur_speed) v->cur_speed = break_speed;
4088 } else {
4089 v->vehstatus &= ~VS_TRAIN_SLOWING;
4092 if (v->trackdir == TRACKDIR_WORMHOLE) {
4093 DiagDirection dir = GetTunnelBridgeDirection(v->tile);
4095 /* Only check when the train is on the last tile segment */
4096 if (TileVirtXY(v->x_pos, v->y_pos) != v->tile + TileOffsByDiagDir(dir)) return true;
4098 TrackStatus ts = GetTileRailwayStatus(v->tile, INVALID_DIAGDIR);
4099 TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(ReverseDiagDir(dir));
4101 TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
4102 TrackdirBits red_signals = TrackStatusToRedSignals(ts) & reachable_trackdirs;
4104 assert(trackdirbits != TRACKDIR_BIT_NONE);
4105 assert(CheckCompatibleRail(v, v->tile, TrackdirToTrack(FindFirstTrackdir(trackdirbits))));
4107 return (trackdirbits & red_signals) == 0 || TrainApproachingLineEnd(v, true, reverse);
4110 if (!TrainStayOnMap(v)) return true;
4112 /* Determine the non-diagonal direction in which we will exit this tile */
4113 DiagDirection dir = TrackdirToExitdir(v->trackdir);
4114 /* Calculate next tile */
4115 TileIndex tile = v->tile + TileOffsByDiagDir(dir);
4117 /* Determine the track status on the next tile */
4118 TrackStatus ts = GetTileRailwayStatus(tile, ReverseDiagDir(dir));
4119 TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(dir);
4121 TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
4122 TrackdirBits red_signals = TrackStatusToRedSignals(ts) & reachable_trackdirs;
4124 /* We are sure the train is not entering a depot, it is detected above */
4126 /* mask unreachable track bits if we are forbidden to do 90deg turns */
4127 if (_settings_game.pf.forbid_90_deg) {
4128 trackdirbits &= ~TrackdirCrossesTrackdirs(v->trackdir);
4131 /* no suitable trackbits at all || unusable rail (wrong type or owner) */
4132 if (trackdirbits == TRACKDIR_BIT_NONE || !CheckCompatibleRail(v, tile, TrackdirToTrack(FindFirstTrackdir(trackdirbits)))) {
4133 return TrainApproachingLineEnd(v, false, reverse);
4136 /* approaching red signal */
4137 if ((trackdirbits & red_signals) != 0) return TrainApproachingLineEnd(v, true, reverse);
4139 /* approaching a rail/road crossing? then make it red */
4140 if (IsLevelCrossingTile(tile)) MaybeBarCrossingWithSound(tile);
4142 return true;
4146 static bool TrainLocoHandler(Train *v, bool mode)
4148 /* train has crashed? */
4149 if (v->vehstatus & VS_CRASHED) {
4150 return mode ? true : HandleCrashedTrain(v); // 'this' can be deleted here
4153 if (v->force_proceed != TFP_NONE) {
4154 ClrBit(v->flags, VRF_TRAIN_STUCK);
4155 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
4158 /* train is broken down? */
4159 if (v->HandleBreakdown()) return true;
4161 if (HasBit(v->flags, VRF_REVERSING) && v->cur_speed == 0) {
4162 ReverseTrainDirection(v);
4165 /* exit if train is stopped */
4166 if ((v->vehstatus & VS_STOPPED) && v->cur_speed == 0) return true;
4168 bool valid_order = !v->current_order.IsType(OT_NOTHING) && v->current_order.GetType() != OT_CONDITIONAL;
4169 if (ProcessOrders(v) && CheckReverseTrain(v)) {
4170 v->wait_counter = 0;
4171 v->cur_speed = 0;
4172 v->subspeed = 0;
4173 ClrBit(v->flags, VRF_LEAVING_STATION);
4174 ReverseTrainDirection(v);
4175 return true;
4176 } else if (HasBit(v->flags, VRF_LEAVING_STATION)) {
4177 /* Try to reserve a path when leaving the station as we
4178 * might not be marked as wanting a reservation, e.g.
4179 * when an overlength train gets turned around in a station. */
4180 assert(IsSignalBufferEmpty());
4181 AddPosToSignalBuffer(v->GetPos(), v->owner);
4182 if (UpdateSignalsInBuffer() == SIGSEG_PBS || _settings_game.pf.reserve_paths) {
4183 TryPathReserve(v, true, true);
4185 ClrBit(v->flags, VRF_LEAVING_STATION);
4188 v->HandleLoading(mode);
4190 if (v->current_order.IsType(OT_LOADING)) return true;
4192 if (CheckTrainStayInDepot(v)) return true;
4194 if (!mode) v->ShowVisualEffect();
4196 /* We had no order but have an order now, do look ahead. */
4197 if (!valid_order && !v->current_order.IsType(OT_NOTHING)) {
4198 CheckNextTrainTile(v);
4201 /* Handle stuck trains. */
4202 if (!mode && HasBit(v->flags, VRF_TRAIN_STUCK)) {
4203 ++v->wait_counter;
4205 /* Should we try reversing this tick if still stuck? */
4206 bool turn_around = v->wait_counter % (_settings_game.pf.wait_for_pbs_path * DAY_TICKS) == 0 && _settings_game.pf.reverse_at_signals;
4208 if (!turn_around && v->wait_counter % _settings_game.pf.path_backoff_interval != 0 && v->force_proceed == TFP_NONE) return true;
4209 if (!TryPathReserve(v)) {
4210 /* Still stuck. */
4211 if (turn_around) ReverseTrainDirection(v);
4213 if (HasBit(v->flags, VRF_TRAIN_STUCK) && v->wait_counter > 2 * _settings_game.pf.wait_for_pbs_path * DAY_TICKS) {
4214 /* Show message to player. */
4215 if (_settings_client.gui.lost_vehicle_warn && v->owner == _local_company) {
4216 SetDParam(0, v->index);
4217 AddVehicleAdviceNewsItem(STR_NEWS_TRAIN_IS_STUCK, v->index);
4219 v->wait_counter = 0;
4221 /* Exit if force proceed not pressed, else reset stuck flag anyway. */
4222 if (v->force_proceed == TFP_NONE) return true;
4223 ClrBit(v->flags, VRF_TRAIN_STUCK);
4224 v->wait_counter = 0;
4225 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
4229 if (v->current_order.IsType(OT_LEAVESTATION)) {
4230 v->current_order.Free();
4231 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
4232 return true;
4235 int j = v->UpdateSpeed();
4237 /* we need to invalidate the widget if we are stopping from 'Stopping 0 km/h' to 'Stopped' */
4238 if (v->cur_speed == 0 && (v->vehstatus & VS_STOPPED)) {
4239 /* If we manually stopped, we're not force-proceeding anymore. */
4240 v->force_proceed = TFP_NONE;
4241 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
4244 int adv_spd = v->GetAdvanceDistance();
4245 if (j < adv_spd) {
4246 /* if the vehicle has speed 0, update the last_speed field. */
4247 if (v->cur_speed == 0) v->SetLastSpeed();
4248 } else {
4249 TrainCheckIfLineEnds(v);
4250 /* Loop until the train has finished moving. */
4251 for (;;) {
4252 j -= adv_spd;
4253 TrainController(v, NULL);
4254 /* Don't continue to move if the train crashed. */
4255 if (CheckTrainCollision(v)) break;
4256 /* Determine distance to next map position */
4257 adv_spd = v->GetAdvanceDistance();
4259 /* No more moving this tick */
4260 if (j < adv_spd || v->cur_speed == 0) break;
4262 OrderType order_type = v->current_order.GetType();
4263 /* Do not skip waypoints (incl. 'via' stations) when passing through at full speed. */
4264 if ((order_type == OT_GOTO_WAYPOINT || order_type == OT_GOTO_STATION) &&
4265 (v->current_order.GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION) &&
4266 IsStationTile(v->tile) &&
4267 v->current_order.GetDestination() == GetStationIndex(v->tile)) {
4268 ProcessOrders(v);
4271 v->SetLastSpeed();
4274 for (Train *u = v; u != NULL; u = u->Next()) {
4275 if ((u->vehstatus & VS_HIDDEN) != 0) continue;
4277 u->UpdateViewport(false, false);
4280 if (v->progress == 0) v->progress = j; // Save unused spd for next time, if TrainController didn't set progress
4282 return true;
4286 * Get running cost for the train consist.
4287 * @return Yearly running costs.
4289 Money Train::GetRunningCost() const
4291 Money cost = 0;
4292 const Train *v = this;
4294 do {
4295 const Engine *e = v->GetEngine();
4296 if (e->u.rail.running_cost_class == INVALID_PRICE) continue;
4298 uint cost_factor = GetVehicleProperty(v, PROP_TRAIN_RUNNING_COST_FACTOR, e->u.rail.running_cost);
4299 if (cost_factor == 0) continue;
4301 /* Halve running cost for multiheaded parts */
4302 if (v->IsMultiheaded()) cost_factor /= 2;
4304 cost += GetPrice(e->u.rail.running_cost_class, cost_factor, e->GetGRF());
4305 } while ((v = v->GetNextVehicle()) != NULL);
4307 return cost;
4311 * Update train vehicle data for a tick.
4312 * @return True if the vehicle still exists, false if it has ceased to exist (front of consists only).
4314 bool Train::Tick()
4316 this->tick_counter++;
4318 if (this->IsFrontEngine()) {
4319 if (!(this->vehstatus & VS_STOPPED) || this->cur_speed > 0) this->running_ticks++;
4321 this->current_order_time++;
4323 if (!TrainLocoHandler(this, false)) return false;
4325 return TrainLocoHandler(this, true);
4326 } else if (this->IsFreeWagon() && (this->vehstatus & VS_CRASHED)) {
4327 /* Delete flooded standalone wagon chain */
4328 if (++this->crash_anim_pos >= 4400) {
4329 delete this;
4330 return false;
4334 return true;
4338 * Check whether a train needs service, and if so, find a depot or service it.
4339 * @return v %Train to check.
4341 static void CheckIfTrainNeedsService(Train *v)
4343 if (Company::Get(v->owner)->settings.vehicle.servint_trains == 0 || !v->NeedsAutomaticServicing()) return;
4344 if (v->IsChainInDepot()) {
4345 VehicleServiceInDepot(v);
4346 return;
4349 FindDepotData tfdd;
4350 /* Only go to the depot if it is not too far out of our way. */
4351 if (!FindClosestTrainDepot(v, true, &tfdd)) {
4352 if (v->current_order.IsType(OT_GOTO_DEPOT)) {
4353 /* If we were already heading for a depot but it has
4354 * suddenly moved farther away, we continue our normal
4355 * schedule? */
4356 v->current_order.MakeDummy();
4357 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
4359 return;
4362 DepotID depot = GetDepotIndex(tfdd.tile);
4364 if (v->current_order.IsType(OT_GOTO_DEPOT) &&
4365 v->current_order.GetDestination() != depot &&
4366 !Chance16(3, 16)) {
4367 return;
4370 SetBit(v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS);
4371 v->current_order.MakeGoToDepot(depot, ODTFB_SERVICE);
4372 v->dest_tile = tfdd.tile;
4373 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
4376 /** Update day counters of the train vehicle. */
4377 void Train::OnNewDay()
4379 AgeVehicle(this);
4381 if ((++this->day_counter & 7) == 0) DecreaseVehicleValue(this);
4383 if (this->IsFrontEngine()) {
4384 CheckVehicleBreakdown(this);
4386 CheckIfTrainNeedsService(this);
4388 CheckOrders(this);
4390 /* update destination */
4391 if (this->current_order.IsType(OT_GOTO_STATION)) {
4392 TileIndex tile = Station::Get(this->current_order.GetDestination())->train_station.tile;
4393 if (tile != INVALID_TILE) this->dest_tile = tile;
4396 if (this->running_ticks != 0) {
4397 /* running costs */
4398 CommandCost cost(EXPENSES_TRAIN_RUN, this->GetRunningCost() * this->running_ticks / (DAYS_IN_YEAR * DAY_TICKS));
4400 this->profit_this_year -= cost.GetCost();
4401 this->running_ticks = 0;
4403 SubtractMoneyFromCompanyFract(this->owner, cost);
4405 SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
4406 SetWindowClassesDirty(WC_TRAINS_LIST);
4412 * Get the trackdir of the train vehicle.
4413 * @return Current trackdir of the vehicle.
4415 Trackdir Train::GetTrackdir() const
4417 assert(!(this->vehstatus & VS_CRASHED));
4418 assert(this->trackdir != TRACKDIR_WORMHOLE);
4420 if (this->trackdir == TRACKDIR_DEPOT) {
4421 /* We'll assume the train is facing outwards */
4422 return DiagDirToDiagTrackdir(GetGroundDepotDirection(this->tile)); // Train in depot
4425 return this->trackdir;
4428 RailPathPos Train::GetPos() const
4430 if (this->vehstatus & VS_CRASHED) return RailPathPos();
4432 if (this->trackdir == TRACKDIR_WORMHOLE) {
4433 DiagDirection rev = GetTunnelBridgeDirection(this->tile);
4434 assert(ReverseDiagDir(rev) == DirToDiagDir(this->direction));
4435 return RailPathPos(TILE_ADD(this->tile, TileOffsByDiagDir(rev)), DiagDirToDiagTrackdir(ReverseDiagDir(rev)), this->tile);
4438 return RailPathPos(this->tile, this->GetTrackdir());
4441 RailPathPos Train::GetReversePos() const
4443 if (this->vehstatus & VS_CRASHED) return RailPathPos();
4445 if (this->trackdir == TRACKDIR_WORMHOLE) {
4446 TileIndex other_end = GetOtherTunnelBridgeEnd(this->tile);
4447 DiagDirection dir = GetTunnelBridgeDirection(other_end);
4448 assert(dir == DirToDiagDir(this->direction));
4449 return RailPathPos(TILE_ADD(other_end, TileOffsByDiagDir(dir)), DiagDirToDiagTrackdir(ReverseDiagDir(dir)), other_end);
4452 return RailPathPos(this->tile, ReverseTrackdir(this->GetTrackdir()));