# train_cmd.cpp

Go to the documentation of this file.

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