train_cmd.cpp

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

Generated on Sun Jan 9 16:02:04 2011 for OpenTTD by  doxygen 1.6.1