# train_cmd.cpp

Go to the documentation of this file.

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