train_cmd.cpp

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

Generated on Fri Feb 4 20:53:49 2011 for OpenTTD by  doxygen 1.6.1