# train_cmd.cpp

Go to the documentation of this file.

    00001 /* $Id: train_cmd.cpp 18866 2010-01-18 22:57:21Z rubidium $ */
    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 "gui.h"
    00014 #include "articulated_vehicles.h"
    00015 #include "command_func.h"
    00016 #include "pathfinder/npf/npf_func.h"
    00017 #include "pathfinder/yapf/yapf.hpp"
    00018 #include "news_func.h"
    00019 #include "company_func.h"
    00020 #include "vehicle_gui.h"
    00021 #include "newgrf_engine.h"
    00022 #include "newgrf_sound.h"
    00023 #include "newgrf_text.h"
    00024 #include "group.h"
    00025 #include "table/sprites.h"
    00026 #include "strings_func.h"
    00027 #include "functions.h"
    00028 #include "window_func.h"
    00029 #include "vehicle_func.h"
    00030 #include "sound_func.h"
    00031 #include "autoreplace_gui.h"
    00032 #include "ai/ai.hpp"
    00033 #include "newgrf_station.h"
    00034 #include "effectvehicle_func.h"
    00035 #include "effectvehicle_base.h"
    00036 #include "gamelog.h"
    00037 #include "network/network.h"
    00038 #include "spritecache.h"
    00039 #include "core/random_func.hpp"
    00040 #include "company_base.h"
    00041 #include "engine_base.h"
    00042 #include "engine_func.h"
    00043 #include "newgrf.h"
    00044
    00045 #include "table/strings.h"
    00046 #include "table/train_cmd.h"
    00047
    00048 static Track ChooseTrainTrack(Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool force_res, bool *got_reservation, bool mark_stuck);
    00049 static bool TrainCheckIfLineEnds(Train *v);
    00050 static void TrainController(Train *v, Vehicle *nomove);
    00051 static TileIndex TrainApproachingCrossingTile(const Train *v);
    00052 static void CheckIfTrainNeedsService(Train *v);
    00053 static void CheckNextTrainTile(Train *v);
    00054
    00055 static const byte _vehicle_initial_x_fract[4] = {10, 8, 4,  8};
    00056 static const byte _vehicle_initial_y_fract[4] = { 8, 4, 8, 10};
    00057
    00058
    00066 static inline DiagDirection TrainExitDir(Direction direction, TrackBits track)
    00067 {
    00068   static const TrackBits state_dir_table[DIAGDIR_END] = { TRACK_BIT_RIGHT, TRACK_BIT_LOWER, TRACK_BIT_LEFT, TRACK_BIT_UPPER };
    00069
    00070   DiagDirection diagdir = DirToDiagDir(direction);
    00071
    00072   /* Determine the diagonal direction in which we will exit this tile */
    00073   if (!HasBit(direction, 0) && track != state_dir_table[diagdir]) {
    00074     diagdir = ChangeDiagDir(diagdir, DIAGDIRDIFF_90LEFT);
    00075   }
    00076
    00077   return diagdir;
    00078 }
    00079
    00080
    00085 byte FreightWagonMult(CargoID cargo)
    00086 {
    00087   if (!CargoSpec::Get(cargo)->is_freight) return 1;
    00088   return _settings_game.vehicle.freight_trains;
    00089 }
    00090
    00091
    00095 void Train::PowerChanged()
    00096 {
    00097   assert(this->First() == this);
    00098
    00099   uint32 total_power = 0;
    00100   uint32 max_te = 0;
    00101   uint32 number_of_parts = 0;
    00102
    00103   for (const Train *u = this; u != NULL; u = u->Next()) {
    00104     uint32 current_power = u->GetPower();
    00105     total_power += current_power;
    00106
    00107     /* Only powered parts add tractive effort */
    00108     if (current_power > 0) max_te += u->GetWeight() * u->GetTractiveEffort();
    00109     total_power += u->GetPoweredPartPower(this);
    00110     number_of_parts++;
    00111   }
    00112
    00113   this->tcache.cached_axle_resistance = 60 * number_of_parts;
    00114   this->tcache.cached_air_drag = 20 + 3 * number_of_parts;
    00115
    00116   max_te *= 10000; // Tractive effort in (tonnes * 1000 * 10 =) N
    00117   max_te /= 256;   // Tractive effort is a [0-255] coefficient
    00118   if (this->tcache.cached_power != total_power || this->tcache.cached_max_te != max_te) {
    00119     /* Stop the vehicle if it has no power */
    00120     if (total_power == 0) this->vehstatus |= VS_STOPPED;
    00121
    00122     this->tcache.cached_power = total_power;
    00123     this->tcache.cached_max_te = max_te;
    00124     SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
    00125     SetWindowWidgetDirty(WC_VEHICLE_VIEW, this->index, VVW_WIDGET_START_STOP_VEH);
    00126   }
    00127 }
    00128
    00129
    00134 void Train::CargoChanged()
    00135 {
    00136   assert(this->First() == this);
    00137   uint32 weight = 0;
    00138
    00139   for (Train *u = this; u != NULL; u = u->Next()) {
    00140     uint32 current_weight = u->GetWeight();
    00141     weight += current_weight;
    00142     u->tcache.cached_slope_resistance = current_weight * 20 * _settings_game.vehicle.train_slope_steepness; //1% slope * slope steepness
    00143   }
    00144
    00145   /* store consist weight in cache */
    00146   this->tcache.cached_weight = weight;
    00147
    00148   /* Now update train power (tractive effort is dependent on weight) */
    00149   this->PowerChanged();
    00150 }
    00151
    00152
    00157 static void RailVehicleLengthChanged(const Train *u)
    00158 {
    00159   /* show a warning once for each engine in whole game and once for each GRF after each game load */
    00160   const Engine *engine = Engine::Get(u->engine_type);
    00161   uint32 grfid = engine->grffile->grfid;
    00162   GRFConfig *grfconfig = GetGRFConfig(grfid);
    00163   if (GamelogGRFBugReverse(grfid, engine->internal_id) || !HasBit(grfconfig->grf_bugs, GBUG_VEH_LENGTH)) {
    00164     ShowNewGrfVehicleError(u->engine_type, STR_NEWGRF_BROKEN, STR_NEWGRF_BROKEN_VEHICLE_LENGTH, GBUG_VEH_LENGTH, true);
    00165   }
    00166 }
    00167
    00169 void CheckTrainsLengths()
    00170 {
    00171   const Train *v;
    00172
    00173   FOR_ALL_TRAINS(v) {
    00174     if (v->First() == v && !(v->vehstatus & VS_CRASHED)) {
    00175       for (const Train *u = v, *w = v->Next(); w != NULL; u = w, w = w->Next()) {
    00176         if (u->track != TRACK_BIT_DEPOT) {
    00177           if ((w->track != TRACK_BIT_DEPOT &&
    00178               max(abs(u->x_pos - w->x_pos), abs(u->y_pos - w->y_pos)) != u->tcache.cached_veh_length) ||
    00179               (w->track == TRACK_BIT_DEPOT && TicksToLeaveDepot(u) <= 0)) {
    00180             SetDParam(0, v->index);
    00181             SetDParam(1, v->owner);
    00182             ShowErrorMessage(STR_BROKEN_VEHICLE_LENGTH, INVALID_STRING_ID, 0, 0, true);
    00183
    00184             if (!_networking) DoCommandP(0, PM_PAUSED_ERROR, 1, CMD_PAUSE);
    00185           }
    00186         }
    00187       }
    00188     }
    00189   }
    00190 }
    00191
    00198 void Train::ConsistChanged(bool same_length)
    00199 {
    00200   uint16 max_speed = UINT16_MAX;
    00201
    00202   assert(this->IsFrontEngine() || this->IsFreeWagon());
    00203
    00204   const RailVehicleInfo *rvi_v = RailVehInfo(this->engine_type);
    00205   EngineID first_engine = this->IsFrontEngine() ? this->engine_type : INVALID_ENGINE;
    00206   this->tcache.cached_total_length = 0;
    00207   this->compatible_railtypes = RAILTYPES_NONE;
    00208
    00209   bool train_can_tilt = true;
    00210
    00211   for (Train *u = this; u != NULL; u = u->Next()) {
    00212     const RailVehicleInfo *rvi_u = RailVehInfo(u->engine_type);
    00213
    00214     /* Check the this->first cache. */
    00215     assert(u->First() == this);
    00216
    00217     /* update the 'first engine' */
    00218     u->tcache.first_engine = this == u ? INVALID_ENGINE : first_engine;
    00219     u->railtype = rvi_u->railtype;
    00220
    00221     if (u->IsEngine()) first_engine = u->engine_type;
    00222
    00223     /* Set user defined data to its default value */
    00224     u->tcache.user_def_data = rvi_u->user_def_data;
    00225     this->InvalidateNewGRFCache();
    00226     u->InvalidateNewGRFCache();
    00227   }
    00228
    00229   for (Train *u = this; u != NULL; u = u->Next()) {
    00230     /* Update user defined data (must be done before other properties) */
    00231     u->tcache.user_def_data = GetVehicleProperty(u, PROP_TRAIN_USER_DATA, u->tcache.user_def_data);
    00232     this->InvalidateNewGRFCache();
    00233     u->InvalidateNewGRFCache();
    00234   }
    00235
    00236   for (Train *u = this; u != NULL; u = u->Next()) {
    00237     const Engine *e_u = Engine::Get(u->engine_type);
    00238     const RailVehicleInfo *rvi_u = &e_u->u.rail;
    00239
    00240     if (!HasBit(e_u->info.misc_flags, EF_RAIL_TILTS)) train_can_tilt = false;
    00241
    00242     /* Cache wagon override sprite group. NULL is returned if there is none */
    00243     u->tcache.cached_override = GetWagonOverrideSpriteSet(u->engine_type, u->cargo_type, u->tcache.first_engine);
    00244
    00245     /* Reset colour map */
    00246     u->colourmap = PAL_NONE;
    00247
    00248     if (rvi_u->visual_effect != 0) {
    00249       u->tcache.cached_vis_effect = rvi_u->visual_effect;
    00250     } else {
    00251       if (u->IsWagon() || u->IsArticulatedPart()) {
    00252         /* Wagons and articulated parts have no effect by default */
    00253         u->tcache.cached_vis_effect = 0x40;
    00254       } else if (rvi_u->engclass == 0) {
    00255         /* Steam is offset by -4 units */
    00256         u->tcache.cached_vis_effect = 4;
    00257       } else {
    00258         /* Diesel fumes and sparks come from the centre */
    00259         u->tcache.cached_vis_effect = 8;
    00260       }
    00261     }
    00262
    00263     /* Check powered wagon / visual effect callback */
    00264     if (HasBit(e_u->info.callback_mask, CBM_TRAIN_WAGON_POWER)) {
    00265       uint16 callback = GetVehicleCallback(CBID_TRAIN_WAGON_POWER, 0, 0, u->engine_type, u);
    00266
    00267       if (callback != CALLBACK_FAILED) u->tcache.cached_vis_effect = GB(callback, 0, 8);
    00268     }
    00269
    00270     if (rvi_v->pow_wag_power != 0 && rvi_u->railveh_type == RAILVEH_WAGON &&
    00271       UsesWagonOverride(u) && !HasBit(u->tcache.cached_vis_effect, 7)) {
    00272       /* wagon is powered */
    00273       SetBit(u->flags, VRF_POWEREDWAGON); // cache 'powered' status
    00274     } else {
    00275       ClrBit(u->flags, VRF_POWEREDWAGON);
    00276     }
    00277
    00278     if (!u->IsArticulatedPart()) {
    00279       /* Do not count powered wagons for the compatible railtypes, as wagons always
    00280          have railtype normal */
    00281       if (rvi_u->power > 0) {
    00282         this->compatible_railtypes |= GetRailTypeInfo(u->railtype)->powered_railtypes;
    00283       }
    00284
    00285       /* Some electric engines can be allowed to run on normal rail. It happens to all
    00286        * existing electric engines when elrails are disabled and then re-enabled */
    00287       if (HasBit(u->flags, VRF_EL_ENGINE_ALLOWED_NORMAL_RAIL)) {
    00288         u->railtype = RAILTYPE_RAIL;
    00289         u->compatible_railtypes |= RAILTYPES_RAIL;
    00290       }
    00291
    00292       /* max speed is the minimum of the speed limits of all vehicles in the consist */
    00293       if ((rvi_u->railveh_type != RAILVEH_WAGON || _settings_game.vehicle.wagon_speed_limits) && !UsesWagonOverride(u)) {
    00294         uint16 speed = GetVehicleProperty(u, PROP_TRAIN_SPEED, rvi_u->max_speed);
    00295         if (speed != 0) max_speed = min(speed, max_speed);
    00296       }
    00297     }
    00298
    00299     u->cargo_cap = GetVehicleCapacity(u);
    00300
    00301     /* check the vehicle length (callback) */
    00302     uint16 veh_len = CALLBACK_FAILED;
    00303     if (HasBit(e_u->info.callback_mask, CBM_VEHICLE_LENGTH)) {
    00304       veh_len = GetVehicleCallback(CBID_VEHICLE_LENGTH, 0, 0, u->engine_type, u);
    00305     }
    00306     if (veh_len == CALLBACK_FAILED) veh_len = rvi_u->shorten_factor;
    00307     veh_len = 8 - Clamp(veh_len, 0, 7);
    00308
    00309     /* verify length hasn't changed */
    00310     if (same_length && veh_len != u->tcache.cached_veh_length) RailVehicleLengthChanged(u);
    00311
    00312     /* update vehicle length? */
    00313     if (!same_length) u->tcache.cached_veh_length = veh_len;
    00314
    00315     this->tcache.cached_total_length += u->tcache.cached_veh_length;
    00316     this->InvalidateNewGRFCache();
    00317     u->InvalidateNewGRFCache();
    00318   }
    00319
    00320   /* store consist weight/max speed in cache */
    00321   this->tcache.cached_max_speed = max_speed;
    00322   this->tcache.cached_tilt = train_can_tilt;
    00323   this->tcache.cached_max_curve_speed = this->GetCurveSpeedLimit();
    00324
    00325   /* 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) */
    00326   this->CargoChanged();
    00327
    00328   if (this->IsFrontEngine()) {
    00329     this->UpdateAcceleration();
    00330     SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
    00331   }
    00332 }
    00333
    00344 int GetTrainStopLocation(StationID station_id, TileIndex tile, const Train *v, int *station_ahead, int *station_length)
    00345 {
    00346   const Station *st = Station::Get(station_id);
    00347   *station_ahead  = st->GetPlatformLength(tile, DirToDiagDir(v->direction)) * TILE_SIZE;
    00348   *station_length = st->GetPlatformLength(tile) * TILE_SIZE;
    00349
    00350   /* Default to the middle of the station for stations stops that are not in
    00351    * the order list like intermediate stations when non-stop is disabled */
    00352   OrderStopLocation osl = OSL_PLATFORM_MIDDLE;
    00353   if (v->tcache.cached_total_length >= *station_length) {
    00354     /* The train is longer than the station, make it stop at the far end of the platform */
    00355     osl = OSL_PLATFORM_FAR_END;
    00356   } else if (v->current_order.IsType(OT_GOTO_STATION) && v->current_order.GetDestination() == station_id) {
    00357     osl = v->current_order.GetStopLocation();
    00358   }
    00359
    00360   /* The stop location of the FRONT! of the train */
    00361   int stop;
    00362   switch (osl) {
    00363     default: NOT_REACHED();
    00364
    00365     case OSL_PLATFORM_NEAR_END:
    00366       stop = v->tcache.cached_total_length;
    00367       break;
    00368
    00369     case OSL_PLATFORM_MIDDLE:
    00370       stop = *station_length - (*station_length - v->tcache.cached_total_length) / 2;
    00371       break;
    00372
    00373     case OSL_PLATFORM_FAR_END:
    00374       stop = *station_length;
    00375       break;
    00376   }
    00377
    00378   /* Substract half the front vehicle length of the train so we get the real
    00379    * stop location of the train. */
    00380   return stop - (v->tcache.cached_veh_length + 1) / 2;
    00381 }
    00382
    00383
    00388 int Train::GetCurveSpeedLimit() const
    00389 {
    00390   assert(this->First() == this);
    00391
    00392   static const int absolute_max_speed = UINT16_MAX;
    00393   int max_speed = absolute_max_speed;
    00394
    00395   if (_settings_game.vehicle.train_acceleration_model == TAM_ORIGINAL) return max_speed;
    00396
    00397   int curvecount[2] = {0, 0};
    00398
    00399   /* first find the curve speed limit */
    00400   int numcurve = 0;
    00401   int sum = 0;
    00402   int pos = 0;
    00403   int lastpos = -1;
    00404   for (const Vehicle *u = this; u->Next() != NULL; u = u->Next(), pos++) {
    00405     Direction this_dir = u->direction;
    00406     Direction next_dir = u->Next()->direction;
    00407
    00408     DirDiff dirdiff = DirDifference(this_dir, next_dir);
    00409     if (dirdiff == DIRDIFF_SAME) continue;
    00410
    00411     if (dirdiff == DIRDIFF_45LEFT) curvecount[0]++;
    00412     if (dirdiff == DIRDIFF_45RIGHT) curvecount[1]++;
    00413     if (dirdiff == DIRDIFF_45LEFT || dirdiff == DIRDIFF_45RIGHT) {
    00414       if (lastpos != -1) {
    00415         numcurve++;
    00416         sum += pos - lastpos;
    00417         if (pos - lastpos == 1) {
    00418           max_speed = 88;
    00419         }
    00420       }
    00421       lastpos = pos;
    00422     }
    00423
    00424     /* if we have a 90 degree turn, fix the speed limit to 60 */
    00425     if (dirdiff == DIRDIFF_90LEFT || dirdiff == DIRDIFF_90RIGHT) {
    00426       max_speed = 61;
    00427     }
    00428   }
    00429
    00430   if (numcurve > 0 && max_speed > 88) {
    00431     if (curvecount[0] == 1 && curvecount[1] == 1) {
    00432       max_speed = absolute_max_speed;
    00433     } else {
    00434       sum /= numcurve;
    00435       max_speed = 232 - (13 - Clamp(sum, 1, 12)) * (13 - Clamp(sum, 1, 12));
    00436     }
    00437   }
    00438
    00439   if (max_speed != absolute_max_speed) {
    00440     /* Apply the engine's rail type curve speed advantage, if it slowed by curves */
    00441     const RailtypeInfo *rti = GetRailTypeInfo(this->railtype);
    00442     max_speed += (max_speed / 2) * rti->curve_speed;
    00443
    00444     if (this->tcache.cached_tilt) {
    00445       /* Apply max_speed bonus of 20% for a tilting train */
    00446       max_speed += max_speed / 5;
    00447     }
    00448   }
    00449
    00450   return max_speed;
    00451 }
    00452
    00457 int Train::GetCurrentMaxSpeed() const
    00458 {
    00459   int max_speed = this->tcache.cached_max_curve_speed;
    00460   assert(max_speed == this->GetCurveSpeedLimit());
    00461
    00462   if (IsRailStationTile(this->tile)) {
    00463     StationID sid = GetStationIndex(this->tile);
    00464     if (this->current_order.ShouldStopAtStation(this, sid)) {
    00465       int station_ahead;
    00466       int station_length;
    00467       int stop_at = GetTrainStopLocation(sid, this->tile, this, &station_ahead, &station_length);
    00468
    00469       /* The distance to go is whatever is still ahead of the train minus the
    00470        * distance from the train's stop location to the end of the platform */
    00471       int distance_to_go = station_ahead / TILE_SIZE - (station_length - stop_at) / TILE_SIZE;
    00472
    00473       if (distance_to_go > 0) {
    00474         int st_max_speed = 120;
    00475
    00476         int delta_v = this->cur_speed / (distance_to_go + 1);
    00477         if (this->max_speed > (this->cur_speed - delta_v)) {
    00478           st_max_speed = this->cur_speed - (delta_v / 10);
    00479         }
    00480
    00481         st_max_speed = max(st_max_speed, 25 * distance_to_go);
    00482         max_speed = min(max_speed, st_max_speed);
    00483       }
    00484     }
    00485   }
    00486
    00487   for (const Train *u = this; u != NULL; u = u->Next()) {
    00488     if (u->track == TRACK_BIT_DEPOT) {
    00489       max_speed = min(max_speed, 61);
    00490       break;
    00491     }
    00492   }
    00493
    00494   return min(max_speed, this->tcache.cached_max_speed);
    00495 }
    00496
    00502 int Train::GetAcceleration() const
    00503 {
    00504   int32 speed = this->GetCurrentSpeed();
    00505
    00506   /* Weight is stored in tonnes */
    00507   int32 mass = this->tcache.cached_weight;
    00508
    00509   /* Power is stored in HP, we need it in watts. */
    00510   int32 power = this->tcache.cached_power * 746;
    00511
    00512   int32 resistance = 0;
    00513
    00514   bool maglev = this->GetAccelerationType() == 2;
    00515
    00516   const int area = 120;
    00517   if (!maglev) {
    00518     resistance = (13 * mass) / 10;
    00519     resistance += this->tcache.cached_axle_resistance;
    00520     resistance += (this->GetRollingFriction() * mass * speed) / 1000;
    00521     resistance += (area * this->tcache.cached_air_drag * speed * speed) / 10000;
    00522   } else {
    00523     resistance += (area * this->tcache.cached_air_drag * speed * speed) / 20000;
    00524   }
    00525
    00526   resistance += this->GetSlopeResistance();
    00527   resistance *= 4; //[N]
    00528
    00529   /* This value allows to know if the vehicle is accelerating or braking. */
    00530   AccelStatus mode = this->GetAccelerationStatus();
    00531
    00532   const int max_te = this->tcache.cached_max_te; // [N]
    00533   int force;
    00534   if (speed > 0) {
    00535     if (!maglev) {
    00536       force = power / speed; //[N]
    00537       force *= 22;
    00538       force /= 10;
    00539       if (mode == AS_ACCEL && force > max_te) force = max_te;
    00540     } else {
    00541       force = power / 25;
    00542     }
    00543   } else {
    00544     /* "kickoff" acceleration */
    00545     force = (mode == AS_ACCEL && !maglev) ? min(max_te, power) : power;
    00546     force = max(force, (mass * 8) + resistance);
    00547   }
    00548
    00549   if (mode == AS_ACCEL) {
    00550     return (force - resistance) / (mass * 2);
    00551   } else {
    00552     return min(-force - resistance, -10000) / mass;
    00553   }
    00554 }
    00555
    00556 void Train::UpdateAcceleration()
    00557 {
    00558   assert(this->IsFrontEngine());
    00559
    00560   this->max_speed = this->tcache.cached_max_speed;
    00561
    00562   uint power = this->tcache.cached_power;
    00563   uint weight = this->tcache.cached_weight;
    00564   assert(weight != 0);
    00565   this->acceleration = Clamp(power / weight * 4, 1, 255);
    00566 }
    00567
    00573 int Train::GetDisplayImageWidth(Point *offset) const
    00574 {
    00575   int reference_width = TRAININFO_DEFAULT_VEHICLE_WIDTH;
    00576   int vehicle_pitch = 0;
    00577
    00578   const Engine *e = Engine::Get(this->engine_type);
    00579   if (e->grffile != NULL && is_custom_sprite(e->u.rail.image_index)) {
    00580     reference_width = e->grffile->traininfo_vehicle_width;
    00581     vehicle_pitch = e->grffile->traininfo_vehicle_pitch;
    00582   }
    00583
    00584   if (offset != NULL) {
    00585     offset->x = reference_width / 2;
    00586     offset->y = vehicle_pitch;
    00587   }
    00588   return this->tcache.cached_veh_length * reference_width / 8;
    00589 }
    00590
    00591 static SpriteID GetDefaultTrainSprite(uint8 spritenum, Direction direction)
    00592 {
    00593   return ((direction + _engine_sprite_add[spritenum]) & _engine_sprite_and[spritenum]) + _engine_sprite_base[spritenum];
    00594 }
    00595
    00596 SpriteID Train::GetImage(Direction direction) const
    00597 {
    00598   uint8 spritenum = this->spritenum;
    00599   SpriteID sprite;
    00600
    00601   if (HasBit(this->flags, VRF_REVERSE_DIRECTION)) direction = ReverseDir(direction);
    00602
    00603   if (is_custom_sprite(spritenum)) {
    00604     sprite = GetCustomVehicleSprite(this, (Direction)(direction + 4 * IS_CUSTOM_SECONDHEAD_SPRITE(spritenum)));
    00605     if (sprite != 0) return sprite;
    00606
    00607     spritenum = Engine::Get(this->engine_type)->original_image_index;
    00608   }
    00609
    00610   sprite = GetDefaultTrainSprite(spritenum, direction);
    00611
    00612   if (this->cargo.Count() >= this->cargo_cap / 2U) sprite += _wagon_full_adder[spritenum];
    00613
    00614   return sprite;
    00615 }
    00616
    00617 static SpriteID GetRailIcon(EngineID engine, bool rear_head, int &y)
    00618 {
    00619   const Engine *e = Engine::Get(engine);
    00620   Direction dir = rear_head ? DIR_E : DIR_W;
    00621   uint8 spritenum = e->u.rail.image_index;
    00622
    00623   if (is_custom_sprite(spritenum)) {
    00624     SpriteID sprite = GetCustomVehicleIcon(engine, dir);
    00625     if (sprite != 0) {
    00626       if (e->grffile != NULL) {
    00627         y += e->grffile->traininfo_vehicle_pitch;
    00628       }
    00629       return sprite;
    00630     }
    00631
    00632     spritenum = Engine::Get(engine)->original_image_index;
    00633   }
    00634
    00635   if (rear_head) spritenum++;
    00636
    00637   return GetDefaultTrainSprite(spritenum, DIR_W);
    00638 }
    00639
    00640 void DrawTrainEngine(int left, int right, int preferred_x, int y, EngineID engine, SpriteID pal)
    00641 {
    00642   if (RailVehInfo(engine)->railveh_type == RAILVEH_MULTIHEAD) {
    00643     int yf = y;
    00644     int yr = y;
    00645
    00646     SpriteID spritef = GetRailIcon(engine, false, yf);
    00647     SpriteID spriter = GetRailIcon(engine, true, yr);
    00648     const Sprite *real_spritef = GetSprite(spritef, ST_NORMAL);
    00649     const Sprite *real_spriter = GetSprite(spriter, ST_NORMAL);
    00650
    00651     preferred_x = Clamp(preferred_x, left - real_spritef->x_offs + 14, right - real_spriter->width - real_spriter->x_offs - 15);
    00652
    00653     DrawSprite(spritef, pal, preferred_x - 14, yf);
    00654     DrawSprite(spriter, pal, preferred_x + 15, yr);
    00655   } else {
    00656     SpriteID sprite = GetRailIcon(engine, false, y);
    00657     const Sprite *real_sprite = GetSprite(sprite, ST_NORMAL);
    00658     preferred_x = Clamp(preferred_x, left - real_sprite->x_offs, right - real_sprite->width - real_sprite->x_offs);
    00659     DrawSprite(sprite, pal, preferred_x, y);
    00660   }
    00661 }
    00662
    00663 static CommandCost CmdBuildRailWagon(EngineID engine, TileIndex tile, DoCommandFlag flags)
    00664 {
    00665   const Engine *e = Engine::Get(engine);
    00666   const RailVehicleInfo *rvi = &e->u.rail;
    00667   CommandCost value(EXPENSES_NEW_VEHICLES, e->GetCost());
    00668
    00669   /* Engines without valid cargo should not be available */
    00670   if (e->GetDefaultCargoType() == CT_INVALID) return CMD_ERROR;
    00671
    00672   if (flags & DC_QUERY_COST) return value;
    00673
    00674   /* Check that the wagon can drive on the track in question */
    00675   if (!IsCompatibleRail(rvi->railtype, GetRailType(tile))) return CMD_ERROR;
    00676
    00677   uint num_vehicles = 1 + CountArticulatedParts(engine, false);
    00678
    00679   /* Allow for the wagon and the articulated parts */
    00680   if (!Vehicle::CanAllocateItem(num_vehicles)) {
    00681     return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
    00682   }
    00683
    00684   if (flags & DC_EXEC) {
    00685     Train *v = new Train();
    00686     v->spritenum = rvi->image_index;
    00687
    00688     v->engine_type = engine;
    00689     v->tcache.first_engine = INVALID_ENGINE; // needs to be set before first callback
    00690
    00691     DiagDirection dir = GetRailDepotDirection(tile);
    00692
    00693     v->direction = DiagDirToDir(dir);
    00694     v->tile = tile;
    00695
    00696     int x = TileX(tile) * TILE_SIZE | _vehicle_initial_x_fract[dir];
    00697     int y = TileY(tile) * TILE_SIZE | _vehicle_initial_y_fract[dir];
    00698
    00699     v->x_pos = x;
    00700     v->y_pos = y;
    00701     v->z_pos = GetSlopeZ(x, y);
    00702     v->owner = _current_company;
    00703     v->track = TRACK_BIT_DEPOT;
    00704     v->vehstatus = VS_HIDDEN | VS_DEFPAL;
    00705
    00706 //    v->subtype = 0;
    00707     v->SetWagon();
    00708
    00709     v->SetFreeWagon();
    00710     InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
    00711
    00712     v->cargo_type = e->GetDefaultCargoType();
    00713 //    v->cargo_subtype = 0;
    00714     v->cargo_cap = rvi->capacity;
    00715     v->value = value.GetCost();
    00716 //    v->day_counter = 0;
    00717
    00718     v->railtype = rvi->railtype;
    00719
    00720     v->build_year = _cur_year;
    00721     v->cur_image = SPR_IMG_QUERY;
    00722     v->random_bits = VehicleRandomBits();
    00723
    00724     v->group_id = DEFAULT_GROUP;
    00725
    00726     AddArticulatedParts(v);
    00727
    00728     _new_vehicle_id = v->index;
    00729
    00730     VehicleMove(v, false);
    00731     v->First()->ConsistChanged(false);
    00732     UpdateTrainGroupID(v->First());
    00733
    00734     SetWindowDirty(WC_VEHICLE_DEPOT, v->tile);
    00735     if (IsLocalCompany()) {
    00736       InvalidateAutoreplaceWindow(v->engine_type, v->group_id); // updates the replace Train window
    00737     }
    00738     Company::Get(_current_company)->num_engines[engine]++;
    00739
    00740     CheckConsistencyOfArticulatedVehicle(v);
    00741
    00742     /* Try to connect the vehicle to one of free chains of wagons. */
    00743     Train *w;
    00744     FOR_ALL_TRAINS(w) {
    00745       if (w->tile == tile &&
    00746           w->IsFreeWagon() &&
    00747           w->engine_type == engine &&
    00748           w->First() != v &&
    00749           !(w->vehstatus & VS_CRASHED)) {
    00750         DoCommand(0, v->index | (w->Last()->index << 16), 1, DC_EXEC, CMD_MOVE_RAIL_VEHICLE);
    00751         break;
    00752       }
    00753     }
    00754   }
    00755
    00756   return value;
    00757 }
    00758
    00760 static void NormalizeTrainVehInDepot(const Train *u)
    00761 {
    00762   const Train *v;
    00763   FOR_ALL_TRAINS(v) {
    00764     if (v->IsFreeWagon() && v->tile == u->tile &&
    00765         v->track == TRACK_BIT_DEPOT) {
    00766       if (DoCommand(0, v->index | (u->index << 16), 1, DC_EXEC,
    00767           CMD_MOVE_RAIL_VEHICLE).Failed())
    00768         break;
    00769     }
    00770   }
    00771 }
    00772
    00773 static void AddRearEngineToMultiheadedTrain(Train *v)
    00774 {
    00775   Train *u = new Train();
    00776   v->value >>= 1;
    00777   u->value = v->value;
    00778   u->direction = v->direction;
    00779   u->owner = v->owner;
    00780   u->tile = v->tile;
    00781   u->x_pos = v->x_pos;
    00782   u->y_pos = v->y_pos;
    00783   u->z_pos = v->z_pos;
    00784   u->track = TRACK_BIT_DEPOT;
    00785   u->vehstatus = v->vehstatus & ~VS_STOPPED;
    00786 //  u->subtype = 0;
    00787   u->spritenum = v->spritenum + 1;
    00788   u->cargo_type = v->cargo_type;
    00789   u->cargo_subtype = v->cargo_subtype;
    00790   u->cargo_cap = v->cargo_cap;
    00791   u->railtype = v->railtype;
    00792   u->engine_type = v->engine_type;
    00793   u->build_year = v->build_year;
    00794   u->cur_image = SPR_IMG_QUERY;
    00795   u->random_bits = VehicleRandomBits();
    00796   v->SetMultiheaded();
    00797   u->SetMultiheaded();
    00798   v->SetNext(u);
    00799   VehicleMove(u, false);
    00800
    00801   /* Now we need to link the front and rear engines together */
    00802   v->other_multiheaded_part = u;
    00803   u->other_multiheaded_part = v;
    00804 }
    00805
    00814 CommandCost CmdBuildRailVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00815 {
    00816   /* Check if the engine-type is valid (for the company) */
    00817   if (!IsEngineBuildable(p1, VEH_TRAIN, _current_company)) return_cmd_error(STR_ERROR_RAIL_VEHICLE_NOT_AVAILABLE);
    00818
    00819   const Engine *e = Engine::Get(p1);
    00820   const RailVehicleInfo *rvi = &e->u.rail;
    00821   CommandCost value(EXPENSES_NEW_VEHICLES, e->GetCost());
    00822
    00823   /* Engines with CT_INVALID should not be available */
    00824   if (e->GetDefaultCargoType() == CT_INVALID) return CMD_ERROR;
    00825
    00826   if (flags & DC_QUERY_COST) return value;
    00827
    00828   /* Check if the train is actually being built in a depot belonging
    00829    * to the company. Doesn't matter if only the cost is queried */
    00830   if (!IsRailDepotTile(tile)) return CMD_ERROR;
    00831   if (!IsTileOwner(tile, _current_company)) return CMD_ERROR;
    00832
    00833   if (rvi->railveh_type == RAILVEH_WAGON) return CmdBuildRailWagon(p1, tile, flags);
    00834
    00835   uint num_vehicles =
    00836     (rvi->railveh_type == RAILVEH_MULTIHEAD ? 2 : 1) +
    00837     CountArticulatedParts(p1, false);
    00838
    00839   /* Check if depot and new engine uses the same kind of tracks *
    00840    * We need to see if the engine got power on the tile to avoid eletric engines in non-electric depots */
    00841   if (!HasPowerOnRail(rvi->railtype, GetRailType(tile))) return CMD_ERROR;
    00842
    00843   /* Allow for the dual-heads and the articulated parts */
    00844   if (!Vehicle::CanAllocateItem(num_vehicles)) {
    00845     return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
    00846   }
    00847
    00848   UnitID unit_num = (flags & DC_AUTOREPLACE) ? 0 : GetFreeUnitNumber(VEH_TRAIN);
    00849   if (unit_num > _settings_game.vehicle.max_trains) {
    00850     return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
    00851   }
    00852
    00853   if (flags & DC_EXEC) {
    00854     DiagDirection dir = GetRailDepotDirection(tile);
    00855     int x = TileX(tile) * TILE_SIZE + _vehicle_initial_x_fract[dir];
    00856     int y = TileY(tile) * TILE_SIZE + _vehicle_initial_y_fract[dir];
    00857
    00858     Train *v = new Train();
    00859     v->unitnumber = unit_num;
    00860     v->direction = DiagDirToDir(dir);
    00861     v->tile = tile;
    00862     v->owner = _current_company;
    00863     v->x_pos = x;
    00864     v->y_pos = y;
    00865     v->z_pos = GetSlopeZ(x, y);
    00866 //    v->running_ticks = 0;
    00867     v->track = TRACK_BIT_DEPOT;
    00868     v->vehstatus = VS_HIDDEN | VS_STOPPED | VS_DEFPAL;
    00869     v->spritenum = rvi->image_index;
    00870     v->cargo_type = e->GetDefaultCargoType();
    00871 //    v->cargo_subtype = 0;
    00872     v->cargo_cap = rvi->capacity;
    00873     v->max_speed = rvi->max_speed;
    00874     v->value = value.GetCost();
    00875     v->last_station_visited = INVALID_STATION;
    00876 //    v->dest_tile = 0;
    00877
    00878     v->engine_type = p1;
    00879     v->tcache.first_engine = INVALID_ENGINE; // needs to be set before first callback
    00880
    00881     v->reliability = e->reliability;
    00882     v->reliability_spd_dec = e->reliability_spd_dec;
    00883     v->max_age = e->GetLifeLengthInDays();
    00884
    00885     v->name = NULL;
    00886     v->railtype = rvi->railtype;
    00887     _new_vehicle_id = v->index;
    00888
    00889     v->service_interval = Company::Get(_current_company)->settings.vehicle.servint_trains;
    00890     v->date_of_last_service = _date;
    00891     v->build_year = _cur_year;
    00892     v->cur_image = SPR_IMG_QUERY;
    00893     v->random_bits = VehicleRandomBits();
    00894
    00895 //    v->vehicle_flags = 0;
    00896     if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) SetBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE);
    00897
    00898     v->group_id = DEFAULT_GROUP;
    00899
    00900 //    v->subtype = 0;
    00901     v->SetFrontEngine();
    00902     v->SetEngine();
    00903
    00904     VehicleMove(v, false);
    00905
    00906     if (rvi->railveh_type == RAILVEH_MULTIHEAD) {
    00907       AddRearEngineToMultiheadedTrain(v);
    00908     } else {
    00909       AddArticulatedParts(v);
    00910     }
    00911
    00912     v->ConsistChanged(false);
    00913     UpdateTrainGroupID(v);
    00914
    00915     if (!HasBit(p2, 1) && !(flags & DC_AUTOREPLACE)) { // check if the cars should be added to the new vehicle
    00916       NormalizeTrainVehInDepot(v);
    00917     }
    00918
    00919     InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
    00920     InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
    00921     SetWindowDirty(WC_COMPANY, v->owner);
    00922     if (IsLocalCompany()) {
    00923       InvalidateAutoreplaceWindow(v->engine_type, v->group_id); // updates the replace Train window
    00924     }
    00925
    00926     Company::Get(_current_company)->num_engines[p1]++;
    00927
    00928     CheckConsistencyOfArticulatedVehicle(v);
    00929   }
    00930
    00931   return value;
    00932 }
    00933
    00934
    00935 bool Train::IsInDepot() const
    00936 {
    00937   /* Is the front engine stationary in the depot? */
    00938   if (!IsRailDepotTile(this->tile) || this->cur_speed != 0) return false;
    00939
    00940   /* Check whether the rest is also already trying to enter the depot. */
    00941   for (const Train *v = this; v != NULL; v = v->Next()) {
    00942     if (v->track != TRACK_BIT_DEPOT || v->tile != this->tile) return false;
    00943   }
    00944
    00945   return true;
    00946 }
    00947
    00948 bool Train::IsStoppedInDepot() const
    00949 {
    00950   /* Are we stopped? Ofcourse wagons don't really care... */
    00951   if (this->IsFrontEngine() && !(this->vehstatus & VS_STOPPED)) return false;
    00952   return this->IsInDepot();
    00953 }
    00954
    00955 static Train *FindGoodVehiclePos(const Train *src)
    00956 {
    00957   EngineID eng = src->engine_type;
    00958   TileIndex tile = src->tile;
    00959
    00960   Train *dst;
    00961   FOR_ALL_TRAINS(dst) {
    00962     if (dst->IsFreeWagon() && dst->tile == tile && !(dst->vehstatus & VS_CRASHED)) {
    00963       /* check so all vehicles in the line have the same engine. */
    00964       Train *t = dst;
    00965       while (t->engine_type == eng) {
    00966         t = t->Next();
    00967         if (t == NULL) return dst;
    00968       }
    00969     }
    00970   }
    00971
    00972   return NULL;
    00973 }
    00974
    00976 typedef SmallVector<Train *, 16> TrainList;
    00977
    00983 static void MakeTrainBackup(TrainList &list, Train *t)
    00984 {
    00985   for (; t != NULL; t = t->Next()) *list.Append() = t;
    00986 }
    00987
    00992 static void RestoreTrainBackup(TrainList &list)
    00993 {
    00994   /* No train, nothing to do. */
    00995   if (list.Length() == 0) return;
    00996
    00997   Train *prev = NULL;
    00998   /* Iterate over the list and rebuild it. */
    00999   for (Train **iter = list.Begin(); iter != list.End(); iter++) {
    01000     Train *t = *iter;
    01001     if (prev != NULL) {
    01002       prev->SetNext(t);
    01003     } else if (t->Previous() != NULL) {
    01004       /* Make sure the head of the train is always the first in the chain. */
    01005       t->Previous()->SetNext(NULL);
    01006     }
    01007     prev = t;
    01008   }
    01009 }
    01010
    01016 static void RemoveFromConsist(Train *part, bool chain = false)
    01017 {
    01018   Train *tail = chain ? part->Last() : part->GetLastEnginePart();
    01019
    01020   /* Unlink at the front, but make it point to the next
    01021    * vehicle after the to be remove part. */
    01022   if (part->Previous() != NULL) part->Previous()->SetNext(tail->Next());
    01023
    01024   /* Unlink at the back */
    01025   tail->SetNext(NULL);
    01026 }
    01027
    01033 static void InsertInConsist(Train *dst, Train *chain)
    01034 {
    01035   /* We do not want to add something in the middle of an articulated part. */
    01036   assert(dst->Next() == NULL || !dst->Next()->IsArticulatedPart());
    01037
    01038   chain->Last()->SetNext(dst->Next());
    01039   dst->SetNext(chain);
    01040 }
    01041
    01047 static void NormaliseDualHeads(Train *t)
    01048 {
    01049   for (; t != NULL; t = t->GetNextVehicle()) {
    01050     if (!t->IsMultiheaded() || !t->IsEngine()) continue;
    01051
    01052     /* Make sure that there are no free cars before next engine */
    01053     Train *u;
    01054     for (u = t; u->Next() != NULL && !u->Next()->IsEngine(); u = u->Next()) {}
    01055
    01056     if (u == t->other_multiheaded_part) continue;
    01057
    01058     /* Remove the part from the 'wrong' train */
    01059     RemoveFromConsist(t->other_multiheaded_part);
    01060     /* And add it to the 'right' train */
    01061     InsertInConsist(u, t->other_multiheaded_part);
    01062   }
    01063 }
    01064
    01069 static void NormaliseSubtypes(Train *chain)
    01070 {
    01071   /* Nothing to do */
    01072   if (chain == NULL) return;
    01073
    01074   /* We must be the first in the chain. */
    01075   assert(chain->Previous() == NULL);
    01076
    01077   /* Set the appropirate bits for the first in the chain. */
    01078   if (chain->IsWagon()) {
    01079     chain->SetFreeWagon();
    01080   } else {
    01081     assert(chain->IsEngine());
    01082     chain->SetFrontEngine();
    01083   }
    01084
    01085   /* Now clear the bits for the rest of the chain */
    01086   for (Train *t = chain->Next(); t != NULL; t = t->Next()) {
    01087     t->ClearFreeWagon();
    01088     t->ClearFrontEngine();
    01089   }
    01090 }
    01091
    01101 static CommandCost CheckNewTrain(Train *original_dst, Train *dst, Train *original_src, Train *src)
    01102 {
    01103   /* Just add 'new' engines and substract the original ones.
    01104    * If that's less than or equal to 0 we can be sure we did
    01105    * not add any engines (read: trains) along the way. */
    01106   if ((src          != NULL && src->IsEngine()          ? 1 : 0) +
    01107       (dst          != NULL && dst->IsEngine()          ? 1 : 0) -
    01108       (original_src != NULL && original_src->IsEngine() ? 1 : 0) -
    01109       (original_dst != NULL && original_dst->IsEngine() ? 1 : 0) <= 0) {
    01110     return CommandCost();
    01111   }
    01112
    01113   /* Get a free unit number and check whether it's within the bounds.
    01114    * There will always be a maximum of one new train. */
    01115   if (GetFreeUnitNumber(VEH_TRAIN) <= _settings_game.vehicle.max_trains) return CommandCost();
    01116
    01117   return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
    01118 }
    01119
    01125 static CommandCost CheckTrainAttachment(Train *t)
    01126 {
    01127   /* No multi-part train, no need to check. */
    01128   if (t == NULL || t->Next() == NULL || !t->IsEngine()) return CommandCost();
    01129
    01130   /* The maximum length for a train. For each part we decrease this by one
    01131    * and if the result is negative the train is simply too long. */
    01132   int allowed_len = _settings_game.vehicle.mammoth_trains ? 100 : 10;
    01133
    01134   Train *head = t;
    01135   Train *prev = t;
    01136
    01137   /* Break the prev -> t link so it always holds within the loop. */
    01138   t = t->Next();
    01139   allowed_len--;
    01140   prev->SetNext(NULL);
    01141
    01142   /* Make sure the cache is cleared. */
    01143   head->InvalidateNewGRFCache();
    01144
    01145   while (t != NULL) {
    01146     Train *next = t->Next();
    01147
    01148     /* Unlink the to-be-added piece; it is already unlinked from the previous
    01149      * part due to the fact that the prev -> t link is broken. */
    01150     t->SetNext(NULL);
    01151
    01152     /* Don't check callback for articulated or rear dual headed parts */
    01153     if (!t->IsArticulatedPart() && !t->IsRearDualheaded()) {
    01154       allowed_len--; // We do not count articulated parts and rear heads either.
    01155
    01156       /* Back up and clear the first_engine data to avoid using wagon override group */
    01157       EngineID first_engine = t->tcache.first_engine;
    01158       t->tcache.first_engine = INVALID_ENGINE;
    01159
    01160       /* We don't want the cache to interfere. head's cache is cleared before
    01161        * the loop and after each callback does not need to be cleared here. */
    01162       t->InvalidateNewGRFCache();
    01163
    01164       uint16 callback = GetVehicleCallbackParent(CBID_TRAIN_ALLOW_WAGON_ATTACH, 0, 0, head->engine_type, t, head);
    01165
    01166       /* Restore original first_engine data */
    01167       t->tcache.first_engine = first_engine;
    01168
    01169       /* We do not want to remember any cached variables from the test run */
    01170       t->InvalidateNewGRFCache();
    01171       head->InvalidateNewGRFCache();
    01172
    01173       if (callback != CALLBACK_FAILED) {
    01174         /* A failing callback means everything is okay */
    01175         StringID error = STR_NULL;
    01176
    01177         if (callback == 0xFD) error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
    01178         if (callback  < 0xFD) error = GetGRFStringID(GetEngineGRFID(head->engine_type), 0xD000 + callback);
    01179
    01180         if (error != STR_NULL) return_cmd_error(error);
    01181       }
    01182     }
    01183
    01184     /* And link it to the new part. */
    01185     prev->SetNext(t);
    01186     prev = t;
    01187     t = next;
    01188   }
    01189
    01190   if (allowed_len <= 0) return_cmd_error(STR_ERROR_TRAIN_TOO_LONG);
    01191   return CommandCost();
    01192 }
    01193
    01203 static CommandCost ValidateTrains(Train *original_dst, Train *dst, Train *original_src, Train *src)
    01204 {
    01205   /* Check whether we may actually construct the trains. */
    01206   CommandCost ret = CheckTrainAttachment(src);
    01207   if (ret.Failed()) return ret;
    01208   ret = CheckTrainAttachment(dst);
    01209   if (ret.Failed()) return ret;
    01210
    01211   /* Check whether we need to build a new train. */
    01212   return CheckNewTrain(original_dst, dst, original_src, src);
    01213 }
    01214
    01223 static void ArrangeTrains(Train **dst_head, Train *dst, Train **src_head, Train *src, bool move_chain)
    01224 {
    01225   /* First determine the front of the two resulting trains */
    01226   if (*src_head == *dst_head) {
    01227     /* If we aren't moving part(s) to a new train, we are just moving the
    01228      * front back and there is not destination head. */
    01229     *dst_head = NULL;
    01230   } else if (*dst_head == NULL) {
    01231     /* If we are moving to a new train the head of the move train would become
    01232      * the head of the new vehicle. */
    01233     *dst_head = src;
    01234   }
    01235
    01236   if (src == *src_head) {
    01237     /* If we are moving the front of a train then we are, in effect, creating
    01238      * a new head for the train. Point to that. Unless we are moving the whole
    01239      * train in which case there is not 'source' train anymore.
    01240      * In case we are a multiheaded part we want the complete thing to come
    01241      * with us, so src->GetNextUnit(), however... when we are e.g. a wagon
    01242      * that is followed by a rear multihead we do not want to include that. */
    01243     *src_head = move_chain ? NULL :
    01244         (src->IsMultiheaded() ? src->GetNextUnit() : src->GetNextVehicle());
    01245   }
    01246
    01247   /* Now it's just simply removing the part that we are going to move from the
    01248    * source train and *if* the destination is a not a new train add the chain
    01249    * at the destination location. */
    01250   RemoveFromConsist(src, move_chain);
    01251   if (*dst_head != src) InsertInConsist(dst, src);
    01252
    01253   /* Now normalise the dual heads, that is move the dual heads around in such
    01254    * a way that the head and rear of a dual head are in the same train */
    01255   NormaliseDualHeads(*src_head);
    01256   NormaliseDualHeads(*dst_head);
    01257 }
    01258
    01264 static void NormaliseTrainHead(Train *head)
    01265 {
    01266   /* Not much to do! */
    01267   if (head == NULL) return;
    01268
    01269   /* Tell the 'world' the train changed. */
    01270   head->ConsistChanged(false);
    01271   UpdateTrainGroupID(head);
    01272
    01273   /* Not a front engine, i.e. a free wagon chain. No need to do more. */
    01274   if (!head->IsFrontEngine()) return;
    01275
    01276   /* Update the refit button and window */
    01277   SetWindowDirty(WC_VEHICLE_REFIT, head->index);
    01278   SetWindowWidgetDirty(WC_VEHICLE_VIEW, head->index, VVW_WIDGET_REFIT_VEH);
    01279
    01280   /* If we don't have a unit number yet, set one. */
    01281   if (head->unitnumber != 0) return;
    01282   head->unitnumber = GetFreeUnitNumber(VEH_TRAIN);
    01283 }
    01284
    01296 CommandCost CmdMoveRailVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    01297 {
    01298   VehicleID s = GB(p1, 0, 16);
    01299   VehicleID d = GB(p1, 16, 16);
    01300   bool move_chain = HasBit(p2, 0);
    01301
    01302   Train *src = Train::GetIfValid(s);
    01303   if (src == NULL || !CheckOwnership(src->owner)) return CMD_ERROR;
    01304
    01305   /* Do not allow moving crashed vehicles inside the depot, it is likely to cause asserts later */
    01306   if (src->vehstatus & VS_CRASHED) return CMD_ERROR;
    01307
    01308   /* if nothing is selected as destination, try and find a matching vehicle to drag to. */
    01309   Train *dst;
    01310   if (d == INVALID_VEHICLE) {
    01311     dst = src->IsEngine() ? NULL : FindGoodVehiclePos(src);
    01312   } else {
    01313     dst = Train::GetIfValid(d);
    01314     if (dst == NULL || !CheckOwnership(dst->owner)) return CMD_ERROR;
    01315
    01316     /* Do not allow appending to crashed vehicles, too */
    01317     if (dst->vehstatus & VS_CRASHED) return CMD_ERROR;
    01318   }
    01319
    01320   /* if an articulated part is being handled, deal with its parent vehicle */
    01321   src = src->GetFirstEnginePart();
    01322   if (dst != NULL) {
    01323     dst = dst->GetFirstEnginePart();
    01324   }
    01325
    01326   /* don't move the same vehicle.. */
    01327   if (src == dst) return CommandCost();
    01328
    01329   /* locate the head of the two chains */
    01330   Train *src_head = src->First();
    01331   Train *dst_head;
    01332   if (dst != NULL) {
    01333     dst_head = dst->First();
    01334     if (dst_head->tile != src_head->tile) return CMD_ERROR;
    01335     /* Now deal with articulated part of destination wagon */
    01336     dst = dst->GetLastEnginePart();
    01337   } else {
    01338     dst_head = NULL;
    01339   }
    01340
    01341   if (src->IsRearDualheaded()) return_cmd_error(STR_ERROR_REAR_ENGINE_FOLLOW_FRONT);
    01342
    01343   /* When moving all wagons, we can't have the same src_head and dst_head */
    01344   if (move_chain && src_head == dst_head) return CommandCost();
    01345
    01346   /* When moving a multiheaded part to be place after itself, bail out. */
    01347   if (!move_chain && dst != NULL && dst->IsRearDualheaded() && src == dst->other_multiheaded_part) return CommandCost();
    01348
    01349   /* Check if all vehicles in the source train are stopped inside a depot. */
    01350   if (!src_head->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
    01351
    01352   /* Check if all vehicles in the destination train are stopped inside a depot. */
    01353   if (dst_head != NULL && !dst_head->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
    01354
    01355   /* First make a backup of the order of the trains. That way we can do
    01356    * whatever we want with the order and later on easily revert. */
    01357   TrainList original_src;
    01358   TrainList original_dst;
    01359
    01360   MakeTrainBackup(original_src, src_head);
    01361   MakeTrainBackup(original_dst, dst_head);
    01362
    01363   /* Also make backup of the original heads as ArrangeTrains can change them.
    01364    * For the destination head we do not care if it is the same as the source
    01365    * head because in that case it's just a copy. */
    01366   Train *original_src_head = src_head;
    01367   Train *original_dst_head = (dst_head == src_head ? NULL : dst_head);
    01368
    01369   /* (Re)arrange the trains in the wanted arrangement. */
    01370   ArrangeTrains(&dst_head, dst, &src_head, src, move_chain);
    01371
    01372   if ((flags & DC_AUTOREPLACE) == 0) {
    01373     /* If the autoreplace flag is set we do not need to test for the validity
    01374      * because we are going to revert the train to its original state. As we
    01375      * assume the original state was correct autoreplace can skip this. */
    01376     CommandCost ret = ValidateTrains(original_dst_head, dst_head, original_src_head, src_head);
    01377     if (ret.Failed()) {
    01378       /* Restore the train we had. */
    01379       RestoreTrainBackup(original_src);
    01380       RestoreTrainBackup(original_dst);
    01381       return ret;
    01382     }
    01383   }
    01384
    01385   /* do it? */
    01386   if (flags & DC_EXEC) {
    01387     /* First normalise the sub types of the chains. */
    01388     NormaliseSubtypes(src_head);
    01389     NormaliseSubtypes(dst_head);
    01390
    01391     /* There are 14 different cases:
    01392      *  1) front engine gets moved to a new train, it stays a front engine.
    01393      *     a) the 'next' part is a wagon, that becomes a free wagon chain.
    01394      *     b) the 'next' part is an engine, that becomes a front engine.
    01395      *     c) there is no 'next' part, nothing else happens
    01396      *  2) front engine gets moved to another train, it is not a front engine anymore
    01397      *     a) the 'next' part is a wagon, that becomes a free wagon chain.
    01398      *     b) the 'next' part is an engine, that becomes a front engine.
    01399      *     c) there is no 'next' part, nothing else happens
    01400      *  3) front engine gets moved to later in the current train, it is not an engine anymore.
    01401      *     a) the 'next' part is a wagon, that becomes a free wagon chain.
    01402      *     b) the 'next' part is an engine, that becomes a front engine.
    01403      *  4) free wagon gets moved
    01404      *     a) the 'next' part is a wagon, that becomes a free wagon chain.
    01405      *     b) the 'next' part is an engine, that becomes a front engine.
    01406      *     c) there is no 'next' part, nothing else happens
    01407      *  5) non front engine gets moved and becomes a new train, nothing else happens
    01408      *  6) non front engine gets moved within a train / to another train, nothing hapens
    01409      *  7) wagon gets moved, nothing happens
    01410      */
    01411     if (src == original_src_head && src->IsEngine() && !src->IsFrontEngine()) {
    01412       /* Cases #2 and #3: the front engine gets trashed. */
    01413       DeleteWindowById(WC_VEHICLE_VIEW, src->index);
    01414       DeleteWindowById(WC_VEHICLE_ORDERS, src->index);
    01415       DeleteWindowById(WC_VEHICLE_REFIT, src->index);
    01416       DeleteWindowById(WC_VEHICLE_DETAILS, src->index);
    01417       DeleteWindowById(WC_VEHICLE_TIMETABLE, src->index);
    01418
    01419       /* We are going to be move to another train. So we
    01420        * are no part of this group anymore. In case we
    01421        * are not moving group... well, then we do not need
    01422        * to move.
    01423        * Or we are moving to later in the train and our
    01424        * new head isn't a front engine anymore.
    01425        */
    01426       if (dst_head != NULL ? dst_head != src : !src_head->IsFrontEngine()) {
    01427         DecreaseGroupNumVehicle(src->group_id);
    01428       }
    01429
    01430       /* Delete orders, group stuff and the unit number as we're not the
    01431        * front of any vehicle anymore. */
    01432       DeleteVehicleOrders(src);
    01433       RemoveVehicleFromGroup(src);
    01434       src->unitnumber = 0;
    01435     }
    01436
    01437     /* We weren't a front engine but are becoming one. So
    01438      * we should be put in the default group. */
    01439     if (original_src_head != src && dst_head == src) {
    01440       SetTrainGroupID(src, DEFAULT_GROUP);
    01441     }
    01442
    01443     /* Handle 'new engine' part of cases #1b, #2b, #3b, #4b and #5 in NormaliseTrainHead. */
    01444     NormaliseTrainHead(src_head);
    01445     NormaliseTrainHead(dst_head);
    01446
    01447     /* We are undoubtedly changing something in the depot and train list. */
    01448     InvalidateWindowData(WC_VEHICLE_DEPOT, src->tile);
    01449     InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
    01450   } else {
    01451     /* We don't want to execute what we're just tried. */
    01452     RestoreTrainBackup(original_src);
    01453     RestoreTrainBackup(original_dst);
    01454   }
    01455
    01456   return CommandCost();
    01457 }
    01458
    01470 CommandCost CmdSellRailWagon(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    01471 {
    01472   /* Check if we deleted a vehicle window */
    01473   Window *w = NULL;
    01474
    01475   Train *v = Train::GetIfValid(p1);
    01476   if (v == NULL || !CheckOwnership(v->owner)) return CMD_ERROR;
    01477
    01478   /* Sell a chain of vehicles or not? */
    01479   bool sell_chain = HasBit(p2, 0);
    01480
    01481   if (v->vehstatus & VS_CRASHED) return_cmd_error(STR_ERROR_CAN_T_SELL_DESTROYED_VEHICLE);
    01482
    01483   v = v->GetFirstEnginePart();
    01484   Train *first = v->First();
    01485
    01486   /* make sure the vehicle is stopped in the depot */
    01487   if (!first->IsStoppedInDepot()) {
    01488     return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
    01489   }
    01490
    01491   if (v->IsRearDualheaded()) return_cmd_error(STR_ERROR_REAR_ENGINE_FOLLOW_FRONT);
    01492
    01493   /* First make a backup of the order of the train. That way we can do
    01494    * whatever we want with the order and later on easily revert. */
    01495   TrainList original;
    01496   MakeTrainBackup(original, first);
    01497
    01498   /* We need to keep track of the new head and the head of what we're going to sell. */
    01499   Train *new_head = first;
    01500   Train *sell_head = NULL;
    01501
    01502   /* Split the train in the wanted way. */
    01503   ArrangeTrains(&sell_head, NULL, &new_head, v, sell_chain);
    01504
    01505   /* We don't need to validate the second train; it's going to be sold. */
    01506   CommandCost ret = ValidateTrains(NULL, NULL, first, new_head);
    01507   if (ret.Failed()) {
    01508     /* Restore the train we had. */
    01509     RestoreTrainBackup(original);
    01510     return ret;
    01511   }
    01512
    01513   CommandCost cost(EXPENSES_NEW_VEHICLES);
    01514   for (Train *t = sell_head; t != NULL; t = t->Next()) cost.AddCost(-t->value);
    01515
    01516   /* do it? */
    01517   if (flags & DC_EXEC) {
    01518     /* First normalise the sub types of the chain. */
    01519     NormaliseSubtypes(new_head);
    01520
    01521     if (v == first && v->IsEngine() && !sell_chain && new_head != NULL && new_head->IsFrontEngine()) {
    01522       /* We are selling the front engine. In this case we want to
    01523        * 'give' the order, unitnumber and such to the new head. */
    01524       new_head->orders.list = first->orders.list;
    01525       new_head->AddToShared(first);
    01526       DeleteVehicleOrders(first);
    01527
    01528       /* Copy other important data from the front engine */
    01529       new_head->CopyVehicleConfigAndStatistics(first);
    01530       IncreaseGroupNumVehicle(new_head->group_id);
    01531
    01532       /* If we deleted a window then open a new one for the 'new' train */
    01533       if (IsLocalCompany() && w != NULL) ShowVehicleViewWindow(new_head);
    01534     }
    01535
    01536     /* We need to update the information about the train. */
    01537     NormaliseTrainHead(new_head);
    01538
    01539     /* We are undoubtedly changing something in the depot and train list. */
    01540     InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
    01541     InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
    01542
    01543     /* Actually delete the sold 'goods' */
    01544     delete sell_head;
    01545   } else {
    01546     /* We don't want to execute what we're just tried. */
    01547     RestoreTrainBackup(original);
    01548   }
    01549
    01550   return cost;
    01551 }
    01552
    01553 void Train::UpdateDeltaXY(Direction direction)
    01554 {
    01555 #define MKIT(a, b, c, d) ((a & 0xFF) << 24) | ((b & 0xFF) << 16) | ((c & 0xFF) << 8) | ((d & 0xFF) << 0)
    01556   static const uint32 _delta_xy_table[8] = {
    01557     MKIT(3, 3, -1, -1),
    01558     MKIT(3, 7, -1, -3),
    01559     MKIT(3, 3, -1, -1),
    01560     MKIT(7, 3, -3, -1),
    01561     MKIT(3, 3, -1, -1),
    01562     MKIT(3, 7, -1, -3),
    01563     MKIT(3, 3, -1, -1),
    01564     MKIT(7, 3, -3, -1),
    01565   };
    01566 #undef MKIT
    01567
    01568   uint32 x = _delta_xy_table[direction];
    01569   this->x_offs        = GB(x,  0, 8);
    01570   this->y_offs        = GB(x,  8, 8);
    01571   this->x_extent      = GB(x, 16, 8);
    01572   this->y_extent      = GB(x, 24, 8);
    01573   this->z_extent      = 6;
    01574 }
    01575
    01576 static inline void SetLastSpeed(Train *v, int spd)
    01577 {
    01578   int old = v->tcache.last_speed;
    01579   if (spd != old) {
    01580     v->tcache.last_speed = spd;
    01581     if (_settings_client.gui.vehicle_speed || (old == 0) != (spd == 0)) {
    01582       SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
    01583     }
    01584   }
    01585 }
    01586
    01588 static void MarkTrainAsStuck(Train *v)
    01589 {
    01590   if (!HasBit(v->flags, VRF_TRAIN_STUCK)) {
    01591     /* It is the first time the problem occured, set the "train stuck" flag. */
    01592     SetBit(v->flags, VRF_TRAIN_STUCK);
    01593
    01594     v->wait_counter = 0;
    01595
    01596     /* Stop train */
    01597     v->cur_speed = 0;
    01598     v->subspeed = 0;
    01599     SetLastSpeed(v, 0);
    01600
    01601     SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
    01602   }
    01603 }
    01604
    01605 static void SwapTrainFlags(uint16 *swap_flag1, uint16 *swap_flag2)
    01606 {
    01607   uint16 flag1 = *swap_flag1;
    01608   uint16 flag2 = *swap_flag2;
    01609
    01610   /* Clear the flags */
    01611   ClrBit(*swap_flag1, VRF_GOINGUP);
    01612   ClrBit(*swap_flag1, VRF_GOINGDOWN);
    01613   ClrBit(*swap_flag2, VRF_GOINGUP);
    01614   ClrBit(*swap_flag2, VRF_GOINGDOWN);
    01615
    01616   /* Reverse the rail-flags (if needed) */
    01617   if (HasBit(flag1, VRF_GOINGUP)) {
    01618     SetBit(*swap_flag2, VRF_GOINGDOWN);
    01619   } else if (HasBit(flag1, VRF_GOINGDOWN)) {
    01620     SetBit(*swap_flag2, VRF_GOINGUP);
    01621   }
    01622   if (HasBit(flag2, VRF_GOINGUP)) {
    01623     SetBit(*swap_flag1, VRF_GOINGDOWN);
    01624   } else if (HasBit(flag2, VRF_GOINGDOWN)) {
    01625     SetBit(*swap_flag1, VRF_GOINGUP);
    01626   }
    01627 }
    01628
    01629 static void ReverseTrainSwapVeh(Train *v, int l, int r)
    01630 {
    01631   Train *a, *b;
    01632
    01633   /* locate vehicles to swap */
    01634   for (a = v; l != 0; l--) a = a->Next();
    01635   for (b = v; r != 0; r--) b = b->Next();
    01636
    01637   if (a != b) {
    01638     /* swap the hidden bits */
    01639     {
    01640       uint16 tmp = (a->vehstatus & ~VS_HIDDEN) | (b->vehstatus&VS_HIDDEN);
    01641       b->vehstatus = (b->vehstatus & ~VS_HIDDEN) | (a->vehstatus&VS_HIDDEN);
    01642       a->vehstatus = tmp;
    01643     }
    01644
    01645     Swap(a->track, b->track);
    01646     Swap(a->direction,    b->direction);
    01647
    01648     /* toggle direction */
    01649     if (a->track != TRACK_BIT_DEPOT) a->direction = ReverseDir(a->direction);
    01650     if (b->track != TRACK_BIT_DEPOT) b->direction = ReverseDir(b->direction);
    01651
    01652     Swap(a->x_pos, b->x_pos);
    01653     Swap(a->y_pos, b->y_pos);
    01654     Swap(a->tile,  b->tile);
    01655     Swap(a->z_pos, b->z_pos);
    01656
    01657     SwapTrainFlags(&a->flags, &b->flags);
    01658
    01659     /* update other vars */
    01660     a->UpdateViewport(true, true);
    01661     b->UpdateViewport(true, true);
    01662
    01663     /* call the proper EnterTile function unless we are in a wormhole */
    01664     if (a->track != TRACK_BIT_WORMHOLE) VehicleEnterTile(a, a->tile, a->x_pos, a->y_pos);
    01665     if (b->track != TRACK_BIT_WORMHOLE) VehicleEnterTile(b, b->tile, b->x_pos, b->y_pos);
    01666   } else {
    01667     if (a->track != TRACK_BIT_DEPOT) a->direction = ReverseDir(a->direction);
    01668     a->UpdateViewport(true, true);
    01669
    01670     if (a->track != TRACK_BIT_WORMHOLE) VehicleEnterTile(a, a->tile, a->x_pos, a->y_pos);
    01671   }
    01672
    01673   /* Update train's power incase tiles were different rail type */
    01674   v->PowerChanged();
    01675 }
    01676
    01677
    01683 static Vehicle *TrainOnTileEnum(Vehicle *v, void *)
    01684 {
    01685   return (v->type == VEH_TRAIN) ? v : NULL;
    01686 }
    01687
    01688
    01695 static Vehicle *TrainApproachingCrossingEnum(Vehicle *v, void *data)
    01696 {
    01697   if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) return NULL;
    01698
    01699   Train *t = Train::From(v);
    01700   if (!t->IsFrontEngine()) return NULL;
    01701
    01702   TileIndex tile = *(TileIndex *)data;
    01703
    01704   if (TrainApproachingCrossingTile(t) != tile) return NULL;
    01705
    01706   return t;
    01707 }
    01708
    01709
    01716 static bool TrainApproachingCrossing(TileIndex tile)
    01717 {
    01718   assert(IsLevelCrossingTile(tile));
    01719
    01720   DiagDirection dir = AxisToDiagDir(GetCrossingRailAxis(tile));
    01721   TileIndex tile_from = tile + TileOffsByDiagDir(dir);
    01722
    01723   if (HasVehicleOnPos(tile_from, &tile, &TrainApproachingCrossingEnum)) return true;
    01724
    01725   dir = ReverseDiagDir(dir);
    01726   tile_from = tile + TileOffsByDiagDir(dir);
    01727
    01728   return HasVehicleOnPos(tile_from, &tile, &TrainApproachingCrossingEnum);
    01729 }
    01730
    01731
    01738 void UpdateLevelCrossing(TileIndex tile, bool sound)
    01739 {
    01740   assert(IsLevelCrossingTile(tile));
    01741
    01742   /* train on crossing || train approaching crossing || reserved */
    01743   bool new_state = HasVehicleOnPos(tile, NULL, &TrainOnTileEnum) || TrainApproachingCrossing(tile) || HasCrossingReservation(tile);
    01744
    01745   if (new_state != IsCrossingBarred(tile)) {
    01746     if (new_state && sound) {
    01747       SndPlayTileFx(SND_0E_LEVEL_CROSSING, tile);
    01748     }
    01749     SetCrossingBarred(tile, new_state);
    01750     MarkTileDirtyByTile(tile);
    01751   }
    01752 }
    01753
    01754
    01760 static inline void MaybeBarCrossingWithSound(TileIndex tile)
    01761 {
    01762   if (!IsCrossingBarred(tile)) {
    01763     BarCrossing(tile);
    01764     SndPlayTileFx(SND_0E_LEVEL_CROSSING, tile);
    01765     MarkTileDirtyByTile(tile);
    01766   }
    01767 }
    01768
    01769
    01775 static void AdvanceWagonsBeforeSwap(Train *v)
    01776 {
    01777   Train *base = v;
    01778   Train *first = base; // first vehicle to move
    01779   Train *last = v->Last(); // last vehicle to move
    01780   uint length = CountVehiclesInChain(v);
    01781
    01782   while (length > 2) {
    01783     last = last->Previous();
    01784     first = first->Next();
    01785
    01786     int differential = base->tcache.cached_veh_length - last->tcache.cached_veh_length;
    01787
    01788     /* do not update images now
    01789      * negative differential will be handled in AdvanceWagonsAfterSwap() */
    01790     for (int i = 0; i < differential; i++) TrainController(first, last->Next());
    01791
    01792     base = first; // == base->Next()
    01793     length -= 2;
    01794   }
    01795 }
    01796
    01797
    01803 static void AdvanceWagonsAfterSwap(Train *v)
    01804 {
    01805   /* first of all, fix the situation when the train was entering a depot */
    01806   Train *dep = v; // last vehicle in front of just left depot
    01807   while (dep->Next() != NULL && (dep->track == TRACK_BIT_DEPOT || dep->Next()->track != TRACK_BIT_DEPOT)) {
    01808     dep = dep->Next(); // find first vehicle outside of a depot, with next vehicle inside a depot
    01809   }
    01810
    01811   Train *leave = dep->Next(); // first vehicle in a depot we are leaving now
    01812
    01813   if (leave != NULL) {
    01814     /* 'pull' next wagon out of the depot, so we won't miss it (it could stay in depot forever) */
    01815     int d = TicksToLeaveDepot(dep);
    01816
    01817     if (d <= 0) {
    01818       leave->vehstatus &= ~VS_HIDDEN; // move it out of the depot
    01819       leave->track = TrackToTrackBits(GetRailDepotTrack(leave->tile));
    01820       for (int i = 0; i >= d; i--) TrainController(leave, NULL); // maybe move it, and maybe let another wagon leave
    01821     }
    01822   } else {
    01823     dep = NULL; // no vehicle in a depot, so no vehicle leaving a depot
    01824   }
    01825
    01826   Train *base = v;
    01827   Train *first = base; // first vehicle to move
    01828   Train *last = v->Last(); // last vehicle to move
    01829   uint length = CountVehiclesInChain(v);
    01830
    01831   /* we have to make sure all wagons that leave a depot because of train reversing are moved coorectly
    01832    * they have already correct spacing, so we have to make sure they are moved how they should */
    01833   bool nomove = (dep == NULL); // if there is no vehicle leaving a depot, limit the number of wagons moved immediatelly
    01834
    01835   while (length > 2) {
    01836     /* we reached vehicle (originally) in front of a depot, stop now
    01837      * (we would move wagons that are alredy moved with new wagon length) */
    01838     if (base == dep) break;
    01839
    01840     /* the last wagon was that one leaving a depot, so do not move it anymore */
    01841     if (last == dep) nomove = true;
    01842
    01843     last = last->Previous();
    01844     first = first->Next();
    01845
    01846     int differential = last->tcache.cached_veh_length - base->tcache.cached_veh_length;
    01847
    01848     /* do not update images now */
    01849     for (int i = 0; i < differential; i++) TrainController(first, (nomove ? last->Next() : NULL));
    01850
    01851     base = first; // == base->Next()
    01852     length -= 2;
    01853   }
    01854 }
    01855
    01856
    01857 static void ReverseTrainDirection(Train *v)
    01858 {
    01859   if (IsRailDepotTile(v->tile)) {
    01860     InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
    01861   }
    01862
    01863   /* Clear path reservation in front if train is not stuck. */
    01864   if (!HasBit(v->flags, VRF_TRAIN_STUCK)) FreeTrainTrackReservation(v);
    01865
    01866   /* Check if we were approaching a rail/road-crossing */
    01867   TileIndex crossing = TrainApproachingCrossingTile(v);
    01868
    01869   /* count number of vehicles */
    01870   int r = CountVehiclesInChain(v) - 1;  // number of vehicles - 1
    01871
    01872   AdvanceWagonsBeforeSwap(v);
    01873
    01874   /* swap start<>end, start+1<>end-1, ... */
    01875   int l = 0;
    01876   do {
    01877     ReverseTrainSwapVeh(v, l++, r--);
    01878   } while (l <= r);
    01879
    01880   AdvanceWagonsAfterSwap(v);
    01881
    01882   if (IsRailDepotTile(v->tile)) {
    01883     InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
    01884   }
    01885
    01886   ToggleBit(v->flags, VRF_TOGGLE_REVERSE);
    01887
    01888   ClrBit(v->flags, VRF_REVERSING);
    01889
    01890   /* recalculate cached data */
    01891   v->ConsistChanged(true);
    01892
    01893   /* update all images */
    01894   for (Vehicle *u = v; u != NULL; u = u->Next()) u->UpdateViewport(false, false);
    01895
    01896   /* update crossing we were approaching */
    01897   if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
    01898
    01899   /* maybe we are approaching crossing now, after reversal */
    01900   crossing = TrainApproachingCrossingTile(v);
    01901   if (crossing != INVALID_TILE) MaybeBarCrossingWithSound(crossing);
    01902
    01903   /* If we are inside a depot after reversing, don't bother with path reserving. */
    01904   if (v->track == TRACK_BIT_DEPOT) {
    01905     /* Can't be stuck here as inside a depot is always a safe tile. */
    01906     if (HasBit(v->flags, VRF_TRAIN_STUCK)) SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
    01907     ClrBit(v->flags, VRF_TRAIN_STUCK);
    01908     return;
    01909   }
    01910
    01911   /* TrainExitDir does not always produce the desired dir for depots and
    01912    * tunnels/bridges that is needed for UpdateSignalsOnSegment. */
    01913   DiagDirection dir = TrainExitDir(v->direction, v->track);
    01914   if (IsRailDepotTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE)) dir = INVALID_DIAGDIR;
    01915
    01916   if (UpdateSignalsOnSegment(v->tile, dir, v->owner) == SIGSEG_PBS || _settings_game.pf.reserve_paths) {
    01917     /* If we are currently on a tile with conventional signals, we can't treat the
    01918      * current tile as a safe tile or we would enter a PBS block without a reservation. */
    01919     bool first_tile_okay = !(IsTileType(v->tile, MP_RAILWAY) &&
    01920       HasSignalOnTrackdir(v->tile, v->GetVehicleTrackdir()) &&
    01921       !IsPbsSignal(GetSignalType(v->tile, FindFirstTrack(v->track))));
    01922
    01923     if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
    01924     if (TryPathReserve(v, false, first_tile_okay)) {
    01925       /* Do a look-ahead now in case our current tile was already a safe tile. */
    01926       CheckNextTrainTile(v);
    01927     } else if (v->current_order.GetType() != OT_LOADING) {
    01928       /* Do not wait for a way out when we're still loading */
    01929       MarkTrainAsStuck(v);
    01930     }
    01931   } else if (HasBit(v->flags, VRF_TRAIN_STUCK)) {
    01932     /* A train not inside a PBS block can't be stuck. */
    01933     ClrBit(v->flags, VRF_TRAIN_STUCK);
    01934     v->wait_counter = 0;
    01935   }
    01936 }
    01937
    01946 CommandCost CmdReverseTrainDirection(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    01947 {
    01948   Train *v = Train::GetIfValid(p1);
    01949   if (v == NULL || !CheckOwnership(v->owner)) return CMD_ERROR;
    01950
    01951   if (p2 != 0) {
    01952     /* turn a single unit around */
    01953
    01954     if (v->IsMultiheaded() || HasBit(EngInfo(v->engine_type)->callback_mask, CBM_VEHICLE_ARTIC_ENGINE)) {
    01955       return_cmd_error(STR_ERROR_CAN_T_REVERSE_DIRECTION_RAIL_VEHICLE_MULTIPLE_UNITS);
    01956     }
    01957
    01958     Train *front = v->First();
    01959     /* make sure the vehicle is stopped in the depot */
    01960     if (!front->IsStoppedInDepot()) {
    01961       return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
    01962     }
    01963
    01964     if (flags & DC_EXEC) {
    01965       ToggleBit(v->flags, VRF_REVERSE_DIRECTION);
    01966       SetWindowDirty(WC_VEHICLE_DEPOT, v->tile);
    01967       SetWindowDirty(WC_VEHICLE_DETAILS, v->index);
    01968       /* We cancel any 'skip signal at dangers' here */
    01969       v->force_proceed = 0;
    01970       SetWindowDirty(WC_VEHICLE_VIEW, v->index);
    01971     }
    01972   } else {
    01973     /* turn the whole train around */
    01974     if ((v->vehstatus & VS_CRASHED) || v->breakdown_ctr != 0) return CMD_ERROR;
    01975
    01976     if (flags & DC_EXEC) {
    01977       /* Properly leave the station if we are loading and won't be loading anymore */
    01978       if (v->current_order.IsType(OT_LOADING)) {
    01979         const Vehicle *last = v;
    01980         while (last->Next() != NULL) last = last->Next();
    01981
    01982         /* not a station || different station --> leave the station */
    01983         if (!IsTileType(last->tile, MP_STATION) || GetStationIndex(last->tile) != GetStationIndex(v->tile)) {
    01984           v->LeaveStation();
    01985         }
    01986       }
    01987
    01988       /* We cancel any 'skip signal at dangers' here */
    01989       v->force_proceed = 0;
    01990       SetWindowDirty(WC_VEHICLE_VIEW, v->index);
    01991
    01992       if (_settings_game.vehicle.train_acceleration_model != TAM_ORIGINAL && v->cur_speed != 0) {
    01993         ToggleBit(v->flags, VRF_REVERSING);
    01994       } else {
    01995         v->cur_speed = 0;
    01996         SetLastSpeed(v, 0);
    01997         HideFillingPercent(&v->fill_percent_te_id);
    01998         ReverseTrainDirection(v);
    01999       }
    02000     }
    02001   }
    02002   return CommandCost();
    02003 }
    02004
    02013 CommandCost CmdForceTrainProceed(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    02014 {
    02015   Train *t = Train::GetIfValid(p1);
    02016   if (t == NULL || !CheckOwnership(t->owner)) return CMD_ERROR;
    02017
    02018   if (flags & DC_EXEC) {
    02019     /* If we are forced to proceed, cancel that order.
    02020      * If we are marked stuck we would want to force the train
    02021      * to proceed to the next signal. In the other cases we
    02022      * would like to pass the signal at danger and run till the
    02023      * next signal we encounter. */
    02024     t->force_proceed = t->force_proceed == 2 ? 0 : HasBit(t->flags, VRF_TRAIN_STUCK) || t->IsInDepot() ? 1 : 2;
    02025     SetWindowDirty(WC_VEHICLE_VIEW, t->index);
    02026   }
    02027
    02028   return CommandCost();
    02029 }
    02030
    02042 CommandCost CmdRefitRailVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    02043 {
    02044   CargoID new_cid = GB(p2, 0, 8);
    02045   byte new_subtype = GB(p2, 8, 8);
    02046   bool only_this = HasBit(p2, 16);
    02047
    02048   Train *v = Train::GetIfValid(p1);
    02049   if (v == NULL || !CheckOwnership(v->owner)) return CMD_ERROR;
    02050
    02051   if (!v->IsStoppedInDepot()) return_cmd_error(STR_TRAIN_MUST_BE_STOPPED);
    02052   if (v->vehstatus & VS_CRASHED) return_cmd_error(STR_ERROR_CAN_T_REFIT_DESTROYED_VEHICLE);
    02053
    02054   /* Check cargo */
    02055   if (new_cid >= NUM_CARGO) return CMD_ERROR;
    02056
    02057   CommandCost cost = RefitVehicle(v, only_this, new_cid, new_subtype, flags);
    02058
    02059   /* Update the train's cached variables */
    02060   if (flags & DC_EXEC) {
    02061     Train *front = v->First();
    02062     front->ConsistChanged(false);
    02063     SetWindowDirty(WC_VEHICLE_DETAILS, front->index);
    02064     SetWindowDirty(WC_VEHICLE_DEPOT, front->tile);
    02065     InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
    02066   } else {
    02067     v->InvalidateNewGRFCacheOfChain(); // always invalidate; querycost might have filled it
    02068   }
    02069
    02070   return cost;
    02071 }
    02072
    02075 static FindDepotData FindClosestTrainDepot(Train *v, int max_distance)
    02076 {
    02077   assert(!(v->vehstatus & VS_CRASHED));
    02078
    02079   if (IsRailDepotTile(v->tile)) return FindDepotData(v->tile, 0);
    02080
    02081   PBSTileInfo origin = FollowTrainReservation(v);
    02082   if (IsRailDepotTile(origin.tile)) return FindDepotData(origin.tile, 0);
    02083
    02084   switch (_settings_game.pf.pathfinder_for_trains) {
    02085     case VPF_NPF: return NPFTrainFindNearestDepot(v, max_distance);
    02086     case VPF_YAPF: return YapfTrainFindNearestDepot(v, max_distance);
    02087
    02088     default: NOT_REACHED();
    02089   }
    02090 }
    02091
    02092 bool Train::FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
    02093 {
    02094   FindDepotData tfdd = FindClosestTrainDepot(this, 0);
    02095   if (tfdd.best_length == UINT_MAX) return false;
    02096
    02097   if (location    != NULL) *location    = tfdd.tile;
    02098   if (destination != NULL) *destination = GetDepotIndex(tfdd.tile);
    02099   if (reverse     != NULL) *reverse     = tfdd.reverse;
    02100
    02101   return true;
    02102 }
    02103
    02114 CommandCost CmdSendTrainToDepot(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    02115 {
    02116   if (p2 & DEPOT_MASS_SEND) {
    02117     /* Mass goto depot requested */
    02118     if (!ValidVLWFlags(p2 & VLW_MASK)) return CMD_ERROR;
    02119     return SendAllVehiclesToDepot(VEH_TRAIN, flags, p2 & DEPOT_SERVICE, _current_company, (p2 & VLW_MASK), p1);
    02120   }
    02121
    02122   Train *v = Train::GetIfValid(p1);
    02123   if (v == NULL) return CMD_ERROR;
    02124
    02125   return v->SendToDepot(flags, (DepotCommand)(p2 & DEPOT_COMMAND_MASK));
    02126 }
    02127
    02128 static const int8 _vehicle_smoke_pos[8] = {
    02129   1, 1, 1, 0, -1, -1, -1, 0
    02130 };
    02131
    02132 static void HandleLocomotiveSmokeCloud(const Train *v)
    02133 {
    02134   bool sound = false;
    02135
    02136   if ((v->vehstatus & VS_TRAIN_SLOWING) || v->cur_speed < 2) {
    02137     return;
    02138   }
    02139
    02140   const Train *u = v;
    02141
    02142   do {
    02143     const RailVehicleInfo *rvi = RailVehInfo(v->engine_type);
    02144     int effect_offset = GB(v->tcache.cached_vis_effect, 0, 4) - 8;
    02145     byte effect_type = GB(v->tcache.cached_vis_effect, 4, 2);
    02146     bool disable_effect = HasBit(v->tcache.cached_vis_effect, 6);
    02147
    02148     /* no smoke? */
    02149     if ((rvi->railveh_type == RAILVEH_WAGON && effect_type == 0) ||
    02150         disable_effect ||
    02151         v->vehstatus & VS_HIDDEN) {
    02152       continue;
    02153     }
    02154
    02155     /* No smoke in depots or tunnels */
    02156     if (IsRailDepotTile(v->tile) || IsTunnelTile(v->tile)) continue;
    02157
    02158     /* No sparks for electric vehicles on nonelectrified tracks */
    02159     if (!HasPowerOnRail(v->railtype, GetTileRailType(v->tile))) continue;
    02160
    02161     if (effect_type == 0) {
    02162       /* Use default effect type for engine class. */
    02163       effect_type = rvi->engclass;
    02164     } else {
    02165       effect_type--;
    02166     }
    02167
    02168     int x = _vehicle_smoke_pos[v->direction] * effect_offset;
    02169     int y = _vehicle_smoke_pos[(v->direction + 2) % 8] * effect_offset;
    02170
    02171     if (HasBit(v->flags, VRF_REVERSE_DIRECTION)) {
    02172       x = -x;
    02173       y = -y;
    02174     }
    02175
    02176     switch (effect_type) {
    02177       case 0:
    02178         /* steam smoke. */
    02179         if (GB(v->tick_counter, 0, 4) == 0) {
    02180           CreateEffectVehicleRel(v, x, y, 10, EV_STEAM_SMOKE);
    02181           sound = true;
    02182         }
    02183         break;
    02184
    02185       case 1:
    02186         /* diesel smoke */
    02187         if (u->cur_speed <= 40 && Chance16(15, 128)) {
    02188           CreateEffectVehicleRel(v, 0, 0, 10, EV_DIESEL_SMOKE);
    02189           sound = true;
    02190         }
    02191         break;
    02192
    02193       case 2:
    02194         /* blue spark */
    02195         if (GB(v->tick_counter, 0, 2) == 0 && Chance16(1, 45)) {
    02196           CreateEffectVehicleRel(v, 0, 0, 10, EV_ELECTRIC_SPARK);
    02197           sound = true;
    02198         }
    02199         break;
    02200
    02201       default:
    02202         break;
    02203     }
    02204   } while ((v = v->Next()) != NULL);
    02205
    02206   if (sound) PlayVehicleSound(u, VSE_TRAIN_EFFECT);
    02207 }
    02208
    02209 void Train::PlayLeaveStationSound() const
    02210 {
    02211   static const SoundFx sfx[] = {
    02212     SND_04_TRAIN,
    02213     SND_0A_TRAIN_HORN,
    02214     SND_0A_TRAIN_HORN,
    02215     SND_47_MAGLEV_2,
    02216     SND_41_MAGLEV
    02217   };
    02218
    02219   if (PlayVehicleSound(this, VSE_START)) return;
    02220
    02221   EngineID engtype = this->engine_type;
    02222   SndPlayVehicleFx(sfx[RailVehInfo(engtype)->engclass], this);
    02223 }
    02224
    02226 static void CheckNextTrainTile(Train *v)
    02227 {
    02228   /* Don't do any look-ahead if path_backoff_interval is 255. */
    02229   if (_settings_game.pf.path_backoff_interval == 255) return;
    02230
    02231   /* Exit if we reached our destination depot or are inside a depot. */
    02232   if ((v->tile == v->dest_tile && v->current_order.IsType(OT_GOTO_DEPOT)) || v->track == TRACK_BIT_DEPOT) return;
    02233   /* Exit if we are on a station tile and are going to stop. */
    02234   if (IsRailStationTile(v->tile) && v->current_order.ShouldStopAtStation(v, GetStationIndex(v->tile))) return;
    02235   /* Exit if the current order doesn't have a destination, but the train has orders. */
    02236   if ((v->current_order.IsType(OT_NOTHING) || v->current_order.IsType(OT_LEAVESTATION) || v->current_order.IsType(OT_LOADING)) && v->GetNumOrders() > 0) return;
    02237
    02238   Trackdir td = v->GetVehicleTrackdir();
    02239
    02240   /* On a tile with a red non-pbs signal, don't look ahead. */
    02241   if (IsTileType(v->tile, MP_RAILWAY) && HasSignalOnTrackdir(v->tile, td) &&
    02242       !IsPbsSignal(GetSignalType(v->tile, TrackdirToTrack(td))) &&
    02243       GetSignalStateByTrackdir(v->tile, td) == SIGNAL_STATE_RED) return;
    02244
    02245   CFollowTrackRail ft(v);
    02246   if (!ft.Follow(v->tile, td)) return;
    02247
    02248   if (!HasReservedTracks(ft.m_new_tile, TrackdirBitsToTrackBits(ft.m_new_td_bits))) {
    02249     /* Next tile is not reserved. */
    02250     if (KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE) {
    02251       if (HasPbsSignalOnTrackdir(ft.m_new_tile, FindFirstTrackdir(ft.m_new_td_bits))) {
    02252         /* If the next tile is a PBS signal, try to make a reservation. */
    02253         TrackBits tracks = TrackdirBitsToTrackBits(ft.m_new_td_bits);
    02254         if (_settings_game.pf.forbid_90_deg) {
    02255           tracks &= ~TrackCrossesTracks(TrackdirToTrack(ft.m_old_td));
    02256         }
    02257         ChooseTrainTrack(v, ft.m_new_tile, ft.m_exitdir, tracks, false, NULL, false);
    02258       }
    02259     }
    02260   }
    02261 }
    02262
    02263 static bool CheckTrainStayInDepot(Train *v)
    02264 {
    02265   /* bail out if not all wagons are in the same depot or not in a depot at all */
    02266   for (const Train *u = v; u != NULL; u = u->Next()) {
    02267     if (u->track != TRACK_BIT_DEPOT || u->tile != v->tile) return false;
    02268   }
    02269
    02270   /* if the train got no power, then keep it in the depot */
    02271   if (v->tcache.cached_power == 0) {
    02272     v->vehstatus |= VS_STOPPED;
    02273     SetWindowDirty(WC_VEHICLE_DEPOT, v->tile);
    02274     return true;
    02275   }
    02276
    02277   SigSegState seg_state;
    02278
    02279   if (v->force_proceed == 0) {
    02280     /* force proceed was not pressed */
    02281     if (++v->wait_counter < 37) {
    02282       SetWindowClassesDirty(WC_TRAINS_LIST);
    02283       return true;
    02284     }
    02285
    02286     v->wait_counter = 0;
    02287
    02288     seg_state = _settings_game.pf.reserve_paths ? SIGSEG_PBS : UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
    02289     if (seg_state == SIGSEG_FULL || HasDepotReservation(v->tile)) {
    02290       /* Full and no PBS signal in block or depot reserved, can't exit. */
    02291       SetWindowClassesDirty(WC_TRAINS_LIST);
    02292       return true;
    02293     }
    02294   } else {
    02295     seg_state = _settings_game.pf.reserve_paths ? SIGSEG_PBS : UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
    02296   }
    02297
    02298   /* We are leaving a depot, but have to go to the exact same one; re-enter */
    02299   if (v->current_order.IsType(OT_GOTO_DEPOT) && v->tile == v->dest_tile) {
    02300     /* We need to have a reservation for this to work. */
    02301     if (HasDepotReservation(v->tile)) return true;
    02302     SetDepotReservation(v->tile, true);
    02303     VehicleEnterDepot(v);
    02304     return true;
    02305   }
    02306
    02307   /* Only leave when we can reserve a path to our destination. */
    02308   if (seg_state == SIGSEG_PBS && !TryPathReserve(v) && v->force_proceed == 0) {
    02309     /* No path and no force proceed. */
    02310     SetWindowClassesDirty(WC_TRAINS_LIST);
    02311     MarkTrainAsStuck(v);
    02312     return true;
    02313   }
    02314
    02315   SetDepotReservation(v->tile, true);
    02316   if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(v->tile);
    02317
    02318   VehicleServiceInDepot(v);
    02319   SetWindowClassesDirty(WC_TRAINS_LIST);
    02320   v->PlayLeaveStationSound();
    02321
    02322   v->track = TRACK_BIT_X;
    02323   if (v->direction & 2) v->track = TRACK_BIT_Y;
    02324
    02325   v->vehstatus &= ~VS_HIDDEN;
    02326   v->cur_speed = 0;
    02327
    02328   v->UpdateDeltaXY(v->direction);
    02329   v->cur_image = v->GetImage(v->direction);
    02330   VehicleMove(v, false);
    02331   UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
    02332   v->UpdateAcceleration();
    02333   InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
    02334
    02335   return false;
    02336 }
    02337
    02339 static void ClearPathReservation(const Train *v, TileIndex tile, Trackdir track_dir)
    02340 {
    02341   DiagDirection dir = TrackdirToExitdir(track_dir);
    02342
    02343   if (IsTileType(tile, MP_TUNNELBRIDGE)) {
    02344     /* Are we just leaving a tunnel/bridge? */
    02345     if (GetTunnelBridgeDirection(tile) == ReverseDiagDir(dir)) {
    02346       TileIndex end = GetOtherTunnelBridgeEnd(tile);
    02347
    02348       if (!HasVehicleOnTunnelBridge(tile, end, v)) {
    02349         /* Free the reservation only if no other train is on the tiles. */
    02350         SetTunnelBridgeReservation(tile, false);
    02351         SetTunnelBridgeReservation(end, false);
    02352
    02353         if (_settings_client.gui.show_track_reservation) {
    02354           MarkTileDirtyByTile(tile);
    02355           MarkTileDirtyByTile(end);
    02356         }
    02357       }
    02358     }
    02359   } else if (IsRailStationTile(tile)) {
    02360     TileIndex new_tile = TileAddByDiagDir(tile, dir);
    02361     /* If the new tile is not a further tile of the same station, we
    02362      * clear the reservation for the whole platform. */
    02363     if (!IsCompatibleTrainStationTile(new_tile, tile)) {
    02364       SetRailStationPlatformReservation(tile, ReverseDiagDir(dir), false);
    02365     }
    02366   } else {
    02367     /* Any other tile */
    02368     UnreserveRailTrack(tile, TrackdirToTrack(track_dir));
    02369   }
    02370 }
    02371
    02373 void FreeTrainTrackReservation(const Train *v, TileIndex origin, Trackdir orig_td)
    02374 {
    02375   assert(v->IsFrontEngine());
    02376
    02377   TileIndex tile = origin != INVALID_TILE ? origin : v->tile;
    02378   Trackdir  td = orig_td != INVALID_TRACKDIR ? orig_td : v->GetVehicleTrackdir();
    02379   bool      free_tile = tile != v->tile || !(IsRailStationTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE));
    02380   StationID station_id = IsRailStationTile(v->tile) ? GetStationIndex(v->tile) : INVALID_STATION;
    02381
    02382   /* Don't free reservation if it's not ours. */
    02383   if (TracksOverlap(GetReservedTrackbits(tile) | TrackToTrackBits(TrackdirToTrack(td)))) return;
    02384
    02385   CFollowTrackRail ft(v, GetRailTypeInfo(v->railtype)->compatible_railtypes);
    02386   while (ft.Follow(tile, td)) {
    02387     tile = ft.m_new_tile;
    02388     TrackdirBits bits = ft.m_new_td_bits & TrackBitsToTrackdirBits(GetReservedTrackbits(tile));
    02389     td = RemoveFirstTrackdir(&bits);
    02390     assert(bits == TRACKDIR_BIT_NONE);
    02391
    02392     if (!IsValidTrackdir(td)) break;
    02393
    02394     if (IsTileType(tile, MP_RAILWAY)) {
    02395       if (HasSignalOnTrackdir(tile, td) && !IsPbsSignal(GetSignalType(tile, TrackdirToTrack(td)))) {
    02396         /* Conventional signal along trackdir: remove reservation and stop. */
    02397         UnreserveRailTrack(tile, TrackdirToTrack(td));
    02398         break;
    02399       }
    02400       if (HasPbsSignalOnTrackdir(tile, td)) {
    02401         if (GetSignalStateByTrackdir(tile, td) == SIGNAL_STATE_RED) {
    02402           /* Red PBS signal? Can't be our reservation, would be green then. */
    02403           break;
    02404         } else {
    02405           /* Turn the signal back to red. */
    02406           SetSignalStateByTrackdir(tile, td, SIGNAL_STATE_RED);
    02407           MarkTileDirtyByTile(tile);
    02408         }
    02409       } else if (HasSignalOnTrackdir(tile, ReverseTrackdir(td)) && IsOnewaySignal(tile, TrackdirToTrack(td))) {
    02410         break;
    02411       }
    02412     }
    02413
    02414     /* Don't free first station/bridge/tunnel if we are on it. */
    02415     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);
    02416
    02417     free_tile = true;
    02418   }
    02419 }
    02420
    02421 static const byte _initial_tile_subcoord[6][4][3] = {
    02422 {{ 15, 8, 1 }, { 0, 0, 0 }, { 0, 8, 5 }, { 0,  0, 0 }},
    02423 {{  0, 0, 0 }, { 8, 0, 3 }, { 0, 0, 0 }, { 8, 15, 7 }},
    02424 {{  0, 0, 0 }, { 7, 0, 2 }, { 0, 7, 6 }, { 0,  0, 0 }},
    02425 {{ 15, 8, 2 }, { 0, 0, 0 }, { 0, 0, 0 }, { 8, 15, 6 }},
    02426 {{ 15, 7, 0 }, { 8, 0, 4 }, { 0, 0, 0 }, { 0,  0, 0 }},
    02427 {{  0, 0, 0 }, { 0, 0, 0 }, { 0, 8, 4 }, { 7, 15, 0 }},
    02428 };
    02429
    02442 static Track DoTrainPathfind(const Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool *path_not_found, bool do_track_reservation, PBSTileInfo *dest)
    02443 {
    02444   switch (_settings_game.pf.pathfinder_for_trains) {
    02445     case VPF_NPF: return NPFTrainChooseTrack(v, tile, enterdir, tracks, path_not_found, do_track_reservation, dest);
    02446     case VPF_YAPF: return YapfTrainChooseTrack(v, tile, enterdir, tracks, path_not_found, do_track_reservation, dest);
    02447
    02448     default: NOT_REACHED();
    02449   }
    02450 }
    02451
    02457 static PBSTileInfo ExtendTrainReservation(const Train *v, TrackBits *new_tracks, DiagDirection *enterdir)
    02458 {
    02459   PBSTileInfo origin = FollowTrainReservation(v);
    02460
    02461   CFollowTrackRail ft(v);
    02462
    02463   TileIndex tile = origin.tile;
    02464   Trackdir  cur_td = origin.trackdir;
    02465   while (ft.Follow(tile, cur_td)) {
    02466     if (KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE) {
    02467       /* Possible signal tile. */
    02468       if (HasOnewaySignalBlockingTrackdir(ft.m_new_tile, FindFirstTrackdir(ft.m_new_td_bits))) break;
    02469     }
    02470
    02471     if (_settings_game.pf.forbid_90_deg) {
    02472       ft.m_new_td_bits &= ~TrackdirCrossesTrackdirs(ft.m_old_td);
    02473       if (ft.m_new_td_bits == TRACKDIR_BIT_NONE) break;
    02474     }
    02475
    02476     /* Station, depot or waypoint are a possible target. */
    02477     bool target_seen = ft.m_is_station || (IsTileType(ft.m_new_tile, MP_RAILWAY) && !IsPlainRail(ft.m_new_tile));
    02478     if (target_seen || KillFirstBit(ft.m_new_td_bits) != TRACKDIR_BIT_NONE) {
    02479       /* Choice found or possible target encountered.
    02480        * On finding a possible target, we need to stop and let the pathfinder handle the
    02481        * remaining path. This is because we don't know if this target is in one of our
    02482        * orders, so we might cause pathfinding to fail later on if we find a choice.
    02483        * This failure would cause a bogous call to TryReserveSafePath which might reserve
    02484        * a wrong path not leading to our next destination. */
    02485       if (HasReservedTracks(ft.m_new_tile, TrackdirBitsToTrackBits(TrackdirReachesTrackdirs(ft.m_old_td)))) break;
    02486
    02487       /* If we did skip some tiles, backtrack to the first skipped tile so the pathfinder
    02488        * actually starts its search at the first unreserved tile. */
    02489       if (ft.m_tiles_skipped != 0) ft.m_new_tile -= TileOffsByDiagDir(ft.m_exitdir) * ft.m_tiles_skipped;
    02490
    02491       /* Choice found, path valid but not okay. Save info about the choice tile as well. */
    02492       if (new_tracks) *new_tracks = TrackdirBitsToTrackBits(ft.m_new_td_bits);
    02493       if (enterdir) *enterdir = ft.m_exitdir;
    02494       return PBSTileInfo(ft.m_new_tile, ft.m_old_td, false);
    02495     }
    02496
    02497     tile = ft.m_new_tile;
    02498     cur_td = FindFirstTrackdir(ft.m_new_td_bits);
    02499
    02500     if (IsSafeWaitingPosition(v, tile, cur_td, true, _settings_game.pf.forbid_90_deg)) {
    02501       bool wp_free = IsWaitingPositionFree(v, tile, cur_td, _settings_game.pf.forbid_90_deg);
    02502       if (!(wp_free && TryReserveRailTrack(tile, TrackdirToTrack(cur_td)))) break;
    02503       /* Safe position is all good, path valid and okay. */
    02504       return PBSTileInfo(tile, cur_td, true);
    02505     }
    02506
    02507     if (!TryReserveRailTrack(tile, TrackdirToTrack(cur_td))) break;
    02508   }
    02509
    02510   if (ft.m_err == CFollowTrackRail::EC_OWNER || ft.m_err == CFollowTrackRail::EC_NO_WAY) {
    02511     /* End of line, path valid and okay. */
    02512     return PBSTileInfo(ft.m_old_tile, ft.m_old_td, true);
    02513   }
    02514
    02515   /* Sorry, can't reserve path, back out. */
    02516   tile = origin.tile;
    02517   cur_td = origin.trackdir;
    02518   TileIndex stopped = ft.m_old_tile;
    02519   Trackdir  stopped_td = ft.m_old_td;
    02520   while (tile != stopped || cur_td != stopped_td) {
    02521     if (!ft.Follow(tile, cur_td)) break;
    02522
    02523     if (_settings_game.pf.forbid_90_deg) {
    02524       ft.m_new_td_bits &= ~TrackdirCrossesTrackdirs(ft.m_old_td);
    02525       assert(ft.m_new_td_bits != TRACKDIR_BIT_NONE);
    02526     }
    02527     assert(KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE);
    02528
    02529     tile = ft.m_new_tile;
    02530     cur_td = FindFirstTrackdir(ft.m_new_td_bits);
    02531
    02532     UnreserveRailTrack(tile, TrackdirToTrack(cur_td));
    02533   }
    02534
    02535   /* Path invalid. */
    02536   return PBSTileInfo();
    02537 }
    02538
    02549 static bool TryReserveSafeTrack(const Train *v, TileIndex tile, Trackdir td, bool override_tailtype)
    02550 {
    02551   switch (_settings_game.pf.pathfinder_for_trains) {
    02552     case VPF_NPF: return NPFTrainFindNearestSafeTile(v, tile, td, override_tailtype);
    02553     case VPF_YAPF: return YapfTrainFindNearestSafeTile(v, tile, td, override_tailtype);
    02554
    02555     default: NOT_REACHED();
    02556   }
    02557 }
    02558
    02560 class VehicleOrderSaver
    02561 {
    02562 private:
    02563   Vehicle        *v;
    02564   Order          old_order;
    02565   TileIndex      old_dest_tile;
    02566   StationID      old_last_station_visited;
    02567   VehicleOrderID index;
    02568
    02569 public:
    02570   VehicleOrderSaver(Vehicle *_v) :
    02571     v(_v),
    02572     old_order(_v->current_order),
    02573     old_dest_tile(_v->dest_tile),
    02574     old_last_station_visited(_v->last_station_visited),
    02575     index(_v->cur_order_index)
    02576   {
    02577   }
    02578
    02579   ~VehicleOrderSaver()
    02580   {
    02581     this->v->current_order = this->old_order;
    02582     this->v->dest_tile = this->old_dest_tile;
    02583     this->v->last_station_visited = this->old_last_station_visited;
    02584   }
    02585
    02591   bool SwitchToNextOrder(bool skip_first)
    02592   {
    02593     if (this->v->GetNumOrders() == 0) return false;
    02594
    02595     if (skip_first) ++this->index;
    02596
    02597     int conditional_depth = 0;
    02598
    02599     do {
    02600       /* Wrap around. */
    02601       if (this->index >= this->v->GetNumOrders()) this->index = 0;
    02602
    02603       Order *order = this->v->GetOrder(this->index);
    02604       assert(order != NULL);
    02605
    02606       switch (order->GetType()) {
    02607         case OT_GOTO_DEPOT:
    02608           /* Skip service in depot orders when the train doesn't need service. */
    02609           if ((order->GetDepotOrderType() & ODTFB_SERVICE) && !this->v->NeedsServicing()) break;
    02610         case OT_GOTO_STATION:
    02611         case OT_GOTO_WAYPOINT:
    02612           this->v->current_order = *order;
    02613           UpdateOrderDest(this->v, order);
    02614           return true;
    02615         case OT_CONDITIONAL: {
    02616           if (conditional_depth > this->v->GetNumOrders()) return false;
    02617           VehicleOrderID next = ProcessConditionalOrder(order, this->v);
    02618           if (next != INVALID_VEH_ORDER_ID) {
    02619             conditional_depth++;
    02620             this->index = next;
    02621             /* Don't increment next, so no break here. */
    02622             continue;
    02623           }
    02624           break;
    02625         }
    02626         default:
    02627           break;
    02628       }
    02629       /* Don't increment inside the while because otherwise conditional
    02630        * orders can lead to an infinite loop. */
    02631       ++this->index;
    02632     } while (this->index != this->v->cur_order_index);
    02633
    02634     return false;
    02635   }
    02636 };
    02637
    02638 /* choose a track */
    02639 static Track ChooseTrainTrack(Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool force_res, bool *got_reservation, bool mark_stuck)
    02640 {
    02641   Track best_track = INVALID_TRACK;
    02642   bool do_track_reservation = _settings_game.pf.reserve_paths || force_res;
    02643   bool changed_signal = false;
    02644
    02645   assert((tracks & ~TRACK_BIT_MASK) == 0);
    02646
    02647   if (got_reservation != NULL) *got_reservation = false;
    02648
    02649   /* Don't use tracks here as the setting to forbid 90 deg turns might have been switched between reservation and now. */
    02650   TrackBits res_tracks = (TrackBits)(GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir));
    02651   /* Do we have a suitable reserved track? */
    02652   if (res_tracks != TRACK_BIT_NONE) return FindFirstTrack(res_tracks);
    02653
    02654   /* Quick return in case only one possible track is available */
    02655   if (KillFirstBit(tracks) == TRACK_BIT_NONE) {
    02656     Track track = FindFirstTrack(tracks);
    02657     /* We need to check for signals only here, as a junction tile can't have signals. */
    02658     if (track != INVALID_TRACK && HasPbsSignalOnTrackdir(tile, TrackEnterdirToTrackdir(track, enterdir))) {
    02659       do_track_reservation = true;
    02660       changed_signal = true;
    02661       SetSignalStateByTrackdir(tile, TrackEnterdirToTrackdir(track, enterdir), SIGNAL_STATE_GREEN);
    02662     } else if (!do_track_reservation) {
    02663       return track;
    02664     }
    02665     best_track = track;
    02666   }
    02667
    02668   PBSTileInfo   res_dest(tile, INVALID_TRACKDIR, false);
    02669   DiagDirection dest_enterdir = enterdir;
    02670   if (do_track_reservation) {
    02671     /* Check if the train needs service here, so it has a chance to always find a depot.
    02672      * Also check if the current order is a service order so we don't reserve a path to
    02673      * the destination but instead to the next one if service isn't needed. */
    02674     CheckIfTrainNeedsService(v);
    02675     if (v->current_order.IsType(OT_DUMMY) || v->current_order.IsType(OT_CONDITIONAL) || v->current_order.IsType(OT_GOTO_DEPOT)) ProcessOrders(v);
    02676
    02677     res_dest = ExtendTrainReservation(v, &tracks, &dest_enterdir);
    02678     if (res_dest.tile == INVALID_TILE) {
    02679       /* Reservation failed? */
    02680       if (mark_stuck) MarkTrainAsStuck(v);
    02681       if (changed_signal) SetSignalStateByTrackdir(tile, TrackEnterdirToTrackdir(best_track, enterdir), SIGNAL_STATE_RED);
    02682       return FindFirstTrack(tracks);
    02683     }
    02684   }
    02685
    02686   /* Save the current train order. The destructor will restore the old order on function exit. */
    02687   VehicleOrderSaver orders(v);
    02688
    02689   /* If the current tile is the destination of the current order and
    02690    * a reservation was requested, advance to the next order.
    02691    * Don't advance on a depot order as depots are always safe end points
    02692    * for a path and no look-ahead is necessary. This also avoids a
    02693    * problem with depot orders not part of the order list when the
    02694    * order list itself is empty. */
    02695   if (v->current_order.IsType(OT_LEAVESTATION)) {
    02696     orders.SwitchToNextOrder(false);
    02697   } else if (v->current_order.IsType(OT_LOADING) || (!v->current_order.IsType(OT_GOTO_DEPOT) && (
    02698       v->current_order.IsType(OT_GOTO_STATION) ?
    02699       IsRailStationTile(v->tile) && v->current_order.GetDestination() == GetStationIndex(v->tile) :
    02700       v->tile == v->dest_tile))) {
    02701     orders.SwitchToNextOrder(true);
    02702   }
    02703
    02704   if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
    02705     /* Pathfinders are able to tell that route was only 'guessed'. */
    02706     bool      path_not_found = false;
    02707     TileIndex new_tile = res_dest.tile;
    02708
    02709     Track next_track = DoTrainPathfind(v, new_tile, dest_enterdir, tracks, &path_not_found, do_track_reservation, &res_dest);
    02710     if (new_tile == tile) best_track = next_track;
    02711
    02712     /* handle "path not found" state */
    02713     if (path_not_found) {
    02714       /* PF didn't find the route */
    02715       if (!HasBit(v->flags, VRF_NO_PATH_TO_DESTINATION)) {
    02716         /* it is first time the problem occurred, set the "path not found" flag */
    02717         SetBit(v->flags, VRF_NO_PATH_TO_DESTINATION);
    02718         /* and notify user about the event */
    02719         AI::NewEvent(v->owner, new AIEventVehicleLost(v->index));
    02720         if (_settings_client.gui.lost_train_warn && v->owner == _local_company) {
    02721           SetDParam(0, v->index);
    02722           AddVehicleNewsItem(
    02723             STR_NEWS_TRAIN_IS_LOST,
    02724             NS_ADVICE,
    02725             v->index
    02726           );
    02727         }
    02728       }
    02729     } else {
    02730       /* route found, is the train marked with "path not found" flag? */
    02731       if (HasBit(v->flags, VRF_NO_PATH_TO_DESTINATION)) {
    02732         /* clear the flag as the PF's problem was solved */
    02733         ClrBit(v->flags, VRF_NO_PATH_TO_DESTINATION);
    02734         /* can we also delete the "News" item somehow? */
    02735       }
    02736     }
    02737   }
    02738
    02739   /* No track reservation requested -> finished. */
    02740   if (!do_track_reservation) return best_track;
    02741
    02742   /* A path was found, but could not be reserved. */
    02743   if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
    02744     if (mark_stuck) MarkTrainAsStuck(v);
    02745     FreeTrainTrackReservation(v);
    02746     return best_track;
    02747   }
    02748
    02749   /* No possible reservation target found, we are probably lost. */
    02750   if (res_dest.tile == INVALID_TILE) {
    02751     /* Try to find any safe destination. */
    02752     PBSTileInfo origin = FollowTrainReservation(v);
    02753     if (TryReserveSafeTrack(v, origin.tile, origin.trackdir, false)) {
    02754       TrackBits res = GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir);
    02755       best_track = FindFirstTrack(res);
    02756       TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
    02757       if (got_reservation != NULL) *got_reservation = true;
    02758       if (changed_signal) MarkTileDirtyByTile(tile);
    02759     } else {
    02760       FreeTrainTrackReservation(v);
    02761       if (mark_stuck) MarkTrainAsStuck(v);
    02762     }
    02763     return best_track;
    02764   }
    02765
    02766   if (got_reservation != NULL) *got_reservation = true;
    02767
    02768   /* Reservation target found and free, check if it is safe. */
    02769   while (!IsSafeWaitingPosition(v, res_dest.tile, res_dest.trackdir, true, _settings_game.pf.forbid_90_deg)) {
    02770     /* Extend reservation until we have found a safe position. */
    02771     DiagDirection exitdir = TrackdirToExitdir(res_dest.trackdir);
    02772     TileIndex     next_tile = TileAddByDiagDir(res_dest.tile, exitdir);
    02773     TrackBits     reachable = TrackdirBitsToTrackBits((TrackdirBits)(GetTileTrackStatus(next_tile, TRANSPORT_RAIL, 0))) & DiagdirReachesTracks(exitdir);
    02774     if (_settings_game.pf.forbid_90_deg) {
    02775       reachable &= ~TrackCrossesTracks(TrackdirToTrack(res_dest.trackdir));
    02776     }
    02777
    02778     /* Get next order with destination. */
    02779     if (orders.SwitchToNextOrder(true)) {
    02780       PBSTileInfo cur_dest;
    02781       DoTrainPathfind(v, next_tile, exitdir, reachable, NULL, true, &cur_dest);
    02782       if (cur_dest.tile != INVALID_TILE) {
    02783         res_dest = cur_dest;
    02784         if (res_dest.okay) continue;
    02785         /* Path found, but could not be reserved. */
    02786         FreeTrainTrackReservation(v);
    02787         if (mark_stuck) MarkTrainAsStuck(v);
    02788         if (got_reservation != NULL) *got_reservation = false;
    02789         changed_signal = false;
    02790         break;
    02791       }
    02792     }
    02793     /* No order or no safe position found, try any position. */
    02794     if (!TryReserveSafeTrack(v, res_dest.tile, res_dest.trackdir, true)) {
    02795       FreeTrainTrackReservation(v);
    02796       if (mark_stuck) MarkTrainAsStuck(v);
    02797       if (got_reservation != NULL) *got_reservation = false;
    02798       changed_signal = false;
    02799     }
    02800     break;
    02801   }
    02802
    02803   TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
    02804
    02805   if (changed_signal) MarkTileDirtyByTile(tile);
    02806
    02807   return best_track;
    02808 }
    02809
    02818 bool TryPathReserve(Train *v, bool mark_as_stuck, bool first_tile_okay)
    02819 {
    02820   assert(v->IsFrontEngine());
    02821
    02822   /* We have to handle depots specially as the track follower won't look
    02823    * at the depot tile itself but starts from the next tile. If we are still
    02824    * inside the depot, a depot reservation can never be ours. */
    02825   if (v->track == TRACK_BIT_DEPOT) {
    02826     if (HasDepotReservation(v->tile)) {
    02827       if (mark_as_stuck) MarkTrainAsStuck(v);
    02828       return false;
    02829     } else {
    02830       /* Depot not reserved, but the next tile might be. */
    02831       TileIndex next_tile = TileAddByDiagDir(v->tile, GetRailDepotDirection(v->tile));
    02832       if (HasReservedTracks(next_tile, DiagdirReachesTracks(GetRailDepotDirection(v->tile)))) return false;
    02833     }
    02834   }
    02835
    02836   Vehicle *other_train = NULL;
    02837   PBSTileInfo origin = FollowTrainReservation(v, &other_train);
    02838   /* The path we are driving on is alread blocked by some other train.
    02839    * This can only happen in certain situations when mixing path and
    02840    * block signals or when changing tracks and/or signals.
    02841    * Exit here as doing any further reservations will probably just
    02842    * make matters worse. */
    02843   if (other_train != NULL && other_train->index != v->index) {
    02844     if (mark_as_stuck) MarkTrainAsStuck(v);
    02845     return false;
    02846   }
    02847   /* If we have a reserved path and the path ends at a safe tile, we are finished already. */
    02848   if (origin.okay && (v->tile != origin.tile || first_tile_okay)) {
    02849     /* Can't be stuck then. */
    02850     if (HasBit(v->flags, VRF_TRAIN_STUCK)) SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
    02851     ClrBit(v->flags, VRF_TRAIN_STUCK);
    02852     return true;
    02853   }
    02854
    02855   /* If we are in a depot, tentativly reserve the depot. */
    02856   if (v->track == TRACK_BIT_DEPOT) {
    02857     SetDepotReservation(v->tile, true);
    02858     if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(v->tile);
    02859   }
    02860
    02861   DiagDirection exitdir = TrackdirToExitdir(origin.trackdir);
    02862   TileIndex     new_tile = TileAddByDiagDir(origin.tile, exitdir);
    02863   TrackBits     reachable = TrackdirBitsToTrackBits(TrackStatusToTrackdirBits(GetTileTrackStatus(new_tile, TRANSPORT_RAIL, 0)) & DiagdirReachesTrackdirs(exitdir));
    02864
    02865   if (_settings_game.pf.forbid_90_deg) reachable &= ~TrackCrossesTracks(TrackdirToTrack(origin.trackdir));
    02866
    02867   bool res_made = false;
    02868   ChooseTrainTrack(v, new_tile, exitdir, reachable, true, &res_made, mark_as_stuck);
    02869
    02870   if (!res_made) {
    02871     /* Free the depot reservation as well. */
    02872     if (v->track == TRACK_BIT_DEPOT) SetDepotReservation(v->tile, false);
    02873     return false;
    02874   }
    02875
    02876   if (HasBit(v->flags, VRF_TRAIN_STUCK)) {
    02877     v->wait_counter = 0;
    02878     SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
    02879   }
    02880   ClrBit(v->flags, VRF_TRAIN_STUCK);
    02881   return true;
    02882 }
    02883
    02884
    02885 static bool CheckReverseTrain(const Train *v)
    02886 {
    02887   if (_settings_game.difficulty.line_reverse_mode != 0 ||
    02888       v->track == TRACK_BIT_DEPOT || v->track == TRACK_BIT_WORMHOLE ||
    02889       !(v->direction & 1)) {
    02890     return false;
    02891   }
    02892
    02893   assert(v->track != TRACK_BIT_NONE);
    02894
    02895   switch (_settings_game.pf.pathfinder_for_trains) {
    02896     case VPF_NPF: return NPFTrainCheckReverse(v);
    02897     case VPF_YAPF: return YapfTrainCheckReverse(v);
    02898
    02899     default: NOT_REACHED();
    02900   }
    02901 }
    02902
    02903 TileIndex Train::GetOrderStationLocation(StationID station)
    02904 {
    02905   if (station == this->last_station_visited) this->last_station_visited = INVALID_STATION;
    02906
    02907   const Station *st = Station::Get(station);
    02908   if (!(st->facilities & FACIL_TRAIN)) {
    02909     /* The destination station has no trainstation tiles. */
    02910     this->IncrementOrderIndex();
    02911     return 0;
    02912   }
    02913
    02914   return st->xy;
    02915 }
    02916
    02917 void Train::MarkDirty()
    02918 {
    02919   Vehicle *v = this;
    02920   do {
    02921     v->UpdateViewport(false, false);
    02922   } while ((v = v->Next()) != NULL);
    02923
    02924   /* need to update acceleration and cached values since the goods on the train changed. */
    02925   this->CargoChanged();
    02926   this->UpdateAcceleration();
    02927 }
    02928
    02938 int Train::UpdateSpeed()
    02939 {
    02940   uint accel;
    02941
    02942   switch (_settings_game.vehicle.train_acceleration_model) {
    02943     default: NOT_REACHED();
    02944     case TAM_ORIGINAL: accel = this->acceleration * (this->GetAccelerationStatus() == AS_BRAKE ? -4 : 2); break;
    02945     case TAM_REALISTIC:
    02946       this->max_speed = this->GetCurrentMaxSpeed();
    02947       accel = this->GetAcceleration();
    02948       break;
    02949   }
    02950
    02951   uint spd = this->subspeed + accel;
    02952   this->subspeed = (byte)spd;
    02953   {
    02954     int tempmax = this->max_speed;
    02955     if (this->cur_speed > this->max_speed)
    02956       tempmax = this->cur_speed - (this->cur_speed / 10) - 1;
    02957     this->cur_speed = spd = Clamp(this->cur_speed + ((int)spd >> 8), 0, tempmax);
    02958   }
    02959
    02960   /* Scale speed by 3/4. Previously this was only done when the train was
    02961    * facing diagonally and would apply to however many moves the train made
    02962    * regardless the of direction actually moved in. Now it is always scaled,
    02963    * 256 spd is used to go straight and 192 is used to go diagonally
    02964    * (3/4 of 256). This results in the same effect, but without the error the
    02965    * previous method caused.
    02966    *
    02967    * The scaling is done in this direction and not by multiplying the amount
    02968    * to be subtracted by 4/3 so that the leftover speed can be saved in a
    02969    * byte in this->progress.
    02970    */
    02971   int scaled_spd = spd * 3 >> 2;
    02972
    02973   scaled_spd += this->progress;
    02974   this->progress = 0; // set later in TrainLocoHandler or TrainController
    02975   return scaled_spd;
    02976 }
    02977
    02978 static void TrainEnterStation(Train *v, StationID station)
    02979 {
    02980   v->last_station_visited = station;
    02981
    02982   /* check if a train ever visited this station before */
    02983   Station *st = Station::Get(station);
    02984   if (!(st->had_vehicle_of_type & HVOT_TRAIN)) {
    02985     st->had_vehicle_of_type |= HVOT_TRAIN;
    02986     SetDParam(0, st->index);
    02987     AddVehicleNewsItem(
    02988       STR_NEWS_FIRST_TRAIN_ARRIVAL,
    02989       v->owner == _local_company ? NS_ARRIVAL_COMPANY : NS_ARRIVAL_OTHER,
    02990       v->index,
    02991       st->index
    02992     );
    02993     AI::NewEvent(v->owner, new AIEventStationFirstVehicle(st->index, v->index));
    02994   }
    02995
    02996   v->BeginLoading();
    02997
    02998   StationAnimationTrigger(st, v->tile, STAT_ANIM_TRAIN_ARRIVES);
    02999 }
    03000
    03001 static byte AfterSetTrainPos(Train *v, bool new_tile)
    03002 {
    03003   byte old_z = v->z_pos;
    03004   v->z_pos = GetSlopeZ(v->x_pos, v->y_pos);
    03005
    03006   if (new_tile) {
    03007     ClrBit(v->flags, VRF_GOINGUP);
    03008     ClrBit(v->flags, VRF_GOINGDOWN);
    03009
    03010     if (v->track == TRACK_BIT_X || v->track == TRACK_BIT_Y) {
    03011       /* Any track that isn't TRACK_BIT_X or TRACK_BIT_Y cannot be sloped.
    03012        * To check whether the current tile is sloped, and in which
    03013        * direction it is sloped, we get the 'z' at the center of
    03014        * the tile (middle_z) and the edge of the tile (old_z),
    03015        * which we then can compare. */
    03016       static const int HALF_TILE_SIZE = TILE_SIZE / 2;
    03017       static const int INV_TILE_SIZE_MASK = ~(TILE_SIZE - 1);
    03018
    03019       byte middle_z = GetSlopeZ((v->x_pos & INV_TILE_SIZE_MASK) | HALF_TILE_SIZE, (v->y_pos & INV_TILE_SIZE_MASK) | HALF_TILE_SIZE);
    03020
    03021       if (middle_z != v->z_pos) {
    03022         SetBit(v->flags, (middle_z > old_z) ? VRF_GOINGUP : VRF_GOINGDOWN);
    03023       }
    03024     }
    03025   }
    03026
    03027   VehicleMove(v, true);
    03028   return old_z;
    03029 }
    03030
    03031 /* Check if the vehicle is compatible with the specified tile */
    03032 static inline bool CheckCompatibleRail(const Train *v, TileIndex tile)
    03033 {
    03034   return
    03035     IsTileOwner(tile, v->owner) && (
    03036       !v->IsFrontEngine() ||
    03037       HasBit(v->compatible_railtypes, GetRailType(tile))
    03038     );
    03039 }
    03040
    03041 struct RailtypeSlowdownParams {
    03042   byte small_turn, large_turn;
    03043   byte z_up; // fraction to remove when moving up
    03044   byte z_down; // fraction to remove when moving down
    03045 };
    03046
    03047 static const RailtypeSlowdownParams _railtype_slowdown[] = {
    03048   /* normal accel */
    03049   {256 / 4, 256 / 2, 256 / 4, 2},
    03050   {256 / 4, 256 / 2, 256 / 4, 2},
    03051   {256 / 4, 256 / 2, 256 / 4, 2},
    03052   {0,       256 / 2, 256 / 4, 2},
    03053 };
    03054
    03056 static inline void AffectSpeedByZChange(Train *v, byte old_z)
    03057 {
    03058   if (old_z == v->z_pos || _settings_game.vehicle.train_acceleration_model != TAM_ORIGINAL) return;
    03059
    03060   const RailtypeSlowdownParams *rsp = &_railtype_slowdown[v->railtype];
    03061
    03062   if (old_z < v->z_pos) {
    03063     v->cur_speed -= (v->cur_speed * rsp->z_up >> 8);
    03064   } else {
    03065     uint16 spd = v->cur_speed + rsp->z_down;
    03066     if (spd <= v->max_speed) v->cur_speed = spd;
    03067   }
    03068 }
    03069
    03070 static bool TrainMovedChangeSignals(TileIndex tile, DiagDirection dir)
    03071 {
    03072   if (IsTileType(tile, MP_RAILWAY) &&
    03073       GetRailTileType(tile) == RAIL_TILE_SIGNALS) {
    03074     TrackdirBits tracks = TrackBitsToTrackdirBits(GetTrackBits(tile)) & DiagdirReachesTrackdirs(dir);
    03075     Trackdir trackdir = FindFirstTrackdir(tracks);
    03076     if (UpdateSignalsOnSegment(tile,  TrackdirToExitdir(trackdir), GetTileOwner(tile)) == SIGSEG_PBS && HasSignalOnTrackdir(tile, trackdir)) {
    03077       /* A PBS block with a non-PBS signal facing us? */
    03078       if (!IsPbsSignal(GetSignalType(tile, TrackdirToTrack(trackdir)))) return true;
    03079     }
    03080   }
    03081   return false;
    03082 }
    03083
    03087 void Train::ReserveTrackUnderConsist() const
    03088 {
    03089   for (const Train *u = this; u != NULL; u = u->Next()) {
    03090     switch (u->track) {
    03091       case TRACK_BIT_WORMHOLE:
    03092         TryReserveRailTrack(u->tile, DiagDirToDiagTrack(GetTunnelBridgeDirection(u->tile)));
    03093         break;
    03094       case TRACK_BIT_DEPOT:
    03095         break;
    03096       default:
    03097         TryReserveRailTrack(u->tile, TrackBitsToTrack(u->track));
    03098         break;
    03099     }
    03100   }
    03101 }
    03102
    03103 uint Train::Crash(bool flooded)
    03104 {
    03105   uint pass = 0;
    03106   if (this->IsFrontEngine()) {
    03107     pass += 4; // driver
    03108
    03109     /* Remove the reserved path in front of the train if it is not stuck.
    03110      * Also clear all reserved tracks the train is currently on. */
    03111     if (!HasBit(this->flags, VRF_TRAIN_STUCK)) FreeTrainTrackReservation(this);
    03112     for (const Train *v = this; v != NULL; v = v->Next()) {
    03113       ClearPathReservation(v, v->tile, v->GetVehicleTrackdir());
    03114       if (IsTileType(v->tile, MP_TUNNELBRIDGE)) {
    03115         /* ClearPathReservation will not free the wormhole exit
    03116          * if the train has just entered the wormhole. */
    03117         SetTunnelBridgeReservation(GetOtherTunnelBridgeEnd(v->tile), false);
    03118       }
    03119     }
    03120
    03121     /* we may need to update crossing we were approaching,
    03122     * but must be updated after the train has been marked crashed */
    03123     TileIndex crossing = TrainApproachingCrossingTile(this);
    03124     if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
    03125   }
    03126
    03127   pass += Vehicle::Crash(flooded);
    03128
    03129   this->crash_anim_pos = flooded ? 4000 : 1; // max 4440, disappear pretty fast when flooded
    03130   return pass;
    03131 }
    03132
    03139 static uint TrainCrashed(Train *v)
    03140 {
    03141   uint num = 0;
    03142
    03143   /* do not crash train twice */
    03144   if (!(v->vehstatus & VS_CRASHED)) {
    03145     num = v->Crash();
    03146     AI::NewEvent(v->owner, new AIEventVehicleCrashed(v->index, v->tile, AIEventVehicleCrashed::CRASH_TRAIN));
    03147   }
    03148
    03149   /* Try to re-reserve track under already crashed train too.
    03150    * SetVehicleCrashed() clears the reservation! */
    03151   v->ReserveTrackUnderConsist();
    03152
    03153   return num;
    03154 }
    03155
    03156 struct TrainCollideChecker {
    03157   Train *v;
    03158   uint num;
    03159 };
    03160
    03161 static Vehicle *FindTrainCollideEnum(Vehicle *v, void *data)
    03162 {
    03163   TrainCollideChecker *tcc = (TrainCollideChecker*)data;
    03164
    03165   /* not a train or in depot */
    03166   if (v->type != VEH_TRAIN || Train::From(v)->track == TRACK_BIT_DEPOT) return NULL;
    03167
    03168   /* get first vehicle now to make most usual checks faster */
    03169   Train *coll = Train::From(v)->First();
    03170
    03171   /* can't collide with own wagons */
    03172   if (coll == tcc->v) return NULL;
    03173
    03174   int x_diff = v->x_pos - tcc->v->x_pos;
    03175   int y_diff = v->y_pos - tcc->v->y_pos;
    03176
    03177   /* Do fast calculation to check whether trains are not in close vicinity
    03178    * and quickly reject trains distant enough for any collision.
    03179    * Differences are shifted by 7, mapping range [-7 .. 8] into [0 .. 15]
    03180    * Differences are then ORed and then we check for any higher bits */
    03181   uint hash = (y_diff + 7) | (x_diff + 7);
    03182   if (hash & ~15) return NULL;
    03183
    03184   /* Slower check using multiplication */
    03185   if (x_diff * x_diff + y_diff * y_diff > 25) return NULL;
    03186
    03187   /* Happens when there is a train under bridge next to bridge head */
    03188   if (abs(v->z_pos - tcc->v->z_pos) > 5) return NULL;
    03189
    03190   /* crash both trains */
    03191   tcc->num += TrainCrashed(tcc->v);
    03192   tcc->num += TrainCrashed(coll);
    03193
    03194   return NULL; // continue searching
    03195 }
    03196
    03203 static bool CheckTrainCollision(Train *v)
    03204 {
    03205   /* can't collide in depot */
    03206   if (v->track == TRACK_BIT_DEPOT) return false;
    03207
    03208   assert(v->track == TRACK_BIT_WORMHOLE || TileVirtXY(v->x_pos, v->y_pos) == v->tile);
    03209
    03210   TrainCollideChecker tcc;
    03211   tcc.v = v;
    03212   tcc.num = 0;
    03213
    03214   /* find colliding vehicles */
    03215   if (v->track == TRACK_BIT_WORMHOLE) {
    03216     FindVehicleOnPos(v->tile, &tcc, FindTrainCollideEnum);
    03217     FindVehicleOnPos(GetOtherTunnelBridgeEnd(v->tile), &tcc, FindTrainCollideEnum);
    03218   } else {
    03219     FindVehicleOnPosXY(v->x_pos, v->y_pos, &tcc, FindTrainCollideEnum);
    03220   }
    03221
    03222   /* any dead -> no crash */
    03223   if (tcc.num == 0) return false;
    03224
    03225   SetDParam(0, tcc.num);
    03226   AddVehicleNewsItem(STR_NEWS_TRAIN_CRASH,
    03227     NS_ACCIDENT,
    03228     v->index
    03229   );
    03230
    03231   ModifyStationRatingAround(v->tile, v->owner, -160, 30);
    03232   SndPlayVehicleFx(SND_13_BIG_CRASH, v);
    03233   return true;
    03234 }
    03235
    03236 static Vehicle *CheckTrainAtSignal(Vehicle *v, void *data)
    03237 {
    03238   if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) return NULL;
    03239
    03240   Train *t = Train::From(v);
    03241   DiagDirection exitdir = *(DiagDirection *)data;
    03242
    03243   /* not front engine of a train, inside wormhole or depot, crashed */
    03244   if (!t->IsFrontEngine() || !(t->track & TRACK_BIT_MASK)) return NULL;
    03245
    03246   if (t->cur_speed > 5 || TrainExitDir(t->direction, t->track) != exitdir) return NULL;
    03247
    03248   return t;
    03249 }
    03250
    03251 static void TrainController(Train *v, Vehicle *nomove)
    03252 {
    03253   Train *first = v->First();
    03254   Train *prev;
    03255   bool direction_changed = false; // has direction of any part changed?
    03256
    03257   /* For every vehicle after and including the given vehicle */
    03258   for (prev = v->Previous(); v != nomove; prev = v, v = v->Next()) {
    03259     DiagDirection enterdir = DIAGDIR_BEGIN;
    03260     bool update_signals_crossing = false; // will we update signals or crossing state?
    03261
    03262     GetNewVehiclePosResult gp = GetNewVehiclePos(v);
    03263     if (v->track != TRACK_BIT_WORMHOLE) {
    03264       /* Not inside tunnel */
    03265       if (gp.old_tile == gp.new_tile) {
    03266         /* Staying in the old tile */
    03267         if (v->track == TRACK_BIT_DEPOT) {
    03268           /* Inside depot */
    03269           gp.x = v->x_pos;
    03270           gp.y = v->y_pos;
    03271         } else {
    03272           /* Not inside depot */
    03273
    03274           /* Reverse when we are at the end of the track already, do not move to the new position */
    03275           if (v->IsFrontEngine() && !TrainCheckIfLineEnds(v)) return;
    03276
    03277           uint32 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
    03278           if (HasBit(r, VETS_CANNOT_ENTER)) {
    03279             goto invalid_rail;
    03280           }
    03281           if (HasBit(r, VETS_ENTERED_STATION)) {
    03282             /* The new position is the end of the platform */
    03283             TrainEnterStation(v, r >> VETS_STATION_ID_OFFSET);
    03284           }
    03285         }
    03286       } else {
    03287         /* A new tile is about to be entered. */
    03288
    03289         /* Determine what direction we're entering the new tile from */
    03290         enterdir = DiagdirBetweenTiles(gp.old_tile, gp.new_tile);
    03291         assert(IsValidDiagDirection(enterdir));
    03292
    03293         /* Get the status of the tracks in the new tile and mask
    03294          * away the bits that aren't reachable. */
    03295         TrackStatus ts = GetTileTrackStatus(gp.new_tile, TRANSPORT_RAIL, 0, ReverseDiagDir(enterdir));
    03296         TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(enterdir);
    03297
    03298         TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
    03299         TrackBits red_signals = TrackdirBitsToTrackBits(TrackStatusToRedSignals(ts) & reachable_trackdirs);
    03300
    03301         TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
    03302         if (_settings_game.pf.forbid_90_deg && prev == NULL) {
    03303           /* We allow wagons to make 90 deg turns, because forbid_90_deg
    03304            * can be switched on halfway a turn */
    03305           bits &= ~TrackCrossesTracks(FindFirstTrack(v->track));
    03306         }
    03307
    03308         if (bits == TRACK_BIT_NONE) goto invalid_rail;
    03309
    03310         /* Check if the new tile contrains tracks that are compatible
    03311          * with the current train, if not, bail out. */
    03312         if (!CheckCompatibleRail(v, gp.new_tile)) goto invalid_rail;
    03313
    03314         TrackBits chosen_track;
    03315         if (prev == NULL) {
    03316           /* Currently the locomotive is active. Determine which one of the
    03317            * available tracks to choose */
    03318           chosen_track = TrackToTrackBits(ChooseTrainTrack(v, gp.new_tile, enterdir, bits, false, NULL, true));
    03319           assert(chosen_track & (bits | GetReservedTrackbits(gp.new_tile)));
    03320
    03321           if (v->force_proceed != 0 && IsPlainRailTile(gp.new_tile) && HasSignals(gp.new_tile)) {
    03322             /* For each signal we find decrease the counter by one.
    03323              * We start at two, so the first signal we pass decreases
    03324              * this to one, then if we reach the next signal it is
    03325              * decreased to zero and we won't pass that new signal. */
    03326             Trackdir dir = FindFirstTrackdir(trackdirbits);
    03327             if (GetSignalType(gp.new_tile, TrackdirToTrack(dir)) != SIGTYPE_PBS ||
    03328                 !HasSignalOnTrackdir(gp.new_tile, ReverseTrackdir(dir))) {
    03329               /* However, we do not want to be stopped by PBS signals
    03330                * entered via the back. */
    03331               v->force_proceed--;
    03332               SetWindowDirty(WC_VEHICLE_VIEW, v->index);
    03333             }
    03334           }
    03335
    03336           /* Check if it's a red signal and that force proceed is not clicked. */
    03337           if ((red_signals & chosen_track) && v->force_proceed == 0) {
    03338             /* In front of a red signal */
    03339             Trackdir i = FindFirstTrackdir(trackdirbits);
    03340
    03341             /* Don't handle stuck trains here. */
    03342             if (HasBit(v->flags, VRF_TRAIN_STUCK)) return;
    03343
    03344             if (!HasSignalOnTrackdir(gp.new_tile, ReverseTrackdir(i))) {
    03345               v->cur_speed = 0;
    03346               v->subspeed = 0;
    03347               v->progress = 255 - 100;
    03348               if (_settings_game.pf.wait_oneway_signal == 255 || ++v->wait_counter < _settings_game.pf.wait_oneway_signal * 20) return;
    03349             } else if (HasSignalOnTrackdir(gp.new_tile, i)) {
    03350               v->cur_speed = 0;
    03351               v->subspeed = 0;
    03352               v->progress = 255 - 10;
    03353               if (_settings_game.pf.wait_twoway_signal == 255 || ++v->wait_counter < _settings_game.pf.wait_twoway_signal * 73) {
    03354                 DiagDirection exitdir = TrackdirToExitdir(i);
    03355                 TileIndex o_tile = TileAddByDiagDir(gp.new_tile, exitdir);
    03356
    03357                 exitdir = ReverseDiagDir(exitdir);
    03358
    03359                 /* check if a train is waiting on the other side */
    03360                 if (!HasVehicleOnPos(o_tile, &exitdir, &CheckTrainAtSignal)) return;
    03361               }
    03362             }
    03363
    03364             /* If we would reverse but are currently in a PBS block and
    03365              * reversing of stuck trains is disabled, don't reverse. */
    03366             if (_settings_game.pf.wait_for_pbs_path == 255 && UpdateSignalsOnSegment(v->tile, enterdir, v->owner) == SIGSEG_PBS) {
    03367               v->wait_counter = 0;
    03368               return;
    03369             }
    03370             goto reverse_train_direction;
    03371           } else {
    03372             TryReserveRailTrack(gp.new_tile, TrackBitsToTrack(chosen_track));
    03373           }
    03374         } else {
    03375           /* The wagon is active, simply follow the prev vehicle. */
    03376           if (prev->tile == gp.new_tile) {
    03377             /* Choose the same track as prev */
    03378             if (prev->track == TRACK_BIT_WORMHOLE) {
    03379               /* Vehicles entering tunnels enter the wormhole earlier than for bridges.
    03380                * However, just choose the track into the wormhole. */
    03381               assert(IsTunnel(prev->tile));
    03382               chosen_track = bits;
    03383             } else {
    03384               chosen_track = prev->track;
    03385             }
    03386           } else {
    03387             /* Choose the track that leads to the tile where prev is.
    03388              * This case is active if 'prev' is already on the second next tile, when 'v' just enters the next tile.
    03389              * I.e. when the tile between them has only space for a single vehicle like
    03390              *  1) horizontal/vertical track tiles and
    03391              *  2) some orientations of tunnelentries, where the vehicle is already inside the wormhole at 8/16 from the tileedge.
    03392              *     Is also the train just reversing, the wagon inside the tunnel is 'on' the tile of the opposite tunnelentry.
    03393              */
    03394             static const TrackBits _connecting_track[DIAGDIR_END][DIAGDIR_END] = {
    03395               {TRACK_BIT_X,     TRACK_BIT_LOWER, TRACK_BIT_NONE,  TRACK_BIT_LEFT },
    03396               {TRACK_BIT_UPPER, TRACK_BIT_Y,     TRACK_BIT_LEFT,  TRACK_BIT_NONE },
    03397               {TRACK_BIT_NONE,  TRACK_BIT_RIGHT, TRACK_BIT_X,     TRACK_BIT_UPPER},
    03398               {TRACK_BIT_RIGHT, TRACK_BIT_NONE,  TRACK_BIT_LOWER, TRACK_BIT_Y    }
    03399             };
    03400             DiagDirection exitdir = DiagdirBetweenTiles(gp.new_tile, prev->tile);
    03401             assert(IsValidDiagDirection(exitdir));
    03402             chosen_track = _connecting_track[enterdir][exitdir];
    03403           }
    03404           chosen_track &= bits;
    03405         }
    03406
    03407         /* Make sure chosen track is a valid track */
    03408         assert(
    03409             chosen_track == TRACK_BIT_X     || chosen_track == TRACK_BIT_Y ||
    03410             chosen_track == TRACK_BIT_UPPER || chosen_track == TRACK_BIT_LOWER ||
    03411             chosen_track == TRACK_BIT_LEFT  || chosen_track == TRACK_BIT_RIGHT);
    03412
    03413         /* Update XY to reflect the entrance to the new tile, and select the direction to use */
    03414         const byte *b = _initial_tile_subcoord[FIND_FIRST_BIT(chosen_track)][enterdir];
    03415         gp.x = (gp.x & ~0xF) | b[0];
    03416         gp.y = (gp.y & ~0xF) | b[1];
    03417         Direction chosen_dir = (Direction)b[2];
    03418
    03419         /* Call the landscape function and tell it that the vehicle entered the tile */
    03420         uint32 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
    03421         if (HasBit(r, VETS_CANNOT_ENTER)) {
    03422           goto invalid_rail;
    03423         }
    03424
    03425         if (!HasBit(r, VETS_ENTERED_WORMHOLE)) {
    03426           Track track = FindFirstTrack(chosen_track);
    03427           Trackdir tdir = TrackDirectionToTrackdir(track, chosen_dir);
    03428           if (v->IsFrontEngine() && HasPbsSignalOnTrackdir(gp.new_tile, tdir)) {
    03429             SetSignalStateByTrackdir(gp.new_tile, tdir, SIGNAL_STATE_RED);
    03430             MarkTileDirtyByTile(gp.new_tile);
    03431           }
    03432
    03433           /* Clear any track reservation when the last vehicle leaves the tile */
    03434           if (v->Next() == NULL) ClearPathReservation(v, v->tile, v->GetVehicleTrackdir());
    03435
    03436           v->tile = gp.new_tile;
    03437
    03438           if (GetTileRailType(gp.new_tile) != GetTileRailType(gp.old_tile)) {
    03439             v->First()->PowerChanged();
    03440           }
    03441
    03442           v->track = chosen_track;
    03443           assert(v->track);
    03444         }
    03445
    03446         /* We need to update signal status, but after the vehicle position hash
    03447          * has been updated by AfterSetTrainPos() */
    03448         update_signals_crossing = true;
    03449
    03450         if (chosen_dir != v->direction) {
    03451           if (prev == NULL && _settings_game.vehicle.train_acceleration_model == TAM_ORIGINAL) {
    03452             const RailtypeSlowdownParams *rsp = &_railtype_slowdown[v->railtype];
    03453             DirDiff diff = DirDifference(v->direction, chosen_dir);
    03454             v->cur_speed -= (diff == DIRDIFF_45RIGHT || diff == DIRDIFF_45LEFT ? rsp->small_turn : rsp->large_turn) * v->cur_speed >> 8;
    03455           }
    03456           direction_changed = true;
    03457           v->direction = chosen_dir;
    03458         }
    03459
    03460         if (v->IsFrontEngine()) {
    03461           v->wait_counter = 0;
    03462
    03463           /* If we are approching a crossing that is reserved, play the sound now. */
    03464           TileIndex crossing = TrainApproachingCrossingTile(v);
    03465           if (crossing != INVALID_TILE && HasCrossingReservation(crossing)) SndPlayTileFx(SND_0E_LEVEL_CROSSING, crossing);
    03466
    03467           /* Always try to extend the reservation when entering a tile. */
    03468           CheckNextTrainTile(v);
    03469         }
    03470
    03471         if (HasBit(r, VETS_ENTERED_STATION)) {
    03472           /* The new position is the location where we want to stop */
    03473           TrainEnterStation(v, r >> VETS_STATION_ID_OFFSET);
    03474         }
    03475       }
    03476     } else {
    03477       /* In a tunnel or on a bridge
    03478        * - for tunnels, only the part when the vehicle is not visible (part of enter/exit tile too)
    03479        * - for bridges, only the middle part - without the bridge heads */
    03480       if (!(v->vehstatus & VS_HIDDEN)) {
    03481         v->cur_speed =
    03482           min(v->cur_speed, GetBridgeSpec(GetBridgeType(v->tile))->speed);
    03483       }
    03484
    03485       if (IsTileType(gp.new_tile, MP_TUNNELBRIDGE) && HasBit(VehicleEnterTile(v, gp.new_tile, gp.x, gp.y), VETS_ENTERED_WORMHOLE)) {
    03486         /* Perform look-ahead on tunnel exit. */
    03487         if (v->IsFrontEngine()) {
    03488           TryReserveRailTrack(gp.new_tile, DiagDirToDiagTrack(GetTunnelBridgeDirection(gp.new_tile)));
    03489           CheckNextTrainTile(v);
    03490         }
    03491       } else {
    03492         v->x_pos = gp.x;
    03493         v->y_pos = gp.y;
    03494         VehicleMove(v, !(v->vehstatus & VS_HIDDEN));
    03495         continue;
    03496       }
    03497     }
    03498
    03499     /* update image of train, as well as delta XY */
    03500     v->UpdateDeltaXY(v->direction);
    03501
    03502     v->x_pos = gp.x;
    03503     v->y_pos = gp.y;
    03504
    03505     /* update the Z position of the vehicle */
    03506     byte old_z = AfterSetTrainPos(v, (gp.new_tile != gp.old_tile));
    03507
    03508     if (prev == NULL) {
    03509       /* This is the first vehicle in the train */
    03510       AffectSpeedByZChange(v, old_z);
    03511     }
    03512
    03513     if (update_signals_crossing) {
    03514       if (v->IsFrontEngine()) {
    03515         if (TrainMovedChangeSignals(gp.new_tile, enterdir)) {
    03516           /* We are entering a block with PBS signals right now, but
    03517            * not through a PBS signal. This means we don't have a
    03518            * reservation right now. As a conventional signal will only
    03519            * ever be green if no other train is in the block, getting
    03520            * a path should always be possible. If the player built
    03521            * such a strange network that it is not possible, the train
    03522            * will be marked as stuck and the player has to deal with
    03523            * the problem. */
    03524           if ((!HasReservedTracks(gp.new_tile, v->track) &&
    03525               !TryReserveRailTrack(gp.new_tile, FindFirstTrack(v->track))) ||
    03526               !TryPathReserve(v)) {
    03527             MarkTrainAsStuck(v);
    03528           }
    03529         }
    03530       }
    03531
    03532       /* Signals can only change when the first
    03533        * (above) or the last vehicle moves. */
    03534       if (v->Next() == NULL) {
    03535         TrainMovedChangeSignals(gp.old_tile, ReverseDiagDir(enterdir));
    03536         if (IsLevelCrossingTile(gp.old_tile)) UpdateLevelCrossing(gp.old_tile);
    03537       }
    03538     }
    03539
    03540     /* Do not check on every tick to save some computing time. */
    03541     if (v->IsFrontEngine() && v->tick_counter % _settings_game.pf.path_backoff_interval == 0) CheckNextTrainTile(v);
    03542   }
    03543
    03544   if (direction_changed) first->tcache.cached_max_curve_speed = first->GetCurveSpeedLimit();
    03545
    03546   return;
    03547
    03548 invalid_rail:
    03549   /* We've reached end of line?? */
    03550   if (prev != NULL) error("Disconnecting train");
    03551
    03552 reverse_train_direction:
    03553   v->wait_counter = 0;
    03554   v->cur_speed = 0;
    03555   v->subspeed = 0;
    03556   ReverseTrainDirection(v);
    03557 }
    03558
    03564 static Vehicle *CollectTrackbitsFromCrashedVehiclesEnum(Vehicle *v, void *data)
    03565 {
    03566   TrackBits *trackbits = (TrackBits *)data;
    03567
    03568   if (v->type == VEH_TRAIN && (v->vehstatus & VS_CRASHED) != 0) {
    03569     if (Train::From(v)->track == TRACK_BIT_WORMHOLE) {
    03570       /* Vehicle is inside a wormhole, v->track contains no useful value then. */
    03571       *trackbits |= DiagDirToDiagTrackBits(GetTunnelBridgeDirection(v->tile));
    03572     } else {
    03573       *trackbits |= Train::From(v)->track;
    03574     }
    03575   }
    03576
    03577   return NULL;
    03578 }
    03579
    03587 static void DeleteLastWagon(Train *v)
    03588 {
    03589   Train *first = v->First();
    03590
    03591   /* Go to the last wagon and delete the link pointing there
    03592    * *u is then the one-before-last wagon, and *v the last
    03593    * one which will physicially be removed */
    03594   Train *u = v;
    03595   for (; v->Next() != NULL; v = v->Next()) u = v;
    03596   u->SetNext(NULL);
    03597
    03598   if (first != v) {
    03599     /* Recalculate cached train properties */
    03600     first->ConsistChanged(false);
    03601     /* Update the depot window if the first vehicle is in depot -
    03602      * if v == first, then it is updated in PreDestructor() */
    03603     if (first->track == TRACK_BIT_DEPOT) {
    03604       SetWindowDirty(WC_VEHICLE_DEPOT, first->tile);
    03605     }
    03606   }
    03607
    03608   /* 'v' shouldn't be accessed after it has been deleted */
    03609   TrackBits trackbits = v->track;
    03610   TileIndex tile = v->tile;
    03611   Owner owner = v->owner;
    03612
    03613   delete v;
    03614   v = NULL; // make sure nobody will try to read 'v' anymore
    03615
    03616   if (trackbits == TRACK_BIT_WORMHOLE) {
    03617     /* Vehicle is inside a wormhole, v->track contains no useful value then. */
    03618     trackbits = DiagDirToDiagTrackBits(GetTunnelBridgeDirection(tile));
    03619   }
    03620
    03621   Track track = TrackBitsToTrack(trackbits);
    03622   if (HasReservedTracks(tile, trackbits)) {
    03623     UnreserveRailTrack(tile, track);
    03624
    03625     /* If there are still crashed vehicles on the tile, give the track reservation to them */
    03626     TrackBits remaining_trackbits = TRACK_BIT_NONE;
    03627     FindVehicleOnPos(tile, &remaining_trackbits, CollectTrackbitsFromCrashedVehiclesEnum);
    03628
    03629     /* It is important that these two are the first in the loop, as reservation cannot deal with every trackbit combination */
    03630     assert(TRACK_BEGIN == TRACK_X && TRACK_Y == TRACK_BEGIN + 1);
    03631     for (Track t = TRACK_BEGIN; t < TRACK_END; t++) {
    03632       if (HasBit(remaining_trackbits, t)) {
    03633         TryReserveRailTrack(tile, t);
    03634       }
    03635     }
    03636   }
    03637
    03638   /* check if the wagon was on a road/rail-crossing */
    03639   if (IsLevelCrossingTile(tile)) UpdateLevelCrossing(tile);
    03640
    03641   /* Update signals */
    03642   if (IsTileType(tile, MP_TUNNELBRIDGE) || IsRailDepotTile(tile)) {
    03643     UpdateSignalsOnSegment(tile, INVALID_DIAGDIR, owner);
    03644   } else {
    03645     SetSignalsOnBothDir(tile, track, owner);
    03646   }
    03647 }
    03648
    03649 static void ChangeTrainDirRandomly(Train *v)
    03650 {
    03651   static const DirDiff delta[] = {
    03652     DIRDIFF_45LEFT, DIRDIFF_SAME, DIRDIFF_SAME, DIRDIFF_45RIGHT
    03653   };
    03654
    03655   do {
    03656     /* We don't need to twist around vehicles if they're not visible */
    03657     if (!(v->vehstatus & VS_HIDDEN)) {
    03658       v->direction = ChangeDir(v->direction, delta[GB(Random(), 0, 2)]);
    03659       v->UpdateDeltaXY(v->direction);
    03660       v->cur_image = v->GetImage(v->direction);
    03661       /* Refrain from updating the z position of the vehicle when on
    03662        * a bridge, because AfterSetTrainPos will put the vehicle under
    03663        * the bridge in that case */
    03664       if (v->track != TRACK_BIT_WORMHOLE) AfterSetTrainPos(v, false);
    03665     }
    03666   } while ((v = v->Next()) != NULL);
    03667 }
    03668
    03669 static bool HandleCrashedTrain(Train *v)
    03670 {
    03671   int state = ++v->crash_anim_pos;
    03672
    03673   if (state == 4 && !(v->vehstatus & VS_HIDDEN)) {
    03674     CreateEffectVehicleRel(v, 4, 4, 8, EV_EXPLOSION_LARGE);
    03675   }
    03676
    03677   uint32 r;
    03678   if (state <= 200 && Chance16R(1, 7, r)) {
    03679     int index = (r * 10 >> 16);
    03680
    03681     Vehicle *u = v;
    03682     do {
    03683       if (--index < 0) {
    03684         r = Random();
    03685
    03686         CreateEffectVehicleRel(u,
    03687           GB(r,  8, 3) + 2,
    03688           GB(r, 16, 3) + 2,
    03689           GB(r,  0, 3) + 5,
    03690           EV_EXPLOSION_SMALL);
    03691         break;
    03692       }
    03693     } while ((u = u->Next()) != NULL);
    03694   }
    03695
    03696   if (state <= 240 && !(v->tick_counter & 3)) ChangeTrainDirRandomly(v);
    03697
    03698   if (state >= 4440 && !(v->tick_counter & 0x1F)) {
    03699     bool ret = v->Next() != NULL;
    03700     DeleteLastWagon(v);
    03701     return ret;
    03702   }
    03703
    03704   return true;
    03705 }
    03706
    03707 static void HandleBrokenTrain(Train *v)
    03708 {
    03709   if (v->breakdown_ctr != 1) {
    03710     v->breakdown_ctr = 1;
    03711     v->cur_speed = 0;
    03712
    03713     if (v->breakdowns_since_last_service != 255)
    03714       v->breakdowns_since_last_service++;
    03715
    03716     v->MarkDirty();
    03717     SetWindowDirty(WC_VEHICLE_VIEW, v->index);
    03718     SetWindowDirty(WC_VEHICLE_DETAILS, v->index);
    03719
    03720     if (!PlayVehicleSound(v, VSE_BREAKDOWN)) {
    03721       SndPlayVehicleFx((_settings_game.game_creation.landscape != LT_TOYLAND) ?
    03722         SND_10_TRAIN_BREAKDOWN : SND_3A_COMEDY_BREAKDOWN_2, v);
    03723     }
    03724
    03725     if (!(v->vehstatus & VS_HIDDEN)) {
    03726       EffectVehicle *u = CreateEffectVehicleRel(v, 4, 4, 5, EV_BREAKDOWN_SMOKE);
    03727       if (u != NULL) u->animation_state = v->breakdown_delay * 2;
    03728     }
    03729   }
    03730
    03731   if (!(v->tick_counter & 3)) {
    03732     if (!--v->breakdown_delay) {
    03733       v->breakdown_ctr = 0;
    03734       v->MarkDirty();
    03735       SetWindowDirty(WC_VEHICLE_VIEW, v->index);
    03736     }
    03737   }
    03738 }
    03739
    03741 static const uint16 _breakdown_speeds[16] = {
    03742   225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, 15
    03743 };
    03744
    03745
    03753 static bool TrainApproachingLineEnd(Train *v, bool signal)
    03754 {
    03755   /* Calc position within the current tile */
    03756   uint x = v->x_pos & 0xF;
    03757   uint y = v->y_pos & 0xF;
    03758
    03759   /* for diagonal directions, 'x' will be 0..15 -
    03760    * for other directions, it will be 1, 3, 5, ..., 15 */
    03761   switch (v->direction) {
    03762     case DIR_N : x = ~x + ~y + 25; break;
    03763     case DIR_NW: x = y;            // FALLTHROUGH
    03764     case DIR_NE: x = ~x + 16;      break;
    03765     case DIR_E : x = ~x + y + 9;   break;
    03766     case DIR_SE: x = y;            break;
    03767     case DIR_S : x = x + y - 7;    break;
    03768     case DIR_W : x = ~y + x + 9;   break;
    03769     default: break;
    03770   }
    03771
    03772   /* do not reverse when approaching red signal */
    03773   if (!signal && x + (v->tcache.cached_veh_length + 1) / 2 >= TILE_SIZE) {
    03774     /* we are too near the tile end, reverse now */
    03775     v->cur_speed = 0;
    03776     ReverseTrainDirection(v);
    03777     return false;
    03778   }
    03779
    03780   /* slow down */
    03781   v->vehstatus |= VS_TRAIN_SLOWING;
    03782   uint16 break_speed = _breakdown_speeds[x & 0xF];
    03783   if (break_speed < v->cur_speed) v->cur_speed = break_speed;
    03784
    03785   return true;
    03786 }
    03787
    03788
    03794 static bool TrainCanLeaveTile(const Train *v)
    03795 {
    03796   /* Exit if inside a tunnel/bridge or a depot */
    03797   if (v->track == TRACK_BIT_WORMHOLE || v->track == TRACK_BIT_DEPOT) return false;
    03798
    03799   TileIndex tile = v->tile;
    03800
    03801   /* entering a tunnel/bridge? */
    03802   if (IsTileType(tile, MP_TUNNELBRIDGE)) {
    03803     DiagDirection dir = GetTunnelBridgeDirection(tile);
    03804     if (DiagDirToDir(dir) == v->direction) return false;
    03805   }
    03806
    03807   /* entering a depot? */
    03808   if (IsRailDepotTile(tile)) {
    03809     DiagDirection dir = ReverseDiagDir(GetRailDepotDirection(tile));
    03810     if (DiagDirToDir(dir) == v->direction) return false;
    03811   }
    03812
    03813   return true;
    03814 }
    03815
    03816
    03824 static TileIndex TrainApproachingCrossingTile(const Train *v)
    03825 {
    03826   assert(v->IsFrontEngine());
    03827   assert(!(v->vehstatus & VS_CRASHED));
    03828
    03829   if (!TrainCanLeaveTile(v)) return INVALID_TILE;
    03830
    03831   DiagDirection dir = TrainExitDir(v->direction, v->track);
    03832   TileIndex tile = v->tile + TileOffsByDiagDir(dir);
    03833
    03834   /* not a crossing || wrong axis || unusable rail (wrong type or owner) */
    03835   if (!IsLevelCrossingTile(tile) || DiagDirToAxis(dir) == GetCrossingRoadAxis(tile) ||
    03836       !CheckCompatibleRail(v, tile)) {
    03837     return INVALID_TILE;
    03838   }
    03839
    03840   return tile;
    03841 }
    03842
    03843
    03850 static bool TrainCheckIfLineEnds(Train *v)
    03851 {
    03852   /* First, handle broken down train */
    03853
    03854   int t = v->breakdown_ctr;
    03855   if (t > 1) {
    03856     v->vehstatus |= VS_TRAIN_SLOWING;
    03857
    03858     uint16 break_speed = _breakdown_speeds[GB(~t, 4, 4)];
    03859     if (break_speed < v->cur_speed) v->cur_speed = break_speed;
    03860   } else {
    03861     v->vehstatus &= ~VS_TRAIN_SLOWING;
    03862   }
    03863
    03864   if (!TrainCanLeaveTile(v)) return true;
    03865
    03866   /* Determine the non-diagonal direction in which we will exit this tile */
    03867   DiagDirection dir = TrainExitDir(v->direction, v->track);
    03868   /* Calculate next tile */
    03869   TileIndex tile = v->tile + TileOffsByDiagDir(dir);
    03870
    03871   /* Determine the track status on the next tile */
    03872   TrackStatus ts = GetTileTrackStatus(tile, TRANSPORT_RAIL, 0, ReverseDiagDir(dir));
    03873   TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(dir);
    03874
    03875   TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
    03876   TrackdirBits red_signals = TrackStatusToRedSignals(ts) & reachable_trackdirs;
    03877
    03878   /* We are sure the train is not entering a depot, it is detected above */
    03879
    03880   /* mask unreachable track bits if we are forbidden to do 90deg turns */
    03881   TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
    03882   if (_settings_game.pf.forbid_90_deg) {
    03883     bits &= ~TrackCrossesTracks(FindFirstTrack(v->track));
    03884   }
    03885
    03886   /* no suitable trackbits at all || unusable rail (wrong type or owner) */
    03887   if (bits == TRACK_BIT_NONE || !CheckCompatibleRail(v, tile)) {
    03888     return TrainApproachingLineEnd(v, false);
    03889   }
    03890
    03891   /* approaching red signal */
    03892   if ((trackdirbits & red_signals) != 0) return TrainApproachingLineEnd(v, true);
    03893
    03894   /* approaching a rail/road crossing? then make it red */
    03895   if (IsLevelCrossingTile(tile)) MaybeBarCrossingWithSound(tile);
    03896
    03897   return true;
    03898 }
    03899
    03900
    03901 static bool TrainLocoHandler(Train *v, bool mode)
    03902 {
    03903   /* train has crashed? */
    03904   if (v->vehstatus & VS_CRASHED) {
    03905     return mode ? true : HandleCrashedTrain(v); // 'this' can be deleted here
    03906   }
    03907
    03908   if (v->force_proceed != 0) {
    03909     ClrBit(v->flags, VRF_TRAIN_STUCK);
    03910     SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
    03911   }
    03912
    03913   /* train is broken down? */
    03914   if (v->breakdown_ctr != 0) {
    03915     if (v->breakdown_ctr <= 2) {
    03916       HandleBrokenTrain(v);
    03917       return true;
    03918     }
    03919     if (!v->current_order.IsType(OT_LOADING)) v->breakdown_ctr--;
    03920   }
    03921
    03922   if (HasBit(v->flags, VRF_REVERSING) && v->cur_speed == 0) {
    03923     ReverseTrainDirection(v);
    03924   }
    03925
    03926   /* exit if train is stopped */
    03927   if ((v->vehstatus & VS_STOPPED) && v->cur_speed == 0) return true;
    03928
    03929   bool valid_order = !v->current_order.IsType(OT_NOTHING) && v->current_order.GetType() != OT_CONDITIONAL;
    03930   if (ProcessOrders(v) && CheckReverseTrain(v)) {
    03931     v->wait_counter = 0;
    03932     v->cur_speed = 0;
    03933     v->subspeed = 0;
    03934     ReverseTrainDirection(v);
    03935     return true;
    03936   }
    03937
    03938   v->HandleLoading(mode);
    03939
    03940   if (v->current_order.IsType(OT_LOADING)) return true;
    03941
    03942   if (CheckTrainStayInDepot(v)) return true;
    03943
    03944   if (!mode) HandleLocomotiveSmokeCloud(v);
    03945
    03946   /* We had no order but have an order now, do look ahead. */
    03947   if (!valid_order && !v->current_order.IsType(OT_NOTHING)) {
    03948     CheckNextTrainTile(v);
    03949   }
    03950
    03951   /* Handle stuck trains. */
    03952   if (!mode && HasBit(v->flags, VRF_TRAIN_STUCK)) {
    03953     ++v->wait_counter;
    03954
    03955     /* Should we try reversing this tick if still stuck? */
    03956     bool turn_around = v->wait_counter % (_settings_game.pf.wait_for_pbs_path * DAY_TICKS) == 0 && _settings_game.pf.wait_for_pbs_path < 255;
    03957
    03958     if (!turn_around && v->wait_counter % _settings_game.pf.path_backoff_interval != 0 && v->force_proceed == 0) return true;
    03959     if (!TryPathReserve(v)) {
    03960       /* Still stuck. */
    03961       if (turn_around) ReverseTrainDirection(v);
    03962
    03963       if (HasBit(v->flags, VRF_TRAIN_STUCK) && v->wait_counter > 2 * _settings_game.pf.wait_for_pbs_path * DAY_TICKS) {
    03964         /* Show message to player. */
    03965         if (_settings_client.gui.lost_train_warn && v->owner == _local_company) {
    03966           SetDParam(0, v->index);
    03967           AddVehicleNewsItem(
    03968             STR_NEWS_TRAIN_IS_STUCK,
    03969             NS_ADVICE,
    03970             v->index
    03971           );
    03972         }
    03973         v->wait_counter = 0;
    03974       }
    03975       /* Exit if force proceed not pressed, else reset stuck flag anyway. */
    03976       if (v->force_proceed == 0) return true;
    03977       ClrBit(v->flags, VRF_TRAIN_STUCK);
    03978       v->wait_counter = 0;
    03979       SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
    03980     }
    03981   }
    03982
    03983   if (v->current_order.IsType(OT_LEAVESTATION)) {
    03984     v->current_order.Free();
    03985     SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
    03986     return true;
    03987   }
    03988
    03989   int j = v->UpdateSpeed();
    03990
    03991   /* we need to invalidate the widget if we are stopping from 'Stopping 0 km/h' to 'Stopped' */
    03992   if (v->cur_speed == 0 && v->tcache.last_speed == 0 && (v->vehstatus & VS_STOPPED)) {
    03993     /* If we manually stopped, we're not force-proceeding anymore. */
    03994     v->force_proceed = 0;
    03995     SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
    03996   }
    03997
    03998   int adv_spd = (v->direction & 1) ? 192 : 256;
    03999   if (j < adv_spd) {
    04000     /* if the vehicle has speed 0, update the last_speed field. */
    04001     if (v->cur_speed == 0) SetLastSpeed(v, v->cur_speed);
    04002   } else {
    04003     TrainCheckIfLineEnds(v);
    04004     /* Loop until the train has finished moving. */
    04005     for (;;) {
    04006       j -= adv_spd;
    04007       TrainController(v, NULL);
    04008       /* Don't continue to move if the train crashed. */
    04009       if (CheckTrainCollision(v)) break;
    04010       /* 192 spd used for going straight, 256 for going diagonally. */
    04011       adv_spd = (v->direction & 1) ? 192 : 256;
    04012
    04013       /* No more moving this tick */
    04014       if (j < adv_spd || v->cur_speed == 0) break;
    04015
    04016       OrderType order_type = v->current_order.GetType();
    04017       /* Do not skip waypoints (incl. 'via' stations) when passing through at full speed. */
    04018       if ((order_type == OT_GOTO_WAYPOINT || order_type == OT_GOTO_STATION) &&
    04019             (v->current_order.GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION) &&
    04020             IsTileType(v->tile, MP_STATION) &&
    04021             v->current_order.GetDestination() == GetStationIndex(v->tile)) {
    04022         ProcessOrders(v);
    04023       }
    04024     }
    04025     SetLastSpeed(v, v->cur_speed);
    04026   }
    04027
    04028   for (Train *u = v; u != NULL; u = u->Next()) {
    04029     if ((u->vehstatus & VS_HIDDEN) != 0) continue;
    04030
    04031     u->UpdateViewport(false, false);
    04032   }
    04033
    04034   if (v->progress == 0) v->progress = j; // Save unused spd for next time, if TrainController didn't set progress
    04035
    04036   return true;
    04037 }
    04038
    04039
    04040
    04041 Money Train::GetRunningCost() const
    04042 {
    04043   Money cost = 0;
    04044   const Train *v = this;
    04045
    04046   do {
    04047     const Engine *e = Engine::Get(v->engine_type);
    04048     if (e->u.rail.running_cost_class == INVALID_PRICE) continue;
    04049
    04050     uint cost_factor = GetVehicleProperty(v, PROP_TRAIN_RUNNING_COST_FACTOR, e->u.rail.running_cost);
    04051     if (cost_factor == 0) continue;
    04052
    04053     /* Halve running cost for multiheaded parts */
    04054     if (v->IsMultiheaded()) cost_factor /= 2;
    04055
    04056     cost += GetPrice(e->u.rail.running_cost_class, cost_factor, e->grffile);
    04057   } while ((v = v->GetNextVehicle()) != NULL);
    04058
    04059   return cost;
    04060 }
    04061
    04062
    04063 bool Train::Tick()
    04064 {
    04065   this->tick_counter++;
    04066
    04067   if (this->IsFrontEngine()) {
    04068     if (!(this->vehstatus & VS_STOPPED)) this->running_ticks++;
    04069
    04070     this->current_order_time++;
    04071
    04072     if (!TrainLocoHandler(this, false)) return false;
    04073
    04074     return TrainLocoHandler(this, true);
    04075   } else if (this->IsFreeWagon() && (this->vehstatus & VS_CRASHED)) {
    04076     /* Delete flooded standalone wagon chain */
    04077     if (++this->crash_anim_pos >= 4400) {
    04078       delete this;
    04079       return false;
    04080     }
    04081   }
    04082
    04083   return true;
    04084 }
    04085
    04086 static void CheckIfTrainNeedsService(Train *v)
    04087 {
    04088   if (Company::Get(v->owner)->settings.vehicle.servint_trains == 0 || !v->NeedsAutomaticServicing()) return;
    04089   if (v->IsInDepot()) {
    04090     VehicleServiceInDepot(v);
    04091     return;
    04092   }
    04093
    04094   uint max_penalty;
    04095   switch (_settings_game.pf.pathfinder_for_trains) {
    04096     case VPF_NPF:  max_penalty = _settings_game.pf.npf.maximum_go_to_depot_penalty;  break;
    04097     case VPF_YAPF: max_penalty = _settings_game.pf.yapf.maximum_go_to_depot_penalty; break;
    04098     default: NOT_REACHED();
    04099   }
    04100
    04101   FindDepotData tfdd = FindClosestTrainDepot(v, max_penalty);
    04102   /* Only go to the depot if it is not too far out of our way. */
    04103   if (tfdd.best_length == UINT_MAX || tfdd.best_length > max_penalty) {
    04104     if (v->current_order.IsType(OT_GOTO_DEPOT)) {
    04105       /* If we were already heading for a depot but it has
    04106        * suddenly moved farther away, we continue our normal
    04107        * schedule? */
    04108       v->current_order.MakeDummy();
    04109       SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
    04110     }
    04111     return;
    04112   }
    04113
    04114   DepotID depot = GetDepotIndex(tfdd.tile);
    04115
    04116   if (v->current_order.IsType(OT_GOTO_DEPOT) &&
    04117       v->current_order.GetDestination() != depot &&
    04118       !Chance16(3, 16)) {
    04119     return;
    04120   }
    04121
    04122   v->current_order.MakeGoToDepot(depot, ODTFB_SERVICE);
    04123   v->dest_tile = tfdd.tile;
    04124   SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
    04125 }
    04126
    04127 void Train::OnNewDay()
    04128 {
    04129   if ((++this->day_counter & 7) == 0) DecreaseVehicleValue(this);
    04130
    04131   if (this->IsFrontEngine()) {
    04132     CheckVehicleBreakdown(this);
    04133     AgeVehicle(this);
    04134
    04135     CheckIfTrainNeedsService(this);
    04136
    04137     CheckOrders(this);
    04138
    04139     /* update destination */
    04140     if (this->current_order.IsType(OT_GOTO_STATION)) {
    04141       TileIndex tile = Station::Get(this->current_order.GetDestination())->train_station.tile;
    04142       if (tile != INVALID_TILE) this->dest_tile = tile;
    04143     }
    04144
    04145     if (this->running_ticks != 0) {
    04146       /* running costs */
    04147       CommandCost cost(EXPENSES_TRAIN_RUN, this->GetRunningCost() * this->running_ticks / (DAYS_IN_YEAR  * DAY_TICKS));
    04148
    04149       this->profit_this_year -= cost.GetCost();
    04150       this->running_ticks = 0;
    04151
    04152       SubtractMoneyFromCompanyFract(this->owner, cost);
    04153
    04154       SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
    04155       SetWindowClassesDirty(WC_TRAINS_LIST);
    04156     }
    04157   } else if (this->IsEngine()) {
    04158     /* Also age engines that aren't front engines */
    04159     AgeVehicle(this);
    04160   }
    04161 }
    04162
    04163 Trackdir Train::GetVehicleTrackdir() const
    04164 {
    04165   if (this->vehstatus & VS_CRASHED) return INVALID_TRACKDIR;
    04166
    04167   if (this->track == TRACK_BIT_DEPOT) {
    04168     /* We'll assume the train is facing outwards */
    04169     return DiagDirToDiagTrackdir(GetRailDepotDirection(this->tile)); // Train in depot
    04170   }
    04171
    04172   if (this->track == TRACK_BIT_WORMHOLE) {
    04173     /* train in tunnel or on bridge, so just use his direction and assume a diagonal track */
    04174     return DiagDirToDiagTrackdir(DirToDiagDir(this->direction));
    04175   }
    04176
    04177   return TrackDirectionToTrackdir(FindFirstTrack(this->track), this->direction);
    04178 }