train_cmd.cpp

Go to the documentation of this file.
00001 /* $Id: train_cmd.cpp 26317 2014-02-07 23:48:56Z frosch $ */
00002 
00003 /*
00004  * This file is part of OpenTTD.
00005  * 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.
00006  * 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.
00007  * 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/>.
00008  */
00009 
00012 #include "stdafx.h"
00013 #include "error.h"
00014 #include "articulated_vehicles.h"
00015 #include "command_func.h"
00016 #include "pathfinder/npf/npf_func.h"
00017 #include "pathfinder/yapf/yapf.hpp"
00018 #include "news_func.h"
00019 #include "company_func.h"
00020 #include "newgrf_sound.h"
00021 #include "newgrf_text.h"
00022 #include "strings_func.h"
00023 #include "viewport_func.h"
00024 #include "vehicle_func.h"
00025 #include "sound_func.h"
00026 #include "ai/ai.hpp"
00027 #include "game/game.hpp"
00028 #include "newgrf_station.h"
00029 #include "effectvehicle_func.h"
00030 #include "network/network.h"
00031 #include "spritecache.h"
00032 #include "core/random_func.hpp"
00033 #include "company_base.h"
00034 #include "newgrf.h"
00035 #include "order_backup.h"
00036 #include "zoom_func.h"
00037 #include "newgrf_debug.h"
00038 
00039 #include "table/strings.h"
00040 #include "table/train_cmd.h"
00041 
00042 static Track ChooseTrainTrack(Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool force_res, bool *got_reservation, bool mark_stuck);
00043 static bool TrainCheckIfLineEnds(Train *v, bool reverse = true);
00044 bool TrainController(Train *v, Vehicle *nomove, bool reverse = true); // Also used in vehicle_sl.cpp.
00045 static TileIndex TrainApproachingCrossingTile(const Train *v);
00046 static void CheckIfTrainNeedsService(Train *v);
00047 static void CheckNextTrainTile(Train *v);
00048 
00049 static const byte _vehicle_initial_x_fract[4] = {10, 8, 4,  8};
00050 static const byte _vehicle_initial_y_fract[4] = { 8, 4, 8, 10};
00051 
00052 template <>
00053 bool IsValidImageIndex<VEH_TRAIN>(uint8 image_index)
00054 {
00055   return image_index < lengthof(_engine_sprite_base);
00056 }
00057 
00065 static inline DiagDirection TrainExitDir(Direction direction, TrackBits track)
00066 {
00067   static const TrackBits state_dir_table[DIAGDIR_END] = { TRACK_BIT_RIGHT, TRACK_BIT_LOWER, TRACK_BIT_LEFT, TRACK_BIT_UPPER };
00068 
00069   DiagDirection diagdir = DirToDiagDir(direction);
00070 
00071   /* Determine the diagonal direction in which we will exit this tile */
00072   if (!HasBit(direction, 0) && track != state_dir_table[diagdir]) {
00073     diagdir = ChangeDiagDir(diagdir, DIAGDIRDIFF_90LEFT);
00074   }
00075 
00076   return diagdir;
00077 }
00078 
00079 
00085 byte FreightWagonMult(CargoID cargo)
00086 {
00087   if (!CargoSpec::Get(cargo)->is_freight) return 1;
00088   return _settings_game.vehicle.freight_trains;
00089 }
00090 
00092 void CheckTrainsLengths()
00093 {
00094   const Train *v;
00095   bool first = true;
00096 
00097   FOR_ALL_TRAINS(v) {
00098     if (v->First() == v && !(v->vehstatus & VS_CRASHED)) {
00099       for (const Train *u = v, *w = v->Next(); w != NULL; u = w, w = w->Next()) {
00100         if (u->track != TRACK_BIT_DEPOT) {
00101           if ((w->track != TRACK_BIT_DEPOT &&
00102               max(abs(u->x_pos - w->x_pos), abs(u->y_pos - w->y_pos)) != u->CalcNextVehicleOffset()) ||
00103               (w->track == TRACK_BIT_DEPOT && TicksToLeaveDepot(u) <= 0)) {
00104             SetDParam(0, v->index);
00105             SetDParam(1, v->owner);
00106             ShowErrorMessage(STR_BROKEN_VEHICLE_LENGTH, INVALID_STRING_ID, WL_CRITICAL);
00107 
00108             if (!_networking && first) {
00109               first = false;
00110               DoCommandP(0, PM_PAUSED_ERROR, 1, CMD_PAUSE);
00111             }
00112             /* Break so we warn only once for each train. */
00113             break;
00114           }
00115         }
00116       }
00117     }
00118   }
00119 }
00120 
00127 void Train::ConsistChanged(ConsistChangeFlags allowed_changes)
00128 {
00129   uint16 max_speed = UINT16_MAX;
00130 
00131   assert(this->IsFrontEngine() || this->IsFreeWagon());
00132 
00133   const RailVehicleInfo *rvi_v = RailVehInfo(this->engine_type);
00134   EngineID first_engine = this->IsFrontEngine() ? this->engine_type : INVALID_ENGINE;
00135   this->gcache.cached_total_length = 0;
00136   this->compatible_railtypes = RAILTYPES_NONE;
00137 
00138   bool train_can_tilt = true;
00139 
00140   for (Train *u = this; u != NULL; u = u->Next()) {
00141     const RailVehicleInfo *rvi_u = RailVehInfo(u->engine_type);
00142 
00143     /* Check the this->first cache. */
00144     assert(u->First() == this);
00145 
00146     /* update the 'first engine' */
00147     u->gcache.first_engine = this == u ? INVALID_ENGINE : first_engine;
00148     u->railtype = rvi_u->railtype;
00149 
00150     if (u->IsEngine()) first_engine = u->engine_type;
00151 
00152     /* Set user defined data to its default value */
00153     u->tcache.user_def_data = rvi_u->user_def_data;
00154     this->InvalidateNewGRFCache();
00155     u->InvalidateNewGRFCache();
00156   }
00157 
00158   for (Train *u = this; u != NULL; u = u->Next()) {
00159     /* Update user defined data (must be done before other properties) */
00160     u->tcache.user_def_data = GetVehicleProperty(u, PROP_TRAIN_USER_DATA, u->tcache.user_def_data);
00161     this->InvalidateNewGRFCache();
00162     u->InvalidateNewGRFCache();
00163   }
00164 
00165   for (Train *u = this; u != NULL; u = u->Next()) {
00166     const Engine *e_u = u->GetEngine();
00167     const RailVehicleInfo *rvi_u = &e_u->u.rail;
00168 
00169     if (!HasBit(e_u->info.misc_flags, EF_RAIL_TILTS)) train_can_tilt = false;
00170 
00171     /* Cache wagon override sprite group. NULL is returned if there is none */
00172     u->tcache.cached_override = GetWagonOverrideSpriteSet(u->engine_type, u->cargo_type, u->gcache.first_engine);
00173 
00174     /* Reset colour map */
00175     u->colourmap = PAL_NONE;
00176 
00177     /* Update powered-wagon-status and visual effect */
00178     u->UpdateVisualEffect(true);
00179 
00180     if (rvi_v->pow_wag_power != 0 && rvi_u->railveh_type == RAILVEH_WAGON &&
00181         UsesWagonOverride(u) && !HasBit(u->vcache.cached_vis_effect, VE_DISABLE_WAGON_POWER)) {
00182       /* wagon is powered */
00183       SetBit(u->flags, VRF_POWEREDWAGON); // cache 'powered' status
00184     } else {
00185       ClrBit(u->flags, VRF_POWEREDWAGON);
00186     }
00187 
00188     if (!u->IsArticulatedPart()) {
00189       /* Do not count powered wagons for the compatible railtypes, as wagons always
00190          have railtype normal */
00191       if (rvi_u->power > 0) {
00192         this->compatible_railtypes |= GetRailTypeInfo(u->railtype)->powered_railtypes;
00193       }
00194 
00195       /* Some electric engines can be allowed to run on normal rail. It happens to all
00196        * existing electric engines when elrails are disabled and then re-enabled */
00197       if (HasBit(u->flags, VRF_EL_ENGINE_ALLOWED_NORMAL_RAIL)) {
00198         u->railtype = RAILTYPE_RAIL;
00199         u->compatible_railtypes |= RAILTYPES_RAIL;
00200       }
00201 
00202       /* max speed is the minimum of the speed limits of all vehicles in the consist */
00203       if ((rvi_u->railveh_type != RAILVEH_WAGON || _settings_game.vehicle.wagon_speed_limits) && !UsesWagonOverride(u)) {
00204         uint16 speed = GetVehicleProperty(u, PROP_TRAIN_SPEED, rvi_u->max_speed);
00205         if (speed != 0) max_speed = min(speed, max_speed);
00206       }
00207     }
00208 
00209     uint16 new_cap = e_u->DetermineCapacity(u);
00210     if (allowed_changes & CCF_CAPACITY) {
00211       /* Update vehicle capacity. */
00212       if (u->cargo_cap > new_cap) u->cargo.Truncate(new_cap);
00213       u->refit_cap = min(new_cap, u->refit_cap);
00214       u->cargo_cap = new_cap;
00215     } else {
00216       /* Verify capacity hasn't changed. */
00217       if (new_cap != u->cargo_cap) ShowNewGrfVehicleError(u->engine_type, STR_NEWGRF_BROKEN, STR_NEWGRF_BROKEN_CAPACITY, GBUG_VEH_CAPACITY, true);
00218     }
00219     u->vcache.cached_cargo_age_period = GetVehicleProperty(u, PROP_TRAIN_CARGO_AGE_PERIOD, e_u->info.cargo_age_period);
00220 
00221     /* check the vehicle length (callback) */
00222     uint16 veh_len = CALLBACK_FAILED;
00223     if (e_u->GetGRF() != NULL && e_u->GetGRF()->grf_version >= 8) {
00224       /* Use callback 36 */
00225       veh_len = GetVehicleProperty(u, PROP_TRAIN_SHORTEN_FACTOR, CALLBACK_FAILED);
00226 
00227       if (veh_len != CALLBACK_FAILED && veh_len >= VEHICLE_LENGTH) {
00228         ErrorUnknownCallbackResult(e_u->GetGRFID(), CBID_VEHICLE_LENGTH, veh_len);
00229       }
00230     } else if (HasBit(e_u->info.callback_mask, CBM_VEHICLE_LENGTH)) {
00231       /* Use callback 11 */
00232       veh_len = GetVehicleCallback(CBID_VEHICLE_LENGTH, 0, 0, u->engine_type, u);
00233     }
00234     if (veh_len == CALLBACK_FAILED) veh_len = rvi_u->shorten_factor;
00235     veh_len = VEHICLE_LENGTH - Clamp(veh_len, 0, VEHICLE_LENGTH - 1);
00236 
00237     if (allowed_changes & CCF_LENGTH) {
00238       /* Update vehicle length. */
00239       u->gcache.cached_veh_length = veh_len;
00240     } else {
00241       /* Verify length hasn't changed. */
00242       if (veh_len != u->gcache.cached_veh_length) VehicleLengthChanged(u);
00243     }
00244 
00245     this->gcache.cached_total_length += u->gcache.cached_veh_length;
00246     this->InvalidateNewGRFCache();
00247     u->InvalidateNewGRFCache();
00248   }
00249 
00250   /* store consist weight/max speed in cache */
00251   this->vcache.cached_max_speed = max_speed;
00252   this->tcache.cached_tilt = train_can_tilt;
00253   this->tcache.cached_max_curve_speed = this->GetCurveSpeedLimit();
00254 
00255   /* 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) */
00256   this->CargoChanged();
00257 
00258   if (this->IsFrontEngine()) {
00259     this->UpdateAcceleration();
00260     SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
00261     InvalidateWindowData(WC_VEHICLE_REFIT, this->index, VIWD_CONSIST_CHANGED);
00262     InvalidateWindowData(WC_VEHICLE_ORDERS, this->index, VIWD_CONSIST_CHANGED);
00263     InvalidateNewGRFInspectWindow(GSF_TRAINS, this->index);
00264   }
00265 }
00266 
00277 int GetTrainStopLocation(StationID station_id, TileIndex tile, const Train *v, int *station_ahead, int *station_length)
00278 {
00279   const Station *st = Station::Get(station_id);
00280   *station_ahead  = st->GetPlatformLength(tile, DirToDiagDir(v->direction)) * TILE_SIZE;
00281   *station_length = st->GetPlatformLength(tile) * TILE_SIZE;
00282 
00283   /* Default to the middle of the station for stations stops that are not in
00284    * the order list like intermediate stations when non-stop is disabled */
00285   OrderStopLocation osl = OSL_PLATFORM_MIDDLE;
00286   if (v->gcache.cached_total_length >= *station_length) {
00287     /* The train is longer than the station, make it stop at the far end of the platform */
00288     osl = OSL_PLATFORM_FAR_END;
00289   } else if (v->current_order.IsType(OT_GOTO_STATION) && v->current_order.GetDestination() == station_id) {
00290     osl = v->current_order.GetStopLocation();
00291   }
00292 
00293   /* The stop location of the FRONT! of the train */
00294   int stop;
00295   switch (osl) {
00296     default: NOT_REACHED();
00297 
00298     case OSL_PLATFORM_NEAR_END:
00299       stop = v->gcache.cached_total_length;
00300       break;
00301 
00302     case OSL_PLATFORM_MIDDLE:
00303       stop = *station_length - (*station_length - v->gcache.cached_total_length) / 2;
00304       break;
00305 
00306     case OSL_PLATFORM_FAR_END:
00307       stop = *station_length;
00308       break;
00309   }
00310 
00311   /* Subtract half the front vehicle length of the train so we get the real
00312    * stop location of the train. */
00313   return stop - (v->gcache.cached_veh_length + 1) / 2;
00314 }
00315 
00316 
00321 int Train::GetCurveSpeedLimit() const
00322 {
00323   assert(this->First() == this);
00324 
00325   static const int absolute_max_speed = UINT16_MAX;
00326   int max_speed = absolute_max_speed;
00327 
00328   if (_settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) return max_speed;
00329 
00330   int curvecount[2] = {0, 0};
00331 
00332   /* first find the curve speed limit */
00333   int numcurve = 0;
00334   int sum = 0;
00335   int pos = 0;
00336   int lastpos = -1;
00337   for (const Vehicle *u = this; u->Next() != NULL; u = u->Next(), pos++) {
00338     Direction this_dir = u->direction;
00339     Direction next_dir = u->Next()->direction;
00340 
00341     DirDiff dirdiff = DirDifference(this_dir, next_dir);
00342     if (dirdiff == DIRDIFF_SAME) continue;
00343 
00344     if (dirdiff == DIRDIFF_45LEFT) curvecount[0]++;
00345     if (dirdiff == DIRDIFF_45RIGHT) curvecount[1]++;
00346     if (dirdiff == DIRDIFF_45LEFT || dirdiff == DIRDIFF_45RIGHT) {
00347       if (lastpos != -1) {
00348         numcurve++;
00349         sum += pos - lastpos;
00350         if (pos - lastpos == 1 && max_speed > 88) {
00351           max_speed = 88;
00352         }
00353       }
00354       lastpos = pos;
00355     }
00356 
00357     /* if we have a 90 degree turn, fix the speed limit to 60 */
00358     if (dirdiff == DIRDIFF_90LEFT || dirdiff == DIRDIFF_90RIGHT) {
00359       max_speed = 61;
00360     }
00361   }
00362 
00363   if (numcurve > 0 && max_speed > 88) {
00364     if (curvecount[0] == 1 && curvecount[1] == 1) {
00365       max_speed = absolute_max_speed;
00366     } else {
00367       sum /= numcurve;
00368       max_speed = 232 - (13 - Clamp(sum, 1, 12)) * (13 - Clamp(sum, 1, 12));
00369     }
00370   }
00371 
00372   if (max_speed != absolute_max_speed) {
00373     /* Apply the engine's rail type curve speed advantage, if it slowed by curves */
00374     const RailtypeInfo *rti = GetRailTypeInfo(this->railtype);
00375     max_speed += (max_speed / 2) * rti->curve_speed;
00376 
00377     if (this->tcache.cached_tilt) {
00378       /* Apply max_speed bonus of 20% for a tilting train */
00379       max_speed += max_speed / 5;
00380     }
00381   }
00382 
00383   return max_speed;
00384 }
00385 
00390 int Train::GetCurrentMaxSpeed() const
00391 {
00392   int max_speed = _settings_game.vehicle.train_acceleration_model == AM_ORIGINAL ?
00393       this->gcache.cached_max_track_speed :
00394       this->tcache.cached_max_curve_speed;
00395 
00396   if (_settings_game.vehicle.train_acceleration_model == AM_REALISTIC && IsRailStationTile(this->tile)) {
00397     StationID sid = GetStationIndex(this->tile);
00398     if (this->current_order.ShouldStopAtStation(this, sid)) {
00399       int station_ahead;
00400       int station_length;
00401       int stop_at = GetTrainStopLocation(sid, this->tile, this, &station_ahead, &station_length);
00402 
00403       /* The distance to go is whatever is still ahead of the train minus the
00404        * distance from the train's stop location to the end of the platform */
00405       int distance_to_go = station_ahead / TILE_SIZE - (station_length - stop_at) / TILE_SIZE;
00406 
00407       if (distance_to_go > 0) {
00408         int st_max_speed = 120;
00409 
00410         int delta_v = this->cur_speed / (distance_to_go + 1);
00411         if (max_speed > (this->cur_speed - delta_v)) {
00412           st_max_speed = this->cur_speed - (delta_v / 10);
00413         }
00414 
00415         st_max_speed = max(st_max_speed, 25 * distance_to_go);
00416         max_speed = min(max_speed, st_max_speed);
00417       }
00418     }
00419   }
00420 
00421   for (const Train *u = this; u != NULL; u = u->Next()) {
00422     if (_settings_game.vehicle.train_acceleration_model == AM_REALISTIC && u->track == TRACK_BIT_DEPOT) {
00423       max_speed = min(max_speed, 61);
00424       break;
00425     }
00426 
00427     /* Vehicle is on the middle part of a bridge. */
00428     if (u->track == TRACK_BIT_WORMHOLE && !(u->vehstatus & VS_HIDDEN)) {
00429       max_speed = min(max_speed, GetBridgeSpec(GetBridgeType(u->tile))->speed);
00430     }
00431   }
00432 
00433   max_speed = min(max_speed, this->current_order.max_speed);
00434   return min(max_speed, this->gcache.cached_max_track_speed);
00435 }
00436 
00438 void Train::UpdateAcceleration()
00439 {
00440   assert(this->IsFrontEngine() || this->IsFreeWagon());
00441 
00442   uint power = this->gcache.cached_power;
00443   uint weight = this->gcache.cached_weight;
00444   assert(weight != 0);
00445   this->acceleration = Clamp(power / weight * 4, 1, 255);
00446 }
00447 
00453 int Train::GetDisplayImageWidth(Point *offset) const
00454 {
00455   int reference_width = TRAININFO_DEFAULT_VEHICLE_WIDTH;
00456   int vehicle_pitch = 0;
00457 
00458   const Engine *e = this->GetEngine();
00459   if (e->GetGRF() != NULL && is_custom_sprite(e->u.rail.image_index)) {
00460     reference_width = e->GetGRF()->traininfo_vehicle_width;
00461     vehicle_pitch = e->GetGRF()->traininfo_vehicle_pitch;
00462   }
00463 
00464   if (offset != NULL) {
00465     offset->x = reference_width / 2;
00466     offset->y = vehicle_pitch;
00467   }
00468   return this->gcache.cached_veh_length * reference_width / VEHICLE_LENGTH;
00469 }
00470 
00471 static SpriteID GetDefaultTrainSprite(uint8 spritenum, Direction direction)
00472 {
00473   assert(IsValidImageIndex<VEH_TRAIN>(spritenum));
00474   return ((direction + _engine_sprite_add[spritenum]) & _engine_sprite_and[spritenum]) + _engine_sprite_base[spritenum];
00475 }
00476 
00483 SpriteID Train::GetImage(Direction direction, EngineImageType image_type) const
00484 {
00485   uint8 spritenum = this->spritenum;
00486   SpriteID sprite;
00487 
00488   if (HasBit(this->flags, VRF_REVERSE_DIRECTION)) direction = ReverseDir(direction);
00489 
00490   if (is_custom_sprite(spritenum)) {
00491     sprite = GetCustomVehicleSprite(this, (Direction)(direction + 4 * IS_CUSTOM_SECONDHEAD_SPRITE(spritenum)), image_type);
00492     if (sprite != 0) return sprite;
00493 
00494     spritenum = this->GetEngine()->original_image_index;
00495   }
00496 
00497   assert(IsValidImageIndex<VEH_TRAIN>(spritenum));
00498   sprite = GetDefaultTrainSprite(spritenum, direction);
00499 
00500   if (this->cargo.StoredCount() >= this->cargo_cap / 2U) sprite += _wagon_full_adder[spritenum];
00501 
00502   return sprite;
00503 }
00504 
00505 static SpriteID GetRailIcon(EngineID engine, bool rear_head, int &y, EngineImageType image_type)
00506 {
00507   const Engine *e = Engine::Get(engine);
00508   Direction dir = rear_head ? DIR_E : DIR_W;
00509   uint8 spritenum = e->u.rail.image_index;
00510 
00511   if (is_custom_sprite(spritenum)) {
00512     SpriteID sprite = GetCustomVehicleIcon(engine, dir, image_type);
00513     if (sprite != 0) {
00514       if (e->GetGRF() != NULL) {
00515         y += e->GetGRF()->traininfo_vehicle_pitch;
00516       }
00517       return sprite;
00518     }
00519 
00520     spritenum = Engine::Get(engine)->original_image_index;
00521   }
00522 
00523   if (rear_head) spritenum++;
00524 
00525   return GetDefaultTrainSprite(spritenum, DIR_W);
00526 }
00527 
00528 void DrawTrainEngine(int left, int right, int preferred_x, int y, EngineID engine, PaletteID pal, EngineImageType image_type)
00529 {
00530   if (RailVehInfo(engine)->railveh_type == RAILVEH_MULTIHEAD) {
00531     int yf = y;
00532     int yr = y;
00533 
00534     SpriteID spritef = GetRailIcon(engine, false, yf, image_type);
00535     SpriteID spriter = GetRailIcon(engine, true, yr, image_type);
00536     const Sprite *real_spritef = GetSprite(spritef, ST_NORMAL);
00537     const Sprite *real_spriter = GetSprite(spriter, ST_NORMAL);
00538 
00539     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);
00540 
00541     DrawSprite(spritef, pal, preferred_x - 14, yf);
00542     DrawSprite(spriter, pal, preferred_x + 15, yr);
00543   } else {
00544     SpriteID sprite = GetRailIcon(engine, false, y, image_type);
00545     const Sprite *real_sprite = GetSprite(sprite, ST_NORMAL);
00546     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));
00547     DrawSprite(sprite, pal, preferred_x, y);
00548   }
00549 }
00550 
00560 void GetTrainSpriteSize(EngineID engine, uint &width, uint &height, int &xoffs, int &yoffs, EngineImageType image_type)
00561 {
00562   int y = 0;
00563 
00564   SpriteID sprite = GetRailIcon(engine, false, y, image_type);
00565   const Sprite *real_sprite = GetSprite(sprite, ST_NORMAL);
00566 
00567   width  = UnScaleByZoom(real_sprite->width, ZOOM_LVL_GUI);
00568   height = UnScaleByZoom(real_sprite->height, ZOOM_LVL_GUI);
00569   xoffs  = UnScaleByZoom(real_sprite->x_offs, ZOOM_LVL_GUI);
00570   yoffs  = UnScaleByZoom(real_sprite->y_offs, ZOOM_LVL_GUI);
00571 
00572   if (RailVehInfo(engine)->railveh_type == RAILVEH_MULTIHEAD) {
00573     sprite = GetRailIcon(engine, true, y, image_type);
00574     real_sprite = GetSprite(sprite, ST_NORMAL);
00575 
00576     /* Calculate values relative to an imaginary center between the two sprites. */
00577     width = TRAININFO_DEFAULT_VEHICLE_WIDTH + UnScaleByZoom(real_sprite->width, ZOOM_LVL_GUI) + UnScaleByZoom(real_sprite->x_offs, ZOOM_LVL_GUI) - xoffs;
00578     height = max<uint>(height, UnScaleByZoom(real_sprite->height, ZOOM_LVL_GUI));
00579     xoffs  = xoffs - TRAININFO_DEFAULT_VEHICLE_WIDTH / 2;
00580     yoffs  = min(yoffs, UnScaleByZoom(real_sprite->y_offs, ZOOM_LVL_GUI));
00581   }
00582 }
00583 
00592 static CommandCost CmdBuildRailWagon(TileIndex tile, DoCommandFlag flags, const Engine *e, Vehicle **ret)
00593 {
00594   const RailVehicleInfo *rvi = &e->u.rail;
00595 
00596   /* Check that the wagon can drive on the track in question */
00597   if (!IsCompatibleRail(rvi->railtype, GetRailType(tile))) return CMD_ERROR;
00598 
00599   if (flags & DC_EXEC) {
00600     Train *v = new Train();
00601     *ret = v;
00602     v->spritenum = rvi->image_index;
00603 
00604     v->engine_type = e->index;
00605     v->gcache.first_engine = INVALID_ENGINE; // needs to be set before first callback
00606 
00607     DiagDirection dir = GetRailDepotDirection(tile);
00608 
00609     v->direction = DiagDirToDir(dir);
00610     v->tile = tile;
00611 
00612     int x = TileX(tile) * TILE_SIZE | _vehicle_initial_x_fract[dir];
00613     int y = TileY(tile) * TILE_SIZE | _vehicle_initial_y_fract[dir];
00614 
00615     v->x_pos = x;
00616     v->y_pos = y;
00617     v->z_pos = GetSlopePixelZ(x, y);
00618     v->owner = _current_company;
00619     v->track = TRACK_BIT_DEPOT;
00620     v->vehstatus = VS_HIDDEN | VS_DEFPAL;
00621 
00622     v->SetWagon();
00623 
00624     v->SetFreeWagon();
00625     InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
00626 
00627     v->cargo_type = e->GetDefaultCargoType();
00628     v->cargo_cap = rvi->capacity;
00629     v->refit_cap = 0;
00630 
00631     v->railtype = rvi->railtype;
00632 
00633     v->build_year = _cur_year;
00634     v->cur_image = SPR_IMG_QUERY;
00635     v->random_bits = VehicleRandomBits();
00636 
00637     v->group_id = DEFAULT_GROUP;
00638 
00639     AddArticulatedParts(v);
00640 
00641     _new_vehicle_id = v->index;
00642 
00643     VehicleUpdatePosition(v);
00644     v->First()->ConsistChanged(CCF_ARRANGE);
00645     UpdateTrainGroupID(v->First());
00646 
00647     CheckConsistencyOfArticulatedVehicle(v);
00648 
00649     /* Try to connect the vehicle to one of free chains of wagons. */
00650     Train *w;
00651     FOR_ALL_TRAINS(w) {
00652       if (w->tile == tile &&              
00653           w->IsFreeWagon() &&             
00654           w->engine_type == e->index &&   
00655           w->First() != v &&              
00656           !(w->vehstatus & VS_CRASHED)) { 
00657         DoCommand(0, v->index | 1 << 20, w->Last()->index, DC_EXEC, CMD_MOVE_RAIL_VEHICLE);
00658         break;
00659       }
00660     }
00661   }
00662 
00663   return CommandCost();
00664 }
00665 
00667 static void NormalizeTrainVehInDepot(const Train *u)
00668 {
00669   const Train *v;
00670   FOR_ALL_TRAINS(v) {
00671     if (v->IsFreeWagon() && v->tile == u->tile &&
00672         v->track == TRACK_BIT_DEPOT) {
00673       if (DoCommand(0, v->index | 1 << 20, u->index, DC_EXEC,
00674           CMD_MOVE_RAIL_VEHICLE).Failed())
00675         break;
00676     }
00677   }
00678 }
00679 
00680 static void AddRearEngineToMultiheadedTrain(Train *v)
00681 {
00682   Train *u = new Train();
00683   v->value >>= 1;
00684   u->value = v->value;
00685   u->direction = v->direction;
00686   u->owner = v->owner;
00687   u->tile = v->tile;
00688   u->x_pos = v->x_pos;
00689   u->y_pos = v->y_pos;
00690   u->z_pos = v->z_pos;
00691   u->track = TRACK_BIT_DEPOT;
00692   u->vehstatus = v->vehstatus & ~VS_STOPPED;
00693   u->spritenum = v->spritenum + 1;
00694   u->cargo_type = v->cargo_type;
00695   u->cargo_subtype = v->cargo_subtype;
00696   u->cargo_cap = v->cargo_cap;
00697   u->refit_cap = v->refit_cap;
00698   u->railtype = v->railtype;
00699   u->engine_type = v->engine_type;
00700   u->build_year = v->build_year;
00701   u->cur_image = SPR_IMG_QUERY;
00702   u->random_bits = VehicleRandomBits();
00703   v->SetMultiheaded();
00704   u->SetMultiheaded();
00705   v->SetNext(u);
00706   VehicleUpdatePosition(u);
00707 
00708   /* Now we need to link the front and rear engines together */
00709   v->other_multiheaded_part = u;
00710   u->other_multiheaded_part = v;
00711 }
00712 
00722 CommandCost CmdBuildRailVehicle(TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **ret)
00723 {
00724   const RailVehicleInfo *rvi = &e->u.rail;
00725 
00726   if (rvi->railveh_type == RAILVEH_WAGON) return CmdBuildRailWagon(tile, flags, e, ret);
00727 
00728   /* Check if depot and new engine uses the same kind of tracks *
00729    * We need to see if the engine got power on the tile to avoid electric engines in non-electric depots */
00730   if (!HasPowerOnRail(rvi->railtype, GetRailType(tile))) return CMD_ERROR;
00731 
00732   if (flags & DC_EXEC) {
00733     DiagDirection dir = GetRailDepotDirection(tile);
00734     int x = TileX(tile) * TILE_SIZE + _vehicle_initial_x_fract[dir];
00735     int y = TileY(tile) * TILE_SIZE + _vehicle_initial_y_fract[dir];
00736 
00737     Train *v = new Train();
00738     *ret = v;
00739     v->direction = DiagDirToDir(dir);
00740     v->tile = tile;
00741     v->owner = _current_company;
00742     v->x_pos = x;
00743     v->y_pos = y;
00744     v->z_pos = GetSlopePixelZ(x, y);
00745     v->track = TRACK_BIT_DEPOT;
00746     v->vehstatus = VS_HIDDEN | VS_STOPPED | VS_DEFPAL;
00747     v->spritenum = rvi->image_index;
00748     v->cargo_type = e->GetDefaultCargoType();
00749     v->cargo_cap = rvi->capacity;
00750     v->refit_cap = 0;
00751     v->last_station_visited = INVALID_STATION;
00752     v->last_loading_station = INVALID_STATION;
00753 
00754     v->engine_type = e->index;
00755     v->gcache.first_engine = INVALID_ENGINE; // needs to be set before first callback
00756 
00757     v->reliability = e->reliability;
00758     v->reliability_spd_dec = e->reliability_spd_dec;
00759     v->max_age = e->GetLifeLengthInDays();
00760 
00761     v->railtype = rvi->railtype;
00762     _new_vehicle_id = v->index;
00763 
00764     v->SetServiceInterval(Company::Get(_current_company)->settings.vehicle.servint_trains);
00765     v->date_of_last_service = _date;
00766     v->build_year = _cur_year;
00767     v->cur_image = SPR_IMG_QUERY;
00768     v->random_bits = VehicleRandomBits();
00769 
00770     if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) SetBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE);
00771     v->SetServiceIntervalIsPercent(Company::Get(_current_company)->settings.vehicle.servint_ispercent);
00772 
00773     v->group_id = DEFAULT_GROUP;
00774 
00775     v->SetFrontEngine();
00776     v->SetEngine();
00777 
00778     VehicleUpdatePosition(v);
00779 
00780     if (rvi->railveh_type == RAILVEH_MULTIHEAD) {
00781       AddRearEngineToMultiheadedTrain(v);
00782     } else {
00783       AddArticulatedParts(v);
00784     }
00785 
00786     v->ConsistChanged(CCF_ARRANGE);
00787     UpdateTrainGroupID(v);
00788 
00789     if (!HasBit(data, 0) && !(flags & DC_AUTOREPLACE)) { // check if the cars should be added to the new vehicle
00790       NormalizeTrainVehInDepot(v);
00791     }
00792 
00793     CheckConsistencyOfArticulatedVehicle(v);
00794   }
00795 
00796   return CommandCost();
00797 }
00798 
00799 static Train *FindGoodVehiclePos(const Train *src)
00800 {
00801   EngineID eng = src->engine_type;
00802   TileIndex tile = src->tile;
00803 
00804   Train *dst;
00805   FOR_ALL_TRAINS(dst) {
00806     if (dst->IsFreeWagon() && dst->tile == tile && !(dst->vehstatus & VS_CRASHED)) {
00807       /* check so all vehicles in the line have the same engine. */
00808       Train *t = dst;
00809       while (t->engine_type == eng) {
00810         t = t->Next();
00811         if (t == NULL) return dst;
00812       }
00813     }
00814   }
00815 
00816   return NULL;
00817 }
00818 
00820 typedef SmallVector<Train *, 16> TrainList;
00821 
00827 static void MakeTrainBackup(TrainList &list, Train *t)
00828 {
00829   for (; t != NULL; t = t->Next()) *list.Append() = t;
00830 }
00831 
00836 static void RestoreTrainBackup(TrainList &list)
00837 {
00838   /* No train, nothing to do. */
00839   if (list.Length() == 0) return;
00840 
00841   Train *prev = NULL;
00842   /* Iterate over the list and rebuild it. */
00843   for (Train **iter = list.Begin(); iter != list.End(); iter++) {
00844     Train *t = *iter;
00845     if (prev != NULL) {
00846       prev->SetNext(t);
00847     } else if (t->Previous() != NULL) {
00848       /* Make sure the head of the train is always the first in the chain. */
00849       t->Previous()->SetNext(NULL);
00850     }
00851     prev = t;
00852   }
00853 }
00854 
00860 static void RemoveFromConsist(Train *part, bool chain = false)
00861 {
00862   Train *tail = chain ? part->Last() : part->GetLastEnginePart();
00863 
00864   /* Unlink at the front, but make it point to the next
00865    * vehicle after the to be remove part. */
00866   if (part->Previous() != NULL) part->Previous()->SetNext(tail->Next());
00867 
00868   /* Unlink at the back */
00869   tail->SetNext(NULL);
00870 }
00871 
00877 static void InsertInConsist(Train *dst, Train *chain)
00878 {
00879   /* We do not want to add something in the middle of an articulated part. */
00880   assert(dst->Next() == NULL || !dst->Next()->IsArticulatedPart());
00881 
00882   chain->Last()->SetNext(dst->Next());
00883   dst->SetNext(chain);
00884 }
00885 
00891 static void NormaliseDualHeads(Train *t)
00892 {
00893   for (; t != NULL; t = t->GetNextVehicle()) {
00894     if (!t->IsMultiheaded() || !t->IsEngine()) continue;
00895 
00896     /* Make sure that there are no free cars before next engine */
00897     Train *u;
00898     for (u = t; u->Next() != NULL && !u->Next()->IsEngine(); u = u->Next()) {}
00899 
00900     if (u == t->other_multiheaded_part) continue;
00901 
00902     /* Remove the part from the 'wrong' train */
00903     RemoveFromConsist(t->other_multiheaded_part);
00904     /* And add it to the 'right' train */
00905     InsertInConsist(u, t->other_multiheaded_part);
00906   }
00907 }
00908 
00913 static void NormaliseSubtypes(Train *chain)
00914 {
00915   /* Nothing to do */
00916   if (chain == NULL) return;
00917 
00918   /* We must be the first in the chain. */
00919   assert(chain->Previous() == NULL);
00920 
00921   /* Set the appropriate bits for the first in the chain. */
00922   if (chain->IsWagon()) {
00923     chain->SetFreeWagon();
00924   } else {
00925     assert(chain->IsEngine());
00926     chain->SetFrontEngine();
00927   }
00928 
00929   /* Now clear the bits for the rest of the chain */
00930   for (Train *t = chain->Next(); t != NULL; t = t->Next()) {
00931     t->ClearFreeWagon();
00932     t->ClearFrontEngine();
00933   }
00934 }
00935 
00945 static CommandCost CheckNewTrain(Train *original_dst, Train *dst, Train *original_src, Train *src)
00946 {
00947   /* Just add 'new' engines and subtract the original ones.
00948    * If that's less than or equal to 0 we can be sure we did
00949    * not add any engines (read: trains) along the way. */
00950   if ((src          != NULL && src->IsEngine()          ? 1 : 0) +
00951       (dst          != NULL && dst->IsEngine()          ? 1 : 0) -
00952       (original_src != NULL && original_src->IsEngine() ? 1 : 0) -
00953       (original_dst != NULL && original_dst->IsEngine() ? 1 : 0) <= 0) {
00954     return CommandCost();
00955   }
00956 
00957   /* Get a free unit number and check whether it's within the bounds.
00958    * There will always be a maximum of one new train. */
00959   if (GetFreeUnitNumber(VEH_TRAIN) <= _settings_game.vehicle.max_trains) return CommandCost();
00960 
00961   return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
00962 }
00963 
00969 static CommandCost CheckTrainAttachment(Train *t)
00970 {
00971   /* No multi-part train, no need to check. */
00972   if (t == NULL || t->Next() == NULL || !t->IsEngine()) return CommandCost();
00973 
00974   /* The maximum length for a train. For each part we decrease this by one
00975    * and if the result is negative the train is simply too long. */
00976   int allowed_len = _settings_game.vehicle.max_train_length * TILE_SIZE - t->gcache.cached_veh_length;
00977 
00978   Train *head = t;
00979   Train *prev = t;
00980 
00981   /* Break the prev -> t link so it always holds within the loop. */
00982   t = t->Next();
00983   prev->SetNext(NULL);
00984 
00985   /* Make sure the cache is cleared. */
00986   head->InvalidateNewGRFCache();
00987 
00988   while (t != NULL) {
00989     allowed_len -= t->gcache.cached_veh_length;
00990 
00991     Train *next = t->Next();
00992 
00993     /* Unlink the to-be-added piece; it is already unlinked from the previous
00994      * part due to the fact that the prev -> t link is broken. */
00995     t->SetNext(NULL);
00996 
00997     /* Don't check callback for articulated or rear dual headed parts */
00998     if (!t->IsArticulatedPart() && !t->IsRearDualheaded()) {
00999       /* Back up and clear the first_engine data to avoid using wagon override group */
01000       EngineID first_engine = t->gcache.first_engine;
01001       t->gcache.first_engine = INVALID_ENGINE;
01002 
01003       /* We don't want the cache to interfere. head's cache is cleared before
01004        * the loop and after each callback does not need to be cleared here. */
01005       t->InvalidateNewGRFCache();
01006 
01007       uint16 callback = GetVehicleCallbackParent(CBID_TRAIN_ALLOW_WAGON_ATTACH, 0, 0, head->engine_type, t, head);
01008 
01009       /* Restore original first_engine data */
01010       t->gcache.first_engine = first_engine;
01011 
01012       /* We do not want to remember any cached variables from the test run */
01013       t->InvalidateNewGRFCache();
01014       head->InvalidateNewGRFCache();
01015 
01016       if (callback != CALLBACK_FAILED) {
01017         /* A failing callback means everything is okay */
01018         StringID error = STR_NULL;
01019 
01020         if (head->GetGRF()->grf_version < 8) {
01021           if (callback == 0xFD) error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
01022           if (callback  < 0xFD) error = GetGRFStringID(head->GetGRFID(), 0xD000 + callback);
01023           if (callback >= 0x100) ErrorUnknownCallbackResult(head->GetGRFID(), CBID_TRAIN_ALLOW_WAGON_ATTACH, callback);
01024         } else {
01025           if (callback < 0x400) {
01026             error = GetGRFStringID(head->GetGRFID(), 0xD000 + callback);
01027           } else {
01028             switch (callback) {
01029               case 0x400: // allow if railtypes match (always the case for OpenTTD)
01030               case 0x401: // allow
01031                 break;
01032 
01033               default:    // unknown reason -> disallow
01034               case 0x402: // disallow attaching
01035                 error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
01036                 break;
01037             }
01038           }
01039         }
01040 
01041         if (error != STR_NULL) return_cmd_error(error);
01042       }
01043     }
01044 
01045     /* And link it to the new part. */
01046     prev->SetNext(t);
01047     prev = t;
01048     t = next;
01049   }
01050 
01051   if (allowed_len < 0) return_cmd_error(STR_ERROR_TRAIN_TOO_LONG);
01052   return CommandCost();
01053 }
01054 
01065 static CommandCost ValidateTrains(Train *original_dst, Train *dst, Train *original_src, Train *src, bool check_limit)
01066 {
01067   /* Check whether we may actually construct the trains. */
01068   CommandCost ret = CheckTrainAttachment(src);
01069   if (ret.Failed()) return ret;
01070   ret = CheckTrainAttachment(dst);
01071   if (ret.Failed()) return ret;
01072 
01073   /* Check whether we need to build a new train. */
01074   return check_limit ? CheckNewTrain(original_dst, dst, original_src, src) : CommandCost();
01075 }
01076 
01085 static void ArrangeTrains(Train **dst_head, Train *dst, Train **src_head, Train *src, bool move_chain)
01086 {
01087   /* First determine the front of the two resulting trains */
01088   if (*src_head == *dst_head) {
01089     /* If we aren't moving part(s) to a new train, we are just moving the
01090      * front back and there is not destination head. */
01091     *dst_head = NULL;
01092   } else if (*dst_head == NULL) {
01093     /* If we are moving to a new train the head of the move train would become
01094      * the head of the new vehicle. */
01095     *dst_head = src;
01096   }
01097 
01098   if (src == *src_head) {
01099     /* If we are moving the front of a train then we are, in effect, creating
01100      * a new head for the train. Point to that. Unless we are moving the whole
01101      * train in which case there is not 'source' train anymore.
01102      * In case we are a multiheaded part we want the complete thing to come
01103      * with us, so src->GetNextUnit(), however... when we are e.g. a wagon
01104      * that is followed by a rear multihead we do not want to include that. */
01105     *src_head = move_chain ? NULL :
01106         (src->IsMultiheaded() ? src->GetNextUnit() : src->GetNextVehicle());
01107   }
01108 
01109   /* Now it's just simply removing the part that we are going to move from the
01110    * source train and *if* the destination is a not a new train add the chain
01111    * at the destination location. */
01112   RemoveFromConsist(src, move_chain);
01113   if (*dst_head != src) InsertInConsist(dst, src);
01114 
01115   /* Now normalise the dual heads, that is move the dual heads around in such
01116    * a way that the head and rear of a dual head are in the same train */
01117   NormaliseDualHeads(*src_head);
01118   NormaliseDualHeads(*dst_head);
01119 }
01120 
01126 static void NormaliseTrainHead(Train *head)
01127 {
01128   /* Not much to do! */
01129   if (head == NULL) return;
01130 
01131   /* Tell the 'world' the train changed. */
01132   head->ConsistChanged(CCF_ARRANGE);
01133   UpdateTrainGroupID(head);
01134 
01135   /* Not a front engine, i.e. a free wagon chain. No need to do more. */
01136   if (!head->IsFrontEngine()) return;
01137 
01138   /* Update the refit button and window */
01139   InvalidateWindowData(WC_VEHICLE_REFIT, head->index, VIWD_CONSIST_CHANGED);
01140   SetWindowWidgetDirty(WC_VEHICLE_VIEW, head->index, WID_VV_REFIT);
01141 
01142   /* If we don't have a unit number yet, set one. */
01143   if (head->unitnumber != 0) return;
01144   head->unitnumber = GetFreeUnitNumber(VEH_TRAIN);
01145 }
01146 
01159 CommandCost CmdMoveRailVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01160 {
01161   VehicleID s = GB(p1, 0, 20);
01162   VehicleID d = GB(p2, 0, 20);
01163   bool move_chain = HasBit(p1, 20);
01164 
01165   Train *src = Train::GetIfValid(s);
01166   if (src == NULL) return CMD_ERROR;
01167 
01168   CommandCost ret = CheckOwnership(src->owner);
01169   if (ret.Failed()) return ret;
01170 
01171   /* Do not allow moving crashed vehicles inside the depot, it is likely to cause asserts later */
01172   if (src->vehstatus & VS_CRASHED) return CMD_ERROR;
01173 
01174   /* if nothing is selected as destination, try and find a matching vehicle to drag to. */
01175   Train *dst;
01176   if (d == INVALID_VEHICLE) {
01177     dst = src->IsEngine() ? NULL : FindGoodVehiclePos(src);
01178   } else {
01179     dst = Train::GetIfValid(d);
01180     if (dst == NULL) return CMD_ERROR;
01181 
01182     CommandCost ret = CheckOwnership(dst->owner);
01183     if (ret.Failed()) return ret;
01184 
01185     /* Do not allow appending to crashed vehicles, too */
01186     if (dst->vehstatus & VS_CRASHED) return CMD_ERROR;
01187   }
01188 
01189   /* if an articulated part is being handled, deal with its parent vehicle */
01190   src = src->GetFirstEnginePart();
01191   if (dst != NULL) {
01192     dst = dst->GetFirstEnginePart();
01193   }
01194 
01195   /* don't move the same vehicle.. */
01196   if (src == dst) return CommandCost();
01197 
01198   /* locate the head of the two chains */
01199   Train *src_head = src->First();
01200   Train *dst_head;
01201   if (dst != NULL) {
01202     dst_head = dst->First();
01203     if (dst_head->tile != src_head->tile) return CMD_ERROR;
01204     /* Now deal with articulated part of destination wagon */
01205     dst = dst->GetLastEnginePart();
01206   } else {
01207     dst_head = NULL;
01208   }
01209 
01210   if (src->IsRearDualheaded()) return_cmd_error(STR_ERROR_REAR_ENGINE_FOLLOW_FRONT);
01211 
01212   /* When moving all wagons, we can't have the same src_head and dst_head */
01213   if (move_chain && src_head == dst_head) return CommandCost();
01214 
01215   /* When moving a multiheaded part to be place after itself, bail out. */
01216   if (!move_chain && dst != NULL && dst->IsRearDualheaded() && src == dst->other_multiheaded_part) return CommandCost();
01217 
01218   /* Check if all vehicles in the source train are stopped inside a depot. */
01219   if (!src_head->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
01220 
01221   /* Check if all vehicles in the destination train are stopped inside a depot. */
01222   if (dst_head != NULL && !dst_head->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
01223 
01224   /* First make a backup of the order of the trains. That way we can do
01225    * whatever we want with the order and later on easily revert. */
01226   TrainList original_src;
01227   TrainList original_dst;
01228 
01229   MakeTrainBackup(original_src, src_head);
01230   MakeTrainBackup(original_dst, dst_head);
01231 
01232   /* Also make backup of the original heads as ArrangeTrains can change them.
01233    * For the destination head we do not care if it is the same as the source
01234    * head because in that case it's just a copy. */
01235   Train *original_src_head = src_head;
01236   Train *original_dst_head = (dst_head == src_head ? NULL : dst_head);
01237 
01238   /* We want this information from before the rearrangement, but execute this after the validation.
01239    * original_src_head can't be NULL; src is by definition != NULL, so src_head can't be NULL as
01240    * src->GetFirst() always yields non-NULL, so eventually original_src_head != NULL as well. */
01241   bool original_src_head_front_engine = original_src_head->IsFrontEngine();
01242   bool original_dst_head_front_engine = original_dst_head != NULL && original_dst_head->IsFrontEngine();
01243 
01244   /* (Re)arrange the trains in the wanted arrangement. */
01245   ArrangeTrains(&dst_head, dst, &src_head, src, move_chain);
01246 
01247   if ((flags & DC_AUTOREPLACE) == 0) {
01248     /* If the autoreplace flag is set we do not need to test for the validity
01249      * because we are going to revert the train to its original state. As we
01250      * assume the original state was correct autoreplace can skip this. */
01251     CommandCost ret = ValidateTrains(original_dst_head, dst_head, original_src_head, src_head, true);
01252     if (ret.Failed()) {
01253       /* Restore the train we had. */
01254       RestoreTrainBackup(original_src);
01255       RestoreTrainBackup(original_dst);
01256       return ret;
01257     }
01258   }
01259 
01260   /* do it? */
01261   if (flags & DC_EXEC) {
01262     /* Remove old heads from the statistics */
01263     if (original_src_head_front_engine) GroupStatistics::CountVehicle(original_src_head, -1);
01264     if (original_dst_head_front_engine) GroupStatistics::CountVehicle(original_dst_head, -1);
01265 
01266     /* First normalise the sub types of the chains. */
01267     NormaliseSubtypes(src_head);
01268     NormaliseSubtypes(dst_head);
01269 
01270     /* There are 14 different cases:
01271      *  1) front engine gets moved to a new train, it stays a front engine.
01272      *     a) the 'next' part is a wagon that becomes a free wagon chain.
01273      *     b) the 'next' part is an engine that becomes a front engine.
01274      *     c) there is no 'next' part, nothing else happens
01275      *  2) front engine gets moved to another train, it is not a front engine anymore
01276      *     a) the 'next' part is a wagon that becomes a free wagon chain.
01277      *     b) the 'next' part is an engine that becomes a front engine.
01278      *     c) there is no 'next' part, nothing else happens
01279      *  3) front engine gets moved to later in the current train, it is not a front engine anymore.
01280      *     a) the 'next' part is a wagon that becomes a free wagon chain.
01281      *     b) the 'next' part is an engine that becomes a front engine.
01282      *  4) free wagon gets moved
01283      *     a) the 'next' part is a wagon that becomes a free wagon chain.
01284      *     b) the 'next' part is an engine that becomes a front engine.
01285      *     c) there is no 'next' part, nothing else happens
01286      *  5) non front engine gets moved and becomes a new train, nothing else happens
01287      *  6) non front engine gets moved within a train / to another train, nothing hapens
01288      *  7) wagon gets moved, nothing happens
01289      */
01290     if (src == original_src_head && src->IsEngine() && !src->IsFrontEngine()) {
01291       /* Cases #2 and #3: the front engine gets trashed. */
01292       DeleteWindowById(WC_VEHICLE_VIEW, src->index);
01293       DeleteWindowById(WC_VEHICLE_ORDERS, src->index);
01294       DeleteWindowById(WC_VEHICLE_REFIT, src->index);
01295       DeleteWindowById(WC_VEHICLE_DETAILS, src->index);
01296       DeleteWindowById(WC_VEHICLE_TIMETABLE, src->index);
01297       DeleteNewGRFInspectWindow(GSF_TRAINS, src->index);
01298       SetWindowDirty(WC_COMPANY, _current_company);
01299 
01300       /* Delete orders, group stuff and the unit number as we're not the
01301        * front of any vehicle anymore. */
01302       DeleteVehicleOrders(src);
01303       RemoveVehicleFromGroup(src);
01304       src->unitnumber = 0;
01305     }
01306 
01307     /* We weren't a front engine but are becoming one. So
01308      * we should be put in the default group. */
01309     if (original_src_head != src && dst_head == src) {
01310       SetTrainGroupID(src, DEFAULT_GROUP);
01311       SetWindowDirty(WC_COMPANY, _current_company);
01312     }
01313 
01314     /* Add new heads to statistics */
01315     if (src_head != NULL && src_head->IsFrontEngine()) GroupStatistics::CountVehicle(src_head, 1);
01316     if (dst_head != NULL && dst_head->IsFrontEngine()) GroupStatistics::CountVehicle(dst_head, 1);
01317 
01318     /* Handle 'new engine' part of cases #1b, #2b, #3b, #4b and #5 in NormaliseTrainHead. */
01319     NormaliseTrainHead(src_head);
01320     NormaliseTrainHead(dst_head);
01321 
01322     if ((flags & DC_NO_CARGO_CAP_CHECK) == 0) {
01323       CheckCargoCapacity(src_head);
01324       CheckCargoCapacity(dst_head);
01325     }
01326 
01327     if (src_head != NULL) src_head->First()->MarkDirty();
01328     if (dst_head != NULL) dst_head->First()->MarkDirty();
01329 
01330     /* We are undoubtedly changing something in the depot and train list. */
01331     InvalidateWindowData(WC_VEHICLE_DEPOT, src->tile);
01332     InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
01333   } else {
01334     /* We don't want to execute what we're just tried. */
01335     RestoreTrainBackup(original_src);
01336     RestoreTrainBackup(original_dst);
01337   }
01338 
01339   return CommandCost();
01340 }
01341 
01353 CommandCost CmdSellRailWagon(DoCommandFlag flags, Vehicle *t, uint16 data, uint32 user)
01354 {
01355   /* Sell a chain of vehicles or not? */
01356   bool sell_chain = HasBit(data, 0);
01357 
01358   Train *v = Train::From(t)->GetFirstEnginePart();
01359   Train *first = v->First();
01360 
01361   if (v->IsRearDualheaded()) return_cmd_error(STR_ERROR_REAR_ENGINE_FOLLOW_FRONT);
01362 
01363   /* First make a backup of the order of the train. That way we can do
01364    * whatever we want with the order and later on easily revert. */
01365   TrainList original;
01366   MakeTrainBackup(original, first);
01367 
01368   /* We need to keep track of the new head and the head of what we're going to sell. */
01369   Train *new_head = first;
01370   Train *sell_head = NULL;
01371 
01372   /* Split the train in the wanted way. */
01373   ArrangeTrains(&sell_head, NULL, &new_head, v, sell_chain);
01374 
01375   /* We don't need to validate the second train; it's going to be sold. */
01376   CommandCost ret = ValidateTrains(NULL, NULL, first, new_head, (flags & DC_AUTOREPLACE) == 0);
01377   if (ret.Failed()) {
01378     /* Restore the train we had. */
01379     RestoreTrainBackup(original);
01380     return ret;
01381   }
01382 
01383   CommandCost cost(EXPENSES_NEW_VEHICLES);
01384   for (Train *t = sell_head; t != NULL; t = t->Next()) cost.AddCost(-t->value);
01385 
01386   if (first->orders.list == NULL && !OrderList::CanAllocateItem()) {
01387     return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
01388   }
01389 
01390   /* do it? */
01391   if (flags & DC_EXEC) {
01392     /* First normalise the sub types of the chain. */
01393     NormaliseSubtypes(new_head);
01394 
01395     if (v == first && v->IsEngine() && !sell_chain && new_head != NULL && new_head->IsFrontEngine()) {
01396       /* We are selling the front engine. In this case we want to
01397        * 'give' the order, unit number and such to the new head. */
01398       new_head->orders.list = first->orders.list;
01399       new_head->AddToShared(first);
01400       DeleteVehicleOrders(first);
01401 
01402       /* Copy other important data from the front engine */
01403       new_head->CopyVehicleConfigAndStatistics(first);
01404       GroupStatistics::CountVehicle(new_head, 1); // after copying over the profit
01405     } else if (v->IsPrimaryVehicle() && data & (MAKE_ORDER_BACKUP_FLAG >> 20)) {
01406       OrderBackup::Backup(v, user);
01407     }
01408 
01409     /* We need to update the information about the train. */
01410     NormaliseTrainHead(new_head);
01411 
01412     /* We are undoubtedly changing something in the depot and train list. */
01413     InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
01414     InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
01415 
01416     /* Actually delete the sold 'goods' */
01417     delete sell_head;
01418   } else {
01419     /* We don't want to execute what we're just tried. */
01420     RestoreTrainBackup(original);
01421   }
01422 
01423   return cost;
01424 }
01425 
01426 void Train::UpdateDeltaXY(Direction direction)
01427 {
01428   /* Set common defaults. */
01429   this->x_offs    = -1;
01430   this->y_offs    = -1;
01431   this->x_extent  =  3;
01432   this->y_extent  =  3;
01433   this->z_extent  =  6;
01434   this->x_bb_offs =  0;
01435   this->y_bb_offs =  0;
01436 
01437   if (!IsDiagonalDirection(direction)) {
01438     static const int _sign_table[] =
01439     {
01440       // x, y
01441       -1, -1, // DIR_N
01442       -1,  1, // DIR_E
01443        1,  1, // DIR_S
01444        1, -1, // DIR_W
01445     };
01446 
01447     int half_shorten = (VEHICLE_LENGTH - this->gcache.cached_veh_length) / 2;
01448 
01449     /* For all straight directions, move the bound box to the centre of the vehicle, but keep the size. */
01450     this->x_offs -= half_shorten * _sign_table[direction];
01451     this->y_offs -= half_shorten * _sign_table[direction + 1];
01452     this->x_extent += this->x_bb_offs = half_shorten * _sign_table[direction];
01453     this->y_extent += this->y_bb_offs = half_shorten * _sign_table[direction + 1];
01454   } else {
01455     switch (direction) {
01456         /* Shorten southern corner of the bounding box according the vehicle length
01457          * and center the bounding box on the vehicle. */
01458       case DIR_NE:
01459         this->x_offs    = 1 - (this->gcache.cached_veh_length + 1) / 2;
01460         this->x_extent  = this->gcache.cached_veh_length - 1;
01461         this->x_bb_offs = -1;
01462         break;
01463 
01464       case DIR_NW:
01465         this->y_offs    = 1 - (this->gcache.cached_veh_length + 1) / 2;
01466         this->y_extent  = this->gcache.cached_veh_length - 1;
01467         this->y_bb_offs = -1;
01468         break;
01469 
01470         /* Move northern corner of the bounding box down according to vehicle length
01471          * and center the bounding box on the vehicle. */
01472       case DIR_SW:
01473         this->x_offs    = 1 + (this->gcache.cached_veh_length + 1) / 2 - VEHICLE_LENGTH;
01474         this->x_extent  = VEHICLE_LENGTH - 1;
01475         this->x_bb_offs = VEHICLE_LENGTH - this->gcache.cached_veh_length - 1;
01476         break;
01477 
01478       case DIR_SE:
01479         this->y_offs    = 1 + (this->gcache.cached_veh_length + 1) / 2 - VEHICLE_LENGTH;
01480         this->y_extent  = VEHICLE_LENGTH - 1;
01481         this->y_bb_offs = VEHICLE_LENGTH - this->gcache.cached_veh_length - 1;
01482         break;
01483 
01484       default:
01485         NOT_REACHED();
01486     }
01487   }
01488 }
01489 
01494 static void MarkTrainAsStuck(Train *v)
01495 {
01496   if (!HasBit(v->flags, VRF_TRAIN_STUCK)) {
01497     /* It is the first time the problem occurred, set the "train stuck" flag. */
01498     SetBit(v->flags, VRF_TRAIN_STUCK);
01499 
01500     v->wait_counter = 0;
01501 
01502     /* Stop train */
01503     v->cur_speed = 0;
01504     v->subspeed = 0;
01505     v->SetLastSpeed();
01506 
01507     SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
01508   }
01509 }
01510 
01518 static void SwapTrainFlags(uint16 *swap_flag1, uint16 *swap_flag2)
01519 {
01520   uint16 flag1 = *swap_flag1;
01521   uint16 flag2 = *swap_flag2;
01522 
01523   /* Clear the flags */
01524   ClrBit(*swap_flag1, GVF_GOINGUP_BIT);
01525   ClrBit(*swap_flag1, GVF_GOINGDOWN_BIT);
01526   ClrBit(*swap_flag2, GVF_GOINGUP_BIT);
01527   ClrBit(*swap_flag2, GVF_GOINGDOWN_BIT);
01528 
01529   /* Reverse the rail-flags (if needed) */
01530   if (HasBit(flag1, GVF_GOINGUP_BIT)) {
01531     SetBit(*swap_flag2, GVF_GOINGDOWN_BIT);
01532   } else if (HasBit(flag1, GVF_GOINGDOWN_BIT)) {
01533     SetBit(*swap_flag2, GVF_GOINGUP_BIT);
01534   }
01535   if (HasBit(flag2, GVF_GOINGUP_BIT)) {
01536     SetBit(*swap_flag1, GVF_GOINGDOWN_BIT);
01537   } else if (HasBit(flag2, GVF_GOINGDOWN_BIT)) {
01538     SetBit(*swap_flag1, GVF_GOINGUP_BIT);
01539   }
01540 }
01541 
01546 static void UpdateStatusAfterSwap(Train *v)
01547 {
01548   /* Reverse the direction. */
01549   if (v->track != TRACK_BIT_DEPOT) v->direction = ReverseDir(v->direction);
01550 
01551   /* Call the proper EnterTile function unless we are in a wormhole. */
01552   if (v->track != TRACK_BIT_WORMHOLE) {
01553     VehicleEnterTile(v, v->tile, v->x_pos, v->y_pos);
01554   } else {
01555     /* VehicleEnter_TunnelBridge() sets TRACK_BIT_WORMHOLE when the vehicle
01556      * is on the last bit of the bridge head (frame == TILE_SIZE - 1).
01557      * If we were swapped with such a vehicle, we have set TRACK_BIT_WORMHOLE,
01558      * when we shouldn't have. Check if this is the case. */
01559     TileIndex vt = TileVirtXY(v->x_pos, v->y_pos);
01560     if (IsTileType(vt, MP_TUNNELBRIDGE)) {
01561       VehicleEnterTile(v, vt, v->x_pos, v->y_pos);
01562       if (v->track != TRACK_BIT_WORMHOLE && IsBridgeTile(v->tile)) {
01563         /* We have just left the wormhole, possibly set the
01564          * "goingdown" bit. UpdateInclination() can be used
01565          * because we are at the border of the tile. */
01566         VehicleUpdatePosition(v);
01567         v->UpdateInclination(true, true);
01568         return;
01569       }
01570     }
01571   }
01572 
01573   VehicleUpdatePosition(v);
01574   v->UpdateViewport(true, true);
01575 }
01576 
01583 void ReverseTrainSwapVeh(Train *v, int l, int r)
01584 {
01585   Train *a, *b;
01586 
01587   /* locate vehicles to swap */
01588   for (a = v; l != 0; l--) a = a->Next();
01589   for (b = v; r != 0; r--) b = b->Next();
01590 
01591   if (a != b) {
01592     /* swap the hidden bits */
01593     {
01594       uint16 tmp = (a->vehstatus & ~VS_HIDDEN) | (b->vehstatus & VS_HIDDEN);
01595       b->vehstatus = (b->vehstatus & ~VS_HIDDEN) | (a->vehstatus & VS_HIDDEN);
01596       a->vehstatus = tmp;
01597     }
01598 
01599     Swap(a->track, b->track);
01600     Swap(a->direction, b->direction);
01601     Swap(a->x_pos, b->x_pos);
01602     Swap(a->y_pos, b->y_pos);
01603     Swap(a->tile,  b->tile);
01604     Swap(a->z_pos, b->z_pos);
01605 
01606     SwapTrainFlags(&a->gv_flags, &b->gv_flags);
01607 
01608     UpdateStatusAfterSwap(a);
01609     UpdateStatusAfterSwap(b);
01610   } else {
01611     /* Swap GVF_GOINGUP_BIT/GVF_GOINGDOWN_BIT.
01612      * This is a little bit redundant way, a->gv_flags will
01613      * be (re)set twice, but it reduces code duplication */
01614     SwapTrainFlags(&a->gv_flags, &a->gv_flags);
01615     UpdateStatusAfterSwap(a);
01616   }
01617 }
01618 
01619 
01625 static Vehicle *TrainOnTileEnum(Vehicle *v, void *)
01626 {
01627   return (v->type == VEH_TRAIN) ? v : NULL;
01628 }
01629 
01630 
01637 static Vehicle *TrainApproachingCrossingEnum(Vehicle *v, void *data)
01638 {
01639   if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) return NULL;
01640 
01641   Train *t = Train::From(v);
01642   if (!t->IsFrontEngine()) return NULL;
01643 
01644   TileIndex tile = *(TileIndex *)data;
01645 
01646   if (TrainApproachingCrossingTile(t) != tile) return NULL;
01647 
01648   return t;
01649 }
01650 
01651 
01658 static bool TrainApproachingCrossing(TileIndex tile)
01659 {
01660   assert(IsLevelCrossingTile(tile));
01661 
01662   DiagDirection dir = AxisToDiagDir(GetCrossingRailAxis(tile));
01663   TileIndex tile_from = tile + TileOffsByDiagDir(dir);
01664 
01665   if (HasVehicleOnPos(tile_from, &tile, &TrainApproachingCrossingEnum)) return true;
01666 
01667   dir = ReverseDiagDir(dir);
01668   tile_from = tile + TileOffsByDiagDir(dir);
01669 
01670   return HasVehicleOnPos(tile_from, &tile, &TrainApproachingCrossingEnum);
01671 }
01672 
01673 
01680 void UpdateLevelCrossing(TileIndex tile, bool sound)
01681 {
01682   assert(IsLevelCrossingTile(tile));
01683 
01684   /* train on crossing || train approaching crossing || reserved */
01685   bool new_state = HasVehicleOnPos(tile, NULL, &TrainOnTileEnum) || TrainApproachingCrossing(tile) || HasCrossingReservation(tile);
01686 
01687   if (new_state != IsCrossingBarred(tile)) {
01688     if (new_state && sound) {
01689       if (_settings_client.sound.ambient) SndPlayTileFx(SND_0E_LEVEL_CROSSING, tile);
01690     }
01691     SetCrossingBarred(tile, new_state);
01692     MarkTileDirtyByTile(tile);
01693   }
01694 }
01695 
01696 
01702 static inline void MaybeBarCrossingWithSound(TileIndex tile)
01703 {
01704   if (!IsCrossingBarred(tile)) {
01705     BarCrossing(tile);
01706     if (_settings_client.sound.ambient) SndPlayTileFx(SND_0E_LEVEL_CROSSING, tile);
01707     MarkTileDirtyByTile(tile);
01708   }
01709 }
01710 
01711 
01717 static void AdvanceWagonsBeforeSwap(Train *v)
01718 {
01719   Train *base = v;
01720   Train *first = base; // first vehicle to move
01721   Train *last = v->Last(); // last vehicle to move
01722   uint length = CountVehiclesInChain(v);
01723 
01724   while (length > 2) {
01725     last = last->Previous();
01726     first = first->Next();
01727 
01728     int differential = base->CalcNextVehicleOffset() - last->CalcNextVehicleOffset();
01729 
01730     /* do not update images now
01731      * negative differential will be handled in AdvanceWagonsAfterSwap() */
01732     for (int i = 0; i < differential; i++) TrainController(first, last->Next());
01733 
01734     base = first; // == base->Next()
01735     length -= 2;
01736   }
01737 }
01738 
01739 
01745 static void AdvanceWagonsAfterSwap(Train *v)
01746 {
01747   /* first of all, fix the situation when the train was entering a depot */
01748   Train *dep = v; // last vehicle in front of just left depot
01749   while (dep->Next() != NULL && (dep->track == TRACK_BIT_DEPOT || dep->Next()->track != TRACK_BIT_DEPOT)) {
01750     dep = dep->Next(); // find first vehicle outside of a depot, with next vehicle inside a depot
01751   }
01752 
01753   Train *leave = dep->Next(); // first vehicle in a depot we are leaving now
01754 
01755   if (leave != NULL) {
01756     /* 'pull' next wagon out of the depot, so we won't miss it (it could stay in depot forever) */
01757     int d = TicksToLeaveDepot(dep);
01758 
01759     if (d <= 0) {
01760       leave->vehstatus &= ~VS_HIDDEN; // move it out of the depot
01761       leave->track = TrackToTrackBits(GetRailDepotTrack(leave->tile));
01762       for (int i = 0; i >= d; i--) TrainController(leave, NULL); // maybe move it, and maybe let another wagon leave
01763     }
01764   } else {
01765     dep = NULL; // no vehicle in a depot, so no vehicle leaving a depot
01766   }
01767 
01768   Train *base = v;
01769   Train *first = base; // first vehicle to move
01770   Train *last = v->Last(); // last vehicle to move
01771   uint length = CountVehiclesInChain(v);
01772 
01773   /* We have to make sure all wagons that leave a depot because of train reversing are moved correctly
01774    * they have already correct spacing, so we have to make sure they are moved how they should */
01775   bool nomove = (dep == NULL); // If there is no vehicle leaving a depot, limit the number of wagons moved immediately.
01776 
01777   while (length > 2) {
01778     /* we reached vehicle (originally) in front of a depot, stop now
01779      * (we would move wagons that are already moved with new wagon length). */
01780     if (base == dep) break;
01781 
01782     /* the last wagon was that one leaving a depot, so do not move it anymore */
01783     if (last == dep) nomove = true;
01784 
01785     last = last->Previous();
01786     first = first->Next();
01787 
01788     int differential = last->CalcNextVehicleOffset() - base->CalcNextVehicleOffset();
01789 
01790     /* do not update images now */
01791     for (int i = 0; i < differential; i++) TrainController(first, (nomove ? last->Next() : NULL));
01792 
01793     base = first; // == base->Next()
01794     length -= 2;
01795   }
01796 }
01797 
01802 void ReverseTrainDirection(Train *v)
01803 {
01804   if (IsRailDepotTile(v->tile)) {
01805     InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
01806   }
01807 
01808   /* Clear path reservation in front if train is not stuck. */
01809   if (!HasBit(v->flags, VRF_TRAIN_STUCK)) FreeTrainTrackReservation(v);
01810 
01811   /* Check if we were approaching a rail/road-crossing */
01812   TileIndex crossing = TrainApproachingCrossingTile(v);
01813 
01814   /* count number of vehicles */
01815   int r = CountVehiclesInChain(v) - 1;  // number of vehicles - 1
01816 
01817   AdvanceWagonsBeforeSwap(v);
01818 
01819   /* swap start<>end, start+1<>end-1, ... */
01820   int l = 0;
01821   do {
01822     ReverseTrainSwapVeh(v, l++, r--);
01823   } while (l <= r);
01824 
01825   AdvanceWagonsAfterSwap(v);
01826 
01827   if (IsRailDepotTile(v->tile)) {
01828     InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
01829   }
01830 
01831   ToggleBit(v->flags, VRF_TOGGLE_REVERSE);
01832 
01833   ClrBit(v->flags, VRF_REVERSING);
01834 
01835   /* recalculate cached data */
01836   v->ConsistChanged(CCF_TRACK);
01837 
01838   /* update all images */
01839   for (Train *u = v; u != NULL; u = u->Next()) u->UpdateViewport(false, false);
01840 
01841   /* update crossing we were approaching */
01842   if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
01843 
01844   /* maybe we are approaching crossing now, after reversal */
01845   crossing = TrainApproachingCrossingTile(v);
01846   if (crossing != INVALID_TILE) MaybeBarCrossingWithSound(crossing);
01847 
01848   /* If we are inside a depot after reversing, don't bother with path reserving. */
01849   if (v->track == TRACK_BIT_DEPOT) {
01850     /* Can't be stuck here as inside a depot is always a safe tile. */
01851     if (HasBit(v->flags, VRF_TRAIN_STUCK)) SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
01852     ClrBit(v->flags, VRF_TRAIN_STUCK);
01853     return;
01854   }
01855 
01856   /* TrainExitDir does not always produce the desired dir for depots and
01857    * tunnels/bridges that is needed for UpdateSignalsOnSegment. */
01858   DiagDirection dir = TrainExitDir(v->direction, v->track);
01859   if (IsRailDepotTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE)) dir = INVALID_DIAGDIR;
01860 
01861   if (UpdateSignalsOnSegment(v->tile, dir, v->owner) == SIGSEG_PBS || _settings_game.pf.reserve_paths) {
01862     /* If we are currently on a tile with conventional signals, we can't treat the
01863      * current tile as a safe tile or we would enter a PBS block without a reservation. */
01864     bool first_tile_okay = !(IsTileType(v->tile, MP_RAILWAY) &&
01865       HasSignalOnTrackdir(v->tile, v->GetVehicleTrackdir()) &&
01866       !IsPbsSignal(GetSignalType(v->tile, FindFirstTrack(v->track))));
01867 
01868     /* If we are on a depot tile facing outwards, do not treat the current tile as safe. */
01869     if (IsRailDepotTile(v->tile) && TrackdirToExitdir(v->GetVehicleTrackdir()) == GetRailDepotDirection(v->tile)) first_tile_okay = false;
01870 
01871     if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
01872     if (TryPathReserve(v, false, first_tile_okay)) {
01873       /* Do a look-ahead now in case our current tile was already a safe tile. */
01874       CheckNextTrainTile(v);
01875     } else if (v->current_order.GetType() != OT_LOADING) {
01876       /* Do not wait for a way out when we're still loading */
01877       MarkTrainAsStuck(v);
01878     }
01879   } else if (HasBit(v->flags, VRF_TRAIN_STUCK)) {
01880     /* A train not inside a PBS block can't be stuck. */
01881     ClrBit(v->flags, VRF_TRAIN_STUCK);
01882     v->wait_counter = 0;
01883   }
01884 }
01885 
01895 CommandCost CmdReverseTrainDirection(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01896 {
01897   Train *v = Train::GetIfValid(p1);
01898   if (v == NULL) return CMD_ERROR;
01899 
01900   CommandCost ret = CheckOwnership(v->owner);
01901   if (ret.Failed()) return ret;
01902 
01903   if (p2 != 0) {
01904     /* turn a single unit around */
01905 
01906     if (v->IsMultiheaded() || HasBit(EngInfo(v->engine_type)->callback_mask, CBM_VEHICLE_ARTIC_ENGINE)) {
01907       return_cmd_error(STR_ERROR_CAN_T_REVERSE_DIRECTION_RAIL_VEHICLE_MULTIPLE_UNITS);
01908     }
01909     if (!HasBit(EngInfo(v->engine_type)->misc_flags, EF_RAIL_FLIPS)) return CMD_ERROR;
01910 
01911     Train *front = v->First();
01912     /* make sure the vehicle is stopped in the depot */
01913     if (!front->IsStoppedInDepot()) {
01914       return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
01915     }
01916 
01917     if (flags & DC_EXEC) {
01918       ToggleBit(v->flags, VRF_REVERSE_DIRECTION);
01919 
01920       front->ConsistChanged(CCF_ARRANGE);
01921       SetWindowDirty(WC_VEHICLE_DEPOT, front->tile);
01922       SetWindowDirty(WC_VEHICLE_DETAILS, front->index);
01923       SetWindowDirty(WC_VEHICLE_VIEW, front->index);
01924       SetWindowClassesDirty(WC_TRAINS_LIST);
01925     }
01926   } else {
01927     /* turn the whole train around */
01928     if ((v->vehstatus & VS_CRASHED) || v->breakdown_ctr != 0) return CMD_ERROR;
01929 
01930     if (flags & DC_EXEC) {
01931       /* Properly leave the station if we are loading and won't be loading anymore */
01932       if (v->current_order.IsType(OT_LOADING)) {
01933         const Vehicle *last = v;
01934         while (last->Next() != NULL) last = last->Next();
01935 
01936         /* not a station || different station --> leave the station */
01937         if (!IsTileType(last->tile, MP_STATION) || GetStationIndex(last->tile) != GetStationIndex(v->tile)) {
01938           v->LeaveStation();
01939         }
01940       }
01941 
01942       /* We cancel any 'skip signal at dangers' here */
01943       v->force_proceed = TFP_NONE;
01944       SetWindowDirty(WC_VEHICLE_VIEW, v->index);
01945 
01946       if (_settings_game.vehicle.train_acceleration_model != AM_ORIGINAL && v->cur_speed != 0) {
01947         ToggleBit(v->flags, VRF_REVERSING);
01948       } else {
01949         v->cur_speed = 0;
01950         v->SetLastSpeed();
01951         HideFillingPercent(&v->fill_percent_te_id);
01952         ReverseTrainDirection(v);
01953       }
01954     }
01955   }
01956   return CommandCost();
01957 }
01958 
01968 CommandCost CmdForceTrainProceed(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01969 {
01970   Train *t = Train::GetIfValid(p1);
01971   if (t == NULL) return CMD_ERROR;
01972 
01973   if (!t->IsPrimaryVehicle()) return CMD_ERROR;
01974 
01975   CommandCost ret = CheckOwnership(t->owner);
01976   if (ret.Failed()) return ret;
01977 
01978 
01979   if (flags & DC_EXEC) {
01980     /* If we are forced to proceed, cancel that order.
01981      * If we are marked stuck we would want to force the train
01982      * to proceed to the next signal. In the other cases we
01983      * would like to pass the signal at danger and run till the
01984      * next signal we encounter. */
01985     t->force_proceed = t->force_proceed == TFP_SIGNAL ? TFP_NONE : HasBit(t->flags, VRF_TRAIN_STUCK) || t->IsChainInDepot() ? TFP_STUCK : TFP_SIGNAL;
01986     SetWindowDirty(WC_VEHICLE_VIEW, t->index);
01987   }
01988 
01989   return CommandCost();
01990 }
01991 
01999 static FindDepotData FindClosestTrainDepot(Train *v, int max_distance)
02000 {
02001   assert(!(v->vehstatus & VS_CRASHED));
02002 
02003   if (IsRailDepotTile(v->tile)) return FindDepotData(v->tile, 0);
02004 
02005   PBSTileInfo origin = FollowTrainReservation(v);
02006   if (IsRailDepotTile(origin.tile)) return FindDepotData(origin.tile, 0);
02007 
02008   switch (_settings_game.pf.pathfinder_for_trains) {
02009     case VPF_NPF: return NPFTrainFindNearestDepot(v, max_distance);
02010     case VPF_YAPF: return YapfTrainFindNearestDepot(v, max_distance);
02011 
02012     default: NOT_REACHED();
02013   }
02014 }
02015 
02023 bool Train::FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
02024 {
02025   FindDepotData tfdd = FindClosestTrainDepot(this, 0);
02026   if (tfdd.best_length == UINT_MAX) return false;
02027 
02028   if (location    != NULL) *location    = tfdd.tile;
02029   if (destination != NULL) *destination = GetDepotIndex(tfdd.tile);
02030   if (reverse     != NULL) *reverse     = tfdd.reverse;
02031 
02032   return true;
02033 }
02034 
02036 void Train::PlayLeaveStationSound() const
02037 {
02038   static const SoundFx sfx[] = {
02039     SND_04_TRAIN,
02040     SND_0A_TRAIN_HORN,
02041     SND_0A_TRAIN_HORN,
02042     SND_47_MAGLEV_2,
02043     SND_41_MAGLEV
02044   };
02045 
02046   if (PlayVehicleSound(this, VSE_START)) return;
02047 
02048   EngineID engtype = this->engine_type;
02049   SndPlayVehicleFx(sfx[RailVehInfo(engtype)->engclass], this);
02050 }
02051 
02056 static void CheckNextTrainTile(Train *v)
02057 {
02058   /* Don't do any look-ahead if path_backoff_interval is 255. */
02059   if (_settings_game.pf.path_backoff_interval == 255) return;
02060 
02061   /* Exit if we are inside a depot. */
02062   if (v->track == TRACK_BIT_DEPOT) return;
02063 
02064   switch (v->current_order.GetType()) {
02065     /* Exit if we reached our destination depot. */
02066     case OT_GOTO_DEPOT:
02067       if (v->tile == v->dest_tile) return;
02068       break;
02069 
02070     case OT_GOTO_WAYPOINT:
02071       /* If we reached our waypoint, make sure we see that. */
02072       if (IsRailWaypointTile(v->tile) && GetStationIndex(v->tile) == v->current_order.GetDestination()) ProcessOrders(v);
02073       break;
02074 
02075     case OT_NOTHING:
02076     case OT_LEAVESTATION:
02077     case OT_LOADING:
02078       /* Exit if the current order doesn't have a destination, but the train has orders. */
02079       if (v->GetNumOrders() > 0) return;
02080       break;
02081 
02082     default:
02083       break;
02084   }
02085   /* Exit if we are on a station tile and are going to stop. */
02086   if (IsRailStationTile(v->tile) && v->current_order.ShouldStopAtStation(v, GetStationIndex(v->tile))) return;
02087 
02088   Trackdir td = v->GetVehicleTrackdir();
02089 
02090   /* On a tile with a red non-pbs signal, don't look ahead. */
02091   if (IsTileType(v->tile, MP_RAILWAY) && HasSignalOnTrackdir(v->tile, td) &&
02092       !IsPbsSignal(GetSignalType(v->tile, TrackdirToTrack(td))) &&
02093       GetSignalStateByTrackdir(v->tile, td) == SIGNAL_STATE_RED) return;
02094 
02095   CFollowTrackRail ft(v);
02096   if (!ft.Follow(v->tile, td)) return;
02097 
02098   if (!HasReservedTracks(ft.m_new_tile, TrackdirBitsToTrackBits(ft.m_new_td_bits))) {
02099     /* Next tile is not reserved. */
02100     if (KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE) {
02101       if (HasPbsSignalOnTrackdir(ft.m_new_tile, FindFirstTrackdir(ft.m_new_td_bits))) {
02102         /* If the next tile is a PBS signal, try to make a reservation. */
02103         TrackBits tracks = TrackdirBitsToTrackBits(ft.m_new_td_bits);
02104         if (_settings_game.pf.forbid_90_deg) {
02105           tracks &= ~TrackCrossesTracks(TrackdirToTrack(ft.m_old_td));
02106         }
02107         ChooseTrainTrack(v, ft.m_new_tile, ft.m_exitdir, tracks, false, NULL, false);
02108       }
02109     }
02110   }
02111 }
02112 
02118 static bool CheckTrainStayInDepot(Train *v)
02119 {
02120   /* bail out if not all wagons are in the same depot or not in a depot at all */
02121   for (const Train *u = v; u != NULL; u = u->Next()) {
02122     if (u->track != TRACK_BIT_DEPOT || u->tile != v->tile) return false;
02123   }
02124 
02125   /* if the train got no power, then keep it in the depot */
02126   if (v->gcache.cached_power == 0) {
02127     v->vehstatus |= VS_STOPPED;
02128     SetWindowDirty(WC_VEHICLE_DEPOT, v->tile);
02129     return true;
02130   }
02131 
02132   SigSegState seg_state;
02133 
02134   if (v->force_proceed == TFP_NONE) {
02135     /* force proceed was not pressed */
02136     if (++v->wait_counter < 37) {
02137       SetWindowClassesDirty(WC_TRAINS_LIST);
02138       return true;
02139     }
02140 
02141     v->wait_counter = 0;
02142 
02143     seg_state = _settings_game.pf.reserve_paths ? SIGSEG_PBS : UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
02144     if (seg_state == SIGSEG_FULL || HasDepotReservation(v->tile)) {
02145       /* Full and no PBS signal in block or depot reserved, can't exit. */
02146       SetWindowClassesDirty(WC_TRAINS_LIST);
02147       return true;
02148     }
02149   } else {
02150     seg_state = _settings_game.pf.reserve_paths ? SIGSEG_PBS : UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
02151   }
02152 
02153   /* We are leaving a depot, but have to go to the exact same one; re-enter */
02154   if (v->current_order.IsType(OT_GOTO_DEPOT) && v->tile == v->dest_tile) {
02155     /* We need to have a reservation for this to work. */
02156     if (HasDepotReservation(v->tile)) return true;
02157     SetDepotReservation(v->tile, true);
02158     VehicleEnterDepot(v);
02159     return true;
02160   }
02161 
02162   /* Only leave when we can reserve a path to our destination. */
02163   if (seg_state == SIGSEG_PBS && !TryPathReserve(v) && v->force_proceed == TFP_NONE) {
02164     /* No path and no force proceed. */
02165     SetWindowClassesDirty(WC_TRAINS_LIST);
02166     MarkTrainAsStuck(v);
02167     return true;
02168   }
02169 
02170   SetDepotReservation(v->tile, true);
02171   if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(v->tile);
02172 
02173   VehicleServiceInDepot(v);
02174   SetWindowClassesDirty(WC_TRAINS_LIST);
02175   v->PlayLeaveStationSound();
02176 
02177   v->track = TRACK_BIT_X;
02178   if (v->direction & 2) v->track = TRACK_BIT_Y;
02179 
02180   v->vehstatus &= ~VS_HIDDEN;
02181   v->cur_speed = 0;
02182 
02183   v->UpdateViewport(true, true);
02184   VehicleUpdatePosition(v);
02185   UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
02186   v->UpdateAcceleration();
02187   InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
02188 
02189   return false;
02190 }
02191 
02198 static void ClearPathReservation(const Train *v, TileIndex tile, Trackdir track_dir)
02199 {
02200   DiagDirection dir = TrackdirToExitdir(track_dir);
02201 
02202   if (IsTileType(tile, MP_TUNNELBRIDGE)) {
02203     /* Are we just leaving a tunnel/bridge? */
02204     if (GetTunnelBridgeDirection(tile) == ReverseDiagDir(dir)) {
02205       TileIndex end = GetOtherTunnelBridgeEnd(tile);
02206 
02207       if (TunnelBridgeIsFree(tile, end, v).Succeeded()) {
02208         /* Free the reservation only if no other train is on the tiles. */
02209         SetTunnelBridgeReservation(tile, false);
02210         SetTunnelBridgeReservation(end, false);
02211 
02212         if (_settings_client.gui.show_track_reservation) {
02213           MarkTileDirtyByTile(tile);
02214           MarkTileDirtyByTile(end);
02215         }
02216       }
02217     }
02218   } else if (IsRailStationTile(tile)) {
02219     TileIndex new_tile = TileAddByDiagDir(tile, dir);
02220     /* If the new tile is not a further tile of the same station, we
02221      * clear the reservation for the whole platform. */
02222     if (!IsCompatibleTrainStationTile(new_tile, tile)) {
02223       SetRailStationPlatformReservation(tile, ReverseDiagDir(dir), false);
02224     }
02225   } else {
02226     /* Any other tile */
02227     UnreserveRailTrack(tile, TrackdirToTrack(track_dir));
02228   }
02229 }
02230 
02237 void FreeTrainTrackReservation(const Train *v, TileIndex origin, Trackdir orig_td)
02238 {
02239   assert(v->IsFrontEngine());
02240 
02241   TileIndex tile = origin != INVALID_TILE ? origin : v->tile;
02242   Trackdir  td = orig_td != INVALID_TRACKDIR ? orig_td : v->GetVehicleTrackdir();
02243   bool      free_tile = tile != v->tile || !(IsRailStationTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE));
02244   StationID station_id = IsRailStationTile(v->tile) ? GetStationIndex(v->tile) : INVALID_STATION;
02245 
02246   /* Can't be holding a reservation if we enter a depot. */
02247   if (IsRailDepotTile(tile) && TrackdirToExitdir(td) != GetRailDepotDirection(tile)) return;
02248   if (v->track == TRACK_BIT_DEPOT) {
02249     /* Front engine is in a depot. We enter if some part is not in the depot. */
02250     for (const Train *u = v; u != NULL; u = u->Next()) {
02251       if (u->track != TRACK_BIT_DEPOT || u->tile != v->tile) return;
02252     }
02253   }
02254   /* Don't free reservation if it's not ours. */
02255   if (TracksOverlap(GetReservedTrackbits(tile) | TrackToTrackBits(TrackdirToTrack(td)))) return;
02256 
02257   CFollowTrackRail ft(v, GetRailTypeInfo(v->railtype)->compatible_railtypes);
02258   while (ft.Follow(tile, td)) {
02259     tile = ft.m_new_tile;
02260     TrackdirBits bits = ft.m_new_td_bits & TrackBitsToTrackdirBits(GetReservedTrackbits(tile));
02261     td = RemoveFirstTrackdir(&bits);
02262     assert(bits == TRACKDIR_BIT_NONE);
02263 
02264     if (!IsValidTrackdir(td)) break;
02265 
02266     if (IsTileType(tile, MP_RAILWAY)) {
02267       if (HasSignalOnTrackdir(tile, td) && !IsPbsSignal(GetSignalType(tile, TrackdirToTrack(td)))) {
02268         /* Conventional signal along trackdir: remove reservation and stop. */
02269         UnreserveRailTrack(tile, TrackdirToTrack(td));
02270         break;
02271       }
02272       if (HasPbsSignalOnTrackdir(tile, td)) {
02273         if (GetSignalStateByTrackdir(tile, td) == SIGNAL_STATE_RED) {
02274           /* Red PBS signal? Can't be our reservation, would be green then. */
02275           break;
02276         } else {
02277           /* Turn the signal back to red. */
02278           SetSignalStateByTrackdir(tile, td, SIGNAL_STATE_RED);
02279           MarkTileDirtyByTile(tile);
02280         }
02281       } else if (HasSignalOnTrackdir(tile, ReverseTrackdir(td)) && IsOnewaySignal(tile, TrackdirToTrack(td))) {
02282         break;
02283       }
02284     }
02285 
02286     /* Don't free first station/bridge/tunnel if we are on it. */
02287     if (free_tile || (!(ft.m_is_station && GetStationIndex(ft.m_new_tile) == station_id) && !ft.m_is_tunnel && !ft.m_is_bridge)) ClearPathReservation(v, tile, td);
02288 
02289     free_tile = true;
02290   }
02291 }
02292 
02293 static const byte _initial_tile_subcoord[6][4][3] = {
02294 {{ 15, 8, 1 }, { 0, 0, 0 }, { 0, 8, 5 }, { 0,  0, 0 }},
02295 {{  0, 0, 0 }, { 8, 0, 3 }, { 0, 0, 0 }, { 8, 15, 7 }},
02296 {{  0, 0, 0 }, { 7, 0, 2 }, { 0, 7, 6 }, { 0,  0, 0 }},
02297 {{ 15, 8, 2 }, { 0, 0, 0 }, { 0, 0, 0 }, { 8, 15, 6 }},
02298 {{ 15, 7, 0 }, { 8, 0, 4 }, { 0, 0, 0 }, { 0,  0, 0 }},
02299 {{  0, 0, 0 }, { 0, 0, 0 }, { 0, 8, 4 }, { 7, 15, 0 }},
02300 };
02301 
02314 static Track DoTrainPathfind(const Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool &path_found, bool do_track_reservation, PBSTileInfo *dest)
02315 {
02316   switch (_settings_game.pf.pathfinder_for_trains) {
02317     case VPF_NPF: return NPFTrainChooseTrack(v, tile, enterdir, tracks, path_found, do_track_reservation, dest);
02318     case VPF_YAPF: return YapfTrainChooseTrack(v, tile, enterdir, tracks, path_found, do_track_reservation, dest);
02319 
02320     default: NOT_REACHED();
02321   }
02322 }
02323 
02329 static PBSTileInfo ExtendTrainReservation(const Train *v, TrackBits *new_tracks, DiagDirection *enterdir)
02330 {
02331   PBSTileInfo origin = FollowTrainReservation(v);
02332 
02333   CFollowTrackRail ft(v);
02334 
02335   TileIndex tile = origin.tile;
02336   Trackdir  cur_td = origin.trackdir;
02337   while (ft.Follow(tile, cur_td)) {
02338     if (KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE) {
02339       /* Possible signal tile. */
02340       if (HasOnewaySignalBlockingTrackdir(ft.m_new_tile, FindFirstTrackdir(ft.m_new_td_bits))) break;
02341     }
02342 
02343     if (_settings_game.pf.forbid_90_deg) {
02344       ft.m_new_td_bits &= ~TrackdirCrossesTrackdirs(ft.m_old_td);
02345       if (ft.m_new_td_bits == TRACKDIR_BIT_NONE) break;
02346     }
02347 
02348     /* Station, depot or waypoint are a possible target. */
02349     bool target_seen = ft.m_is_station || (IsTileType(ft.m_new_tile, MP_RAILWAY) && !IsPlainRail(ft.m_new_tile));
02350     if (target_seen || KillFirstBit(ft.m_new_td_bits) != TRACKDIR_BIT_NONE) {
02351       /* Choice found or possible target encountered.
02352        * On finding a possible target, we need to stop and let the pathfinder handle the
02353        * remaining path. This is because we don't know if this target is in one of our
02354        * orders, so we might cause pathfinding to fail later on if we find a choice.
02355        * This failure would cause a bogous call to TryReserveSafePath which might reserve
02356        * a wrong path not leading to our next destination. */
02357       if (HasReservedTracks(ft.m_new_tile, TrackdirBitsToTrackBits(TrackdirReachesTrackdirs(ft.m_old_td)))) break;
02358 
02359       /* If we did skip some tiles, backtrack to the first skipped tile so the pathfinder
02360        * actually starts its search at the first unreserved tile. */
02361       if (ft.m_tiles_skipped != 0) ft.m_new_tile -= TileOffsByDiagDir(ft.m_exitdir) * ft.m_tiles_skipped;
02362 
02363       /* Choice found, path valid but not okay. Save info about the choice tile as well. */
02364       if (new_tracks != NULL) *new_tracks = TrackdirBitsToTrackBits(ft.m_new_td_bits);
02365       if (enterdir != NULL) *enterdir = ft.m_exitdir;
02366       return PBSTileInfo(ft.m_new_tile, ft.m_old_td, false);
02367     }
02368 
02369     tile = ft.m_new_tile;
02370     cur_td = FindFirstTrackdir(ft.m_new_td_bits);
02371 
02372     if (IsSafeWaitingPosition(v, tile, cur_td, true, _settings_game.pf.forbid_90_deg)) {
02373       bool wp_free = IsWaitingPositionFree(v, tile, cur_td, _settings_game.pf.forbid_90_deg);
02374       if (!(wp_free && TryReserveRailTrack(tile, TrackdirToTrack(cur_td)))) break;
02375       /* Safe position is all good, path valid and okay. */
02376       return PBSTileInfo(tile, cur_td, true);
02377     }
02378 
02379     if (!TryReserveRailTrack(tile, TrackdirToTrack(cur_td))) break;
02380   }
02381 
02382   if (ft.m_err == CFollowTrackRail::EC_OWNER || ft.m_err == CFollowTrackRail::EC_NO_WAY) {
02383     /* End of line, path valid and okay. */
02384     return PBSTileInfo(ft.m_old_tile, ft.m_old_td, true);
02385   }
02386 
02387   /* Sorry, can't reserve path, back out. */
02388   tile = origin.tile;
02389   cur_td = origin.trackdir;
02390   TileIndex stopped = ft.m_old_tile;
02391   Trackdir  stopped_td = ft.m_old_td;
02392   while (tile != stopped || cur_td != stopped_td) {
02393     if (!ft.Follow(tile, cur_td)) break;
02394 
02395     if (_settings_game.pf.forbid_90_deg) {
02396       ft.m_new_td_bits &= ~TrackdirCrossesTrackdirs(ft.m_old_td);
02397       assert(ft.m_new_td_bits != TRACKDIR_BIT_NONE);
02398     }
02399     assert(KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE);
02400 
02401     tile = ft.m_new_tile;
02402     cur_td = FindFirstTrackdir(ft.m_new_td_bits);
02403 
02404     UnreserveRailTrack(tile, TrackdirToTrack(cur_td));
02405   }
02406 
02407   /* Path invalid. */
02408   return PBSTileInfo();
02409 }
02410 
02421 static bool TryReserveSafeTrack(const Train *v, TileIndex tile, Trackdir td, bool override_tailtype)
02422 {
02423   switch (_settings_game.pf.pathfinder_for_trains) {
02424     case VPF_NPF: return NPFTrainFindNearestSafeTile(v, tile, td, override_tailtype);
02425     case VPF_YAPF: return YapfTrainFindNearestSafeTile(v, tile, td, override_tailtype);
02426 
02427     default: NOT_REACHED();
02428   }
02429 }
02430 
02432 class VehicleOrderSaver {
02433 private:
02434   Train          *v;
02435   Order          old_order;
02436   TileIndex      old_dest_tile;
02437   StationID      old_last_station_visited;
02438   VehicleOrderID index;
02439   bool           suppress_implicit_orders;
02440 
02441 public:
02442   VehicleOrderSaver(Train *_v) :
02443     v(_v),
02444     old_order(_v->current_order),
02445     old_dest_tile(_v->dest_tile),
02446     old_last_station_visited(_v->last_station_visited),
02447     index(_v->cur_real_order_index),
02448     suppress_implicit_orders(HasBit(_v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS))
02449   {
02450   }
02451 
02452   ~VehicleOrderSaver()
02453   {
02454     this->v->current_order = this->old_order;
02455     this->v->dest_tile = this->old_dest_tile;
02456     this->v->last_station_visited = this->old_last_station_visited;
02457     SB(this->v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS, 1, suppress_implicit_orders ? 1: 0);
02458   }
02459 
02465   bool SwitchToNextOrder(bool skip_first)
02466   {
02467     if (this->v->GetNumOrders() == 0) return false;
02468 
02469     if (skip_first) ++this->index;
02470 
02471     int depth = 0;
02472 
02473     do {
02474       /* Wrap around. */
02475       if (this->index >= this->v->GetNumOrders()) this->index = 0;
02476 
02477       Order *order = this->v->GetOrder(this->index);
02478       assert(order != NULL);
02479 
02480       switch (order->GetType()) {
02481         case OT_GOTO_DEPOT:
02482           /* Skip service in depot orders when the train doesn't need service. */
02483           if ((order->GetDepotOrderType() & ODTFB_SERVICE) && !this->v->NeedsServicing()) break;
02484         case OT_GOTO_STATION:
02485         case OT_GOTO_WAYPOINT:
02486           this->v->current_order = *order;
02487           return UpdateOrderDest(this->v, order, 0, true);
02488         case OT_CONDITIONAL: {
02489           VehicleOrderID next = ProcessConditionalOrder(order, this->v);
02490           if (next != INVALID_VEH_ORDER_ID) {
02491             depth++;
02492             this->index = next;
02493             /* Don't increment next, so no break here. */
02494             continue;
02495           }
02496           break;
02497         }
02498         default:
02499           break;
02500       }
02501       /* Don't increment inside the while because otherwise conditional
02502        * orders can lead to an infinite loop. */
02503       ++this->index;
02504       depth++;
02505     } while (this->index != this->v->cur_real_order_index && depth < this->v->GetNumOrders());
02506 
02507     return false;
02508   }
02509 };
02510 
02511 /* choose a track */
02512 static Track ChooseTrainTrack(Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool force_res, bool *got_reservation, bool mark_stuck)
02513 {
02514   Track best_track = INVALID_TRACK;
02515   bool do_track_reservation = _settings_game.pf.reserve_paths || force_res;
02516   bool changed_signal = false;
02517 
02518   assert((tracks & ~TRACK_BIT_MASK) == 0);
02519 
02520   if (got_reservation != NULL) *got_reservation = false;
02521 
02522   /* Don't use tracks here as the setting to forbid 90 deg turns might have been switched between reservation and now. */
02523   TrackBits res_tracks = (TrackBits)(GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir));
02524   /* Do we have a suitable reserved track? */
02525   if (res_tracks != TRACK_BIT_NONE) return FindFirstTrack(res_tracks);
02526 
02527   /* Quick return in case only one possible track is available */
02528   if (KillFirstBit(tracks) == TRACK_BIT_NONE) {
02529     Track track = FindFirstTrack(tracks);
02530     /* We need to check for signals only here, as a junction tile can't have signals. */
02531     if (track != INVALID_TRACK && HasPbsSignalOnTrackdir(tile, TrackEnterdirToTrackdir(track, enterdir))) {
02532       do_track_reservation = true;
02533       changed_signal = true;
02534       SetSignalStateByTrackdir(tile, TrackEnterdirToTrackdir(track, enterdir), SIGNAL_STATE_GREEN);
02535     } else if (!do_track_reservation) {
02536       return track;
02537     }
02538     best_track = track;
02539   }
02540 
02541   PBSTileInfo   res_dest(tile, INVALID_TRACKDIR, false);
02542   DiagDirection dest_enterdir = enterdir;
02543   if (do_track_reservation) {
02544     res_dest = ExtendTrainReservation(v, &tracks, &dest_enterdir);
02545     if (res_dest.tile == INVALID_TILE) {
02546       /* Reservation failed? */
02547       if (mark_stuck) MarkTrainAsStuck(v);
02548       if (changed_signal) SetSignalStateByTrackdir(tile, TrackEnterdirToTrackdir(best_track, enterdir), SIGNAL_STATE_RED);
02549       return FindFirstTrack(tracks);
02550     }
02551     if (res_dest.okay) {
02552       /* Got a valid reservation that ends at a safe target, quick exit. */
02553       if (got_reservation != NULL) *got_reservation = true;
02554       if (changed_signal) MarkTileDirtyByTile(tile);
02555       TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
02556       return best_track;
02557     }
02558 
02559     /* Check if the train needs service here, so it has a chance to always find a depot.
02560      * Also check if the current order is a service order so we don't reserve a path to
02561      * the destination but instead to the next one if service isn't needed. */
02562     CheckIfTrainNeedsService(v);
02563     if (v->current_order.IsType(OT_DUMMY) || v->current_order.IsType(OT_CONDITIONAL) || v->current_order.IsType(OT_GOTO_DEPOT)) ProcessOrders(v);
02564   }
02565 
02566   /* Save the current train order. The destructor will restore the old order on function exit. */
02567   VehicleOrderSaver orders(v);
02568 
02569   /* If the current tile is the destination of the current order and
02570    * a reservation was requested, advance to the next order.
02571    * Don't advance on a depot order as depots are always safe end points
02572    * for a path and no look-ahead is necessary. This also avoids a
02573    * problem with depot orders not part of the order list when the
02574    * order list itself is empty. */
02575   if (v->current_order.IsType(OT_LEAVESTATION)) {
02576     orders.SwitchToNextOrder(false);
02577   } else if (v->current_order.IsType(OT_LOADING) || (!v->current_order.IsType(OT_GOTO_DEPOT) && (
02578       v->current_order.IsType(OT_GOTO_STATION) ?
02579       IsRailStationTile(v->tile) && v->current_order.GetDestination() == GetStationIndex(v->tile) :
02580       v->tile == v->dest_tile))) {
02581     orders.SwitchToNextOrder(true);
02582   }
02583 
02584   if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
02585     /* Pathfinders are able to tell that route was only 'guessed'. */
02586     bool      path_found = true;
02587     TileIndex new_tile = res_dest.tile;
02588 
02589     Track next_track = DoTrainPathfind(v, new_tile, dest_enterdir, tracks, path_found, do_track_reservation, &res_dest);
02590     if (new_tile == tile) best_track = next_track;
02591     v->HandlePathfindingResult(path_found);
02592   }
02593 
02594   /* No track reservation requested -> finished. */
02595   if (!do_track_reservation) return best_track;
02596 
02597   /* A path was found, but could not be reserved. */
02598   if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
02599     if (mark_stuck) MarkTrainAsStuck(v);
02600     FreeTrainTrackReservation(v);
02601     return best_track;
02602   }
02603 
02604   /* No possible reservation target found, we are probably lost. */
02605   if (res_dest.tile == INVALID_TILE) {
02606     /* Try to find any safe destination. */
02607     PBSTileInfo origin = FollowTrainReservation(v);
02608     if (TryReserveSafeTrack(v, origin.tile, origin.trackdir, false)) {
02609       TrackBits res = GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir);
02610       best_track = FindFirstTrack(res);
02611       TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
02612       if (got_reservation != NULL) *got_reservation = true;
02613       if (changed_signal) MarkTileDirtyByTile(tile);
02614     } else {
02615       FreeTrainTrackReservation(v);
02616       if (mark_stuck) MarkTrainAsStuck(v);
02617     }
02618     return best_track;
02619   }
02620 
02621   if (got_reservation != NULL) *got_reservation = true;
02622 
02623   /* Reservation target found and free, check if it is safe. */
02624   while (!IsSafeWaitingPosition(v, res_dest.tile, res_dest.trackdir, true, _settings_game.pf.forbid_90_deg)) {
02625     /* Extend reservation until we have found a safe position. */
02626     DiagDirection exitdir = TrackdirToExitdir(res_dest.trackdir);
02627     TileIndex     next_tile = TileAddByDiagDir(res_dest.tile, exitdir);
02628     TrackBits     reachable = TrackdirBitsToTrackBits((TrackdirBits)(GetTileTrackStatus(next_tile, TRANSPORT_RAIL, 0))) & DiagdirReachesTracks(exitdir);
02629     if (_settings_game.pf.forbid_90_deg) {
02630       reachable &= ~TrackCrossesTracks(TrackdirToTrack(res_dest.trackdir));
02631     }
02632 
02633     /* Get next order with destination. */
02634     if (orders.SwitchToNextOrder(true)) {
02635       PBSTileInfo cur_dest;
02636       bool path_found;
02637       DoTrainPathfind(v, next_tile, exitdir, reachable, path_found, true, &cur_dest);
02638       if (cur_dest.tile != INVALID_TILE) {
02639         res_dest = cur_dest;
02640         if (res_dest.okay) continue;
02641         /* Path found, but could not be reserved. */
02642         FreeTrainTrackReservation(v);
02643         if (mark_stuck) MarkTrainAsStuck(v);
02644         if (got_reservation != NULL) *got_reservation = false;
02645         changed_signal = false;
02646         break;
02647       }
02648     }
02649     /* No order or no safe position found, try any position. */
02650     if (!TryReserveSafeTrack(v, res_dest.tile, res_dest.trackdir, true)) {
02651       FreeTrainTrackReservation(v);
02652       if (mark_stuck) MarkTrainAsStuck(v);
02653       if (got_reservation != NULL) *got_reservation = false;
02654       changed_signal = false;
02655     }
02656     break;
02657   }
02658 
02659   TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
02660 
02661   if (changed_signal) MarkTileDirtyByTile(tile);
02662 
02663   return best_track;
02664 }
02665 
02674 bool TryPathReserve(Train *v, bool mark_as_stuck, bool first_tile_okay)
02675 {
02676   assert(v->IsFrontEngine());
02677 
02678   /* We have to handle depots specially as the track follower won't look
02679    * at the depot tile itself but starts from the next tile. If we are still
02680    * inside the depot, a depot reservation can never be ours. */
02681   if (v->track == TRACK_BIT_DEPOT) {
02682     if (HasDepotReservation(v->tile)) {
02683       if (mark_as_stuck) MarkTrainAsStuck(v);
02684       return false;
02685     } else {
02686       /* Depot not reserved, but the next tile might be. */
02687       TileIndex next_tile = TileAddByDiagDir(v->tile, GetRailDepotDirection(v->tile));
02688       if (HasReservedTracks(next_tile, DiagdirReachesTracks(GetRailDepotDirection(v->tile)))) return false;
02689     }
02690   }
02691 
02692   Vehicle *other_train = NULL;
02693   PBSTileInfo origin = FollowTrainReservation(v, &other_train);
02694   /* The path we are driving on is already blocked by some other train.
02695    * This can only happen in certain situations when mixing path and
02696    * block signals or when changing tracks and/or signals.
02697    * Exit here as doing any further reservations will probably just
02698    * make matters worse. */
02699   if (other_train != NULL && other_train->index != v->index) {
02700     if (mark_as_stuck) MarkTrainAsStuck(v);
02701     return false;
02702   }
02703   /* If we have a reserved path and the path ends at a safe tile, we are finished already. */
02704   if (origin.okay && (v->tile != origin.tile || first_tile_okay)) {
02705     /* Can't be stuck then. */
02706     if (HasBit(v->flags, VRF_TRAIN_STUCK)) SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
02707     ClrBit(v->flags, VRF_TRAIN_STUCK);
02708     return true;
02709   }
02710 
02711   /* If we are in a depot, tentatively reserve the depot. */
02712   if (v->track == TRACK_BIT_DEPOT) {
02713     SetDepotReservation(v->tile, true);
02714     if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(v->tile);
02715   }
02716 
02717   DiagDirection exitdir = TrackdirToExitdir(origin.trackdir);
02718   TileIndex     new_tile = TileAddByDiagDir(origin.tile, exitdir);
02719   TrackBits     reachable = TrackdirBitsToTrackBits(TrackStatusToTrackdirBits(GetTileTrackStatus(new_tile, TRANSPORT_RAIL, 0)) & DiagdirReachesTrackdirs(exitdir));
02720 
02721   if (_settings_game.pf.forbid_90_deg) reachable &= ~TrackCrossesTracks(TrackdirToTrack(origin.trackdir));
02722 
02723   bool res_made = false;
02724   ChooseTrainTrack(v, new_tile, exitdir, reachable, true, &res_made, mark_as_stuck);
02725 
02726   if (!res_made) {
02727     /* Free the depot reservation as well. */
02728     if (v->track == TRACK_BIT_DEPOT) SetDepotReservation(v->tile, false);
02729     return false;
02730   }
02731 
02732   if (HasBit(v->flags, VRF_TRAIN_STUCK)) {
02733     v->wait_counter = 0;
02734     SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
02735   }
02736   ClrBit(v->flags, VRF_TRAIN_STUCK);
02737   return true;
02738 }
02739 
02740 
02741 static bool CheckReverseTrain(const Train *v)
02742 {
02743   if (_settings_game.difficulty.line_reverse_mode != 0 ||
02744       v->track == TRACK_BIT_DEPOT || v->track == TRACK_BIT_WORMHOLE ||
02745       !(v->direction & 1)) {
02746     return false;
02747   }
02748 
02749   assert(v->track != TRACK_BIT_NONE);
02750 
02751   switch (_settings_game.pf.pathfinder_for_trains) {
02752     case VPF_NPF: return NPFTrainCheckReverse(v);
02753     case VPF_YAPF: return YapfTrainCheckReverse(v);
02754 
02755     default: NOT_REACHED();
02756   }
02757 }
02758 
02764 TileIndex Train::GetOrderStationLocation(StationID station)
02765 {
02766   if (station == this->last_station_visited) this->last_station_visited = INVALID_STATION;
02767 
02768   const Station *st = Station::Get(station);
02769   if (!(st->facilities & FACIL_TRAIN)) {
02770     /* The destination station has no trainstation tiles. */
02771     this->IncrementRealOrderIndex();
02772     return 0;
02773   }
02774 
02775   return st->xy;
02776 }
02777 
02779 void Train::MarkDirty()
02780 {
02781   Train *v = this;
02782   do {
02783     v->colourmap = PAL_NONE;
02784     v->UpdateViewport(true, false);
02785   } while ((v = v->Next()) != NULL);
02786 
02787   /* need to update acceleration and cached values since the goods on the train changed. */
02788   this->CargoChanged();
02789   this->UpdateAcceleration();
02790 }
02791 
02799 int Train::UpdateSpeed()
02800 {
02801   switch (_settings_game.vehicle.train_acceleration_model) {
02802     default: NOT_REACHED();
02803     case AM_ORIGINAL:
02804       return this->DoUpdateSpeed(this->acceleration * (this->GetAccelerationStatus() == AS_BRAKE ? -4 : 2), 0, this->GetCurrentMaxSpeed());
02805 
02806     case AM_REALISTIC:
02807       return this->DoUpdateSpeed(this->GetAcceleration(), this->GetAccelerationStatus() == AS_BRAKE ? 0 : 2, this->GetCurrentMaxSpeed());
02808   }
02809 }
02810 
02816 static void TrainEnterStation(Train *v, StationID station)
02817 {
02818   v->last_station_visited = station;
02819 
02820   /* check if a train ever visited this station before */
02821   Station *st = Station::Get(station);
02822   if (!(st->had_vehicle_of_type & HVOT_TRAIN)) {
02823     st->had_vehicle_of_type |= HVOT_TRAIN;
02824     SetDParam(0, st->index);
02825     AddVehicleNewsItem(
02826       STR_NEWS_FIRST_TRAIN_ARRIVAL,
02827       v->owner == _local_company ? NT_ARRIVAL_COMPANY : NT_ARRIVAL_OTHER,
02828       v->index,
02829       st->index
02830     );
02831     AI::NewEvent(v->owner, new ScriptEventStationFirstVehicle(st->index, v->index));
02832     Game::NewEvent(new ScriptEventStationFirstVehicle(st->index, v->index));
02833   }
02834 
02835   v->force_proceed = TFP_NONE;
02836   SetWindowDirty(WC_VEHICLE_VIEW, v->index);
02837 
02838   v->BeginLoading();
02839 
02840   TriggerStationRandomisation(st, v->tile, SRT_TRAIN_ARRIVES);
02841   TriggerStationAnimation(st, v->tile, SAT_TRAIN_ARRIVES);
02842 }
02843 
02844 /* Check if the vehicle is compatible with the specified tile */
02845 static inline bool CheckCompatibleRail(const Train *v, TileIndex tile)
02846 {
02847   return IsTileOwner(tile, v->owner) &&
02848       (!v->IsFrontEngine() || HasBit(v->compatible_railtypes, GetRailType(tile)));
02849 }
02850 
02852 struct AccelerationSlowdownParams {
02853   byte small_turn; 
02854   byte large_turn; 
02855   byte z_up;       
02856   byte z_down;     
02857 };
02858 
02860 static const AccelerationSlowdownParams _accel_slowdown[] = {
02861   /* normal accel */
02862   {256 / 4, 256 / 2, 256 / 4, 2}, 
02863   {256 / 4, 256 / 2, 256 / 4, 2}, 
02864   {0,       256 / 2, 256 / 4, 2}, 
02865 };
02866 
02872 static inline void AffectSpeedByZChange(Train *v, int old_z)
02873 {
02874   if (old_z == v->z_pos || _settings_game.vehicle.train_acceleration_model != AM_ORIGINAL) return;
02875 
02876   const AccelerationSlowdownParams *asp = &_accel_slowdown[GetRailTypeInfo(v->railtype)->acceleration_type];
02877 
02878   if (old_z < v->z_pos) {
02879     v->cur_speed -= (v->cur_speed * asp->z_up >> 8);
02880   } else {
02881     uint16 spd = v->cur_speed + asp->z_down;
02882     if (spd <= v->gcache.cached_max_track_speed) v->cur_speed = spd;
02883   }
02884 }
02885 
02886 static bool TrainMovedChangeSignals(TileIndex tile, DiagDirection dir)
02887 {
02888   if (IsTileType(tile, MP_RAILWAY) &&
02889       GetRailTileType(tile) == RAIL_TILE_SIGNALS) {
02890     TrackdirBits tracks = TrackBitsToTrackdirBits(GetTrackBits(tile)) & DiagdirReachesTrackdirs(dir);
02891     Trackdir trackdir = FindFirstTrackdir(tracks);
02892     if (UpdateSignalsOnSegment(tile,  TrackdirToExitdir(trackdir), GetTileOwner(tile)) == SIGSEG_PBS && HasSignalOnTrackdir(tile, trackdir)) {
02893       /* A PBS block with a non-PBS signal facing us? */
02894       if (!IsPbsSignal(GetSignalType(tile, TrackdirToTrack(trackdir)))) return true;
02895     }
02896   }
02897   return false;
02898 }
02899 
02901 void Train::ReserveTrackUnderConsist() const
02902 {
02903   for (const Train *u = this; u != NULL; u = u->Next()) {
02904     switch (u->track) {
02905       case TRACK_BIT_WORMHOLE:
02906         TryReserveRailTrack(u->tile, DiagDirToDiagTrack(GetTunnelBridgeDirection(u->tile)));
02907         break;
02908       case TRACK_BIT_DEPOT:
02909         break;
02910       default:
02911         TryReserveRailTrack(u->tile, TrackBitsToTrack(u->track));
02912         break;
02913     }
02914   }
02915 }
02916 
02923 uint Train::Crash(bool flooded)
02924 {
02925   uint pass = 0;
02926   if (this->IsFrontEngine()) {
02927     pass += 2; // driver
02928 
02929     /* Remove the reserved path in front of the train if it is not stuck.
02930      * Also clear all reserved tracks the train is currently on. */
02931     if (!HasBit(this->flags, VRF_TRAIN_STUCK)) FreeTrainTrackReservation(this);
02932     for (const Train *v = this; v != NULL; v = v->Next()) {
02933       ClearPathReservation(v, v->tile, v->GetVehicleTrackdir());
02934       if (IsTileType(v->tile, MP_TUNNELBRIDGE)) {
02935         /* ClearPathReservation will not free the wormhole exit
02936          * if the train has just entered the wormhole. */
02937         SetTunnelBridgeReservation(GetOtherTunnelBridgeEnd(v->tile), false);
02938       }
02939     }
02940 
02941     /* we may need to update crossing we were approaching,
02942      * but must be updated after the train has been marked crashed */
02943     TileIndex crossing = TrainApproachingCrossingTile(this);
02944     if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
02945 
02946     /* Remove the loading indicators (if any) */
02947     HideFillingPercent(&this->fill_percent_te_id);
02948   }
02949 
02950   pass += this->GroundVehicleBase::Crash(flooded);
02951 
02952   this->crash_anim_pos = flooded ? 4000 : 1; // max 4440, disappear pretty fast when flooded
02953   return pass;
02954 }
02955 
02962 static uint TrainCrashed(Train *v)
02963 {
02964   uint num = 0;
02965 
02966   /* do not crash train twice */
02967   if (!(v->vehstatus & VS_CRASHED)) {
02968     num = v->Crash();
02969     AI::NewEvent(v->owner, new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_TRAIN));
02970     Game::NewEvent(new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_TRAIN));
02971   }
02972 
02973   /* Try to re-reserve track under already crashed train too.
02974    * Crash() clears the reservation! */
02975   v->ReserveTrackUnderConsist();
02976 
02977   return num;
02978 }
02979 
02981 struct TrainCollideChecker {
02982   Train *v; 
02983   uint num; 
02984 };
02985 
02992 static Vehicle *FindTrainCollideEnum(Vehicle *v, void *data)
02993 {
02994   TrainCollideChecker *tcc = (TrainCollideChecker*)data;
02995 
02996   /* not a train or in depot */
02997   if (v->type != VEH_TRAIN || Train::From(v)->track == TRACK_BIT_DEPOT) return NULL;
02998 
02999   /* do not crash into trains of another company. */
03000   if (v->owner != tcc->v->owner) return NULL;
03001 
03002   /* get first vehicle now to make most usual checks faster */
03003   Train *coll = Train::From(v)->First();
03004 
03005   /* can't collide with own wagons */
03006   if (coll == tcc->v) return NULL;
03007 
03008   int x_diff = v->x_pos - tcc->v->x_pos;
03009   int y_diff = v->y_pos - tcc->v->y_pos;
03010 
03011   /* Do fast calculation to check whether trains are not in close vicinity
03012    * and quickly reject trains distant enough for any collision.
03013    * Differences are shifted by 7, mapping range [-7 .. 8] into [0 .. 15]
03014    * Differences are then ORed and then we check for any higher bits */
03015   uint hash = (y_diff + 7) | (x_diff + 7);
03016   if (hash & ~15) return NULL;
03017 
03018   /* Slower check using multiplication */
03019   int min_diff = (Train::From(v)->gcache.cached_veh_length + 1) / 2 + (tcc->v->gcache.cached_veh_length + 1) / 2 - 1;
03020   if (x_diff * x_diff + y_diff * y_diff > min_diff * min_diff) return NULL;
03021 
03022   /* Happens when there is a train under bridge next to bridge head */
03023   if (abs(v->z_pos - tcc->v->z_pos) > 5) return NULL;
03024 
03025   /* crash both trains */
03026   tcc->num += TrainCrashed(tcc->v);
03027   tcc->num += TrainCrashed(coll);
03028 
03029   return NULL; // continue searching
03030 }
03031 
03039 static bool CheckTrainCollision(Train *v)
03040 {
03041   /* can't collide in depot */
03042   if (v->track == TRACK_BIT_DEPOT) return false;
03043 
03044   assert(v->track == TRACK_BIT_WORMHOLE || TileVirtXY(v->x_pos, v->y_pos) == v->tile);
03045 
03046   TrainCollideChecker tcc;
03047   tcc.v = v;
03048   tcc.num = 0;
03049 
03050   /* find colliding vehicles */
03051   if (v->track == TRACK_BIT_WORMHOLE) {
03052     FindVehicleOnPos(v->tile, &tcc, FindTrainCollideEnum);
03053     FindVehicleOnPos(GetOtherTunnelBridgeEnd(v->tile), &tcc, FindTrainCollideEnum);
03054   } else {
03055     FindVehicleOnPosXY(v->x_pos, v->y_pos, &tcc, FindTrainCollideEnum);
03056   }
03057 
03058   /* any dead -> no crash */
03059   if (tcc.num == 0) return false;
03060 
03061   SetDParam(0, tcc.num);
03062   AddVehicleNewsItem(STR_NEWS_TRAIN_CRASH, NT_ACCIDENT, v->index);
03063 
03064   ModifyStationRatingAround(v->tile, v->owner, -160, 30);
03065   if (_settings_client.sound.disaster) SndPlayVehicleFx(SND_13_BIG_CRASH, v);
03066   return true;
03067 }
03068 
03069 static Vehicle *CheckTrainAtSignal(Vehicle *v, void *data)
03070 {
03071   if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) return NULL;
03072 
03073   Train *t = Train::From(v);
03074   DiagDirection exitdir = *(DiagDirection *)data;
03075 
03076   /* not front engine of a train, inside wormhole or depot, crashed */
03077   if (!t->IsFrontEngine() || !(t->track & TRACK_BIT_MASK)) return NULL;
03078 
03079   if (t->cur_speed > 5 || TrainExitDir(t->direction, t->track) != exitdir) return NULL;
03080 
03081   return t;
03082 }
03083 
03091 bool TrainController(Train *v, Vehicle *nomove, bool reverse)
03092 {
03093   Train *first = v->First();
03094   Train *prev;
03095   bool direction_changed = false; // has direction of any part changed?
03096 
03097   /* For every vehicle after and including the given vehicle */
03098   for (prev = v->Previous(); v != nomove; prev = v, v = v->Next()) {
03099     DiagDirection enterdir = DIAGDIR_BEGIN;
03100     bool update_signals_crossing = false; // will we update signals or crossing state?
03101 
03102     GetNewVehiclePosResult gp = GetNewVehiclePos(v);
03103     if (v->track != TRACK_BIT_WORMHOLE) {
03104       /* Not inside tunnel */
03105       if (gp.old_tile == gp.new_tile) {
03106         /* Staying in the old tile */
03107         if (v->track == TRACK_BIT_DEPOT) {
03108           /* Inside depot */
03109           gp.x = v->x_pos;
03110           gp.y = v->y_pos;
03111         } else {
03112           /* Not inside depot */
03113 
03114           /* Reverse when we are at the end of the track already, do not move to the new position */
03115           if (v->IsFrontEngine() && !TrainCheckIfLineEnds(v, reverse)) return false;
03116 
03117           uint32 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
03118           if (HasBit(r, VETS_CANNOT_ENTER)) {
03119             goto invalid_rail;
03120           }
03121           if (HasBit(r, VETS_ENTERED_STATION)) {
03122             /* The new position is the end of the platform */
03123             TrainEnterStation(v, r >> VETS_STATION_ID_OFFSET);
03124           }
03125         }
03126       } else {
03127         /* A new tile is about to be entered. */
03128 
03129         /* Determine what direction we're entering the new tile from */
03130         enterdir = DiagdirBetweenTiles(gp.old_tile, gp.new_tile);
03131         assert(IsValidDiagDirection(enterdir));
03132 
03133         /* Get the status of the tracks in the new tile and mask
03134          * away the bits that aren't reachable. */
03135         TrackStatus ts = GetTileTrackStatus(gp.new_tile, TRANSPORT_RAIL, 0, ReverseDiagDir(enterdir));
03136         TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(enterdir);
03137 
03138         TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
03139         TrackBits red_signals = TrackdirBitsToTrackBits(TrackStatusToRedSignals(ts) & reachable_trackdirs);
03140 
03141         TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
03142         if (_settings_game.pf.forbid_90_deg && prev == NULL) {
03143           /* We allow wagons to make 90 deg turns, because forbid_90_deg
03144            * can be switched on halfway a turn */
03145           bits &= ~TrackCrossesTracks(FindFirstTrack(v->track));
03146         }
03147 
03148         if (bits == TRACK_BIT_NONE) goto invalid_rail;
03149 
03150         /* Check if the new tile constrains tracks that are compatible
03151          * with the current train, if not, bail out. */
03152         if (!CheckCompatibleRail(v, gp.new_tile)) goto invalid_rail;
03153 
03154         TrackBits chosen_track;
03155         if (prev == NULL) {
03156           /* Currently the locomotive is active. Determine which one of the
03157            * available tracks to choose */
03158           chosen_track = TrackToTrackBits(ChooseTrainTrack(v, gp.new_tile, enterdir, bits, false, NULL, true));
03159           assert(chosen_track & (bits | GetReservedTrackbits(gp.new_tile)));
03160 
03161           if (v->force_proceed != TFP_NONE && IsPlainRailTile(gp.new_tile) && HasSignals(gp.new_tile)) {
03162             /* For each signal we find decrease the counter by one.
03163              * We start at two, so the first signal we pass decreases
03164              * this to one, then if we reach the next signal it is
03165              * decreased to zero and we won't pass that new signal. */
03166             Trackdir dir = FindFirstTrackdir(trackdirbits);
03167             if (HasSignalOnTrackdir(gp.new_tile, dir) ||
03168                 (HasSignalOnTrackdir(gp.new_tile, ReverseTrackdir(dir)) &&
03169                 GetSignalType(gp.new_tile, TrackdirToTrack(dir)) != SIGTYPE_PBS)) {
03170               /* However, we do not want to be stopped by PBS signals
03171                * entered via the back. */
03172               v->force_proceed = (v->force_proceed == TFP_SIGNAL) ? TFP_STUCK : TFP_NONE;
03173               SetWindowDirty(WC_VEHICLE_VIEW, v->index);
03174             }
03175           }
03176 
03177           /* Check if it's a red signal and that force proceed is not clicked. */
03178           if ((red_signals & chosen_track) && v->force_proceed == TFP_NONE) {
03179             /* In front of a red signal */
03180             Trackdir i = FindFirstTrackdir(trackdirbits);
03181 
03182             /* Don't handle stuck trains here. */
03183             if (HasBit(v->flags, VRF_TRAIN_STUCK)) return false;
03184 
03185             if (!HasSignalOnTrackdir(gp.new_tile, ReverseTrackdir(i))) {
03186               v->cur_speed = 0;
03187               v->subspeed = 0;
03188               v->progress = 255 - 100;
03189               if (!_settings_game.pf.reverse_at_signals || ++v->wait_counter < _settings_game.pf.wait_oneway_signal * 20) return false;
03190             } else if (HasSignalOnTrackdir(gp.new_tile, i)) {
03191               v->cur_speed = 0;
03192               v->subspeed = 0;
03193               v->progress = 255 - 10;
03194               if (!_settings_game.pf.reverse_at_signals || ++v->wait_counter < _settings_game.pf.wait_twoway_signal * 73) {
03195                 DiagDirection exitdir = TrackdirToExitdir(i);
03196                 TileIndex o_tile = TileAddByDiagDir(gp.new_tile, exitdir);
03197 
03198                 exitdir = ReverseDiagDir(exitdir);
03199 
03200                 /* check if a train is waiting on the other side */
03201                 if (!HasVehicleOnPos(o_tile, &exitdir, &CheckTrainAtSignal)) return false;
03202               }
03203             }
03204 
03205             /* If we would reverse but are currently in a PBS block and
03206              * reversing of stuck trains is disabled, don't reverse.
03207              * This does not apply if the reason for reversing is a one-way
03208              * signal blocking us, because a train would then be stuck forever. */
03209             if (!_settings_game.pf.reverse_at_signals && !HasOnewaySignalBlockingTrackdir(gp.new_tile, i) &&
03210                 UpdateSignalsOnSegment(v->tile, enterdir, v->owner) == SIGSEG_PBS) {
03211               v->wait_counter = 0;
03212               return false;
03213             }
03214             goto reverse_train_direction;
03215           } else {
03216             TryReserveRailTrack(gp.new_tile, TrackBitsToTrack(chosen_track), false);
03217           }
03218         } else {
03219           /* The wagon is active, simply follow the prev vehicle. */
03220           if (prev->tile == gp.new_tile) {
03221             /* Choose the same track as prev */
03222             if (prev->track == TRACK_BIT_WORMHOLE) {
03223               /* Vehicles entering tunnels enter the wormhole earlier than for bridges.
03224                * However, just choose the track into the wormhole. */
03225               assert(IsTunnel(prev->tile));
03226               chosen_track = bits;
03227             } else {
03228               chosen_track = prev->track;
03229             }
03230           } else {
03231             /* Choose the track that leads to the tile where prev is.
03232              * This case is active if 'prev' is already on the second next tile, when 'v' just enters the next tile.
03233              * I.e. when the tile between them has only space for a single vehicle like
03234              *  1) horizontal/vertical track tiles and
03235              *  2) some orientations of tunnel entries, where the vehicle is already inside the wormhole at 8/16 from the tile edge.
03236              *     Is also the train just reversing, the wagon inside the tunnel is 'on' the tile of the opposite tunnel entry.
03237              */
03238             static const TrackBits _connecting_track[DIAGDIR_END][DIAGDIR_END] = {
03239               {TRACK_BIT_X,     TRACK_BIT_LOWER, TRACK_BIT_NONE,  TRACK_BIT_LEFT },
03240               {TRACK_BIT_UPPER, TRACK_BIT_Y,     TRACK_BIT_LEFT,  TRACK_BIT_NONE },
03241               {TRACK_BIT_NONE,  TRACK_BIT_RIGHT, TRACK_BIT_X,     TRACK_BIT_UPPER},
03242               {TRACK_BIT_RIGHT, TRACK_BIT_NONE,  TRACK_BIT_LOWER, TRACK_BIT_Y    }
03243             };
03244             DiagDirection exitdir = DiagdirBetweenTiles(gp.new_tile, prev->tile);
03245             assert(IsValidDiagDirection(exitdir));
03246             chosen_track = _connecting_track[enterdir][exitdir];
03247           }
03248           chosen_track &= bits;
03249         }
03250 
03251         /* Make sure chosen track is a valid track */
03252         assert(
03253             chosen_track == TRACK_BIT_X     || chosen_track == TRACK_BIT_Y ||
03254             chosen_track == TRACK_BIT_UPPER || chosen_track == TRACK_BIT_LOWER ||
03255             chosen_track == TRACK_BIT_LEFT  || chosen_track == TRACK_BIT_RIGHT);
03256 
03257         /* Update XY to reflect the entrance to the new tile, and select the direction to use */
03258         const byte *b = _initial_tile_subcoord[FIND_FIRST_BIT(chosen_track)][enterdir];
03259         gp.x = (gp.x & ~0xF) | b[0];
03260         gp.y = (gp.y & ~0xF) | b[1];
03261         Direction chosen_dir = (Direction)b[2];
03262 
03263         /* Call the landscape function and tell it that the vehicle entered the tile */
03264         uint32 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
03265         if (HasBit(r, VETS_CANNOT_ENTER)) {
03266           goto invalid_rail;
03267         }
03268 
03269         if (!HasBit(r, VETS_ENTERED_WORMHOLE)) {
03270           Track track = FindFirstTrack(chosen_track);
03271           Trackdir tdir = TrackDirectionToTrackdir(track, chosen_dir);
03272           if (v->IsFrontEngine() && HasPbsSignalOnTrackdir(gp.new_tile, tdir)) {
03273             SetSignalStateByTrackdir(gp.new_tile, tdir, SIGNAL_STATE_RED);
03274             MarkTileDirtyByTile(gp.new_tile);
03275           }
03276 
03277           /* Clear any track reservation when the last vehicle leaves the tile */
03278           if (v->Next() == NULL) ClearPathReservation(v, v->tile, v->GetVehicleTrackdir());
03279 
03280           v->tile = gp.new_tile;
03281 
03282           if (GetTileRailType(gp.new_tile) != GetTileRailType(gp.old_tile)) {
03283             v->First()->ConsistChanged(CCF_TRACK);
03284           }
03285 
03286           v->track = chosen_track;
03287           assert(v->track);
03288         }
03289 
03290         /* We need to update signal status, but after the vehicle position hash
03291          * has been updated by UpdateInclination() */
03292         update_signals_crossing = true;
03293 
03294         if (chosen_dir != v->direction) {
03295           if (prev == NULL && _settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) {
03296             const AccelerationSlowdownParams *asp = &_accel_slowdown[GetRailTypeInfo(v->railtype)->acceleration_type];
03297             DirDiff diff = DirDifference(v->direction, chosen_dir);
03298             v->cur_speed -= (diff == DIRDIFF_45RIGHT || diff == DIRDIFF_45LEFT ? asp->small_turn : asp->large_turn) * v->cur_speed >> 8;
03299           }
03300           direction_changed = true;
03301           v->direction = chosen_dir;
03302         }
03303 
03304         if (v->IsFrontEngine()) {
03305           v->wait_counter = 0;
03306 
03307           /* If we are approaching a crossing that is reserved, play the sound now. */
03308           TileIndex crossing = TrainApproachingCrossingTile(v);
03309           if (crossing != INVALID_TILE && HasCrossingReservation(crossing) && _settings_client.sound.ambient) SndPlayTileFx(SND_0E_LEVEL_CROSSING, crossing);
03310 
03311           /* Always try to extend the reservation when entering a tile. */
03312           CheckNextTrainTile(v);
03313         }
03314 
03315         if (HasBit(r, VETS_ENTERED_STATION)) {
03316           /* The new position is the location where we want to stop */
03317           TrainEnterStation(v, r >> VETS_STATION_ID_OFFSET);
03318         }
03319       }
03320     } else {
03321       if (IsTileType(gp.new_tile, MP_TUNNELBRIDGE) && HasBit(VehicleEnterTile(v, gp.new_tile, gp.x, gp.y), VETS_ENTERED_WORMHOLE)) {
03322         /* Perform look-ahead on tunnel exit. */
03323         if (v->IsFrontEngine()) {
03324           TryReserveRailTrack(gp.new_tile, DiagDirToDiagTrack(GetTunnelBridgeDirection(gp.new_tile)));
03325           CheckNextTrainTile(v);
03326         }
03327         /* Prevent v->UpdateInclination() being called with wrong parameters.
03328          * This could happen if the train was reversed inside the tunnel/bridge. */
03329         if (gp.old_tile == gp.new_tile) {
03330           gp.old_tile = GetOtherTunnelBridgeEnd(gp.old_tile);
03331         }
03332       } else {
03333         v->x_pos = gp.x;
03334         v->y_pos = gp.y;
03335         VehicleUpdatePosition(v);
03336         if ((v->vehstatus & VS_HIDDEN) == 0) VehicleUpdateViewport(v, true);
03337         continue;
03338       }
03339     }
03340 
03341     /* update image of train, as well as delta XY */
03342     v->UpdateDeltaXY(v->direction);
03343 
03344     v->x_pos = gp.x;
03345     v->y_pos = gp.y;
03346     VehicleUpdatePosition(v);
03347 
03348     /* update the Z position of the vehicle */
03349     int old_z = v->UpdateInclination(gp.new_tile != gp.old_tile, false);
03350 
03351     if (prev == NULL) {
03352       /* This is the first vehicle in the train */
03353       AffectSpeedByZChange(v, old_z);
03354     }
03355 
03356     if (update_signals_crossing) {
03357       if (v->IsFrontEngine()) {
03358         if (TrainMovedChangeSignals(gp.new_tile, enterdir)) {
03359           /* We are entering a block with PBS signals right now, but
03360            * not through a PBS signal. This means we don't have a
03361            * reservation right now. As a conventional signal will only
03362            * ever be green if no other train is in the block, getting
03363            * a path should always be possible. If the player built
03364            * such a strange network that it is not possible, the train
03365            * will be marked as stuck and the player has to deal with
03366            * the problem. */
03367           if ((!HasReservedTracks(gp.new_tile, v->track) &&
03368               !TryReserveRailTrack(gp.new_tile, FindFirstTrack(v->track))) ||
03369               !TryPathReserve(v)) {
03370             MarkTrainAsStuck(v);
03371           }
03372         }
03373       }
03374 
03375       /* Signals can only change when the first
03376        * (above) or the last vehicle moves. */
03377       if (v->Next() == NULL) {
03378         TrainMovedChangeSignals(gp.old_tile, ReverseDiagDir(enterdir));
03379         if (IsLevelCrossingTile(gp.old_tile)) UpdateLevelCrossing(gp.old_tile);
03380       }
03381     }
03382 
03383     /* Do not check on every tick to save some computing time. */
03384     if (v->IsFrontEngine() && v->tick_counter % _settings_game.pf.path_backoff_interval == 0) CheckNextTrainTile(v);
03385   }
03386 
03387   if (direction_changed) first->tcache.cached_max_curve_speed = first->GetCurveSpeedLimit();
03388 
03389   return true;
03390 
03391 invalid_rail:
03392   /* We've reached end of line?? */
03393   if (prev != NULL) error("Disconnecting train");
03394 
03395 reverse_train_direction:
03396   if (reverse) {
03397     v->wait_counter = 0;
03398     v->cur_speed = 0;
03399     v->subspeed = 0;
03400     ReverseTrainDirection(v);
03401   }
03402 
03403   return false;
03404 }
03405 
03412 static Vehicle *CollectTrackbitsFromCrashedVehiclesEnum(Vehicle *v, void *data)
03413 {
03414   TrackBits *trackbits = (TrackBits *)data;
03415 
03416   if (v->type == VEH_TRAIN && (v->vehstatus & VS_CRASHED) != 0) {
03417     TrackBits train_tbits = Train::From(v)->track;
03418     if (train_tbits == TRACK_BIT_WORMHOLE) {
03419       /* Vehicle is inside a wormhole, v->track contains no useful value then. */
03420       *trackbits |= DiagDirToDiagTrackBits(GetTunnelBridgeDirection(v->tile));
03421     } else if (train_tbits != TRACK_BIT_DEPOT) {
03422       *trackbits |= train_tbits;
03423     }
03424   }
03425 
03426   return NULL;
03427 }
03428 
03436 static void DeleteLastWagon(Train *v)
03437 {
03438   Train *first = v->First();
03439 
03440   /* Go to the last wagon and delete the link pointing there
03441    * *u is then the one-before-last wagon, and *v the last
03442    * one which will physically be removed */
03443   Train *u = v;
03444   for (; v->Next() != NULL; v = v->Next()) u = v;
03445   u->SetNext(NULL);
03446 
03447   if (first != v) {
03448     /* Recalculate cached train properties */
03449     first->ConsistChanged(CCF_ARRANGE);
03450     /* Update the depot window if the first vehicle is in depot -
03451      * if v == first, then it is updated in PreDestructor() */
03452     if (first->track == TRACK_BIT_DEPOT) {
03453       SetWindowDirty(WC_VEHICLE_DEPOT, first->tile);
03454     }
03455     v->last_station_visited = first->last_station_visited; // for PreDestructor
03456   }
03457 
03458   /* 'v' shouldn't be accessed after it has been deleted */
03459   TrackBits trackbits = v->track;
03460   TileIndex tile = v->tile;
03461   Owner owner = v->owner;
03462 
03463   delete v;
03464   v = NULL; // make sure nobody will try to read 'v' anymore
03465 
03466   if (trackbits == TRACK_BIT_WORMHOLE) {
03467     /* Vehicle is inside a wormhole, v->track contains no useful value then. */
03468     trackbits = DiagDirToDiagTrackBits(GetTunnelBridgeDirection(tile));
03469   }
03470 
03471   Track track = TrackBitsToTrack(trackbits);
03472   if (HasReservedTracks(tile, trackbits)) {
03473     UnreserveRailTrack(tile, track);
03474 
03475     /* If there are still crashed vehicles on the tile, give the track reservation to them */
03476     TrackBits remaining_trackbits = TRACK_BIT_NONE;
03477     FindVehicleOnPos(tile, &remaining_trackbits, CollectTrackbitsFromCrashedVehiclesEnum);
03478 
03479     /* It is important that these two are the first in the loop, as reservation cannot deal with every trackbit combination */
03480     assert(TRACK_BEGIN == TRACK_X && TRACK_Y == TRACK_BEGIN + 1);
03481     Track t;
03482     FOR_EACH_SET_TRACK(t, remaining_trackbits) TryReserveRailTrack(tile, t);
03483   }
03484 
03485   /* check if the wagon was on a road/rail-crossing */
03486   if (IsLevelCrossingTile(tile)) UpdateLevelCrossing(tile);
03487 
03488   /* Update signals */
03489   if (IsTileType(tile, MP_TUNNELBRIDGE) || IsRailDepotTile(tile)) {
03490     UpdateSignalsOnSegment(tile, INVALID_DIAGDIR, owner);
03491   } else {
03492     SetSignalsOnBothDir(tile, track, owner);
03493   }
03494 }
03495 
03500 static void ChangeTrainDirRandomly(Train *v)
03501 {
03502   static const DirDiff delta[] = {
03503     DIRDIFF_45LEFT, DIRDIFF_SAME, DIRDIFF_SAME, DIRDIFF_45RIGHT
03504   };
03505 
03506   do {
03507     /* We don't need to twist around vehicles if they're not visible */
03508     if (!(v->vehstatus & VS_HIDDEN)) {
03509       v->direction = ChangeDir(v->direction, delta[GB(Random(), 0, 2)]);
03510       v->UpdateDeltaXY(v->direction);
03511       v->cur_image = v->GetImage(v->direction, EIT_ON_MAP);
03512       /* Refrain from updating the z position of the vehicle when on
03513        * a bridge, because UpdateInclination() will put the vehicle under
03514        * the bridge in that case */
03515       if (v->track != TRACK_BIT_WORMHOLE) {
03516         VehicleUpdatePosition(v);
03517         v->UpdateInclination(false, false);
03518       }
03519     }
03520   } while ((v = v->Next()) != NULL);
03521 }
03522 
03528 static bool HandleCrashedTrain(Train *v)
03529 {
03530   int state = ++v->crash_anim_pos;
03531 
03532   if (state == 4 && !(v->vehstatus & VS_HIDDEN)) {
03533     CreateEffectVehicleRel(v, 4, 4, 8, EV_EXPLOSION_LARGE);
03534   }
03535 
03536   uint32 r;
03537   if (state <= 200 && Chance16R(1, 7, r)) {
03538     int index = (r * 10 >> 16);
03539 
03540     Vehicle *u = v;
03541     do {
03542       if (--index < 0) {
03543         r = Random();
03544 
03545         CreateEffectVehicleRel(u,
03546           GB(r,  8, 3) + 2,
03547           GB(r, 16, 3) + 2,
03548           GB(r,  0, 3) + 5,
03549           EV_EXPLOSION_SMALL);
03550         break;
03551       }
03552     } while ((u = u->Next()) != NULL);
03553   }
03554 
03555   if (state <= 240 && !(v->tick_counter & 3)) ChangeTrainDirRandomly(v);
03556 
03557   if (state >= 4440 && !(v->tick_counter & 0x1F)) {
03558     bool ret = v->Next() != NULL;
03559     DeleteLastWagon(v);
03560     return ret;
03561   }
03562 
03563   return true;
03564 }
03565 
03567 static const uint16 _breakdown_speeds[16] = {
03568   225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, 15
03569 };
03570 
03571 
03580 static bool TrainApproachingLineEnd(Train *v, bool signal, bool reverse)
03581 {
03582   /* Calc position within the current tile */
03583   uint x = v->x_pos & 0xF;
03584   uint y = v->y_pos & 0xF;
03585 
03586   /* for diagonal directions, 'x' will be 0..15 -
03587    * for other directions, it will be 1, 3, 5, ..., 15 */
03588   switch (v->direction) {
03589     case DIR_N : x = ~x + ~y + 25; break;
03590     case DIR_NW: x = y;            // FALL THROUGH
03591     case DIR_NE: x = ~x + 16;      break;
03592     case DIR_E : x = ~x + y + 9;   break;
03593     case DIR_SE: x = y;            break;
03594     case DIR_S : x = x + y - 7;    break;
03595     case DIR_W : x = ~y + x + 9;   break;
03596     default: break;
03597   }
03598 
03599   /* Do not reverse when approaching red signal. Make sure the vehicle's front
03600    * does not cross the tile boundary when we do reverse, but as the vehicle's
03601    * location is based on their center, use half a vehicle's length as offset.
03602    * Multiply the half-length by two for straight directions to compensate that
03603    * we only get odd x offsets there. */
03604   if (!signal && x + (v->gcache.cached_veh_length + 1) / 2 * (IsDiagonalDirection(v->direction) ? 1 : 2) >= TILE_SIZE) {
03605     /* we are too near the tile end, reverse now */
03606     v->cur_speed = 0;
03607     if (reverse) ReverseTrainDirection(v);
03608     return false;
03609   }
03610 
03611   /* slow down */
03612   v->vehstatus |= VS_TRAIN_SLOWING;
03613   uint16 break_speed = _breakdown_speeds[x & 0xF];
03614   if (break_speed < v->cur_speed) v->cur_speed = break_speed;
03615 
03616   return true;
03617 }
03618 
03619 
03625 static bool TrainCanLeaveTile(const Train *v)
03626 {
03627   /* Exit if inside a tunnel/bridge or a depot */
03628   if (v->track == TRACK_BIT_WORMHOLE || v->track == TRACK_BIT_DEPOT) return false;
03629 
03630   TileIndex tile = v->tile;
03631 
03632   /* entering a tunnel/bridge? */
03633   if (IsTileType(tile, MP_TUNNELBRIDGE)) {
03634     DiagDirection dir = GetTunnelBridgeDirection(tile);
03635     if (DiagDirToDir(dir) == v->direction) return false;
03636   }
03637 
03638   /* entering a depot? */
03639   if (IsRailDepotTile(tile)) {
03640     DiagDirection dir = ReverseDiagDir(GetRailDepotDirection(tile));
03641     if (DiagDirToDir(dir) == v->direction) return false;
03642   }
03643 
03644   return true;
03645 }
03646 
03647 
03655 static TileIndex TrainApproachingCrossingTile(const Train *v)
03656 {
03657   assert(v->IsFrontEngine());
03658   assert(!(v->vehstatus & VS_CRASHED));
03659 
03660   if (!TrainCanLeaveTile(v)) return INVALID_TILE;
03661 
03662   DiagDirection dir = TrainExitDir(v->direction, v->track);
03663   TileIndex tile = v->tile + TileOffsByDiagDir(dir);
03664 
03665   /* not a crossing || wrong axis || unusable rail (wrong type or owner) */
03666   if (!IsLevelCrossingTile(tile) || DiagDirToAxis(dir) == GetCrossingRoadAxis(tile) ||
03667       !CheckCompatibleRail(v, tile)) {
03668     return INVALID_TILE;
03669   }
03670 
03671   return tile;
03672 }
03673 
03674 
03682 static bool TrainCheckIfLineEnds(Train *v, bool reverse)
03683 {
03684   /* First, handle broken down train */
03685 
03686   int t = v->breakdown_ctr;
03687   if (t > 1) {
03688     v->vehstatus |= VS_TRAIN_SLOWING;
03689 
03690     uint16 break_speed = _breakdown_speeds[GB(~t, 4, 4)];
03691     if (break_speed < v->cur_speed) v->cur_speed = break_speed;
03692   } else {
03693     v->vehstatus &= ~VS_TRAIN_SLOWING;
03694   }
03695 
03696   if (!TrainCanLeaveTile(v)) return true;
03697 
03698   /* Determine the non-diagonal direction in which we will exit this tile */
03699   DiagDirection dir = TrainExitDir(v->direction, v->track);
03700   /* Calculate next tile */
03701   TileIndex tile = v->tile + TileOffsByDiagDir(dir);
03702 
03703   /* Determine the track status on the next tile */
03704   TrackStatus ts = GetTileTrackStatus(tile, TRANSPORT_RAIL, 0, ReverseDiagDir(dir));
03705   TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(dir);
03706 
03707   TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
03708   TrackdirBits red_signals = TrackStatusToRedSignals(ts) & reachable_trackdirs;
03709 
03710   /* We are sure the train is not entering a depot, it is detected above */
03711 
03712   /* mask unreachable track bits if we are forbidden to do 90deg turns */
03713   TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
03714   if (_settings_game.pf.forbid_90_deg) {
03715     bits &= ~TrackCrossesTracks(FindFirstTrack(v->track));
03716   }
03717 
03718   /* no suitable trackbits at all || unusable rail (wrong type or owner) */
03719   if (bits == TRACK_BIT_NONE || !CheckCompatibleRail(v, tile)) {
03720     return TrainApproachingLineEnd(v, false, reverse);
03721   }
03722 
03723   /* approaching red signal */
03724   if ((trackdirbits & red_signals) != 0) return TrainApproachingLineEnd(v, true, reverse);
03725 
03726   /* approaching a rail/road crossing? then make it red */
03727   if (IsLevelCrossingTile(tile)) MaybeBarCrossingWithSound(tile);
03728 
03729   return true;
03730 }
03731 
03732 
03733 static bool TrainLocoHandler(Train *v, bool mode)
03734 {
03735   /* train has crashed? */
03736   if (v->vehstatus & VS_CRASHED) {
03737     return mode ? true : HandleCrashedTrain(v); // 'this' can be deleted here
03738   }
03739 
03740   if (v->force_proceed != TFP_NONE) {
03741     ClrBit(v->flags, VRF_TRAIN_STUCK);
03742     SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
03743   }
03744 
03745   /* train is broken down? */
03746   if (v->HandleBreakdown()) return true;
03747 
03748   if (HasBit(v->flags, VRF_REVERSING) && v->cur_speed == 0) {
03749     ReverseTrainDirection(v);
03750   }
03751 
03752   /* exit if train is stopped */
03753   if ((v->vehstatus & VS_STOPPED) && v->cur_speed == 0) return true;
03754 
03755   bool valid_order = !v->current_order.IsType(OT_NOTHING) && v->current_order.GetType() != OT_CONDITIONAL;
03756   if (ProcessOrders(v) && CheckReverseTrain(v)) {
03757     v->wait_counter = 0;
03758     v->cur_speed = 0;
03759     v->subspeed = 0;
03760     ClrBit(v->flags, VRF_LEAVING_STATION);
03761     ReverseTrainDirection(v);
03762     return true;
03763   } else if (HasBit(v->flags, VRF_LEAVING_STATION)) {
03764     /* Try to reserve a path when leaving the station as we
03765      * might not be marked as wanting a reservation, e.g.
03766      * when an overlength train gets turned around in a station. */
03767     DiagDirection dir = TrainExitDir(v->direction, v->track);
03768     if (IsRailDepotTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE)) dir = INVALID_DIAGDIR;
03769 
03770     if (UpdateSignalsOnSegment(v->tile, dir, v->owner) == SIGSEG_PBS || _settings_game.pf.reserve_paths) {
03771       TryPathReserve(v, true, true);
03772     }
03773     ClrBit(v->flags, VRF_LEAVING_STATION);
03774   }
03775 
03776   v->HandleLoading(mode);
03777 
03778   if (v->current_order.IsType(OT_LOADING)) return true;
03779 
03780   if (CheckTrainStayInDepot(v)) return true;
03781 
03782   if (!mode) v->ShowVisualEffect();
03783 
03784   /* We had no order but have an order now, do look ahead. */
03785   if (!valid_order && !v->current_order.IsType(OT_NOTHING)) {
03786     CheckNextTrainTile(v);
03787   }
03788 
03789   /* Handle stuck trains. */
03790   if (!mode && HasBit(v->flags, VRF_TRAIN_STUCK)) {
03791     ++v->wait_counter;
03792 
03793     /* Should we try reversing this tick if still stuck? */
03794     bool turn_around = v->wait_counter % (_settings_game.pf.wait_for_pbs_path * DAY_TICKS) == 0 && _settings_game.pf.reverse_at_signals;
03795 
03796     if (!turn_around && v->wait_counter % _settings_game.pf.path_backoff_interval != 0 && v->force_proceed == TFP_NONE) return true;
03797     if (!TryPathReserve(v)) {
03798       /* Still stuck. */
03799       if (turn_around) ReverseTrainDirection(v);
03800 
03801       if (HasBit(v->flags, VRF_TRAIN_STUCK) && v->wait_counter > 2 * _settings_game.pf.wait_for_pbs_path * DAY_TICKS) {
03802         /* Show message to player. */
03803         if (_settings_client.gui.lost_vehicle_warn && v->owner == _local_company) {
03804           SetDParam(0, v->index);
03805           AddVehicleAdviceNewsItem(STR_NEWS_TRAIN_IS_STUCK, v->index);
03806         }
03807         v->wait_counter = 0;
03808       }
03809       /* Exit if force proceed not pressed, else reset stuck flag anyway. */
03810       if (v->force_proceed == TFP_NONE) return true;
03811       ClrBit(v->flags, VRF_TRAIN_STUCK);
03812       v->wait_counter = 0;
03813       SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
03814     }
03815   }
03816 
03817   if (v->current_order.IsType(OT_LEAVESTATION)) {
03818     v->current_order.Free();
03819     SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
03820     return true;
03821   }
03822 
03823   int j = v->UpdateSpeed();
03824 
03825   /* we need to invalidate the widget if we are stopping from 'Stopping 0 km/h' to 'Stopped' */
03826   if (v->cur_speed == 0 && (v->vehstatus & VS_STOPPED)) {
03827     /* If we manually stopped, we're not force-proceeding anymore. */
03828     v->force_proceed = TFP_NONE;
03829     SetWindowDirty(WC_VEHICLE_VIEW, v->index);
03830   }
03831 
03832   int adv_spd = v->GetAdvanceDistance();
03833   if (j < adv_spd) {
03834     /* if the vehicle has speed 0, update the last_speed field. */
03835     if (v->cur_speed == 0) v->SetLastSpeed();
03836   } else {
03837     TrainCheckIfLineEnds(v);
03838     /* Loop until the train has finished moving. */
03839     for (;;) {
03840       j -= adv_spd;
03841       TrainController(v, NULL);
03842       /* Don't continue to move if the train crashed. */
03843       if (CheckTrainCollision(v)) break;
03844       /* Determine distance to next map position */
03845       adv_spd = v->GetAdvanceDistance();
03846 
03847       /* No more moving this tick */
03848       if (j < adv_spd || v->cur_speed == 0) break;
03849 
03850       OrderType order_type = v->current_order.GetType();
03851       /* Do not skip waypoints (incl. 'via' stations) when passing through at full speed. */
03852       if ((order_type == OT_GOTO_WAYPOINT || order_type == OT_GOTO_STATION) &&
03853             (v->current_order.GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION) &&
03854             IsTileType(v->tile, MP_STATION) &&
03855             v->current_order.GetDestination() == GetStationIndex(v->tile)) {
03856         ProcessOrders(v);
03857       }
03858     }
03859     v->SetLastSpeed();
03860   }
03861 
03862   for (Train *u = v; u != NULL; u = u->Next()) {
03863     if ((u->vehstatus & VS_HIDDEN) != 0) continue;
03864 
03865     u->UpdateViewport(false, false);
03866   }
03867 
03868   if (v->progress == 0) v->progress = j; // Save unused spd for next time, if TrainController didn't set progress
03869 
03870   return true;
03871 }
03872 
03877 Money Train::GetRunningCost() const
03878 {
03879   Money cost = 0;
03880   const Train *v = this;
03881 
03882   do {
03883     const Engine *e = v->GetEngine();
03884     if (e->u.rail.running_cost_class == INVALID_PRICE) continue;
03885 
03886     uint cost_factor = GetVehicleProperty(v, PROP_TRAIN_RUNNING_COST_FACTOR, e->u.rail.running_cost);
03887     if (cost_factor == 0) continue;
03888 
03889     /* Halve running cost for multiheaded parts */
03890     if (v->IsMultiheaded()) cost_factor /= 2;
03891 
03892     cost += GetPrice(e->u.rail.running_cost_class, cost_factor, e->GetGRF());
03893   } while ((v = v->GetNextVehicle()) != NULL);
03894 
03895   return cost;
03896 }
03897 
03902 bool Train::Tick()
03903 {
03904   this->tick_counter++;
03905 
03906   if (this->IsFrontEngine()) {
03907     if (!(this->vehstatus & VS_STOPPED) || this->cur_speed > 0) this->running_ticks++;
03908 
03909     this->current_order_time++;
03910 
03911     if (!TrainLocoHandler(this, false)) return false;
03912 
03913     return TrainLocoHandler(this, true);
03914   } else if (this->IsFreeWagon() && (this->vehstatus & VS_CRASHED)) {
03915     /* Delete flooded standalone wagon chain */
03916     if (++this->crash_anim_pos >= 4400) {
03917       delete this;
03918       return false;
03919     }
03920   }
03921 
03922   return true;
03923 }
03924 
03929 static void CheckIfTrainNeedsService(Train *v)
03930 {
03931   if (Company::Get(v->owner)->settings.vehicle.servint_trains == 0 || !v->NeedsAutomaticServicing()) return;
03932   if (v->IsChainInDepot()) {
03933     VehicleServiceInDepot(v);
03934     return;
03935   }
03936 
03937   uint max_penalty;
03938   switch (_settings_game.pf.pathfinder_for_trains) {
03939     case VPF_NPF:  max_penalty = _settings_game.pf.npf.maximum_go_to_depot_penalty;  break;
03940     case VPF_YAPF: max_penalty = _settings_game.pf.yapf.maximum_go_to_depot_penalty; break;
03941     default: NOT_REACHED();
03942   }
03943 
03944   FindDepotData tfdd = FindClosestTrainDepot(v, max_penalty);
03945   /* Only go to the depot if it is not too far out of our way. */
03946   if (tfdd.best_length == UINT_MAX || tfdd.best_length > max_penalty) {
03947     if (v->current_order.IsType(OT_GOTO_DEPOT)) {
03948       /* If we were already heading for a depot but it has
03949        * suddenly moved farther away, we continue our normal
03950        * schedule? */
03951       v->current_order.MakeDummy();
03952       SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
03953     }
03954     return;
03955   }
03956 
03957   DepotID depot = GetDepotIndex(tfdd.tile);
03958 
03959   if (v->current_order.IsType(OT_GOTO_DEPOT) &&
03960       v->current_order.GetDestination() != depot &&
03961       !Chance16(3, 16)) {
03962     return;
03963   }
03964 
03965   SetBit(v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS);
03966   v->current_order.MakeGoToDepot(depot, ODTFB_SERVICE);
03967   v->dest_tile = tfdd.tile;
03968   SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
03969 }
03970 
03972 void Train::OnNewDay()
03973 {
03974   AgeVehicle(this);
03975 
03976   if ((++this->day_counter & 7) == 0) DecreaseVehicleValue(this);
03977 
03978   if (this->IsFrontEngine()) {
03979     CheckVehicleBreakdown(this);
03980 
03981     CheckIfTrainNeedsService(this);
03982 
03983     CheckOrders(this);
03984 
03985     /* update destination */
03986     if (this->current_order.IsType(OT_GOTO_STATION)) {
03987       TileIndex tile = Station::Get(this->current_order.GetDestination())->train_station.tile;
03988       if (tile != INVALID_TILE) this->dest_tile = tile;
03989     }
03990 
03991     if (this->running_ticks != 0) {
03992       /* running costs */
03993       CommandCost cost(EXPENSES_TRAIN_RUN, this->GetRunningCost() * this->running_ticks / (DAYS_IN_YEAR  * DAY_TICKS));
03994 
03995       this->profit_this_year -= cost.GetCost();
03996       this->running_ticks = 0;
03997 
03998       SubtractMoneyFromCompanyFract(this->owner, cost);
03999 
04000       SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
04001       SetWindowClassesDirty(WC_TRAINS_LIST);
04002     }
04003   }
04004 }
04005 
04010 Trackdir Train::GetVehicleTrackdir() const
04011 {
04012   if (this->vehstatus & VS_CRASHED) return INVALID_TRACKDIR;
04013 
04014   if (this->track == TRACK_BIT_DEPOT) {
04015     /* We'll assume the train is facing outwards */
04016     return DiagDirToDiagTrackdir(GetRailDepotDirection(this->tile)); // Train in depot
04017   }
04018 
04019   if (this->track == TRACK_BIT_WORMHOLE) {
04020     /* train in tunnel or on bridge, so just use his direction and assume a diagonal track */
04021     return DiagDirToDiagTrackdir(DirToDiagDir(this->direction));
04022   }
04023 
04024   return TrackDirectionToTrackdir(FindFirstTrack(this->track), this->direction);
04025 }