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