train_cmd.cpp

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