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