# train_cmd.cpp

Go to the documentation of this file.

    00001 /* $Id: train_cmd.cpp 15497 2009-02-16 17:16:58Z smatz $ */
    00002
    00005 #include "stdafx.h"
    00006 #include "gui.h"
    00007 #include "articulated_vehicles.h"
    00008 #include "command_func.h"
    00009 #include "npf.h"
    00010 #include "news_func.h"
    00011 #include "engine_func.h"
    00012 #include "engine_base.h"
    00013 #include "company_func.h"
    00014 #include "depot_base.h"
    00015 #include "vehicle_gui.h"
    00016 #include "train.h"
    00017 #include "newgrf_engine.h"
    00018 #include "newgrf_sound.h"
    00019 #include "newgrf_text.h"
    00020 #include "yapf/follow_track.hpp"
    00021 #include "group.h"
    00022 #include "table/sprites.h"
    00023 #include "strings_func.h"
    00024 #include "functions.h"
    00025 #include "window_func.h"
    00026 #include "vehicle_func.h"
    00027 #include "sound_func.h"
    00028 #include "variables.h"
    00029 #include "autoreplace_gui.h"
    00030 #include "gfx_func.h"
    00031 #include "ai/ai.hpp"
    00032 #include "newgrf_station.h"
    00033 #include "effectvehicle_func.h"
    00034 #include "gamelog.h"
    00035 #include "network/network.h"
    00036
    00037 #include "table/strings.h"
    00038 #include "table/train_cmd.h"
    00039
    00040 static Track ChooseTrainTrack(Vehicle *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool force_res, bool *got_reservation, bool mark_stuck);
    00041 static bool TrainCheckIfLineEnds(Vehicle *v);
    00042 static void TrainController(Vehicle *v, Vehicle *nomove, bool update_image);
    00043 static TileIndex TrainApproachingCrossingTile(const Vehicle *v);
    00044 static void CheckIfTrainNeedsService(Vehicle *v);
    00045 static void CheckNextTrainTile(Vehicle *v);
    00046
    00047 static const byte _vehicle_initial_x_fract[4] = {10, 8, 4,  8};
    00048 static const byte _vehicle_initial_y_fract[4] = { 8, 4, 8, 10};
    00049
    00050
    00058 static inline DiagDirection TrainExitDir(Direction direction, TrackBits track)
    00059 {
    00060   static const TrackBits state_dir_table[DIAGDIR_END] = { TRACK_BIT_RIGHT, TRACK_BIT_LOWER, TRACK_BIT_LEFT, TRACK_BIT_UPPER };
    00061
    00062   DiagDirection diagdir = DirToDiagDir(direction);
    00063
    00064   /* Determine the diagonal direction in which we will exit this tile */
    00065   if (!HasBit(direction, 0) && track != state_dir_table[diagdir]) {
    00066     diagdir = ChangeDiagDir(diagdir, DIAGDIRDIFF_90LEFT);
    00067   }
    00068
    00069   return diagdir;
    00070 }
    00071
    00072
    00077 byte FreightWagonMult(CargoID cargo)
    00078 {
    00079   if (!GetCargo(cargo)->is_freight) return 1;
    00080   return _settings_game.vehicle.freight_trains;
    00081 }
    00082
    00083
    00088 void TrainPowerChanged(Vehicle *v)
    00089 {
    00090   uint32 total_power = 0;
    00091   uint32 max_te = 0;
    00092
    00093   for (const Vehicle *u = v; u != NULL; u = u->Next()) {
    00094     RailType railtype = GetRailType(u->tile);
    00095
    00096     /* Power is not added for articulated parts */
    00097     if (!IsArticulatedPart(u)) {
    00098       bool engine_has_power = HasPowerOnRail(u->u.rail.railtype, railtype);
    00099
    00100       const RailVehicleInfo *rvi_u = RailVehInfo(u->engine_type);
    00101
    00102       if (engine_has_power) {
    00103         uint16 power = GetVehicleProperty(u, 0x0B, rvi_u->power);
    00104         if (power != 0) {
    00105           /* Halve power for multiheaded parts */
    00106           if (IsMultiheaded(u)) power /= 2;
    00107
    00108           total_power += power;
    00109           /* Tractive effort in (tonnes * 1000 * 10 =) N */
    00110           max_te += (u->u.rail.cached_veh_weight * 10000 * GetVehicleProperty(u, 0x1F, rvi_u->tractive_effort)) / 256;
    00111         }
    00112       }
    00113     }
    00114
    00115     if (HasBit(u->u.rail.flags, VRF_POWEREDWAGON) && HasPowerOnRail(v->u.rail.railtype, railtype)) {
    00116       total_power += RailVehInfo(u->u.rail.first_engine)->pow_wag_power;
    00117     }
    00118   }
    00119
    00120   if (v->u.rail.cached_power != total_power || v->u.rail.cached_max_te != max_te) {
    00121     /* If it has no power (no catenary), stop the train */
    00122     if (total_power == 0) v->vehstatus |= VS_STOPPED;
    00123
    00124     v->u.rail.cached_power = total_power;
    00125     v->u.rail.cached_max_te = max_te;
    00126     InvalidateWindow(WC_VEHICLE_DETAILS, v->index);
    00127     InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
    00128   }
    00129 }
    00130
    00131
    00137 static void TrainCargoChanged(Vehicle *v)
    00138 {
    00139   uint32 weight = 0;
    00140
    00141   for (Vehicle *u = v; u != NULL; u = u->Next()) {
    00142     uint32 vweight = GetCargo(u->cargo_type)->weight * u->cargo.Count() * FreightWagonMult(u->cargo_type) / 16;
    00143
    00144     /* Vehicle weight is not added for articulated parts. */
    00145     if (!IsArticulatedPart(u)) {
    00146       /* vehicle weight is the sum of the weight of the vehicle and the weight of its cargo */
    00147       vweight += GetVehicleProperty(u, 0x16, RailVehInfo(u->engine_type)->weight);
    00148     }
    00149
    00150     /* powered wagons have extra weight added */
    00151     if (HasBit(u->u.rail.flags, VRF_POWEREDWAGON)) {
    00152       vweight += RailVehInfo(u->u.rail.first_engine)->pow_wag_weight;
    00153     }
    00154
    00155     /* consist weight is the sum of the weight of all vehicles in the consist */
    00156     weight += vweight;
    00157
    00158     /* store vehicle weight in cache */
    00159     u->u.rail.cached_veh_weight = vweight;
    00160   }
    00161
    00162   /* store consist weight in cache */
    00163   v->u.rail.cached_weight = weight;
    00164
    00165   /* Now update train power (tractive effort is dependent on weight) */
    00166   TrainPowerChanged(v);
    00167 }
    00168
    00169
    00174 static void RailVehicleLengthChanged(const Vehicle *u)
    00175 {
    00176   /* show a warning once for each engine in whole game and once for each GRF after each game load */
    00177   const Engine *engine = GetEngine(u->engine_type);
    00178   uint32 grfid = engine->grffile->grfid;
    00179   GRFConfig *grfconfig = GetGRFConfig(grfid);
    00180   if (GamelogGRFBugReverse(grfid, engine->internal_id) || !HasBit(grfconfig->grf_bugs, GBUG_VEH_LENGTH)) {
    00181     SetBit(grfconfig->grf_bugs, GBUG_VEH_LENGTH);
    00182     SetDParamStr(0, grfconfig->name);
    00183     SetDParam(1, u->engine_type);
    00184     ShowErrorMessage(STR_NEWGRF_BROKEN_VEHICLE_LENGTH, STR_NEWGRF_BROKEN, 0, 0);
    00185
    00186     /* debug output */
    00187     char buffer[512];
    00188
    00189     SetDParamStr(0, grfconfig->name);
    00190     GetString(buffer, STR_NEWGRF_BROKEN, lastof(buffer));
    00191     DEBUG(grf, 0, "%s", buffer + 3);
    00192
    00193     SetDParam(1, u->engine_type);
    00194     GetString(buffer, STR_NEWGRF_BROKEN_VEHICLE_LENGTH, lastof(buffer));
    00195     DEBUG(grf, 0, "%s", buffer + 3);
    00196
    00197     if (!_networking) _pause_game = -1;
    00198   }
    00199 }
    00200
    00202 void CheckTrainsLengths()
    00203 {
    00204   const Vehicle *v;
    00205
    00206   FOR_ALL_VEHICLES(v) {
    00207     if (v->type == VEH_TRAIN && v->First() == v && !(v->vehstatus & VS_CRASHED)) {
    00208       for (const Vehicle *u = v, *w = v->Next(); w != NULL; u = w, w = w->Next()) {
    00209         if (u->u.rail.track != TRACK_BIT_DEPOT) {
    00210           if ((w->u.rail.track != TRACK_BIT_DEPOT &&
    00211               max(abs(u->x_pos - w->x_pos), abs(u->y_pos - w->y_pos)) != u->u.rail.cached_veh_length) ||
    00212               (w->u.rail.track == TRACK_BIT_DEPOT && TicksToLeaveDepot(u) <= 0)) {
    00213             SetDParam(0, v->index);
    00214             SetDParam(1, v->owner);
    00215             ShowErrorMessage(INVALID_STRING_ID, STR_BROKEN_VEHICLE_LENGTH, 0, 0);
    00216
    00217             if (!_networking) _pause_game = -1;
    00218           }
    00219         }
    00220       }
    00221     }
    00222   }
    00223 }
    00224
    00232 void TrainConsistChanged(Vehicle *v, bool same_length)
    00233 {
    00234   uint16 max_speed = UINT16_MAX;
    00235
    00236   assert(v->type == VEH_TRAIN);
    00237   assert(IsFrontEngine(v) || IsFreeWagon(v));
    00238
    00239   const RailVehicleInfo *rvi_v = RailVehInfo(v->engine_type);
    00240   EngineID first_engine = IsFrontEngine(v) ? v->engine_type : INVALID_ENGINE;
    00241   v->u.rail.cached_total_length = 0;
    00242   v->u.rail.compatible_railtypes = RAILTYPES_NONE;
    00243
    00244   bool train_can_tilt = true;
    00245
    00246   for (Vehicle *u = v; u != NULL; u = u->Next()) {
    00247     const RailVehicleInfo *rvi_u = RailVehInfo(u->engine_type);
    00248
    00249     /* Check the v->first cache. */
    00250     assert(u->First() == v);
    00251
    00252     /* update the 'first engine' */
    00253     u->u.rail.first_engine = v == u ? INVALID_ENGINE : first_engine;
    00254     u->u.rail.railtype = rvi_u->railtype;
    00255
    00256     if (IsTrainEngine(u)) first_engine = u->engine_type;
    00257
    00258     /* Set user defined data to its default value */
    00259     u->u.rail.user_def_data = rvi_u->user_def_data;
    00260   }
    00261
    00262   for (Vehicle *u = v; u != NULL; u = u->Next()) {
    00263     /* Update user defined data (must be done before other properties) */
    00264     u->u.rail.user_def_data = GetVehicleProperty(u, 0x25, u->u.rail.user_def_data);
    00265   }
    00266
    00267   for (Vehicle *u = v; u != NULL; u = u->Next()) {
    00268     const RailVehicleInfo *rvi_u = RailVehInfo(u->engine_type);
    00269
    00270     if (!HasBit(EngInfo(u->engine_type)->misc_flags, EF_RAIL_TILTS)) train_can_tilt = false;
    00271
    00272     /* Cache wagon override sprite group. NULL is returned if there is none */
    00273     u->u.rail.cached_override = GetWagonOverrideSpriteSet(u->engine_type, u->cargo_type, u->u.rail.first_engine);
    00274
    00275     /* Reset colour map */
    00276     u->colourmap = PAL_NONE;
    00277
    00278     if (rvi_u->visual_effect != 0) {
    00279       u->u.rail.cached_vis_effect = rvi_u->visual_effect;
    00280     } else {
    00281       if (IsTrainWagon(u) || IsArticulatedPart(u)) {
    00282         /* Wagons and articulated parts have no effect by default */
    00283         u->u.rail.cached_vis_effect = 0x40;
    00284       } else if (rvi_u->engclass == 0) {
    00285         /* Steam is offset by -4 units */
    00286         u->u.rail.cached_vis_effect = 4;
    00287       } else {
    00288         /* Diesel fumes and sparks come from the centre */
    00289         u->u.rail.cached_vis_effect = 8;
    00290       }
    00291     }
    00292
    00293     /* Check powered wagon / visual effect callback */
    00294     if (HasBit(EngInfo(u->engine_type)->callbackmask, CBM_TRAIN_WAGON_POWER)) {
    00295       uint16 callback = GetVehicleCallback(CBID_TRAIN_WAGON_POWER, 0, 0, u->engine_type, u);
    00296
    00297       if (callback != CALLBACK_FAILED) u->u.rail.cached_vis_effect = GB(callback, 0, 8);
    00298     }
    00299
    00300     if (rvi_v->pow_wag_power != 0 && rvi_u->railveh_type == RAILVEH_WAGON &&
    00301       UsesWagonOverride(u) && !HasBit(u->u.rail.cached_vis_effect, 7)) {
    00302       /* wagon is powered */
    00303       SetBit(u->u.rail.flags, VRF_POWEREDWAGON); // cache 'powered' status
    00304     } else {
    00305       ClrBit(u->u.rail.flags, VRF_POWEREDWAGON);
    00306     }
    00307
    00308     if (!IsArticulatedPart(u)) {
    00309       /* Do not count powered wagons for the compatible railtypes, as wagons always
    00310          have railtype normal */
    00311       if (rvi_u->power > 0) {
    00312         v->u.rail.compatible_railtypes |= GetRailTypeInfo(u->u.rail.railtype)->powered_railtypes;
    00313       }
    00314
    00315       /* Some electric engines can be allowed to run on normal rail. It happens to all
    00316        * existing electric engines when elrails are disabled and then re-enabled */
    00317       if (HasBit(u->u.rail.flags, VRF_EL_ENGINE_ALLOWED_NORMAL_RAIL)) {
    00318         u->u.rail.railtype = RAILTYPE_RAIL;
    00319         u->u.rail.compatible_railtypes |= RAILTYPES_RAIL;
    00320       }
    00321
    00322       /* max speed is the minimum of the speed limits of all vehicles in the consist */
    00323       if ((rvi_u->railveh_type != RAILVEH_WAGON || _settings_game.vehicle.wagon_speed_limits) && !UsesWagonOverride(u)) {
    00324         uint16 speed = GetVehicleProperty(u, 0x09, rvi_u->max_speed);
    00325         if (speed != 0) max_speed = min(speed, max_speed);
    00326       }
    00327     }
    00328
    00329     if (u->cargo_type == rvi_u->cargo_type && u->cargo_subtype == 0) {
    00330       /* Set cargo capacity if we've not been refitted */
    00331       u->cargo_cap = GetVehicleProperty(u, 0x14, rvi_u->capacity);
    00332     }
    00333
    00334     /* check the vehicle length (callback) */
    00335     uint16 veh_len = CALLBACK_FAILED;
    00336     if (HasBit(EngInfo(u->engine_type)->callbackmask, CBM_VEHICLE_LENGTH)) {
    00337       veh_len = GetVehicleCallback(CBID_VEHICLE_LENGTH, 0, 0, u->engine_type, u);
    00338     }
    00339     if (veh_len == CALLBACK_FAILED) veh_len = rvi_u->shorten_factor;
    00340     veh_len = 8 - Clamp(veh_len, 0, u->Next() == NULL ? 7 : 5); // the clamp on vehicles not the last in chain is stricter, as too short wagons can break the 'follow next vehicle' code
    00341
    00342     /* verify length hasn't changed */
    00343     if (same_length && veh_len != u->u.rail.cached_veh_length) RailVehicleLengthChanged(u);
    00344
    00345     /* update vehicle length? */
    00346     if (!same_length) u->u.rail.cached_veh_length = veh_len;
    00347
    00348     v->u.rail.cached_total_length += u->u.rail.cached_veh_length;
    00349   }
    00350
    00351   /* store consist weight/max speed in cache */
    00352   v->u.rail.cached_max_speed = max_speed;
    00353   v->u.rail.cached_tilt = train_can_tilt;
    00354
    00355   /* 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) */
    00356   TrainCargoChanged(v);
    00357
    00358   if (IsFrontEngine(v)) {
    00359     UpdateTrainAcceleration(v);
    00360     InvalidateWindow(WC_VEHICLE_DETAILS, v->index);
    00361   }
    00362 }
    00363
    00364 enum AccelType {
    00365   AM_ACCEL,
    00366   AM_BRAKE
    00367 };
    00368
    00370 static int GetTrainAcceleration(Vehicle *v, bool mode)
    00371 {
    00372   static const int absolute_max_speed = UINT16_MAX;
    00373   int max_speed = absolute_max_speed;
    00374   int speed = v->cur_speed * 10 / 16; // km-ish/h -> mp/h
    00375   int curvecount[2] = {0, 0};
    00376
    00377   /*first find the curve speed limit */
    00378   int numcurve = 0;
    00379   int sum = 0;
    00380   int pos = 0;
    00381   int lastpos = -1;
    00382   for (const Vehicle *u = v; u->Next() != NULL; u = u->Next(), pos++) {
    00383     Direction this_dir = u->direction;
    00384     Direction next_dir = u->Next()->direction;
    00385
    00386     DirDiff dirdiff = DirDifference(this_dir, next_dir);
    00387     if (dirdiff == DIRDIFF_SAME) continue;
    00388
    00389     if (dirdiff == DIRDIFF_45LEFT) curvecount[0]++;
    00390     if (dirdiff == DIRDIFF_45RIGHT) curvecount[1]++;
    00391     if (dirdiff == DIRDIFF_45LEFT || dirdiff == DIRDIFF_45RIGHT) {
    00392       if (lastpos != -1) {
    00393         numcurve++;
    00394         sum += pos - lastpos;
    00395         if (pos - lastpos == 1) {
    00396           max_speed = 88;
    00397         }
    00398       }
    00399       lastpos = pos;
    00400     }
    00401
    00402     /*if we have a 90 degree turn, fix the speed limit to 60 */
    00403     if (dirdiff == DIRDIFF_90LEFT || dirdiff == DIRDIFF_90RIGHT) {
    00404       max_speed = 61;
    00405     }
    00406   }
    00407
    00408   if ((curvecount[0] != 0 || curvecount[1] != 0) && max_speed > 88) {
    00409     int total = curvecount[0] + curvecount[1];
    00410
    00411     if (curvecount[0] == 1 && curvecount[1] == 1) {
    00412       max_speed = absolute_max_speed;
    00413     } else if (total > 1) {
    00414       if (numcurve > 0) sum /= numcurve;
    00415       max_speed = 232 - (13 - Clamp(sum, 1, 12)) * (13 - Clamp(sum, 1, 12));
    00416     }
    00417   }
    00418
    00419   if (max_speed != absolute_max_speed) {
    00420     /* Apply the engine's rail type curve speed advantage, if it slowed by curves */
    00421     const RailtypeInfo *rti = GetRailTypeInfo(v->u.rail.railtype);
    00422     max_speed += (max_speed / 2) * rti->curve_speed;
    00423
    00424     if (v->u.rail.cached_tilt) {
    00425       /* Apply max_speed bonus of 20% for a tilting train */
    00426       max_speed += max_speed / 5;
    00427     }
    00428   }
    00429
    00430   if (IsTileType(v->tile, MP_STATION) && IsFrontEngine(v)) {
    00431     if (v->current_order.ShouldStopAtStation(v, GetStationIndex(v->tile))) {
    00432       int station_length = GetStationByTile(v->tile)->GetPlatformLength(v->tile, DirToDiagDir(v->direction));
    00433
    00434       int st_max_speed = 120;
    00435
    00436       int delta_v = v->cur_speed / (station_length + 1);
    00437       if (v->max_speed > (v->cur_speed - delta_v)) {
    00438         st_max_speed = v->cur_speed - (delta_v / 10);
    00439       }
    00440
    00441       st_max_speed = max(st_max_speed, 25 * station_length);
    00442       max_speed = min(max_speed, st_max_speed);
    00443     }
    00444   }
    00445
    00446   int mass = v->u.rail.cached_weight;
    00447   int power = v->u.rail.cached_power * 746;
    00448   max_speed = min(max_speed, v->u.rail.cached_max_speed);
    00449
    00450   int num = 0; //number of vehicles, change this into the number of axles later
    00451   int incl = 0;
    00452   int drag_coeff = 20; //[1e-4]
    00453   for (const Vehicle *u = v; u != NULL; u = u->Next()) {
    00454     num++;
    00455     drag_coeff += 3;
    00456
    00457     if (u->u.rail.track == TRACK_BIT_DEPOT) max_speed = min(max_speed, 61);
    00458
    00459     if (HasBit(u->u.rail.flags, VRF_GOINGUP)) {
    00460       incl += u->u.rail.cached_veh_weight * 60; //3% slope, quite a bit actually
    00461     } else if (HasBit(u->u.rail.flags, VRF_GOINGDOWN)) {
    00462       incl -= u->u.rail.cached_veh_weight * 60;
    00463     }
    00464   }
    00465
    00466   v->max_speed = max_speed;
    00467
    00468   const int area = 120;
    00469   const int friction = 35; //[1e-3]
    00470   int resistance;
    00471   if (v->u.rail.railtype != RAILTYPE_MAGLEV) {
    00472     resistance = 13 * mass / 10;
    00473     resistance += 60 * num;
    00474     resistance += friction * mass * speed / 1000;
    00475     resistance += (area * drag_coeff * speed * speed) / 10000;
    00476   } else {
    00477     resistance = (area * (drag_coeff / 2) * speed * speed) / 10000;
    00478   }
    00479   resistance += incl;
    00480   resistance *= 4; //[N]
    00481
    00482   const int max_te = v->u.rail.cached_max_te; // [N]
    00483   int force;
    00484   if (speed > 0) {
    00485     switch (v->u.rail.railtype) {
    00486       case RAILTYPE_RAIL:
    00487       case RAILTYPE_ELECTRIC:
    00488       case RAILTYPE_MONO:
    00489         force = power / speed; //[N]
    00490         force *= 22;
    00491         force /= 10;
    00492         if (mode == AM_ACCEL && force > max_te) force = max_te;
    00493         break;
    00494
    00495       default: NOT_REACHED();
    00496       case RAILTYPE_MAGLEV:
    00497         force = power / 25;
    00498         break;
    00499     }
    00500   } else {
    00501     /* "kickoff" acceleration */
    00502     force = (mode == AM_ACCEL && v->u.rail.railtype != RAILTYPE_MAGLEV) ? min(max_te, power) : power;
    00503     force = max(force, (mass * 8) + resistance);
    00504   }
    00505
    00506   if (mode == AM_ACCEL) {
    00507     return (force - resistance) / (mass * 2);
    00508   } else {
    00509     return min(-force - resistance, -10000) / mass;
    00510   }
    00511 }
    00512
    00513 void UpdateTrainAcceleration(Vehicle *v)
    00514 {
    00515   assert(IsFrontEngine(v));
    00516
    00517   v->max_speed = v->u.rail.cached_max_speed;
    00518
    00519   uint power = v->u.rail.cached_power;
    00520   uint weight = v->u.rail.cached_weight;
    00521   assert(weight != 0);
    00522   v->acceleration = Clamp(power / weight * 4, 1, 255);
    00523 }
    00524
    00525 SpriteID Train::GetImage(Direction direction) const
    00526 {
    00527   uint8 spritenum = this->spritenum;
    00528   SpriteID sprite;
    00529
    00530   if (HasBit(this->u.rail.flags, VRF_REVERSE_DIRECTION)) direction = ReverseDir(direction);
    00531
    00532   if (is_custom_sprite(spritenum)) {
    00533     sprite = GetCustomVehicleSprite(this, (Direction)(direction + 4 * IS_CUSTOM_SECONDHEAD_SPRITE(spritenum)));
    00534     if (sprite != 0) return sprite;
    00535
    00536     spritenum = GetEngine(this->engine_type)->image_index;
    00537   }
    00538
    00539   sprite = _engine_sprite_base[spritenum] + ((direction + _engine_sprite_add[spritenum]) & _engine_sprite_and[spritenum]);
    00540
    00541   if (this->cargo.Count() >= this->cargo_cap / 2U) sprite += _wagon_full_adder[spritenum];
    00542
    00543   return sprite;
    00544 }
    00545
    00546 static SpriteID GetRailIcon(EngineID engine, bool rear_head, int &y)
    00547 {
    00548   Direction dir = rear_head ? DIR_E : DIR_W;
    00549   uint8 spritenum = RailVehInfo(engine)->image_index;
    00550
    00551   if (is_custom_sprite(spritenum)) {
    00552     SpriteID sprite = GetCustomVehicleIcon(engine, dir);
    00553     if (sprite != 0) {
    00554       y += _traininfo_vehicle_pitch; // TODO Make this per-GRF
    00555       return sprite;
    00556     }
    00557
    00558     spritenum = GetEngine(engine)->image_index;
    00559   }
    00560
    00561   if (rear_head) spritenum++;
    00562
    00563   return ((6 + _engine_sprite_add[spritenum]) & _engine_sprite_and[spritenum]) + _engine_sprite_base[spritenum];
    00564 }
    00565
    00566 void DrawTrainEngine(int x, int y, EngineID engine, SpriteID pal)
    00567 {
    00568   if (RailVehInfo(engine)->railveh_type == RAILVEH_MULTIHEAD) {
    00569     int yf = y;
    00570     int yr = y;
    00571
    00572     SpriteID spritef = GetRailIcon(engine, false, yf);
    00573     SpriteID spriter = GetRailIcon(engine, true, yr);
    00574     DrawSprite(spritef, pal, x - 14, yf);
    00575     DrawSprite(spriter, pal, x + 15, yr);
    00576   } else {
    00577     SpriteID sprite = GetRailIcon(engine, false, y);
    00578     DrawSprite(sprite, pal, x, y);
    00579   }
    00580 }
    00581
    00582 static CommandCost CmdBuildRailWagon(EngineID engine, TileIndex tile, DoCommandFlag flags)
    00583 {
    00584   const RailVehicleInfo *rvi = RailVehInfo(engine);
    00585   CommandCost value(EXPENSES_NEW_VEHICLES, GetEngine(engine)->GetCost());
    00586
    00587   if (flags & DC_QUERY_COST) return value;
    00588
    00589   /* Check that the wagon can drive on the track in question */
    00590   if (!IsCompatibleRail(rvi->railtype, GetRailType(tile))) return CMD_ERROR;
    00591
    00592   uint num_vehicles = 1 + CountArticulatedParts(engine, false);
    00593
    00594   /* Allow for the wagon and the articulated parts, plus one to "terminate" the list. */
    00595   Vehicle **vl = AllocaM(Vehicle*, num_vehicles + 1);
    00596   memset(vl, 0, sizeof(*vl) * (num_vehicles + 1));
    00597
    00598   if (!Vehicle::AllocateList(vl, num_vehicles)) {
    00599     return_cmd_error(STR_00E1_TOO_MANY_VEHICLES_IN_GAME);
    00600   }
    00601
    00602   if (flags & DC_EXEC) {
    00603     Vehicle *v = vl[0];
    00604     v->spritenum = rvi->image_index;
    00605
    00606     Vehicle *u = NULL;
    00607
    00608     Vehicle *w;
    00609     FOR_ALL_VEHICLES(w) {
    00610       if (w->type == VEH_TRAIN && w->tile == tile &&
    00611           IsFreeWagon(w) && w->engine_type == engine &&
    00612           !HASBITS(w->vehstatus, VS_CRASHED)) {
    00613         u = GetLastVehicleInChain(w);
    00614         break;
    00615       }
    00616     }
    00617
    00618     v = new (v) Train();
    00619     v->engine_type = engine;
    00620
    00621     DiagDirection dir = GetRailDepotDirection(tile);
    00622
    00623     v->direction = DiagDirToDir(dir);
    00624     v->tile = tile;
    00625
    00626     int x = TileX(tile) * TILE_SIZE | _vehicle_initial_x_fract[dir];
    00627     int y = TileY(tile) * TILE_SIZE | _vehicle_initial_y_fract[dir];
    00628
    00629     v->x_pos = x;
    00630     v->y_pos = y;
    00631     v->z_pos = GetSlopeZ(x, y);
    00632     v->owner = _current_company;
    00633     v->u.rail.track = TRACK_BIT_DEPOT;
    00634     v->vehstatus = VS_HIDDEN | VS_DEFPAL;
    00635
    00636 //    v->subtype = 0;
    00637     SetTrainWagon(v);
    00638
    00639     if (u != NULL) {
    00640       u->SetNext(v);
    00641     } else {
    00642       SetFreeWagon(v);
    00643       InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
    00644     }
    00645
    00646     v->cargo_type = rvi->cargo_type;
    00647 //    v->cargo_subtype = 0;
    00648     v->cargo_cap = rvi->capacity;
    00649     v->value = value.GetCost();
    00650 //    v->day_counter = 0;
    00651
    00652     v->u.rail.railtype = rvi->railtype;
    00653
    00654     v->build_year = _cur_year;
    00655     v->cur_image = 0xAC2;
    00656     v->random_bits = VehicleRandomBits();
    00657
    00658     v->group_id = DEFAULT_GROUP;
    00659
    00660     AddArticulatedParts(vl, VEH_TRAIN);
    00661
    00662     _new_vehicle_id = v->index;
    00663
    00664     VehiclePositionChanged(v);
    00665     TrainConsistChanged(v->First(), false);
    00666     UpdateTrainGroupID(v->First());
    00667
    00668     InvalidateWindow(WC_VEHICLE_DEPOT, v->tile);
    00669     if (IsLocalCompany()) {
    00670       InvalidateAutoreplaceWindow(v->engine_type, v->group_id); // updates the replace Train window
    00671     }
    00672     GetCompany(_current_company)->num_engines[engine]++;
    00673   }
    00674
    00675   return value;
    00676 }
    00677
    00679 static void NormalizeTrainVehInDepot(const Vehicle *u)
    00680 {
    00681   const Vehicle *v;
    00682
    00683   FOR_ALL_VEHICLES(v) {
    00684     if (v->type == VEH_TRAIN && IsFreeWagon(v) &&
    00685         v->tile == u->tile &&
    00686         v->u.rail.track == TRACK_BIT_DEPOT) {
    00687       if (CmdFailed(DoCommand(0, v->index | (u->index << 16), 1, DC_EXEC,
    00688           CMD_MOVE_RAIL_VEHICLE)))
    00689         break;
    00690     }
    00691   }
    00692 }
    00693
    00694 static void AddRearEngineToMultiheadedTrain(Vehicle *v, Vehicle *u, bool building)
    00695 {
    00696   u = new (u) Train();
    00697   u->direction = v->direction;
    00698   u->owner = v->owner;
    00699   u->tile = v->tile;
    00700   u->x_pos = v->x_pos;
    00701   u->y_pos = v->y_pos;
    00702   u->z_pos = v->z_pos;
    00703   u->u.rail.track = TRACK_BIT_DEPOT;
    00704   u->vehstatus = v->vehstatus & ~VS_STOPPED;
    00705 //  u->subtype = 0;
    00706   SetMultiheaded(u);
    00707   u->spritenum = v->spritenum + 1;
    00708   u->cargo_type = v->cargo_type;
    00709   u->cargo_subtype = v->cargo_subtype;
    00710   u->cargo_cap = v->cargo_cap;
    00711   u->u.rail.railtype = v->u.rail.railtype;
    00712   if (building) v->SetNext(u);
    00713   u->engine_type = v->engine_type;
    00714   u->build_year = v->build_year;
    00715   if (building) v->value >>= 1;
    00716   u->value = v->value;
    00717   u->cur_image = 0xAC2;
    00718   u->random_bits = VehicleRandomBits();
    00719   VehiclePositionChanged(u);
    00720 }
    00721
    00728 CommandCost CmdBuildRailVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00729 {
    00730   /* Check if the engine-type is valid (for the company) */
    00731   if (!IsEngineBuildable(p1, VEH_TRAIN, _current_company)) return_cmd_error(STR_RAIL_VEHICLE_NOT_AVAILABLE);
    00732
    00733   const Engine *e = GetEngine(p1);
    00734   CommandCost value(EXPENSES_NEW_VEHICLES, e->GetCost());
    00735
    00736   if (flags & DC_QUERY_COST) return value;
    00737
    00738   /* Check if the train is actually being built in a depot belonging
    00739    * to the company. Doesn't matter if only the cost is queried */
    00740   if (!IsRailDepotTile(tile)) return CMD_ERROR;
    00741   if (!IsTileOwner(tile, _current_company)) return CMD_ERROR;
    00742
    00743   const RailVehicleInfo *rvi = RailVehInfo(p1);
    00744   if (rvi->railveh_type == RAILVEH_WAGON) return CmdBuildRailWagon(p1, tile, flags);
    00745
    00746   uint num_vehicles =
    00747     (rvi->railveh_type == RAILVEH_MULTIHEAD ? 2 : 1) +
    00748     CountArticulatedParts(p1, false);
    00749
    00750   /* Check if depot and new engine uses the same kind of tracks *
    00751    * We need to see if the engine got power on the tile to avoid eletric engines in non-electric depots */
    00752   if (!HasPowerOnRail(rvi->railtype, GetRailType(tile))) return CMD_ERROR;
    00753
    00754   /* Allow for the dual-heads and the articulated parts, plus one to "terminate" the list. */
    00755   Vehicle **vl = AllocaM(Vehicle*, num_vehicles + 1);
    00756   memset(vl, 0, sizeof(*vl) * (num_vehicles + 1));
    00757
    00758   if (!Vehicle::AllocateList(vl, num_vehicles)) {
    00759     return_cmd_error(STR_00E1_TOO_MANY_VEHICLES_IN_GAME);
    00760   }
    00761
    00762   Vehicle *v = vl[0];
    00763
    00764   UnitID unit_num = (flags & DC_AUTOREPLACE) ? 0 : GetFreeUnitNumber(VEH_TRAIN);
    00765   if (unit_num > _settings_game.vehicle.max_trains) {
    00766     return_cmd_error(STR_00E1_TOO_MANY_VEHICLES_IN_GAME);
    00767   }
    00768
    00769   if (flags & DC_EXEC) {
    00770     DiagDirection dir = GetRailDepotDirection(tile);
    00771     int x = TileX(tile) * TILE_SIZE + _vehicle_initial_x_fract[dir];
    00772     int y = TileY(tile) * TILE_SIZE + _vehicle_initial_y_fract[dir];
    00773
    00774     v = new (v) Train();
    00775     v->unitnumber = unit_num;
    00776     v->direction = DiagDirToDir(dir);
    00777     v->tile = tile;
    00778     v->owner = _current_company;
    00779     v->x_pos = x;
    00780     v->y_pos = y;
    00781     v->z_pos = GetSlopeZ(x, y);
    00782 //    v->running_ticks = 0;
    00783     v->u.rail.track = TRACK_BIT_DEPOT;
    00784     v->vehstatus = VS_HIDDEN | VS_STOPPED | VS_DEFPAL;
    00785     v->spritenum = rvi->image_index;
    00786     v->cargo_type = rvi->cargo_type;
    00787 //    v->cargo_subtype = 0;
    00788     v->cargo_cap = rvi->capacity;
    00789     v->max_speed = rvi->max_speed;
    00790     v->value = value.GetCost();
    00791     v->last_station_visited = INVALID_STATION;
    00792 //    v->dest_tile = 0;
    00793
    00794     v->engine_type = p1;
    00795
    00796     v->reliability = e->reliability;
    00797     v->reliability_spd_dec = e->reliability_spd_dec;
    00798     v->max_age = e->lifelength * DAYS_IN_LEAP_YEAR;
    00799
    00800     v->name = NULL;
    00801     v->u.rail.railtype = rvi->railtype;
    00802     _new_vehicle_id = v->index;
    00803
    00804     v->service_interval = _settings_game.vehicle.servint_trains;
    00805     v->date_of_last_service = _date;
    00806     v->build_year = _cur_year;
    00807     v->cur_image = 0xAC2;
    00808     v->random_bits = VehicleRandomBits();
    00809
    00810 //    v->vehicle_flags = 0;
    00811     if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) SetBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE);
    00812
    00813     v->group_id = DEFAULT_GROUP;
    00814
    00815 //    v->subtype = 0;
    00816     SetFrontEngine(v);
    00817     SetTrainEngine(v);
    00818
    00819     VehiclePositionChanged(v);
    00820
    00821     if (rvi->railveh_type == RAILVEH_MULTIHEAD) {
    00822       SetMultiheaded(v);
    00823       AddRearEngineToMultiheadedTrain(vl[0], vl[1], true);
    00824       /* Now we need to link the front and rear engines together
    00825        * other_multiheaded_part is the pointer that links to the other half of the engine
    00826        * vl[0] is the front and vl[1] is the rear
    00827        */
    00828       vl[0]->u.rail.other_multiheaded_part = vl[1];
    00829       vl[1]->u.rail.other_multiheaded_part = vl[0];
    00830     } else {
    00831       AddArticulatedParts(vl, VEH_TRAIN);
    00832     }
    00833
    00834     TrainConsistChanged(v, false);
    00835     UpdateTrainGroupID(v);
    00836
    00837     if (!HasBit(p2, 1) && !(flags & DC_AUTOREPLACE)) { // check if the cars should be added to the new vehicle
    00838       NormalizeTrainVehInDepot(v);
    00839     }
    00840
    00841     InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
    00842     InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
    00843     InvalidateWindow(WC_COMPANY, v->owner);
    00844     if (IsLocalCompany()) {
    00845       InvalidateAutoreplaceWindow(v->engine_type, v->group_id); // updates the replace Train window
    00846     }
    00847
    00848     GetCompany(_current_company)->num_engines[p1]++;
    00849   }
    00850
    00851   return value;
    00852 }
    00853
    00854
    00855 /* Check if all the wagons of the given train are in a depot, returns the
    00856  * number of cars (including loco) then. If not it returns -1 */
    00857 int CheckTrainInDepot(const Vehicle *v, bool needs_to_be_stopped)
    00858 {
    00859   TileIndex tile = v->tile;
    00860
    00861   /* check if stopped in a depot */
    00862   if (!IsRailDepotTile(tile) || v->cur_speed != 0) return -1;
    00863
    00864   int count = 0;
    00865   for (; v != NULL; v = v->Next()) {
    00866     /* This count is used by the depot code to determine the number of engines
    00867      * in the consist. Exclude articulated parts so that autoreplacing to
    00868      * engines with more articulated parts than before works correctly.
    00869      *
    00870      * Also skip counting rear ends of multiheaded engines */
    00871     if (!IsArticulatedPart(v) && !IsRearDualheaded(v)) count++;
    00872     if (v->u.rail.track != TRACK_BIT_DEPOT || v->tile != tile ||
    00873         (IsFrontEngine(v) && needs_to_be_stopped && !(v->vehstatus & VS_STOPPED))) {
    00874       return -1;
    00875     }
    00876   }
    00877
    00878   return count;
    00879 }
    00880
    00881 /* Used to check if the train is inside the depot and verifying that the VS_STOPPED flag is set */
    00882 int CheckTrainStoppedInDepot(const Vehicle *v)
    00883 {
    00884   return CheckTrainInDepot(v, true);
    00885 }
    00886
    00887 /* Used to check if the train is inside the depot, but not checking the VS_STOPPED flag */
    00888 inline bool CheckTrainIsInsideDepot(const Vehicle *v)
    00889 {
    00890   return CheckTrainInDepot(v, false) > 0;
    00891 }
    00892
    00899 static Vehicle *UnlinkWagon(Vehicle *v, Vehicle *first)
    00900 {
    00901   /* unlinking the first vehicle of the chain? */
    00902   if (v == first) {
    00903     v = GetNextVehicle(v);
    00904     if (v == NULL) return NULL;
    00905
    00906     if (IsTrainWagon(v)) SetFreeWagon(v);
    00907
    00908     /* First can be an articulated engine, meaning GetNextVehicle() isn't
    00909      * v->Next(). Thus set the next vehicle of the last articulated part
    00910      * and the last articulated part is just before the next vehicle (v). */
    00911     v->Previous()->SetNext(NULL);
    00912
    00913     return v;
    00914   }
    00915
    00916   Vehicle *u;
    00917   for (u = first; GetNextVehicle(u) != v; u = GetNextVehicle(u)) {}
    00918   GetLastEnginePart(u)->SetNext(GetNextVehicle(v));
    00919   return first;
    00920 }
    00921
    00922 static Vehicle *FindGoodVehiclePos(const Vehicle *src)
    00923 {
    00924   Vehicle *dst;
    00925   EngineID eng = src->engine_type;
    00926   TileIndex tile = src->tile;
    00927
    00928   FOR_ALL_VEHICLES(dst) {
    00929     if (dst->type == VEH_TRAIN && IsFreeWagon(dst) && dst->tile == tile && !HASBITS(dst->vehstatus, VS_CRASHED)) {
    00930       /* check so all vehicles in the line have the same engine. */
    00931       Vehicle *v = dst;
    00932
    00933       while (v->engine_type == eng) {
    00934         v = v->Next();
    00935         if (v == NULL) return dst;
    00936       }
    00937     }
    00938   }
    00939
    00940   return NULL;
    00941 }
    00942
    00943 /*
    00944  * add a vehicle v behind vehicle dest
    00945  * use this function since it sets flags as needed
    00946  */
    00947 static void AddWagonToConsist(Vehicle *v, Vehicle *dest)
    00948 {
    00949   UnlinkWagon(v, v->First());
    00950   if (dest == NULL) return;
    00951
    00952   Vehicle *next = dest->Next();
    00953   v->SetNext(NULL);
    00954   dest->SetNext(v);
    00955   v->SetNext(next);
    00956   ClearFreeWagon(v);
    00957   ClearFrontEngine(v);
    00958 }
    00959
    00960 /*
    00961  * move around on the train so rear engines are placed correctly according to the other engines
    00962  * always call with the front engine
    00963  */
    00964 static void NormaliseTrainConsist(Vehicle *v)
    00965 {
    00966   if (IsFreeWagon(v)) return;
    00967
    00968   assert(IsFrontEngine(v));
    00969
    00970   for (; v != NULL; v = GetNextVehicle(v)) {
    00971     if (!IsMultiheaded(v) || !IsTrainEngine(v)) continue;
    00972
    00973     /* make sure that there are no free cars before next engine */
    00974     Vehicle *u;
    00975     for (u = v; u->Next() != NULL && !IsTrainEngine(u->Next()); u = u->Next()) {}
    00976
    00977     if (u == v->u.rail.other_multiheaded_part) continue;
    00978     AddWagonToConsist(v->u.rail.other_multiheaded_part, u);
    00979   }
    00980 }
    00981
    00991 CommandCost CmdMoveRailVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00992 {
    00993   VehicleID s = GB(p1, 0, 16);
    00994   VehicleID d = GB(p1, 16, 16);
    00995
    00996   if (!IsValidVehicleID(s)) return CMD_ERROR;
    00997
    00998   Vehicle *src = GetVehicle(s);
    00999
    01000   if (src->type != VEH_TRAIN || !CheckOwnership(src->owner)) return CMD_ERROR;
    01001
    01002   /* Do not allow moving crashed vehicles inside the depot, it is likely to cause asserts later */
    01003   if (HASBITS(src->vehstatus, VS_CRASHED)) return CMD_ERROR;
    01004
    01005   /* if nothing is selected as destination, try and find a matching vehicle to drag to. */
    01006   Vehicle *dst;
    01007   if (d == INVALID_VEHICLE) {
    01008     dst = IsTrainEngine(src) ? NULL : FindGoodVehiclePos(src);
    01009   } else {
    01010     if (!IsValidVehicleID(d)) return CMD_ERROR;
    01011     dst = GetVehicle(d);
    01012     if (dst->type != VEH_TRAIN || !CheckOwnership(dst->owner)) return CMD_ERROR;
    01013
    01014     /* Do not allow appending to crashed vehicles, too */
    01015     if (HASBITS(dst->vehstatus, VS_CRASHED)) return CMD_ERROR;
    01016   }
    01017
    01018   /* if an articulated part is being handled, deal with its parent vehicle */
    01019   while (IsArticulatedPart(src)) src = src->Previous();
    01020   if (dst != NULL) {
    01021     while (IsArticulatedPart(dst)) dst = dst->Previous();
    01022   }
    01023
    01024   /* don't move the same vehicle.. */
    01025   if (src == dst) return CommandCost();
    01026
    01027   /* locate the head of the two chains */
    01028   Vehicle *src_head = src->First();
    01029   Vehicle *dst_head;
    01030   if (dst != NULL) {
    01031     dst_head = dst->First();
    01032     if (dst_head->tile != src_head->tile) return CMD_ERROR;
    01033     /* Now deal with articulated part of destination wagon */
    01034     dst = GetLastEnginePart(dst);
    01035   } else {
    01036     dst_head = NULL;
    01037   }
    01038
    01039   if (IsRearDualheaded(src)) return_cmd_error(STR_REAR_ENGINE_FOLLOW_FRONT_ERROR);
    01040
    01041   /* when moving all wagons, we can't have the same src_head and dst_head */
    01042   if (HasBit(p2, 0) && src_head == dst_head) return CommandCost();
    01043
    01044   /* check if all vehicles in the source train are stopped inside a depot. */
    01045   int src_len = CheckTrainStoppedInDepot(src_head);
    01046   if (src_len < 0) return_cmd_error(STR_881A_TRAINS_CAN_ONLY_BE_ALTERED);
    01047
    01048   if ((flags & DC_AUTOREPLACE) == 0) {
    01049     /* Check whether there are more than 'max_len' train units (articulated parts and rear heads do not count) in the new chain */
    01050     int max_len = _settings_game.vehicle.mammoth_trains ? 100 : 10;
    01051
    01052     /* check the destination row if the source and destination aren't the same. */
    01053     if (src_head != dst_head) {
    01054       int dst_len = 0;
    01055
    01056       if (dst_head != NULL) {
    01057         /* check if all vehicles in the dest train are stopped. */
    01058         dst_len = CheckTrainStoppedInDepot(dst_head);
    01059         if (dst_len < 0) return_cmd_error(STR_881A_TRAINS_CAN_ONLY_BE_ALTERED);
    01060       }
    01061
    01062       /* We are moving between rows, so only count the wagons from the source
    01063        * row that are being moved. */
    01064       if (HasBit(p2, 0)) {
    01065         const Vehicle *u;
    01066         for (u = src_head; u != src && u != NULL; u = GetNextVehicle(u))
    01067           src_len--;
    01068       } else {
    01069         /* If moving only one vehicle, just count that. */
    01070         src_len = 1;
    01071       }
    01072
    01073       if (src_len + dst_len > max_len) {
    01074         /* Abort if we're adding too many wagons to a train. */
    01075         if (dst_head != NULL && IsFrontEngine(dst_head)) return_cmd_error(STR_8819_TRAIN_TOO_LONG);
    01076         /* Abort if we're making a train on a new row. */
    01077         if (dst_head == NULL && IsTrainEngine(src)) return_cmd_error(STR_8819_TRAIN_TOO_LONG);
    01078       }
    01079     } else {
    01080       /* Abort if we're creating a new train on an existing row. */
    01081       if (src_len > max_len && src == src_head && IsTrainEngine(GetNextVehicle(src_head)))
    01082         return_cmd_error(STR_8819_TRAIN_TOO_LONG);
    01083     }
    01084   }
    01085
    01086   /* moving a loco to a new line?, then we need to assign a unitnumber. */
    01087   if (dst == NULL && !IsFrontEngine(src) && IsTrainEngine(src)) {
    01088     UnitID unit_num = ((flags & DC_AUTOREPLACE) != 0 ? 0 : GetFreeUnitNumber(VEH_TRAIN));
    01089     if (unit_num > _settings_game.vehicle.max_trains)
    01090       return_cmd_error(STR_00E1_TOO_MANY_VEHICLES_IN_GAME);
    01091
    01092     if (flags & DC_EXEC) src->unitnumber = unit_num;
    01093   }
    01094
    01095   /* When we move the front vehicle, the second vehicle might need a unitnumber */
    01096   if (!HasBit(p2, 0) && (IsFreeWagon(src) || (IsFrontEngine(src) && dst == NULL)) && (flags & DC_AUTOREPLACE) == 0) {
    01097     Vehicle *second = GetNextUnit(src);
    01098     if (second != NULL && IsTrainEngine(second) && GetFreeUnitNumber(VEH_TRAIN) > _settings_game.vehicle.max_trains) {
    01099       return_cmd_error(STR_00E1_TOO_MANY_VEHICLES_IN_GAME);
    01100     }
    01101   }
    01102
    01103   /*
    01104    * Check whether the vehicles in the source chain are in the destination
    01105    * chain. This can easily be done by checking whether the first vehicle
    01106    * of the source chain is in the destination chain as the Next/Previous
    01107    * pointers always make a doubly linked list of it where the assumption
    01108    * v->Next()->Previous() == v holds (assuming v->Next() != NULL).
    01109    */
    01110   bool src_in_dst = false;
    01111   for (Vehicle *v = dst_head; !src_in_dst && v != NULL; v = v->Next()) src_in_dst = v == src;
    01112
    01113   /*
    01114    * If the source chain is in the destination chain then the user is
    01115    * only reordering the vehicles, thus not attaching a new vehicle.
    01116    * Therefor the 'allow wagon attach' callback does not need to be
    01117    * called. If it would be called strange things would happen because
    01118    * one 'attaches' an already 'attached' vehicle causing more trouble
    01119    * than it actually solves (infinite loops and such).
    01120    */
    01121   if (dst_head != NULL && !src_in_dst && (flags & DC_AUTOREPLACE) == 0) {
    01122     /*
    01123      * When performing the 'allow wagon attach' callback, we have to check
    01124      * that for each and every wagon, not only the first one. This means
    01125      * that we have to test one wagon, attach it to the train and then test
    01126      * the next wagon till we have reached the end. We have to restore it
    01127      * to the state it was before we 'tried' attaching the train when the
    01128      * attaching fails or succeeds because we are not 'only' doing this
    01129      * in the DC_EXEC state.
    01130      */
    01131     Vehicle *dst_tail = dst_head;
    01132     while (dst_tail->Next() != NULL) dst_tail = dst_tail->Next();
    01133
    01134     Vehicle *orig_tail = dst_tail;
    01135     Vehicle *next_to_attach = src;
    01136     Vehicle *src_previous = src->Previous();
    01137
    01138     while (next_to_attach != NULL) {
    01139       /* Don't check callback for articulated or rear dual headed parts */
    01140       if (!IsArticulatedPart(next_to_attach) && !IsRearDualheaded(next_to_attach)) {
    01141         /* Back up and clear the first_engine data to avoid using wagon override group */
    01142         EngineID first_engine = next_to_attach->u.rail.first_engine;
    01143         next_to_attach->u.rail.first_engine = INVALID_ENGINE;
    01144
    01145         uint16 callback = GetVehicleCallbackParent(CBID_TRAIN_ALLOW_WAGON_ATTACH, 0, 0, dst_head->engine_type, next_to_attach, dst_head);
    01146
    01147         /* Restore original first_engine data */
    01148         next_to_attach->u.rail.first_engine = first_engine;
    01149
    01150         if (callback != CALLBACK_FAILED) {
    01151           StringID error = STR_NULL;
    01152
    01153           if (callback == 0xFD) error = STR_INCOMPATIBLE_RAIL_TYPES;
    01154           if (callback < 0xFD) error = GetGRFStringID(GetEngineGRFID(dst_head->engine_type), 0xD000 + callback);
    01155
    01156           if (error != STR_NULL) {
    01157             /*
    01158              * The attaching is not allowed. In this case 'next_to_attach'
    01159              * can contain some vehicles of the 'source' and the destination
    01160              * train can have some too. We 'just' add the to-be added wagons
    01161              * to the chain and then split it where it was previously
    01162              * separated, i.e. the tail of the original destination train.
    01163              * Furthermore the 'previous' link of the original source vehicle needs
    01164              * to be restored, otherwise the train goes missing in the depot.
    01165              */
    01166             dst_tail->SetNext(next_to_attach);
    01167             orig_tail->SetNext(NULL);
    01168             if (src_previous != NULL) src_previous->SetNext(src);
    01169
    01170             return_cmd_error(error);
    01171           }
    01172         }
    01173       }
    01174
    01175       /* Only check further wagons if told to move the chain */
    01176       if (!HasBit(p2, 0)) break;
    01177
    01178       /*
    01179        * Adding a next wagon to the chain so we can test the other wagons.
    01180        * First 'take' the first wagon from 'next_to_attach' and move it
    01181        * to the next wagon. Then add that to the tail of the destination
    01182        * train and update the tail with the new vehicle.
    01183        */
    01184       Vehicle *to_add = next_to_attach;
    01185       next_to_attach = next_to_attach->Next();
    01186
    01187       to_add->SetNext(NULL);
    01188       dst_tail->SetNext(to_add);
    01189       dst_tail = dst_tail->Next();
    01190     }
    01191
    01192     /*
    01193      * When we reach this the attaching is allowed. It also means that the
    01194      * chain of vehicles to attach is empty, so we do not need to merge that.
    01195      * This means only the splitting needs to be done.
    01196      * Furthermore the 'previous' link of the original source vehicle needs
    01197      * to be restored, otherwise the train goes missing in the depot.
    01198      */
    01199     orig_tail->SetNext(NULL);
    01200     if (src_previous != NULL) src_previous->SetNext(src);
    01201   }
    01202
    01203   /* do it? */
    01204   if (flags & DC_EXEC) {
    01205     /* If we move the front Engine and if the second vehicle is not an engine
    01206        add the whole vehicle to the DEFAULT_GROUP */
    01207     if (IsFrontEngine(src) && !IsDefaultGroupID(src->group_id)) {
    01208       Vehicle *v = GetNextVehicle(src);
    01209
    01210       if (v != NULL && IsTrainEngine(v)) {
    01211         v->group_id   = src->group_id;
    01212         src->group_id = DEFAULT_GROUP;
    01213       }
    01214     }
    01215
    01216     if (HasBit(p2, 0)) {
    01217       /* unlink ALL wagons */
    01218       if (src != src_head) {
    01219         Vehicle *v = src_head;
    01220         while (GetNextVehicle(v) != src) v = GetNextVehicle(v);
    01221         GetLastEnginePart(v)->SetNext(NULL);
    01222       } else {
    01223         InvalidateWindowData(WC_VEHICLE_DEPOT, src_head->tile); // We removed a line
    01224         src_head = NULL;
    01225       }
    01226     } else {
    01227       /* if moving within the same chain, dont use dst_head as it may get invalidated */
    01228       if (src_head == dst_head) dst_head = NULL;
    01229       /* unlink single wagon from linked list */
    01230       src_head = UnlinkWagon(src, src_head);
    01231       GetLastEnginePart(src)->SetNext(NULL);
    01232     }
    01233
    01234     if (dst == NULL) {
    01235       /* We make a new line in the depot, so we know already that we invalidate the window data */
    01236       InvalidateWindowData(WC_VEHICLE_DEPOT, src->tile);
    01237
    01238       /* move the train to an empty line. for locomotives, we set the type to TS_Front. for wagons, 4. */
    01239       if (IsTrainEngine(src)) {
    01240         if (!IsFrontEngine(src)) {
    01241           /* setting the type to 0 also involves setting up the orders field. */
    01242           SetFrontEngine(src);
    01243           assert(src->orders.list == NULL);
    01244
    01245           /* Decrease the engines number of the src engine_type */
    01246           if (!IsDefaultGroupID(src->group_id) && IsValidGroupID(src->group_id)) {
    01247             GetGroup(src->group_id)->num_engines[src->engine_type]--;
    01248           }
    01249
    01250           /* If we move an engine to a new line affect it to the DEFAULT_GROUP */
    01251           src->group_id = DEFAULT_GROUP;
    01252         }
    01253       } else {
    01254         SetFreeWagon(src);
    01255       }
    01256       dst_head = src;
    01257     } else {
    01258       if (IsFrontEngine(src)) {
    01259         /* the vehicle was previously a loco. need to free the order list and delete vehicle windows etc. */
    01260         DeleteWindowById(WC_VEHICLE_VIEW, src->index);
    01261         DeleteWindowById(WC_VEHICLE_ORDERS, src->index);
    01262         DeleteWindowById(WC_VEHICLE_REFIT, src->index);
    01263         DeleteWindowById(WC_VEHICLE_DETAILS, src->index);
    01264         DeleteWindowById(WC_VEHICLE_TIMETABLE, src->index);
    01265         DeleteVehicleOrders(src);
    01266         RemoveVehicleFromGroup(src);
    01267       }
    01268
    01269       if (IsFrontEngine(src) || IsFreeWagon(src)) {
    01270         InvalidateWindowData(WC_VEHICLE_DEPOT, src->tile);
    01271         ClearFrontEngine(src);
    01272         ClearFreeWagon(src);
    01273         src->unitnumber = 0; // doesn't occupy a unitnumber anymore.
    01274       }
    01275
    01276       /* link in the wagon(s) in the chain. */
    01277       {
    01278         Vehicle *v;
    01279
    01280         for (v = src; GetNextVehicle(v) != NULL; v = GetNextVehicle(v)) {}
    01281         GetLastEnginePart(v)->SetNext(dst->Next());
    01282       }
    01283       dst->SetNext(src);
    01284     }
    01285
    01286     if (src->u.rail.other_multiheaded_part != NULL) {
    01287       if (src->u.rail.other_multiheaded_part == src_head) {
    01288         src_head = src_head->Next();
    01289       }
    01290       AddWagonToConsist(src->u.rail.other_multiheaded_part, src);
    01291     }
    01292
    01293     /* If there is an engine behind first_engine we moved away, it should become new first_engine
    01294      * To do this, CmdMoveRailVehicle must be called once more
    01295      * we can't loop forever here because next time we reach this line we will have a front engine */
    01296     if (src_head != NULL && !IsFrontEngine(src_head) && IsTrainEngine(src_head)) {
    01297       /* As in CmdMoveRailVehicle src_head->group_id will be equal to DEFAULT_GROUP
    01298        * we need to save the group and reaffect it to src_head */
    01299       const GroupID tmp_g = src_head->group_id;
    01300       CmdMoveRailVehicle(0, flags, src_head->index | (INVALID_VEHICLE << 16), 1, text);
    01301       SetTrainGroupID(src_head, tmp_g);
    01302       src_head = NULL; // don't do anything more to this train since the new call will do it
    01303     }
    01304
    01305     if (src_head != NULL) {
    01306       NormaliseTrainConsist(src_head);
    01307       TrainConsistChanged(src_head, false);
    01308       UpdateTrainGroupID(src_head);
    01309       if (IsFrontEngine(src_head)) {
    01310         /* Update the refit button and window */
    01311         InvalidateWindow(WC_VEHICLE_REFIT, src_head->index);
    01312         InvalidateWindowWidget(WC_VEHICLE_VIEW, src_head->index, VVW_WIDGET_REFIT_VEH);
    01313       }
    01314       /* Update the depot window */
    01315       InvalidateWindow(WC_VEHICLE_DEPOT, src_head->tile);
    01316     }
    01317
    01318     if (dst_head != NULL) {
    01319       NormaliseTrainConsist(dst_head);
    01320       TrainConsistChanged(dst_head, false);
    01321       UpdateTrainGroupID(dst_head);
    01322       if (IsFrontEngine(dst_head)) {
    01323         /* Update the refit button and window */
    01324         InvalidateWindowWidget(WC_VEHICLE_VIEW, dst_head->index, VVW_WIDGET_REFIT_VEH);
    01325         InvalidateWindow(WC_VEHICLE_REFIT, dst_head->index);
    01326       }
    01327       /* Update the depot window */
    01328       InvalidateWindow(WC_VEHICLE_DEPOT, dst_head->tile);
    01329     }
    01330
    01331     InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
    01332   }
    01333
    01334   return CommandCost();
    01335 }
    01336
    01346 CommandCost CmdSellRailWagon(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    01347 {
    01348   /* Check if we deleted a vehicle window */
    01349   Window *w = NULL;
    01350
    01351   if (!IsValidVehicleID(p1) || p2 > 1) return CMD_ERROR;
    01352
    01353   Vehicle *v = GetVehicle(p1);
    01354
    01355   if (v->type != VEH_TRAIN || !CheckOwnership(v->owner)) return CMD_ERROR;
    01356
    01357   if (HASBITS(v->vehstatus, VS_CRASHED)) return_cmd_error(STR_CAN_T_SELL_DESTROYED_VEHICLE);
    01358
    01359   while (IsArticulatedPart(v)) v = v->Previous();
    01360   Vehicle *first = v->First();
    01361
    01362   /* make sure the vehicle is stopped in the depot */
    01363   if (CheckTrainStoppedInDepot(first) < 0) {
    01364     return_cmd_error(STR_881A_TRAINS_CAN_ONLY_BE_ALTERED);
    01365   }
    01366
    01367   if (IsRearDualheaded(v)) return_cmd_error(STR_REAR_ENGINE_FOLLOW_FRONT_ERROR);
    01368
    01369   if (flags & DC_EXEC) {
    01370     if (v == first && IsFrontEngine(first)) {
    01371       DeleteWindowById(WC_VEHICLE_VIEW, first->index);
    01372       DeleteWindowById(WC_VEHICLE_ORDERS, first->index);
    01373       DeleteWindowById(WC_VEHICLE_REFIT, first->index);
    01374       DeleteWindowById(WC_VEHICLE_DETAILS, first->index);
    01375       DeleteWindowById(WC_VEHICLE_TIMETABLE, first->index);
    01376     }
    01377     InvalidateWindow(WC_VEHICLE_DEPOT, first->tile);
    01378     InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
    01379   }
    01380
    01381   CommandCost cost(EXPENSES_NEW_VEHICLES);
    01382   switch (p2) {
    01383     case 0: { /* Delete given wagon */
    01384       bool switch_engine = false;    // update second wagon to engine?
    01385
    01386       /* 1. Delete the engine, if it is dualheaded also delete the matching
    01387        * rear engine of the loco (from the point of deletion onwards) */
    01388       Vehicle *rear = (IsMultiheaded(v) &&
    01389         IsTrainEngine(v)) ? v->u.rail.other_multiheaded_part : NULL;
    01390
    01391       if (rear != NULL) {
    01392         cost.AddCost(-rear->value);
    01393         if (flags & DC_EXEC) {
    01394           UnlinkWagon(rear, first);
    01395           delete rear;
    01396         }
    01397       }
    01398
    01399       /* 2. We are selling the front vehicle, some special action might be required
    01400        * here, so take attention */
    01401       if (v == first) {
    01402         Vehicle *new_f = GetNextVehicle(first);
    01403
    01404         /* 2.2 If there are wagons present after the deleted front engine, check
    01405          * if the second wagon (which will be first) is an engine. If it is one,
    01406          * promote it as a new train, retaining the unitnumber, orders */
    01407         if (new_f != NULL && IsTrainEngine(new_f)) {
    01408           if (IsTrainEngine(first)) {
    01409             /* Let the new front engine take over the setup of the old engine */
    01410             switch_engine = true;
    01411
    01412             if (flags & DC_EXEC) {
    01413               /* Make sure the group counts stay correct. */
    01414               new_f->group_id        = first->group_id;
    01415               first->group_id        = DEFAULT_GROUP;
    01416
    01417               /* Copy orders (by sharing) */
    01418               new_f->orders.list     = first->orders.list;
    01419               new_f->AddToShared(first);
    01420               DeleteVehicleOrders(first);
    01421
    01422               /* Copy other important data from the front engine */
    01423               new_f->CopyVehicleConfigAndStatistics(first);
    01424
    01425               /* If we deleted a window then open a new one for the 'new' train */
    01426               if (IsLocalCompany() && w != NULL) ShowVehicleViewWindow(new_f);
    01427             }
    01428           } else {
    01429             /* We are selling a free wagon, and construct a new train at the same time.
    01430              * This needs lots of extra checks (e.g. train limit), which are done by first moving
    01431              * the remaining vehicles to a new row */
    01432             cost.AddCost(DoCommand(0, new_f->index | INVALID_VEHICLE << 16, 1, flags, CMD_MOVE_RAIL_VEHICLE));
    01433             if (cost.Failed()) return cost;
    01434           }
    01435         }
    01436       }
    01437
    01438       /* 3. Delete the requested wagon */
    01439       cost.AddCost(-v->value);
    01440       if (flags & DC_EXEC) {
    01441         first = UnlinkWagon(v, first);
    01442         delete v;
    01443
    01444         /* 4 If the second wagon was an engine, update it to front_engine
    01445          * which UnlinkWagon() has changed to TS_Free_Car */
    01446         if (switch_engine) SetFrontEngine(first);
    01447
    01448         /* 5. If the train still exists, update its acceleration, window, etc. */
    01449         if (first != NULL) {
    01450           NormaliseTrainConsist(first);
    01451           TrainConsistChanged(first, false);
    01452           UpdateTrainGroupID(first);
    01453           if (IsFrontEngine(first)) InvalidateWindow(WC_VEHICLE_REFIT, first->index);
    01454         }
    01455
    01456       }
    01457     } break;
    01458     case 1: { /* Delete wagon and all wagons after it given certain criteria */
    01459       /* Start deleting every vehicle after the selected one
    01460        * If we encounter a matching rear-engine to a front-engine
    01461        * earlier in the chain (before deletion), leave it alone */
    01462       for (Vehicle *tmp; v != NULL; v = tmp) {
    01463         tmp = GetNextVehicle(v);
    01464
    01465         if (IsMultiheaded(v)) {
    01466           if (IsTrainEngine(v)) {
    01467             /* We got a front engine of a multiheaded set. Now we will sell the rear end too */
    01468             Vehicle *rear = v->u.rail.other_multiheaded_part;
    01469
    01470             if (rear != NULL) {
    01471               cost.AddCost(-rear->value);
    01472
    01473               /* If this is a multiheaded vehicle with nothing
    01474                * between the parts, tmp will be pointing to the
    01475                * rear part, which is unlinked from the train and
    01476                * deleted here. However, because tmp has already
    01477                * been set it needs to be updated now so that the
    01478                * loop never sees the rear part. */
    01479               if (tmp == rear) tmp = GetNextVehicle(tmp);
    01480
    01481               if (flags & DC_EXEC) {
    01482                 first = UnlinkWagon(rear, first);
    01483                 delete rear;
    01484               }
    01485             }
    01486           } else if (v->u.rail.other_multiheaded_part != NULL) {
    01487             /* The front to this engine is earlier in this train. Do nothing */
    01488             continue;
    01489           }
    01490         }
    01491
    01492         cost.AddCost(-v->value);
    01493         if (flags & DC_EXEC) {
    01494           first = UnlinkWagon(v, first);
    01495           delete v;
    01496         }
    01497       }
    01498
    01499       /* 3. If it is still a valid train after selling, update its acceleration and cached values */
    01500       if (flags & DC_EXEC && first != NULL) {
    01501         NormaliseTrainConsist(first);
    01502         TrainConsistChanged(first, false);
    01503         UpdateTrainGroupID(first);
    01504         InvalidateWindow(WC_VEHICLE_REFIT, first->index);
    01505       }
    01506     } break;
    01507   }
    01508   return cost;
    01509 }
    01510
    01511 void Train::UpdateDeltaXY(Direction direction)
    01512 {
    01513 #define MKIT(a, b, c, d) ((a & 0xFF) << 24) | ((b & 0xFF) << 16) | ((c & 0xFF) << 8) | ((d & 0xFF) << 0)
    01514   static const uint32 _delta_xy_table[8] = {
    01515     MKIT(3, 3, -1, -1),
    01516     MKIT(3, 7, -1, -3),
    01517     MKIT(3, 3, -1, -1),
    01518     MKIT(7, 3, -3, -1),
    01519     MKIT(3, 3, -1, -1),
    01520     MKIT(3, 7, -1, -3),
    01521     MKIT(3, 3, -1, -1),
    01522     MKIT(7, 3, -3, -1),
    01523   };
    01524 #undef MKIT
    01525
    01526   uint32 x = _delta_xy_table[direction];
    01527   this->x_offs        = GB(x,  0, 8);
    01528   this->y_offs        = GB(x,  8, 8);
    01529   this->x_extent      = GB(x, 16, 8);
    01530   this->y_extent      = GB(x, 24, 8);
    01531   this->z_extent      = 6;
    01532 }
    01533
    01534 static void UpdateVarsAfterSwap(Vehicle *v)
    01535 {
    01536   v->UpdateDeltaXY(v->direction);
    01537   v->cur_image = v->GetImage(v->direction);
    01538   BeginVehicleMove(v);
    01539   VehiclePositionChanged(v);
    01540   EndVehicleMove(v);
    01541 }
    01542
    01543 static inline void SetLastSpeed(Vehicle *v, int spd)
    01544 {
    01545   int old = v->u.rail.last_speed;
    01546   if (spd != old) {
    01547     v->u.rail.last_speed = spd;
    01548     if (_settings_client.gui.vehicle_speed || (old == 0) != (spd == 0)) {
    01549       InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
    01550     }
    01551   }
    01552 }
    01553
    01555 static void MarkTrainAsStuck(Vehicle *v)
    01556 {
    01557   if (!HasBit(v->u.rail.flags, VRF_TRAIN_STUCK)) {
    01558     /* It is the first time the problem occured, set the "train stuck" flag. */
    01559     SetBit(v->u.rail.flags, VRF_TRAIN_STUCK);
    01560     v->load_unload_time_rem = 0;
    01561
    01562     /* Stop train */
    01563     v->cur_speed = 0;
    01564     v->subspeed = 0;
    01565     SetLastSpeed(v, 0);
    01566
    01567     InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
    01568   }
    01569 }
    01570
    01571 static void SwapTrainFlags(uint16 *swap_flag1, uint16 *swap_flag2)
    01572 {
    01573   uint16 flag1 = *swap_flag1;
    01574   uint16 flag2 = *swap_flag2;
    01575
    01576   /* Clear the flags */
    01577   ClrBit(*swap_flag1, VRF_GOINGUP);
    01578   ClrBit(*swap_flag1, VRF_GOINGDOWN);
    01579   ClrBit(*swap_flag2, VRF_GOINGUP);
    01580   ClrBit(*swap_flag2, VRF_GOINGDOWN);
    01581
    01582   /* Reverse the rail-flags (if needed) */
    01583   if (HasBit(flag1, VRF_GOINGUP)) {
    01584     SetBit(*swap_flag2, VRF_GOINGDOWN);
    01585   } else if (HasBit(flag1, VRF_GOINGDOWN)) {
    01586     SetBit(*swap_flag2, VRF_GOINGUP);
    01587   }
    01588   if (HasBit(flag2, VRF_GOINGUP)) {
    01589     SetBit(*swap_flag1, VRF_GOINGDOWN);
    01590   } else if (HasBit(flag2, VRF_GOINGDOWN)) {
    01591     SetBit(*swap_flag1, VRF_GOINGUP);
    01592   }
    01593 }
    01594
    01595 static void ReverseTrainSwapVeh(Vehicle *v, int l, int r)
    01596 {
    01597   Vehicle *a, *b;
    01598
    01599   /* locate vehicles to swap */
    01600   for (a = v; l != 0; l--) a = a->Next();
    01601   for (b = v; r != 0; r--) b = b->Next();
    01602
    01603   if (a != b) {
    01604     /* swap the hidden bits */
    01605     {
    01606       uint16 tmp = (a->vehstatus & ~VS_HIDDEN) | (b->vehstatus&VS_HIDDEN);
    01607       b->vehstatus = (b->vehstatus & ~VS_HIDDEN) | (a->vehstatus&VS_HIDDEN);
    01608       a->vehstatus = tmp;
    01609     }
    01610
    01611     Swap(a->u.rail.track, b->u.rail.track);
    01612     Swap(a->direction,    b->direction);
    01613
    01614     /* toggle direction */
    01615     if (a->u.rail.track != TRACK_BIT_DEPOT) a->direction = ReverseDir(a->direction);
    01616     if (b->u.rail.track != TRACK_BIT_DEPOT) b->direction = ReverseDir(b->direction);
    01617
    01618     Swap(a->x_pos, b->x_pos);
    01619     Swap(a->y_pos, b->y_pos);
    01620     Swap(a->tile,  b->tile);
    01621     Swap(a->z_pos, b->z_pos);
    01622
    01623     SwapTrainFlags(&a->u.rail.flags, &b->u.rail.flags);
    01624
    01625     /* update other vars */
    01626     UpdateVarsAfterSwap(a);
    01627     UpdateVarsAfterSwap(b);
    01628
    01629     /* call the proper EnterTile function unless we are in a wormhole */
    01630     if (a->u.rail.track != TRACK_BIT_WORMHOLE) VehicleEnterTile(a, a->tile, a->x_pos, a->y_pos);
    01631     if (b->u.rail.track != TRACK_BIT_WORMHOLE) VehicleEnterTile(b, b->tile, b->x_pos, b->y_pos);
    01632   } else {
    01633     if (a->u.rail.track != TRACK_BIT_DEPOT) a->direction = ReverseDir(a->direction);
    01634     UpdateVarsAfterSwap(a);
    01635
    01636     if (a->u.rail.track != TRACK_BIT_WORMHOLE) VehicleEnterTile(a, a->tile, a->x_pos, a->y_pos);
    01637   }
    01638
    01639   /* Update train's power incase tiles were different rail type */
    01640   TrainPowerChanged(v);
    01641 }
    01642
    01643
    01649 static Vehicle *TrainOnTileEnum(Vehicle *v, void *)
    01650 {
    01651   return (v->type == VEH_TRAIN) ? v : NULL;
    01652 }
    01653
    01654
    01661 static Vehicle *TrainApproachingCrossingEnum(Vehicle *v, void *data)
    01662 {
    01663   /* not a train || not front engine || crashed */
    01664   if (v->type != VEH_TRAIN || !IsFrontEngine(v) || v->vehstatus & VS_CRASHED) return NULL;
    01665
    01666   TileIndex tile = *(TileIndex*)data;
    01667
    01668   if (TrainApproachingCrossingTile(v) != tile) return NULL;
    01669
    01670   return v;
    01671 }
    01672
    01673
    01680 static bool TrainApproachingCrossing(TileIndex tile)
    01681 {
    01682   assert(IsLevelCrossingTile(tile));
    01683
    01684   DiagDirection dir = AxisToDiagDir(GetCrossingRailAxis(tile));
    01685   TileIndex tile_from = tile + TileOffsByDiagDir(dir);
    01686
    01687   if (HasVehicleOnPos(tile_from, &tile, &TrainApproachingCrossingEnum)) return true;
    01688
    01689   dir = ReverseDiagDir(dir);
    01690   tile_from = tile + TileOffsByDiagDir(dir);
    01691
    01692   return HasVehicleOnPos(tile_from, &tile, &TrainApproachingCrossingEnum);
    01693 }
    01694
    01695
    01702 void UpdateLevelCrossing(TileIndex tile, bool sound)
    01703 {
    01704   assert(IsLevelCrossingTile(tile));
    01705
    01706   /* train on crossing || train approaching crossing || reserved */
    01707   bool new_state = HasVehicleOnPos(tile, NULL, &TrainOnTileEnum) || TrainApproachingCrossing(tile) || GetCrossingReservation(tile);
    01708
    01709   if (new_state != IsCrossingBarred(tile)) {
    01710     if (new_state && sound) {
    01711       SndPlayTileFx(SND_0E_LEVEL_CROSSING, tile);
    01712     }
    01713     SetCrossingBarred(tile, new_state);
    01714     MarkTileDirtyByTile(tile);
    01715   }
    01716 }
    01717
    01718
    01724 static inline void MaybeBarCrossingWithSound(TileIndex tile)
    01725 {
    01726   if (!IsCrossingBarred(tile)) {
    01727     BarCrossing(tile);
    01728     SndPlayTileFx(SND_0E_LEVEL_CROSSING, tile);
    01729     MarkTileDirtyByTile(tile);
    01730   }
    01731 }
    01732
    01733
    01739 static void AdvanceWagonsBeforeSwap(Vehicle *v)
    01740 {
    01741   Vehicle *base = v;
    01742   Vehicle *first = base;                    // first vehicle to move
    01743   Vehicle *last = GetLastVehicleInChain(v); // last vehicle to move
    01744   uint length = CountVehiclesInChain(v);
    01745
    01746   while (length > 2) {
    01747     last = last->Previous();
    01748     first = first->Next();
    01749
    01750     int differential = base->u.rail.cached_veh_length - last->u.rail.cached_veh_length;
    01751
    01752     /* do not update images now
    01753      * negative differential will be handled in AdvanceWagonsAfterSwap() */
    01754     for (int i = 0; i < differential; i++) TrainController(first, last->Next(), false);
    01755
    01756     base = first; // == base->Next()
    01757     length -= 2;
    01758   }
    01759 }
    01760
    01761
    01767 static void AdvanceWagonsAfterSwap(Vehicle *v)
    01768 {
    01769   /* first of all, fix the situation when the train was entering a depot */
    01770   Vehicle *dep = v; // last vehicle in front of just left depot
    01771   while (dep->Next() != NULL && (dep->u.rail.track == TRACK_BIT_DEPOT || dep->Next()->u.rail.track != TRACK_BIT_DEPOT)) {
    01772     dep = dep->Next(); // find first vehicle outside of a depot, with next vehicle inside a depot
    01773   }
    01774
    01775   Vehicle *leave = dep->Next(); // first vehicle in a depot we are leaving now
    01776
    01777   if (leave != NULL) {
    01778     /* 'pull' next wagon out of the depot, so we won't miss it (it could stay in depot forever) */
    01779     int d = TicksToLeaveDepot(dep);
    01780
    01781     if (d <= 0) {
    01782       leave->vehstatus &= ~VS_HIDDEN; // move it out of the depot
    01783       leave->u.rail.track = TrackToTrackBits(GetRailDepotTrack(leave->tile));
    01784       for (int i = 0; i >= d; i--) TrainController(leave, NULL, false); // maybe move it, and maybe let another wagon leave
    01785     }
    01786   } else {
    01787     dep = NULL; // no vehicle in a depot, so no vehicle leaving a depot
    01788   }
    01789
    01790   Vehicle *base = v;
    01791   Vehicle *first = base;                    // first vehicle to move
    01792   Vehicle *last = GetLastVehicleInChain(v); // last vehicle to move
    01793   uint length = CountVehiclesInChain(v);
    01794
    01795   /* we have to make sure all wagons that leave a depot because of train reversing are moved coorectly
    01796    * they have already correct spacing, so we have to make sure they are moved how they should */
    01797   bool nomove = (dep == NULL); // if there is no vehicle leaving a depot, limit the number of wagons moved immediatelly
    01798
    01799   while (length > 2) {
    01800     /* we reached vehicle (originally) in front of a depot, stop now
    01801      * (we would move wagons that are alredy moved with new wagon length) */
    01802     if (base == dep) break;
    01803
    01804     /* the last wagon was that one leaving a depot, so do not move it anymore */
    01805     if (last == dep) nomove = true;
    01806
    01807     last = last->Previous();
    01808     first = first->Next();
    01809
    01810     int differential = last->u.rail.cached_veh_length - base->u.rail.cached_veh_length;
    01811
    01812     /* do not update images now */
    01813     for (int i = 0; i < differential; i++) TrainController(first, (nomove ? last->Next() : NULL), false);
    01814
    01815     base = first; // == base->Next()
    01816     length -= 2;
    01817   }
    01818 }
    01819
    01820
    01821 static void ReverseTrainDirection(Vehicle *v)
    01822 {
    01823   if (IsRailDepotTile(v->tile)) {
    01824     InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
    01825   }
    01826
    01827   /* Clear path reservation in front. */
    01828   FreeTrainTrackReservation(v);
    01829
    01830   /* Check if we were approaching a rail/road-crossing */
    01831   TileIndex crossing = TrainApproachingCrossingTile(v);
    01832
    01833   /* count number of vehicles */
    01834   int r = CountVehiclesInChain(v) - 1;  // number of vehicles - 1
    01835
    01836   AdvanceWagonsBeforeSwap(v);
    01837
    01838   /* swap start<>end, start+1<>end-1, ... */
    01839   int l = 0;
    01840   do {
    01841     ReverseTrainSwapVeh(v, l++, r--);
    01842   } while (l <= r);
    01843
    01844   AdvanceWagonsAfterSwap(v);
    01845
    01846   if (IsRailDepotTile(v->tile)) {
    01847     InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
    01848   }
    01849
    01850   ToggleBit(v->u.rail.flags, VRF_TOGGLE_REVERSE);
    01851
    01852   ClrBit(v->u.rail.flags, VRF_REVERSING);
    01853
    01854   /* recalculate cached data */
    01855   TrainConsistChanged(v, true);
    01856
    01857   /* update all images */
    01858   for (Vehicle *u = v; u != NULL; u = u->Next()) u->cur_image = u->GetImage(u->direction);
    01859
    01860   /* update crossing we were approaching */
    01861   if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
    01862
    01863   /* maybe we are approaching crossing now, after reversal */
    01864   crossing = TrainApproachingCrossingTile(v);
    01865   if (crossing != INVALID_TILE) MaybeBarCrossingWithSound(crossing);
    01866
    01867   /* If we are inside a depot after reversing, don't bother with path reserving. */
    01868   if (v->u.rail.track & TRACK_BIT_DEPOT) {
    01869     /* Can't be stuck here as inside a depot is always a safe tile. */
    01870     if (HasBit(v->u.rail.flags, VRF_TRAIN_STUCK)) InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
    01871     ClrBit(v->u.rail.flags, VRF_TRAIN_STUCK);
    01872     return;
    01873   }
    01874
    01875   /* TrainExitDir does not always produce the desired dir for depots and
    01876    * tunnels/bridges that is needed for UpdateSignalsOnSegment. */
    01877   DiagDirection dir = TrainExitDir(v->direction, v->u.rail.track);
    01878   if (IsRailDepotTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE)) dir = INVALID_DIAGDIR;
    01879
    01880   if (UpdateSignalsOnSegment(v->tile, dir, v->owner) == SIGSEG_PBS || _settings_game.pf.reserve_paths) {
    01881     /* If we are currently on a tile with conventional signals, we can't treat the
    01882      * current tile as a safe tile or we would enter a PBS block without a reservation. */
    01883     bool first_tile_okay = !(IsTileType(v->tile, MP_RAILWAY) &&
    01884       HasSignalOnTrackdir(v->tile, GetVehicleTrackdir(v)) &&
    01885       !IsPbsSignal(GetSignalType(v->tile, FindFirstTrack(v->u.rail.track))));
    01886
    01887     if (IsRailwayStationTile(v->tile)) SetRailwayStationPlatformReservation(v->tile, TrackdirToExitdir(GetVehicleTrackdir(v)), true);
    01888     if (TryPathReserve(v, false, first_tile_okay)) {
    01889       /* Do a look-ahead now in case our current tile was already a safe tile. */
    01890       CheckNextTrainTile(v);
    01891     } else if (v->current_order.GetType() != OT_LOADING) {
    01892       /* Do not wait for a way out when we're still loading */
    01893       MarkTrainAsStuck(v);
    01894     }
    01895   } else if (HasBit(v->u.rail.flags, VRF_TRAIN_STUCK)) {
    01896     /* A train not inside a PBS block can't be stuck. */
    01897     ClrBit(v->u.rail.flags, VRF_TRAIN_STUCK);
    01898     v->load_unload_time_rem = 0;
    01899   }
    01900 }
    01901
    01908 CommandCost CmdReverseTrainDirection(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    01909 {
    01910   if (!IsValidVehicleID(p1)) return CMD_ERROR;
    01911
    01912   Vehicle *v = GetVehicle(p1);
    01913
    01914   if (v->type != VEH_TRAIN || !CheckOwnership(v->owner)) return CMD_ERROR;
    01915
    01916   if (p2 != 0) {
    01917     /* turn a single unit around */
    01918
    01919     if (IsMultiheaded(v) || HasBit(EngInfo(v->engine_type)->callbackmask, CBM_VEHICLE_ARTIC_ENGINE)) {
    01920       return_cmd_error(STR_ONLY_TURN_SINGLE_UNIT);
    01921     }
    01922
    01923     Vehicle *front = v->First();
    01924     /* make sure the vehicle is stopped in the depot */
    01925     if (CheckTrainStoppedInDepot(front) < 0) {
    01926       return_cmd_error(STR_881A_TRAINS_CAN_ONLY_BE_ALTERED);
    01927     }
    01928
    01929     if (flags & DC_EXEC) {
    01930       ToggleBit(v->u.rail.flags, VRF_REVERSE_DIRECTION);
    01931       InvalidateWindow(WC_VEHICLE_DEPOT, v->tile);
    01932       InvalidateWindow(WC_VEHICLE_DETAILS, v->index);
    01933     }
    01934   } else {
    01935     /* turn the whole train around */
    01936     if (v->vehstatus & VS_CRASHED || v->breakdown_ctr != 0) return CMD_ERROR;
    01937
    01938     if (flags & DC_EXEC) {
    01939       /* Properly leave the station if we are loading and won't be loading anymore */
    01940       if (v->current_order.IsType(OT_LOADING)) {
    01941         const Vehicle *last = v;
    01942         while (last->Next() != NULL) last = last->Next();
    01943
    01944         /* not a station || different station --> leave the station */
    01945         if (!IsTileType(last->tile, MP_STATION) || GetStationIndex(last->tile) != GetStationIndex(v->tile)) {
    01946           v->LeaveStation();
    01947         }
    01948       }
    01949
    01950       if (_settings_game.vehicle.train_acceleration_model != TAM_ORIGINAL && v->cur_speed != 0) {
    01951         ToggleBit(v->u.rail.flags, VRF_REVERSING);
    01952       } else {
    01953         v->cur_speed = 0;
    01954         SetLastSpeed(v, 0);
    01955         HideFillingPercent(&v->fill_percent_te_id);
    01956         ReverseTrainDirection(v);
    01957       }
    01958     }
    01959   }
    01960   return CommandCost();
    01961 }
    01962
    01969 CommandCost CmdForceTrainProceed(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    01970 {
    01971   if (!IsValidVehicleID(p1)) return CMD_ERROR;
    01972
    01973   Vehicle *v = GetVehicle(p1);
    01974
    01975   if (v->type != VEH_TRAIN || !CheckOwnership(v->owner)) return CMD_ERROR;
    01976
    01977   if (flags & DC_EXEC) v->u.rail.force_proceed = 0x50;
    01978
    01979   return CommandCost();
    01980 }
    01981
    01992 CommandCost CmdRefitRailVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    01993 {
    01994   CargoID new_cid = GB(p2, 0, 8);
    01995   byte new_subtype = GB(p2, 8, 8);
    01996   bool only_this = HasBit(p2, 16);
    01997
    01998   if (!IsValidVehicleID(p1)) return CMD_ERROR;
    01999
    02000   Vehicle *v = GetVehicle(p1);
    02001
    02002   if (v->type != VEH_TRAIN || !CheckOwnership(v->owner)) return CMD_ERROR;
    02003   if (CheckTrainStoppedInDepot(v) < 0) return_cmd_error(STR_TRAIN_MUST_BE_STOPPED);
    02004   if (v->vehstatus & VS_CRASHED) return_cmd_error(STR_CAN_T_REFIT_DESTROYED_VEHICLE);
    02005
    02006   /* Check cargo */
    02007   if (new_cid >= NUM_CARGO) return CMD_ERROR;
    02008
    02009   CommandCost cost(EXPENSES_TRAIN_RUN);
    02010   uint num = 0;
    02011
    02012   do {
    02013     /* XXX: We also refit all the attached wagons en-masse if they
    02014      * can be refitted. This is how TTDPatch does it.  TODO: Have
    02015      * some nice [Refit] button near each wagon. --pasky */
    02016     if (!CanRefitTo(v->engine_type, new_cid)) continue;
    02017
    02018     if (v->cargo_cap != 0) {
    02019       uint16 amount = CALLBACK_FAILED;
    02020
    02021       if (HasBit(EngInfo(v->engine_type)->callbackmask, CBM_VEHICLE_REFIT_CAPACITY)) {
    02022         /* Back up the vehicle's cargo type */
    02023         CargoID temp_cid = v->cargo_type;
    02024         byte temp_subtype = v->cargo_subtype;
    02025         v->cargo_type = new_cid;
    02026         v->cargo_subtype = new_subtype;
    02027         /* Check the refit capacity callback */
    02028         amount = GetVehicleCallback(CBID_VEHICLE_REFIT_CAPACITY, 0, 0, v->engine_type, v);
    02029         /* Restore the original cargo type */
    02030         v->cargo_type = temp_cid;
    02031         v->cargo_subtype = temp_subtype;
    02032       }
    02033
    02034       if (amount == CALLBACK_FAILED) { // callback failed or not used, use default
    02035         const RailVehicleInfo *rvi = RailVehInfo(v->engine_type);
    02036         CargoID old_cid = rvi->cargo_type;
    02037         /* normally, the capacity depends on the cargo type, a rail vehicle can
    02038          * carry twice as much mail/goods as normal cargo, and four times as
    02039          * many passengers
    02040          */
    02041         amount = rvi->capacity;
    02042         switch (old_cid) {
    02043           case CT_PASSENGERS: break;
    02044           case CT_MAIL:
    02045           case CT_GOODS: amount *= 2; break;
    02046           default:       amount *= 4; break;
    02047         }
    02048         switch (new_cid) {
    02049           case CT_PASSENGERS: break;
    02050           case CT_MAIL:
    02051           case CT_GOODS: amount /= 2; break;
    02052           default:       amount /= 4; break;
    02053         }
    02054       }
    02055
    02056       if (new_cid != v->cargo_type) {
    02057         cost.AddCost(GetRefitCost(v->engine_type));
    02058       }
    02059
    02060       num += amount;
    02061       if (flags & DC_EXEC) {
    02062         v->cargo.Truncate((v->cargo_type == new_cid) ? amount : 0);
    02063         v->cargo_type = new_cid;
    02064         v->cargo_cap = amount;
    02065         v->cargo_subtype = new_subtype;
    02066         InvalidateWindow(WC_VEHICLE_DETAILS, v->index);
    02067         InvalidateWindow(WC_VEHICLE_DEPOT, v->tile);
    02068         InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
    02069       }
    02070     }
    02071   } while ((v = v->Next()) != NULL && !only_this);
    02072
    02073   _returned_refit_capacity = num;
    02074
    02075   /* Update the train's cached variables */
    02076   if (flags & DC_EXEC) TrainConsistChanged(GetVehicle(p1)->First(), false);
    02077
    02078   return cost;
    02079 }
    02080
    02081 struct TrainFindDepotData {
    02082   uint best_length;
    02083   TileIndex tile;
    02084   Owner owner;
    02089   bool reverse;
    02090 };
    02091
    02092 static bool NtpCallbFindDepot(TileIndex tile, TrainFindDepotData *tfdd, int track, uint length)
    02093 {
    02094   if (IsTileType(tile, MP_RAILWAY) &&
    02095       IsTileOwner(tile, tfdd->owner) &&
    02096       IsRailDepot(tile)) {
    02097     /* approximate number of tiles by dividing by DIAG_FACTOR */
    02098     tfdd->best_length = length / DIAG_FACTOR;
    02099     tfdd->tile = tile;
    02100     return true;
    02101   }
    02102
    02103   return false;
    02104 }
    02105
    02108 static TrainFindDepotData FindClosestTrainDepot(Vehicle *v, int max_distance)
    02109 {
    02110   assert(!(v->vehstatus & VS_CRASHED));
    02111
    02112   TrainFindDepotData tfdd;
    02113   tfdd.owner = v->owner;
    02114   tfdd.reverse = false;
    02115
    02116   if (IsRailDepotTile(v->tile)) {
    02117     tfdd.tile = v->tile;
    02118     tfdd.best_length = 0;
    02119     return tfdd;
    02120   }
    02121
    02122   PBSTileInfo origin = FollowTrainReservation(v);
    02123   if (IsRailDepotTile(origin.tile)) {
    02124     tfdd.tile = origin.tile;
    02125     tfdd.best_length = 0;
    02126     return tfdd;
    02127   }
    02128
    02129   tfdd.best_length = UINT_MAX;
    02130
    02131   uint8 pathfinder = _settings_game.pf.pathfinder_for_trains;
    02132   if ((_settings_game.pf.reserve_paths || HasReservedTracks(v->tile, v->u.rail.track)) && pathfinder == VPF_NTP) pathfinder = VPF_NPF;
    02133
    02134   switch (pathfinder) {
    02135     case VPF_YAPF: { /* YAPF */
    02136       bool found = YapfFindNearestRailDepotTwoWay(v, max_distance, NPF_INFINITE_PENALTY, &tfdd.tile, &tfdd.reverse);
    02137       tfdd.best_length = found ? max_distance / 2 : UINT_MAX; // some fake distance or NOT_FOUND
    02138     } break;
    02139
    02140     case VPF_NPF: { /* NPF */
    02141       const Vehicle *last = GetLastVehicleInChain(v);
    02142       Trackdir trackdir = GetVehicleTrackdir(v);
    02143       Trackdir trackdir_rev = ReverseTrackdir(GetVehicleTrackdir(last));
    02144
    02145       assert(trackdir != INVALID_TRACKDIR);
    02146       NPFFoundTargetData ftd = NPFRouteToDepotBreadthFirstTwoWay(v->tile, trackdir, false, last->tile, trackdir_rev, false, TRANSPORT_RAIL, 0, v->owner, v->u.rail.compatible_railtypes, NPF_INFINITE_PENALTY);
    02147       if (ftd.best_bird_dist == 0) {
    02148         /* Found target */
    02149         tfdd.tile = ftd.node.tile;
    02150         /* Our caller expects a number of tiles, so we just approximate that
    02151          * number by this. It might not be completely what we want, but it will
    02152          * work for now :-) We can possibly change this when the old pathfinder
    02153          * is removed. */
    02154         tfdd.best_length = ftd.best_path_dist / NPF_TILE_LENGTH;
    02155         if (NPFGetFlag(&ftd.node, NPF_FLAG_REVERSE)) tfdd.reverse = true;
    02156       }
    02157     } break;
    02158
    02159     default:
    02160     case VPF_NTP: { /* NTP */
    02161       /* search in the forward direction first. */
    02162       DiagDirection i = TrainExitDir(v->direction, v->u.rail.track);
    02163       NewTrainPathfind(v->tile, 0, v->u.rail.compatible_railtypes, i, (NTPEnumProc*)NtpCallbFindDepot, &tfdd);
    02164       if (tfdd.best_length == UINT_MAX){
    02165         tfdd.reverse = true;
    02166         /* search in backwards direction */
    02167         i = TrainExitDir(ReverseDir(v->direction), v->u.rail.track);
    02168         NewTrainPathfind(v->tile, 0, v->u.rail.compatible_railtypes, i, (NTPEnumProc*)NtpCallbFindDepot, &tfdd);
    02169       }
    02170     } break;
    02171   }
    02172
    02173   return tfdd;
    02174 }
    02175
    02176 bool Train::FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
    02177 {
    02178   TrainFindDepotData tfdd = FindClosestTrainDepot(this, 0);
    02179   if (tfdd.best_length == UINT_MAX) return false;
    02180
    02181   if (location    != NULL) *location    = tfdd.tile;
    02182   if (destination != NULL) *destination = GetDepotByTile(tfdd.tile)->index;
    02183   if (reverse     != NULL) *reverse     = tfdd.reverse;
    02184
    02185   return true;
    02186 }
    02187
    02196 CommandCost CmdSendTrainToDepot(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    02197 {
    02198   if (p2 & DEPOT_MASS_SEND) {
    02199     /* Mass goto depot requested */
    02200     if (!ValidVLWFlags(p2 & VLW_MASK)) return CMD_ERROR;
    02201     return SendAllVehiclesToDepot(VEH_TRAIN, flags, p2 & DEPOT_SERVICE, _current_company, (p2 & VLW_MASK), p1);
    02202   }
    02203
    02204   if (!IsValidVehicleID(p1)) return CMD_ERROR;
    02205
    02206   Vehicle *v = GetVehicle(p1);
    02207
    02208   if (v->type != VEH_TRAIN) return CMD_ERROR;
    02209
    02210   return v->SendToDepot(flags, (DepotCommand)(p2 & DEPOT_COMMAND_MASK));
    02211 }
    02212
    02213
    02214 void OnTick_Train()
    02215 {
    02216   _age_cargo_skip_counter = (_age_cargo_skip_counter == 0) ? 184 : (_age_cargo_skip_counter - 1);
    02217 }
    02218
    02219 static const int8 _vehicle_smoke_pos[8] = {
    02220   1, 1, 1, 0, -1, -1, -1, 0
    02221 };
    02222
    02223 static void HandleLocomotiveSmokeCloud(const Vehicle *v)
    02224 {
    02225   bool sound = false;
    02226
    02227   if (v->vehstatus & VS_TRAIN_SLOWING || v->load_unload_time_rem != 0 || v->cur_speed < 2) {
    02228     return;
    02229   }
    02230
    02231   const Vehicle *u = v;
    02232
    02233   do {
    02234     const RailVehicleInfo *rvi = RailVehInfo(v->engine_type);
    02235     int effect_offset = GB(v->u.rail.cached_vis_effect, 0, 4) - 8;
    02236     byte effect_type = GB(v->u.rail.cached_vis_effect, 4, 2);
    02237     bool disable_effect = HasBit(v->u.rail.cached_vis_effect, 6);
    02238
    02239     /* no smoke? */
    02240     if ((rvi->railveh_type == RAILVEH_WAGON && effect_type == 0) ||
    02241         disable_effect ||
    02242         v->vehstatus & VS_HIDDEN) {
    02243       continue;
    02244     }
    02245
    02246     /* No smoke in depots or tunnels */
    02247     if (IsRailDepotTile(v->tile) || IsTunnelTile(v->tile)) continue;
    02248
    02249     /* No sparks for electric vehicles on nonelectrified tracks */
    02250     if (!HasPowerOnRail(v->u.rail.railtype, GetTileRailType(v->tile))) continue;
    02251
    02252     if (effect_type == 0) {
    02253       /* Use default effect type for engine class. */
    02254       effect_type = rvi->engclass;
    02255     } else {
    02256       effect_type--;
    02257     }
    02258
    02259     int x = _vehicle_smoke_pos[v->direction] * effect_offset;
    02260     int y = _vehicle_smoke_pos[(v->direction + 2) % 8] * effect_offset;
    02261
    02262     if (HasBit(v->u.rail.flags, VRF_REVERSE_DIRECTION)) {
    02263       x = -x;
    02264       y = -y;
    02265     }
    02266
    02267     switch (effect_type) {
    02268       case 0:
    02269         /* steam smoke. */
    02270         if (GB(v->tick_counter, 0, 4) == 0) {
    02271           CreateEffectVehicleRel(v, x, y, 10, EV_STEAM_SMOKE);
    02272           sound = true;
    02273         }
    02274         break;
    02275
    02276       case 1:
    02277         /* diesel smoke */
    02278         if (u->cur_speed <= 40 && Chance16(15, 128)) {
    02279           CreateEffectVehicleRel(v, 0, 0, 10, EV_DIESEL_SMOKE);
    02280           sound = true;
    02281         }
    02282         break;
    02283
    02284       case 2:
    02285         /* blue spark */
    02286         if (GB(v->tick_counter, 0, 2) == 0 && Chance16(1, 45)) {
    02287           CreateEffectVehicleRel(v, 0, 0, 10, EV_ELECTRIC_SPARK);
    02288           sound = true;
    02289         }
    02290         break;
    02291
    02292       default:
    02293         break;
    02294     }
    02295   } while ((v = v->Next()) != NULL);
    02296
    02297   if (sound) PlayVehicleSound(u, VSE_TRAIN_EFFECT);
    02298 }
    02299
    02300 void Train::PlayLeaveStationSound() const
    02301 {
    02302   static const SoundFx sfx[] = {
    02303     SND_04_TRAIN,
    02304     SND_0A_TRAIN_HORN,
    02305     SND_0A_TRAIN_HORN,
    02306     SND_47_MAGLEV_2,
    02307     SND_41_MAGLEV
    02308   };
    02309
    02310   if (PlayVehicleSound(this, VSE_START)) return;
    02311
    02312   EngineID engtype = this->engine_type;
    02313   SndPlayVehicleFx(sfx[RailVehInfo(engtype)->engclass], this);
    02314 }
    02315
    02317 static void CheckNextTrainTile(Vehicle *v)
    02318 {
    02319   /* Don't do any look-ahead if path_backoff_interval is 255. */
    02320   if (_settings_game.pf.path_backoff_interval == 255) return;
    02321
    02322   /* Exit if we reached our destination depot or are inside a depot. */
    02323   if ((v->tile == v->dest_tile && v->current_order.IsType(OT_GOTO_DEPOT)) || v->u.rail.track & TRACK_BIT_DEPOT) return;
    02324   /* Exit if we are on a station tile and are going to stop. */
    02325   if (IsRailwayStationTile(v->tile) && v->current_order.ShouldStopAtStation(v, GetStationIndex(v->tile))) return;
    02326   /* Exit if the current order doesn't have a destination, but the train has orders. */
    02327   if ((v->current_order.IsType(OT_NOTHING) || v->current_order.IsType(OT_LEAVESTATION) || v->current_order.IsType(OT_LOADING)) && v->GetNumOrders() > 0) return;
    02328
    02329   Trackdir td = GetVehicleTrackdir(v);
    02330
    02331   /* On a tile with a red non-pbs signal, don't look ahead. */
    02332   if (IsTileType(v->tile, MP_RAILWAY) && HasSignalOnTrackdir(v->tile, td) &&
    02333       !IsPbsSignal(GetSignalType(v->tile, TrackdirToTrack(td))) &&
    02334       GetSignalStateByTrackdir(v->tile, td) == SIGNAL_STATE_RED) return;
    02335
    02336   CFollowTrackRail ft(v);
    02337   if (!ft.Follow(v->tile, td)) return;
    02338
    02339   if (!HasReservedTracks(ft.m_new_tile, TrackdirBitsToTrackBits(ft.m_new_td_bits))) {
    02340     /* Next tile is not reserved. */
    02341     if (KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE) {
    02342       if (HasPbsSignalOnTrackdir(ft.m_new_tile, FindFirstTrackdir(ft.m_new_td_bits))) {
    02343         /* If the next tile is a PBS signal, try to make a reservation. */
    02344         TrackBits tracks = TrackdirBitsToTrackBits(ft.m_new_td_bits);
    02345         if (_settings_game.pf.pathfinder_for_trains != VPF_NTP && _settings_game.pf.forbid_90_deg) {
    02346           tracks &= ~TrackCrossesTracks(TrackdirToTrack(ft.m_old_td));
    02347         }
    02348         ChooseTrainTrack(v, ft.m_new_tile, ft.m_exitdir, tracks, false, NULL, false);
    02349       }
    02350     }
    02351   }
    02352 }
    02353
    02354 static bool CheckTrainStayInDepot(Vehicle *v)
    02355 {
    02356   /* bail out if not all wagons are in the same depot or not in a depot at all */
    02357   for (const Vehicle *u = v; u != NULL; u = u->Next()) {
    02358     if (u->u.rail.track != TRACK_BIT_DEPOT || u->tile != v->tile) return false;
    02359   }
    02360
    02361   /* if the train got no power, then keep it in the depot */
    02362   if (v->u.rail.cached_power == 0) {
    02363     v->vehstatus |= VS_STOPPED;
    02364     InvalidateWindow(WC_VEHICLE_DEPOT, v->tile);
    02365     return true;
    02366   }
    02367
    02368   SigSegState seg_state;
    02369
    02370   if (v->u.rail.force_proceed == 0) {
    02371     /* force proceed was not pressed */
    02372     if (++v->load_unload_time_rem < 37) {
    02373       InvalidateWindowClasses(WC_TRAINS_LIST);
    02374       return true;
    02375     }
    02376
    02377     v->load_unload_time_rem = 0;
    02378
    02379     seg_state = _settings_game.pf.reserve_paths ? SIGSEG_PBS : UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
    02380     if (seg_state == SIGSEG_FULL || GetDepotWaypointReservation(v->tile)) {
    02381       /* Full and no PBS signal in block or depot reserved, can't exit. */
    02382       InvalidateWindowClasses(WC_TRAINS_LIST);
    02383       return true;
    02384     }
    02385   } else {
    02386     seg_state = _settings_game.pf.reserve_paths ? SIGSEG_PBS : UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
    02387   }
    02388
    02389   /* Only leave when we can reserve a path to our destination. */
    02390   if (seg_state == SIGSEG_PBS && !TryPathReserve(v) && v->u.rail.force_proceed == 0) {
    02391     /* No path and no force proceed. */
    02392     InvalidateWindowClasses(WC_TRAINS_LIST);
    02393     MarkTrainAsStuck(v);
    02394     return true;
    02395   }
    02396
    02397   SetDepotWaypointReservation(v->tile, true);
    02398   if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(v->tile);
    02399
    02400   VehicleServiceInDepot(v);
    02401   InvalidateWindowClasses(WC_TRAINS_LIST);
    02402   v->PlayLeaveStationSound();
    02403
    02404   v->u.rail.track = TRACK_BIT_X;
    02405   if (v->direction & 2) v->u.rail.track = TRACK_BIT_Y;
    02406
    02407   v->vehstatus &= ~VS_HIDDEN;
    02408   v->cur_speed = 0;
    02409
    02410   v->UpdateDeltaXY(v->direction);
    02411   v->cur_image = v->GetImage(v->direction);
    02412   VehiclePositionChanged(v);
    02413   UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
    02414   UpdateTrainAcceleration(v);
    02415   InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
    02416
    02417   return false;
    02418 }
    02419
    02421 static void ClearPathReservation(const Vehicle *v, TileIndex tile, Trackdir track_dir)
    02422 {
    02423   DiagDirection dir = TrackdirToExitdir(track_dir);
    02424
    02425   if (IsTileType(tile, MP_TUNNELBRIDGE)) {
    02426     /* Are we just leaving a tunnel/bridge? */
    02427     if (GetTunnelBridgeDirection(tile) == ReverseDiagDir(dir)) {
    02428       TileIndex end = GetOtherTunnelBridgeEnd(tile);
    02429
    02430       if (!HasVehicleOnTunnelBridge(tile, end, v)) {
    02431         /* Free the reservation only if no other train is on the tiles. */
    02432         SetTunnelBridgeReservation(tile, false);
    02433         SetTunnelBridgeReservation(end, false);
    02434
    02435         if (_settings_client.gui.show_track_reservation) {
    02436           MarkTileDirtyByTile(tile);
    02437           MarkTileDirtyByTile(end);
    02438         }
    02439       }
    02440     }
    02441   } else if (IsRailwayStationTile(tile)) {
    02442     TileIndex new_tile = TileAddByDiagDir(tile, dir);
    02443     /* If the new tile is not a further tile of the same station, we
    02444      * clear the reservation for the whole platform. */
    02445     if (!IsCompatibleTrainStationTile(new_tile, tile)) {
    02446       SetRailwayStationPlatformReservation(tile, ReverseDiagDir(dir), false);
    02447     }
    02448   } else {
    02449     /* Any other tile */
    02450     UnreserveRailTrack(tile, TrackdirToTrack(track_dir));
    02451   }
    02452 }
    02453
    02455 void FreeTrainTrackReservation(const Vehicle *v, TileIndex origin, Trackdir orig_td)
    02456 {
    02457   assert(IsFrontEngine(v));
    02458
    02459   TileIndex tile = origin != INVALID_TILE ? origin : v->tile;
    02460   Trackdir  td = orig_td != INVALID_TRACKDIR ? orig_td : GetVehicleTrackdir(v);
    02461   bool      free_tile = tile != v->tile || !(IsRailwayStationTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE));
    02462   StationID station_id = IsRailwayStationTile(v->tile) ? GetStationIndex(v->tile) : INVALID_STATION;
    02463
    02464   /* Don't free reservation if it's not ours. */
    02465   if (TracksOverlap(GetReservedTrackbits(tile) | TrackToTrackBits(TrackdirToTrack(td)))) return;
    02466
    02467   CFollowTrackRail ft(v, GetRailTypeInfo(v->u.rail.railtype)->compatible_railtypes);
    02468   while (ft.Follow(tile, td)) {
    02469     tile = ft.m_new_tile;
    02470     TrackdirBits bits = ft.m_new_td_bits & TrackBitsToTrackdirBits(GetReservedTrackbits(tile));
    02471     td = RemoveFirstTrackdir(&bits);
    02472     assert(bits == TRACKDIR_BIT_NONE);
    02473
    02474     if (!IsValidTrackdir(td)) break;
    02475
    02476     if (IsTileType(tile, MP_RAILWAY)) {
    02477       if (HasSignalOnTrackdir(tile, td) && !IsPbsSignal(GetSignalType(tile, TrackdirToTrack(td)))) {
    02478         /* Conventional signal along trackdir: remove reservation and stop. */
    02479         UnreserveRailTrack(tile, TrackdirToTrack(td));
    02480         break;
    02481       }
    02482       if (HasPbsSignalOnTrackdir(tile, td)) {
    02483         if (GetSignalStateByTrackdir(tile, td) == SIGNAL_STATE_RED) {
    02484           /* Red PBS signal? Can't be our reservation, would be green then. */
    02485           break;
    02486         } else {
    02487           /* Turn the signal back to red. */
    02488           SetSignalStateByTrackdir(tile, td, SIGNAL_STATE_RED);
    02489           MarkTileDirtyByTile(tile);
    02490         }
    02491       } else if (HasSignalOnTrackdir(tile, ReverseTrackdir(td)) && IsOnewaySignal(tile, TrackdirToTrack(td))) {
    02492         break;
    02493       }
    02494     }
    02495
    02496     /* Don't free first station/bridge/tunnel if we are on it. */
    02497     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);
    02498
    02499     free_tile = true;
    02500   }
    02501 }
    02502
    02504 struct TrainTrackFollowerData {
    02505   TileIndex dest_coords;
    02506   StationID station_index;
    02507   uint best_bird_dist;
    02508   uint best_track_dist;
    02509   TrackdirByte best_track;
    02510 };
    02511
    02512 static bool NtpCallbFindStation(TileIndex tile, TrainTrackFollowerData *ttfd, Trackdir track, uint length)
    02513 {
    02514   /* heading for nowhere? */
    02515   if (ttfd->dest_coords == 0) return false;
    02516
    02517   /* did we reach the final station? */
    02518   if ((ttfd->station_index == INVALID_STATION && tile == ttfd->dest_coords) || (
    02519         IsTileType(tile, MP_STATION) &&
    02520         IsRailwayStation(tile) &&
    02521         GetStationIndex(tile) == ttfd->station_index
    02522       )) {
    02523     /* We do not check for dest_coords if we have a station_index,
    02524      * because in that case the dest_coords are just an
    02525      * approximation of where the station is */
    02526
    02527     /* found station */
    02528     ttfd->best_track = track;
    02529     ttfd->best_bird_dist = 0;
    02530     return true;
    02531   } else {
    02532     /* didn't find station, keep track of the best path so far. */
    02533     uint dist = DistanceManhattan(tile, ttfd->dest_coords);
    02534     if (dist < ttfd->best_bird_dist) {
    02535       ttfd->best_bird_dist = dist;
    02536       ttfd->best_track = track;
    02537     }
    02538     return false;
    02539   }
    02540 }
    02541
    02542 static void FillWithStationData(TrainTrackFollowerData *fd, const Vehicle *v)
    02543 {
    02544   fd->dest_coords = v->dest_tile;
    02545   fd->station_index = v->current_order.IsType(OT_GOTO_STATION) ? v->current_order.GetDestination() : INVALID_STATION;
    02546 }
    02547
    02548 static const byte _initial_tile_subcoord[6][4][3] = {
    02549 {{ 15, 8, 1 }, { 0, 0, 0 }, { 0, 8, 5 }, { 0,  0, 0 }},
    02550 {{  0, 0, 0 }, { 8, 0, 3 }, { 0, 0, 0 }, { 8, 15, 7 }},
    02551 {{  0, 0, 0 }, { 7, 0, 2 }, { 0, 7, 6 }, { 0,  0, 0 }},
    02552 {{ 15, 8, 2 }, { 0, 0, 0 }, { 0, 0, 0 }, { 8, 15, 6 }},
    02553 {{ 15, 7, 0 }, { 8, 0, 4 }, { 0, 0, 0 }, { 0,  0, 0 }},
    02554 {{  0, 0, 0 }, { 0, 0, 0 }, { 0, 8, 4 }, { 7, 15, 0 }},
    02555 };
    02556
    02557 static const byte _search_directions[6][4] = {
    02558   { 0, 9, 2, 9 },
    02559   { 9, 1, 9, 3 },
    02560   { 9, 0, 3, 9 },
    02561   { 1, 9, 9, 2 },
    02562   { 3, 2, 9, 9 },
    02563   { 9, 9, 1, 0 },
    02564 };
    02565
    02566 static const byte _pick_track_table[6] = {1, 3, 2, 2, 0, 0};
    02567
    02580 static Track DoTrainPathfind(Vehicle *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool *path_not_found, bool do_track_reservation, PBSTileInfo *dest)
    02581 {
    02582   Track best_track;
    02583
    02584 #ifdef PF_BENCHMARK
    02585   TIC()
    02586 #endif
    02587
    02588   if (path_not_found) *path_not_found = false;
    02589
    02590   uint8 pathfinder = _settings_game.pf.pathfinder_for_trains;
    02591   if (do_track_reservation && pathfinder == VPF_NTP) pathfinder = VPF_NPF;
    02592
    02593   switch (pathfinder) {
    02594     case VPF_YAPF: { /* YAPF */
    02595       Trackdir trackdir = YapfChooseRailTrack(v, tile, enterdir, tracks, path_not_found, do_track_reservation, dest);
    02596       if (trackdir != INVALID_TRACKDIR) {
    02597         best_track = TrackdirToTrack(trackdir);
    02598       } else {
    02599         best_track = FindFirstTrack(tracks);
    02600       }
    02601     } break;
    02602
    02603     case VPF_NPF: { /* NPF */
    02604       void *perf = NpfBeginInterval();
    02605
    02606       NPFFindStationOrTileData fstd;
    02607       NPFFillWithOrderData(&fstd, v, do_track_reservation);
    02608
    02609       PBSTileInfo origin = FollowTrainReservation(v);
    02610       assert(IsValidTrackdir(origin.trackdir));
    02611
    02612       NPFFoundTargetData ftd = NPFRouteToStationOrTile(origin.tile, origin.trackdir, true, &fstd, TRANSPORT_RAIL, 0, v->owner, v->u.rail.compatible_railtypes);
    02613
    02614       if (dest != NULL) {
    02615         dest->tile = ftd.node.tile;
    02616         dest->trackdir = (Trackdir)ftd.node.direction;
    02617         dest->okay = ftd.res_okay;
    02618       }
    02619
    02620       if (ftd.best_trackdir == INVALID_TRACKDIR) {
    02621         /* We are already at our target. Just do something
    02622          * @todo maybe display error?
    02623          * @todo: go straight ahead if possible? */
    02624         best_track = FindFirstTrack(tracks);
    02625       } else {
    02626         /* If ftd.best_bird_dist is 0, we found our target and ftd.best_trackdir contains
    02627          * the direction we need to take to get there, if ftd.best_bird_dist is not 0,
    02628          * we did not find our target, but ftd.best_trackdir contains the direction leading
    02629          * to the tile closest to our target. */
    02630         if (ftd.best_bird_dist != 0 && path_not_found != NULL) *path_not_found = true;
    02631         /* Discard enterdir information, making it a normal track */
    02632         best_track = TrackdirToTrack(ftd.best_trackdir);
    02633       }
    02634
    02635       int time = NpfEndInterval(perf);
    02636       DEBUG(yapf, 4, "[NPFT] %d us - %d rounds - %d open - %d closed -- ", time, 0, _aystar_stats_open_size, _aystar_stats_closed_size);
    02637     } break;
    02638
    02639     default:
    02640     case VPF_NTP: { /* NTP */
    02641       void *perf = NpfBeginInterval();
    02642
    02643       TrainTrackFollowerData fd;
    02644       FillWithStationData(&fd, v);
    02645
    02646       /* New train pathfinding */
    02647       fd.best_bird_dist = UINT_MAX;
    02648       fd.best_track_dist = UINT_MAX;
    02649       fd.best_track = INVALID_TRACKDIR;
    02650
    02651       NewTrainPathfind(tile - TileOffsByDiagDir(enterdir), v->dest_tile,
    02652         v->u.rail.compatible_railtypes, enterdir, (NTPEnumProc*)NtpCallbFindStation, &fd);
    02653
    02654       /* check whether the path was found or only 'guessed' */
    02655       if (fd.best_bird_dist != 0 && path_not_found != NULL) *path_not_found = true;
    02656
    02657       if (fd.best_track == INVALID_TRACKDIR) {
    02658         /* blaha */
    02659         best_track = FindFirstTrack(tracks);
    02660       } else {
    02661         best_track = TrackdirToTrack(fd.best_track);
    02662       }
    02663
    02664       int time = NpfEndInterval(perf);
    02665       DEBUG(yapf, 4, "[NTPT] %d us - %d rounds - %d open - %d closed -- ", time, 0, 0, 0);
    02666     } break;
    02667   }
    02668
    02669 #ifdef PF_BENCHMARK
    02670   TOC("PF time = ", 1)
    02671 #endif
    02672
    02673   return best_track;
    02674 }
    02675
    02681 static PBSTileInfo ExtendTrainReservation(const Vehicle *v, TrackBits *new_tracks, DiagDirection *enterdir)
    02682 {
    02683   bool no_90deg_turns = _settings_game.pf.pathfinder_for_trains != VPF_NTP && _settings_game.pf.forbid_90_deg;
    02684   PBSTileInfo origin = FollowTrainReservation(v);
    02685
    02686   CFollowTrackRail ft(v);
    02687
    02688   TileIndex tile = origin.tile;
    02689   Trackdir  cur_td = origin.trackdir;
    02690   while (ft.Follow(tile, cur_td)) {
    02691     if (KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE) {
    02692       /* Possible signal tile. */
    02693       if (HasOnewaySignalBlockingTrackdir(ft.m_new_tile, FindFirstTrackdir(ft.m_new_td_bits))) break;
    02694     }
    02695
    02696     if (no_90deg_turns) {
    02697       ft.m_new_td_bits &= ~TrackdirCrossesTrackdirs(ft.m_old_td);
    02698       if (ft.m_new_td_bits == TRACKDIR_BIT_NONE) break;
    02699     }
    02700
    02701     /* Station, depot or waypoint are a possible target. */
    02702     bool target_seen = ft.m_is_station || (IsTileType(ft.m_new_tile, MP_RAILWAY) && !IsPlainRailTile(ft.m_new_tile));
    02703     if (target_seen || KillFirstBit(ft.m_new_td_bits) != TRACKDIR_BIT_NONE) {
    02704       /* Choice found or possible target encountered.
    02705        * On finding a possible target, we need to stop and let the pathfinder handle the
    02706        * remaining path. This is because we don't know if this target is in one of our
    02707        * orders, so we might cause pathfinding to fail later on if we find a choice.
    02708        * This failure would cause a bogous call to TryReserveSafePath which might reserve
    02709        * a wrong path not leading to our next destination. */
    02710       if (HasReservedTracks(ft.m_new_tile, TrackdirBitsToTrackBits(TrackdirReachesTrackdirs(ft.m_old_td)))) break;
    02711
    02712       /* If we did skip some tiles, backtrack to the first skipped tile so the pathfinder
    02713        * actually starts its search at the first unreserved tile. */
    02714       if (ft.m_tiles_skipped != 0) ft.m_new_tile -= TileOffsByDiagDir(ft.m_exitdir) * ft.m_tiles_skipped;
    02715
    02716       /* Choice found, path valid but not okay. Save info about the choice tile as well. */
    02717       if (new_tracks) *new_tracks = TrackdirBitsToTrackBits(ft.m_new_td_bits);
    02718       if (enterdir) *enterdir = ft.m_exitdir;
    02719       return PBSTileInfo(ft.m_new_tile, ft.m_old_td, false);
    02720     }
    02721
    02722     tile = ft.m_new_tile;
    02723     cur_td = FindFirstTrackdir(ft.m_new_td_bits);
    02724
    02725     if (IsSafeWaitingPosition(v, tile, cur_td, true, no_90deg_turns)) {
    02726       bool wp_free = IsWaitingPositionFree(v, tile, cur_td, no_90deg_turns);
    02727       if (!(wp_free && TryReserveRailTrack(tile, TrackdirToTrack(cur_td)))) break;
    02728       /* Safe position is all good, path valid and okay. */
    02729       return PBSTileInfo(tile, cur_td, true);
    02730     }
    02731
    02732     if (!TryReserveRailTrack(tile, TrackdirToTrack(cur_td))) break;
    02733   }
    02734
    02735   if (ft.m_err == CFollowTrackRail::EC_OWNER || ft.m_err == CFollowTrackRail::EC_NO_WAY) {
    02736     /* End of line, path valid and okay. */
    02737     return PBSTileInfo(ft.m_old_tile, ft.m_old_td, true);
    02738   }
    02739
    02740   /* Sorry, can't reserve path, back out. */
    02741   tile = origin.tile;
    02742   cur_td = origin.trackdir;
    02743   TileIndex stopped = ft.m_old_tile;
    02744   Trackdir  stopped_td = ft.m_old_td;
    02745   while (tile != stopped || cur_td != stopped_td) {
    02746     if (!ft.Follow(tile, cur_td)) break;
    02747
    02748     if (no_90deg_turns) {
    02749       ft.m_new_td_bits &= ~TrackdirCrossesTrackdirs(ft.m_old_td);
    02750       assert(ft.m_new_td_bits != TRACKDIR_BIT_NONE);
    02751     }
    02752     assert(KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE);
    02753
    02754     tile = ft.m_new_tile;
    02755     cur_td = FindFirstTrackdir(ft.m_new_td_bits);
    02756
    02757     UnreserveRailTrack(tile, TrackdirToTrack(cur_td));
    02758   }
    02759
    02760   /* Path invalid. */
    02761   return PBSTileInfo();
    02762 }
    02763
    02774 static bool TryReserveSafeTrack(const Vehicle *v, TileIndex tile, Trackdir td, bool override_tailtype)
    02775 {
    02776   if (_settings_game.pf.pathfinder_for_trains == VPF_YAPF) {
    02777     return YapfRailFindNearestSafeTile(v, tile, td, override_tailtype);
    02778   } else {
    02779     return NPFRouteToSafeTile(v, tile, td, override_tailtype).res_okay;
    02780   }
    02781 }
    02782
    02784 class VehicleOrderSaver
    02785 {
    02786 private:
    02787   Vehicle        *v;
    02788   Order          old_order;
    02789   TileIndex      old_dest_tile;
    02790   StationID      old_last_station_visited;
    02791   VehicleOrderID index;
    02792
    02793 public:
    02794   VehicleOrderSaver(Vehicle *_v) :
    02795     v(_v),
    02796     old_order(_v->current_order),
    02797     old_dest_tile(_v->dest_tile),
    02798     old_last_station_visited(_v->last_station_visited),
    02799     index(_v->cur_order_index)
    02800   {
    02801   }
    02802
    02803   ~VehicleOrderSaver()
    02804   {
    02805     this->v->current_order = this->old_order;
    02806     this->v->dest_tile = this->old_dest_tile;
    02807     this->v->last_station_visited = this->old_last_station_visited;
    02808   }
    02809
    02815   bool SwitchToNextOrder(bool skip_first)
    02816   {
    02817     if (this->v->GetNumOrders() == 0) return false;
    02818
    02819     if (skip_first) ++this->index;
    02820
    02821     int conditional_depth = 0;
    02822
    02823     do {
    02824       /* Wrap around. */
    02825       if (this->index >= this->v->GetNumOrders()) this->index = 0;
    02826
    02827       Order *order = GetVehicleOrder(this->v, this->index);
    02828       assert(order != NULL);
    02829
    02830       switch (order->GetType()) {
    02831         case OT_GOTO_DEPOT:
    02832           /* Skip service in depot orders when the train doesn't need service. */
    02833           if ((order->GetDepotOrderType() & ODTFB_SERVICE) && !this->v->NeedsServicing()) break;
    02834         case OT_GOTO_STATION:
    02835         case OT_GOTO_WAYPOINT:
    02836           this->v->current_order = *order;
    02837           UpdateOrderDest(this->v, order);
    02838           return true;
    02839         case OT_CONDITIONAL: {
    02840           if (conditional_depth > this->v->GetNumOrders()) return false;
    02841           VehicleOrderID next = ProcessConditionalOrder(order, this->v);
    02842           if (next != INVALID_VEH_ORDER_ID) {
    02843             conditional_depth++;
    02844             this->index = next;
    02845             /* Don't increment next, so no break here. */
    02846             continue;
    02847           }
    02848           break;
    02849         }
    02850         default:
    02851           break;
    02852       }
    02853       /* Don't increment inside the while because otherwise conditional
    02854        * orders can lead to an infinite loop. */
    02855       ++this->index;
    02856     } while (this->index != this->v->cur_order_index);
    02857
    02858     return false;
    02859   }
    02860 };
    02861
    02862 /* choose a track */
    02863 static Track ChooseTrainTrack(Vehicle *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool force_res, bool *got_reservation, bool mark_stuck)
    02864 {
    02865   Track best_track = INVALID_TRACK;
    02866   bool do_track_reservation = _settings_game.pf.reserve_paths || force_res;
    02867   bool changed_signal = false;
    02868
    02869   assert((tracks & ~TRACK_BIT_MASK) == 0);
    02870
    02871   if (got_reservation != NULL) *got_reservation = false;
    02872
    02873   /* Don't use tracks here as the setting to forbid 90 deg turns might have been switched between reservation and now. */
    02874   TrackBits res_tracks = (TrackBits)(GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir));
    02875   /* Do we have a suitable reserved track? */
    02876   if (res_tracks != TRACK_BIT_NONE) return FindFirstTrack(res_tracks);
    02877
    02878   /* Quick return in case only one possible track is available */
    02879   if (KillFirstBit(tracks) == TRACK_BIT_NONE) {
    02880     Track track = FindFirstTrack(tracks);
    02881     /* We need to check for signals only here, as a junction tile can't have signals. */
    02882     if (track != INVALID_TRACK && HasPbsSignalOnTrackdir(tile, TrackEnterdirToTrackdir(track, enterdir))) {
    02883       do_track_reservation = true;
    02884       changed_signal = true;
    02885       SetSignalStateByTrackdir(tile, TrackEnterdirToTrackdir(track, enterdir), SIGNAL_STATE_GREEN);
    02886     } else if (!do_track_reservation) {
    02887       return track;
    02888     }
    02889     best_track = track;
    02890   }
    02891
    02892   PBSTileInfo   res_dest(tile, INVALID_TRACKDIR, false);
    02893   DiagDirection dest_enterdir = enterdir;
    02894   if (do_track_reservation) {
    02895     /* Check if the train needs service here, so it has a chance to always find a depot.
    02896      * Also check if the current order is a service order so we don't reserve a path to
    02897      * the destination but instead to the next one if service isn't needed. */
    02898     CheckIfTrainNeedsService(v);
    02899     if (v->current_order.IsType(OT_DUMMY) || v->current_order.IsType(OT_CONDITIONAL) || v->current_order.IsType(OT_GOTO_DEPOT)) ProcessOrders(v);
    02900
    02901     res_dest = ExtendTrainReservation(v, &tracks, &dest_enterdir);
    02902     if (res_dest.tile == INVALID_TILE) {
    02903       /* Reservation failed? */
    02904       if (mark_stuck) MarkTrainAsStuck(v);
    02905       if (changed_signal) SetSignalStateByTrackdir(tile, TrackEnterdirToTrackdir(best_track, enterdir), SIGNAL_STATE_RED);
    02906       return FindFirstTrack(tracks);
    02907     }
    02908   }
    02909
    02910   /* Save the current train order. The destructor will restore the old order on function exit. */
    02911   VehicleOrderSaver orders(v);
    02912
    02913   /* If the current tile is the destination of the current order and
    02914    * a reservation was requested, advance to the next order.
    02915    * Don't advance on a depot order as depots are always safe end points
    02916    * for a path and no look-ahead is necessary. This also avoids a
    02917    * problem with depot orders not part of the order list when the
    02918    * order list itself is empty. */
    02919   if (v->current_order.IsType(OT_LEAVESTATION)) {
    02920     orders.SwitchToNextOrder(false);
    02921   } else if (v->current_order.IsType(OT_LOADING) || (!v->current_order.IsType(OT_GOTO_DEPOT) && (
    02922       v->current_order.IsType(OT_GOTO_STATION) ?
    02923       IsRailwayStationTile(v->tile) && v->current_order.GetDestination() == GetStationIndex(v->tile) :
    02924       v->tile == v->dest_tile))) {
    02925     orders.SwitchToNextOrder(true);
    02926   }
    02927
    02928   if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
    02929     /* Pathfinders are able to tell that route was only 'guessed'. */
    02930     bool      path_not_found = false;
    02931     TileIndex new_tile = res_dest.tile;
    02932
    02933     Track next_track = DoTrainPathfind(v, new_tile, dest_enterdir, tracks, &path_not_found, do_track_reservation, &res_dest);
    02934     if (new_tile == tile) best_track = next_track;
    02935
    02936     /* handle "path not found" state */
    02937     if (path_not_found) {
    02938       /* PF didn't find the route */
    02939       if (!HasBit(v->u.rail.flags, VRF_NO_PATH_TO_DESTINATION)) {
    02940         /* it is first time the problem occurred, set the "path not found" flag */
    02941         SetBit(v->u.rail.flags, VRF_NO_PATH_TO_DESTINATION);
    02942         /* and notify user about the event */
    02943         AI::NewEvent(v->owner, new AIEventVehicleLost(v->index));
    02944         if (_settings_client.gui.lost_train_warn && v->owner == _local_company) {
    02945           SetDParam(0, v->index);
    02946           AddNewsItem(
    02947             STR_TRAIN_IS_LOST,
    02948             NS_ADVICE,
    02949             v->index,
    02950             0);
    02951         }
    02952       }
    02953     } else {
    02954       /* route found, is the train marked with "path not found" flag? */
    02955       if (HasBit(v->u.rail.flags, VRF_NO_PATH_TO_DESTINATION)) {
    02956         /* clear the flag as the PF's problem was solved */
    02957         ClrBit(v->u.rail.flags, VRF_NO_PATH_TO_DESTINATION);
    02958         /* can we also delete the "News" item somehow? */
    02959       }
    02960     }
    02961   }
    02962
    02963   /* No track reservation requested -> finished. */
    02964   if (!do_track_reservation) return best_track;
    02965
    02966   /* A path was found, but could not be reserved. */
    02967   if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
    02968     if (mark_stuck) MarkTrainAsStuck(v);
    02969     FreeTrainTrackReservation(v);
    02970     return best_track;
    02971   }
    02972
    02973   /* No possible reservation target found, we are probably lost. */
    02974   if (res_dest.tile == INVALID_TILE) {
    02975     /* Try to find any safe destination. */
    02976     PBSTileInfo origin = FollowTrainReservation(v);
    02977     if (TryReserveSafeTrack(v, origin.tile, origin.trackdir, false)) {
    02978       TrackBits res = GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir);
    02979       best_track = FindFirstTrack(res);
    02980       TryReserveRailTrack(v->tile, TrackdirToTrack(GetVehicleTrackdir(v)));
    02981       if (got_reservation != NULL) *got_reservation = true;
    02982       if (changed_signal) MarkTileDirtyByTile(tile);
    02983     } else {
    02984       FreeTrainTrackReservation(v);
    02985       if (mark_stuck) MarkTrainAsStuck(v);
    02986     }
    02987     return best_track;
    02988   }
    02989
    02990   if (got_reservation != NULL) *got_reservation = true;
    02991
    02992   /* Reservation target found and free, check if it is safe. */
    02993   while (!IsSafeWaitingPosition(v, res_dest.tile, res_dest.trackdir, true, _settings_game.pf.forbid_90_deg)) {
    02994     /* Extend reservation until we have found a safe position. */
    02995     DiagDirection exitdir = TrackdirToExitdir(res_dest.trackdir);
    02996     TileIndex     next_tile = TileAddByDiagDir(res_dest.tile, exitdir);
    02997     TrackBits     reachable = TrackdirBitsToTrackBits((TrackdirBits)(GetTileTrackStatus(next_tile, TRANSPORT_RAIL, 0))) & DiagdirReachesTracks(exitdir);
    02998     if (_settings_game.pf.pathfinder_for_trains != VPF_NTP && _settings_game.pf.forbid_90_deg) {
    02999       reachable &= ~TrackCrossesTracks(TrackdirToTrack(res_dest.trackdir));
    03000     }
    03001
    03002     /* Get next order with destination. */
    03003     if (orders.SwitchToNextOrder(true)) {
    03004       PBSTileInfo cur_dest;
    03005       DoTrainPathfind(v, next_tile, exitdir, reachable, NULL, true, &cur_dest);
    03006       if (cur_dest.tile != INVALID_TILE) {
    03007         res_dest = cur_dest;
    03008         if (res_dest.okay) continue;
    03009         /* Path found, but could not be reserved. */
    03010         FreeTrainTrackReservation(v);
    03011         if (mark_stuck) MarkTrainAsStuck(v);
    03012         if (got_reservation != NULL) *got_reservation = false;
    03013         changed_signal = false;
    03014         break;
    03015       }
    03016     }
    03017     /* No order or no safe position found, try any position. */
    03018     if (!TryReserveSafeTrack(v, res_dest.tile, res_dest.trackdir, true)) {
    03019       FreeTrainTrackReservation(v);
    03020       if (mark_stuck) MarkTrainAsStuck(v);
    03021       if (got_reservation != NULL) *got_reservation = false;
    03022       changed_signal = false;
    03023     }
    03024     break;
    03025   }
    03026
    03027   TryReserveRailTrack(v->tile, TrackdirToTrack(GetVehicleTrackdir(v)));
    03028
    03029   if (changed_signal) MarkTileDirtyByTile(tile);
    03030
    03031   return best_track;
    03032 }
    03033
    03042 bool TryPathReserve(Vehicle *v, bool mark_as_stuck, bool first_tile_okay)
    03043 {
    03044   assert(v->type == VEH_TRAIN && IsFrontEngine(v));
    03045
    03046   /* We have to handle depots specially as the track follower won't look
    03047    * at the depot tile itself but starts from the next tile. If we are still
    03048    * inside the depot, a depot reservation can never be ours. */
    03049   if (v->u.rail.track & TRACK_BIT_DEPOT) {
    03050     if (GetDepotWaypointReservation(v->tile)) {
    03051       if (mark_as_stuck) MarkTrainAsStuck(v);
    03052       return false;
    03053     } else {
    03054       /* Depot not reserved, but the next tile might be. */
    03055       TileIndex next_tile = TileAddByDiagDir(v->tile, GetRailDepotDirection(v->tile));
    03056       if (HasReservedTracks(next_tile, DiagdirReachesTracks(GetRailDepotDirection(v->tile)))) return false;
    03057     }
    03058   }
    03059
    03060   /* Special check if we are in front of a two-sided conventional signal. */
    03061   DiagDirection dir = TrainExitDir(v->direction, v->u.rail.track);
    03062   TileIndex next_tile = TileAddByDiagDir(v->tile, dir);
    03063   if (IsTileType(next_tile, MP_RAILWAY) && HasReservedTracks(next_tile, DiagdirReachesTracks(dir))) {
    03064     /* Can have only one reserved trackdir. */
    03065     Trackdir td = FindFirstTrackdir(TrackBitsToTrackdirBits(GetReservedTrackbits(next_tile)) & DiagdirReachesTrackdirs(dir));
    03066     if (HasSignalOnTrackdir(next_tile, td) && HasSignalOnTrackdir(next_tile, ReverseTrackdir(td)) &&
    03067         !IsPbsSignal(GetSignalType(next_tile, TrackdirToTrack(td)))) {
    03068       /* Signal already reserved, is not ours. */
    03069       if (mark_as_stuck) MarkTrainAsStuck(v);
    03070       return false;
    03071     }
    03072   }
    03073
    03074   bool other_train = false;
    03075   PBSTileInfo origin = FollowTrainReservation(v, &other_train);
    03076   /* If we have a reserved path and the path ends at a safe tile, we are finished already. */
    03077   if (origin.okay && (v->tile != origin.tile || first_tile_okay)) {
    03078     /* Can't be stuck then. */
    03079     if (HasBit(v->u.rail.flags, VRF_TRAIN_STUCK)) InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
    03080     ClrBit(v->u.rail.flags, VRF_TRAIN_STUCK);
    03081     return true;
    03082   }
    03083   /* The path we are driving on is alread blocked by some other train.
    03084    * This can only happen when tracks and signals are changed. A crash
    03085    * is probably imminent, don't do any further reservation because
    03086    * it might cause stale reservations. */
    03087   if (other_train && v->tile != origin.tile) {
    03088     if (mark_as_stuck) MarkTrainAsStuck(v);
    03089     return false;
    03090   }
    03091
    03092   /* If we are in a depot, tentativly reserve the depot. */
    03093   if (v->u.rail.track & TRACK_BIT_DEPOT) {
    03094     SetDepotWaypointReservation(v->tile, true);
    03095     if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(v->tile);
    03096   }
    03097
    03098   DiagDirection exitdir = TrackdirToExitdir(origin.trackdir);
    03099   TileIndex     new_tile = TileAddByDiagDir(origin.tile, exitdir);
    03100   TrackBits     reachable = TrackdirBitsToTrackBits(TrackStatusToTrackdirBits(GetTileTrackStatus(new_tile, TRANSPORT_RAIL, 0)) & DiagdirReachesTrackdirs(exitdir));
    03101
    03102   if (_settings_game.pf.pathfinder_for_trains != VPF_NTP && _settings_game.pf.forbid_90_deg) reachable &= ~TrackCrossesTracks(TrackdirToTrack(origin.trackdir));
    03103
    03104   bool res_made = false;
    03105   ChooseTrainTrack(v, new_tile, exitdir, reachable, true, &res_made, mark_as_stuck);
    03106
    03107   if (!res_made) {
    03108     /* Free the depot reservation as well. */
    03109     if (v->u.rail.track & TRACK_BIT_DEPOT) SetDepotWaypointReservation(v->tile, false);
    03110     return false;
    03111   }
    03112
    03113   if (HasBit(v->u.rail.flags, VRF_TRAIN_STUCK)) {
    03114     v->load_unload_time_rem = 0;
    03115     InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
    03116   }
    03117   ClrBit(v->u.rail.flags, VRF_TRAIN_STUCK);
    03118   return true;
    03119 }
    03120
    03121
    03122 static bool CheckReverseTrain(Vehicle *v)
    03123 {
    03124   if (_settings_game.difficulty.line_reverse_mode != 0 ||
    03125       v->u.rail.track == TRACK_BIT_DEPOT || v->u.rail.track == TRACK_BIT_WORMHOLE ||
    03126       !(v->direction & 1)) {
    03127     return false;
    03128   }
    03129
    03130   uint reverse_best = 0;
    03131
    03132   assert(v->u.rail.track);
    03133
    03134   switch (_settings_game.pf.pathfinder_for_trains) {
    03135     case VPF_YAPF: /* YAPF */
    03136       reverse_best = YapfCheckReverseTrain(v);
    03137       break;
    03138
    03139     case VPF_NPF: { /* NPF */
    03140       NPFFindStationOrTileData fstd;
    03141       NPFFoundTargetData ftd;
    03142       Vehicle *last = GetLastVehicleInChain(v);
    03143
    03144       NPFFillWithOrderData(&fstd, v);
    03145
    03146       Trackdir trackdir = GetVehicleTrackdir(v);
    03147       Trackdir trackdir_rev = ReverseTrackdir(GetVehicleTrackdir(last));
    03148       assert(trackdir != INVALID_TRACKDIR);
    03149       assert(trackdir_rev != INVALID_TRACKDIR);
    03150
    03151       ftd = NPFRouteToStationOrTileTwoWay(v->tile, trackdir, false, last->tile, trackdir_rev, false, &fstd, TRANSPORT_RAIL, 0, v->owner, v->u.rail.compatible_railtypes);
    03152       if (ftd.best_bird_dist != 0) {
    03153         /* We didn't find anything, just keep on going straight ahead */
    03154         reverse_best = false;
    03155       } else {
    03156         if (NPFGetFlag(&ftd.node, NPF_FLAG_REVERSE)) {
    03157           reverse_best = true;
    03158         } else {
    03159           reverse_best = false;
    03160         }
    03161       }
    03162     } break;
    03163
    03164     default:
    03165     case VPF_NTP: { /* NTP */
    03166       TrainTrackFollowerData fd;
    03167       FillWithStationData(&fd, v);
    03168
    03169       int i = _search_directions[FindFirstTrack(v->u.rail.track)][DirToDiagDir(v->direction)];
    03170
    03171       int best_track = -1;
    03172       uint reverse = 0;
    03173       uint best_bird_dist  = 0;
    03174       uint best_track_dist = 0;
    03175
    03176       for (;;) {
    03177         fd.best_bird_dist = UINT_MAX;
    03178         fd.best_track_dist = UINT_MAX;
    03179
    03180         NewTrainPathfind(v->tile, v->dest_tile, v->u.rail.compatible_railtypes, (DiagDirection)(reverse ^ i), (NTPEnumProc*)NtpCallbFindStation, &fd);
    03181
    03182         if (best_track != -1) {
    03183           if (best_bird_dist != 0) {
    03184             if (fd.best_bird_dist != 0) {
    03185               /* neither reached the destination, pick the one with the smallest bird dist */
    03186               if (fd.best_bird_dist > best_bird_dist) goto bad;
    03187               if (fd.best_bird_dist < best_bird_dist) goto good;
    03188             } else {
    03189               /* we found the destination for the first time */
    03190               goto good;
    03191             }
    03192           } else {
    03193             if (fd.best_bird_dist != 0) {
    03194               /* didn't find destination, but we've found the destination previously */
    03195               goto bad;
    03196             } else {
    03197               /* both old & new reached the destination, compare track length */
    03198               if (fd.best_track_dist > best_track_dist) goto bad;
    03199               if (fd.best_track_dist < best_track_dist) goto good;
    03200             }
    03201           }
    03202
    03203           /* if we reach this position, there's two paths of equal value so far.
    03204            * pick one randomly. */
    03205           int r = GB(Random(), 0, 8);
    03206           if (_pick_track_table[i] == (v->direction & 3)) r += 80;
    03207           if (_pick_track_table[best_track] == (v->direction & 3)) r -= 80;
    03208           if (r <= 127) goto bad;
    03209         }
    03210 good:;
    03211         best_track = i;
    03212         best_bird_dist = fd.best_bird_dist;
    03213         best_track_dist = fd.best_track_dist;
    03214         reverse_best = reverse;
    03215 bad:;
    03216         if (reverse != 0) break;
    03217         reverse = 2;
    03218       }
    03219     } break;
    03220   }
    03221
    03222   return reverse_best != 0;
    03223 }
    03224
    03225 TileIndex Train::GetOrderStationLocation(StationID station)
    03226 {
    03227   if (station == this->last_station_visited) this->last_station_visited = INVALID_STATION;
    03228
    03229   const Station *st = GetStation(station);
    03230   if (!(st->facilities & FACIL_TRAIN)) {
    03231     /* The destination station has no trainstation tiles. */
    03232     this->cur_order_index++;
    03233     return 0;
    03234   }
    03235
    03236   return st->xy;
    03237 }
    03238
    03239 void Train::MarkDirty()
    03240 {
    03241   Vehicle *v = this;
    03242   do {
    03243     v->cur_image = v->GetImage(v->direction);
    03244     MarkSingleVehicleDirty(v);
    03245   } while ((v = v->Next()) != NULL);
    03246
    03247   /* need to update acceleration and cached values since the goods on the train changed. */
    03248   TrainCargoChanged(this);
    03249   UpdateTrainAcceleration(this);
    03250 }
    03251
    03262 static int UpdateTrainSpeed(Vehicle *v)
    03263 {
    03264   uint accel;
    03265
    03266   if (v->vehstatus & VS_STOPPED || HasBit(v->u.rail.flags, VRF_REVERSING) || HasBit(v->u.rail.flags, VRF_TRAIN_STUCK)) {
    03267     switch (_settings_game.vehicle.train_acceleration_model) {
    03268       default: NOT_REACHED();
    03269       case TAM_ORIGINAL:  accel = v->acceleration * -4; break;
    03270       case TAM_REALISTIC: accel = GetTrainAcceleration(v, AM_BRAKE); break;
    03271     }
    03272   } else {
    03273     switch (_settings_game.vehicle.train_acceleration_model) {
    03274       default: NOT_REACHED();
    03275       case TAM_ORIGINAL:  accel = v->acceleration * 2; break;
    03276       case TAM_REALISTIC: accel = GetTrainAcceleration(v, AM_ACCEL); break;
    03277     }
    03278   }
    03279
    03280   uint spd = v->subspeed + accel;
    03281   v->subspeed = (byte)spd;
    03282   {
    03283     int tempmax = v->max_speed;
    03284     if (v->cur_speed > v->max_speed)
    03285       tempmax = v->cur_speed - (v->cur_speed / 10) - 1;
    03286     v->cur_speed = spd = Clamp(v->cur_speed + ((int)spd >> 8), 0, tempmax);
    03287   }
    03288
    03289   /* Scale speed by 3/4. Previously this was only done when the train was
    03290    * facing diagonally and would apply to however many moves the train made
    03291    * regardless the of direction actually moved in. Now it is always scaled,
    03292    * 256 spd is used to go straight and 192 is used to go diagonally
    03293    * (3/4 of 256). This results in the same effect, but without the error the
    03294    * previous method caused.
    03295    *
    03296    * The scaling is done in this direction and not by multiplying the amount
    03297    * to be subtracted by 4/3 so that the leftover speed can be saved in a
    03298    * byte in v->progress.
    03299    */
    03300   int scaled_spd = spd * 3 >> 2;
    03301
    03302   scaled_spd += v->progress;
    03303   v->progress = 0; // set later in TrainLocoHandler or TrainController
    03304   return scaled_spd;
    03305 }
    03306
    03307 static void TrainEnterStation(Vehicle *v, StationID station)
    03308 {
    03309   v->last_station_visited = station;
    03310
    03311   /* check if a train ever visited this station before */
    03312   Station *st = GetStation(station);
    03313   if (!(st->had_vehicle_of_type & HVOT_TRAIN)) {
    03314     st->had_vehicle_of_type |= HVOT_TRAIN;
    03315     SetDParam(0, st->index);
    03316     AddNewsItem(
    03317       STR_8801_CITIZENS_CELEBRATE_FIRST,
    03318       v->owner == _local_company ? NS_ARRIVAL_COMPANY : NS_ARRIVAL_OTHER,
    03319       v->index,
    03320       st->index
    03321     );
    03322     AI::NewEvent(v->owner, new AIEventStationFirstVehicle(st->index, v->index));
    03323   }
    03324
    03325   v->BeginLoading();
    03326
    03327   StationAnimationTrigger(st, v->tile, STAT_ANIM_TRAIN_ARRIVES);
    03328 }
    03329
    03330 static byte AfterSetTrainPos(Vehicle *v, bool new_tile)
    03331 {
    03332   byte old_z = v->z_pos;
    03333   v->z_pos = GetSlopeZ(v->x_pos, v->y_pos);
    03334
    03335   if (new_tile) {
    03336     ClrBit(v->u.rail.flags, VRF_GOINGUP);
    03337     ClrBit(v->u.rail.flags, VRF_GOINGDOWN);
    03338
    03339     if (v->u.rail.track == TRACK_BIT_X || v->u.rail.track == TRACK_BIT_Y) {
    03340       /* Any track that isn't TRACK_BIT_X or TRACK_BIT_Y cannot be sloped.
    03341        * To check whether the current tile is sloped, and in which
    03342        * direction it is sloped, we get the 'z' at the center of
    03343        * the tile (middle_z) and the edge of the tile (old_z),
    03344        * which we then can compare. */
    03345       static const int HALF_TILE_SIZE = TILE_SIZE / 2;
    03346       static const int INV_TILE_SIZE_MASK = ~(TILE_SIZE - 1);
    03347
    03348       byte middle_z = GetSlopeZ((v->x_pos & INV_TILE_SIZE_MASK) | HALF_TILE_SIZE, (v->y_pos & INV_TILE_SIZE_MASK) | HALF_TILE_SIZE);
    03349
    03350       /* For some reason tunnel tiles are always given as sloped :(
    03351        * But they are not sloped... */
    03352       if (middle_z != v->z_pos && !IsTunnelTile(TileVirtXY(v->x_pos, v->y_pos))) {
    03353         SetBit(v->u.rail.flags, (middle_z > old_z) ? VRF_GOINGUP : VRF_GOINGDOWN);
    03354       }
    03355     }
    03356   }
    03357
    03358   VehiclePositionChanged(v);
    03359   EndVehicleMove(v);
    03360   return old_z;
    03361 }
    03362
    03363 static const Direction _new_vehicle_direction_table[11] = {
    03364   DIR_N , DIR_NW, DIR_W , INVALID_DIR,
    03365   DIR_NE, DIR_N , DIR_SW, INVALID_DIR,
    03366   DIR_E , DIR_SE, DIR_S
    03367 };
    03368
    03369 static inline Direction GetNewVehicleDirectionByTile(TileIndex new_tile, TileIndex old_tile)
    03370 {
    03371   uint offs = (TileY(new_tile) - TileY(old_tile) + 1) * 4 +
    03372               TileX(new_tile) - TileX(old_tile) + 1;
    03373   assert(offs < 11);
    03374   return _new_vehicle_direction_table[offs];
    03375 }
    03376
    03377 static inline int GetDirectionToVehicle(const Vehicle *v, int x, int y)
    03378 {
    03379   byte offs;
    03380
    03381   x -= v->x_pos;
    03382   if (x >= 0) {
    03383     offs = (x > 2) ? 0 : 1;
    03384   } else {
    03385     offs = (x < -2) ? 2 : 1;
    03386   }
    03387
    03388   y -= v->y_pos;
    03389   if (y >= 0) {
    03390     offs += ((y > 2) ? 0 : 1) * 4;
    03391   } else {
    03392     offs += ((y < -2) ? 2 : 1) * 4;
    03393   }
    03394
    03395   assert(offs < 11);
    03396   return _new_vehicle_direction_table[offs];
    03397 }
    03398
    03399 /* Check if the vehicle is compatible with the specified tile */
    03400 static inline bool CheckCompatibleRail(const Vehicle *v, TileIndex tile)
    03401 {
    03402   return
    03403     IsTileOwner(tile, v->owner) && (
    03404       !IsFrontEngine(v) ||
    03405       HasBit(v->u.rail.compatible_railtypes, GetRailType(tile))
    03406     );
    03407 }
    03408
    03409 struct RailtypeSlowdownParams {
    03410   byte small_turn, large_turn;
    03411   byte z_up; // fraction to remove when moving up
    03412   byte z_down; // fraction to remove when moving down
    03413 };
    03414
    03415 static const RailtypeSlowdownParams _railtype_slowdown[] = {
    03416   // normal accel
    03417   {256 / 4, 256 / 2, 256 / 4, 2},
    03418   {256 / 4, 256 / 2, 256 / 4, 2},
    03419   {256 / 4, 256 / 2, 256 / 4, 2},
    03420   {0,       256 / 2, 256 / 4, 2},
    03421 };
    03422
    03424 static inline void AffectSpeedByDirChange(Vehicle *v, Direction new_dir)
    03425 {
    03426   if (_settings_game.vehicle.train_acceleration_model != TAM_ORIGINAL) return;
    03427
    03428   DirDiff diff = DirDifference(v->direction, new_dir);
    03429   if (diff == DIRDIFF_SAME) return;
    03430
    03431   const RailtypeSlowdownParams *rsp = &_railtype_slowdown[v->u.rail.railtype];
    03432   v->cur_speed -= (diff == DIRDIFF_45RIGHT || diff == DIRDIFF_45LEFT ? rsp->small_turn : rsp->large_turn) * v->cur_speed >> 8;
    03433 }
    03434
    03436 static inline void AffectSpeedByZChange(Vehicle *v, byte old_z)
    03437 {
    03438   if (old_z == v->z_pos || _settings_game.vehicle.train_acceleration_model != TAM_ORIGINAL) return;
    03439
    03440   const RailtypeSlowdownParams *rsp = &_railtype_slowdown[v->u.rail.railtype];
    03441
    03442   if (old_z < v->z_pos) {
    03443     v->cur_speed -= (v->cur_speed * rsp->z_up >> 8);
    03444   } else {
    03445     uint16 spd = v->cur_speed + rsp->z_down;
    03446     if (spd <= v->max_speed) v->cur_speed = spd;
    03447   }
    03448 }
    03449
    03450 static bool TrainMovedChangeSignals(TileIndex tile, DiagDirection dir)
    03451 {
    03452   if (IsTileType(tile, MP_RAILWAY) &&
    03453       GetRailTileType(tile) == RAIL_TILE_SIGNALS) {
    03454     TrackdirBits tracks = TrackBitsToTrackdirBits(GetTrackBits(tile)) & DiagdirReachesTrackdirs(dir);
    03455     Trackdir trackdir = FindFirstTrackdir(tracks);
    03456     if (UpdateSignalsOnSegment(tile,  TrackdirToExitdir(trackdir), GetTileOwner(tile)) == SIGSEG_PBS && HasSignalOnTrackdir(tile, trackdir)) {
    03457       /* A PBS block with a non-PBS signal facing us? */
    03458       if (!IsPbsSignal(GetSignalType(tile, TrackdirToTrack(trackdir)))) return true;
    03459     }
    03460   }
    03461   return false;
    03462 }
    03463
    03464
    03465 static void SetVehicleCrashed(Vehicle *v)
    03466 {
    03467   if (v->u.rail.crash_anim_pos != 0) return;
    03468
    03469   /* Free a possible path reservation and try to mark all tiles occupied by the train reserved. */
    03470   if (IsFrontEngine(v)) {
    03471     /* Remove all reservations, also the ones currently under the train
    03472      * and any railway station paltform reservation. */
    03473     FreeTrainTrackReservation(v);
    03474     for (const Vehicle *u = v; u != NULL; u = u->Next()) {
    03475       ClearPathReservation(u, u->tile, GetVehicleTrackdir(u));
    03476       if (IsTileType(u->tile, MP_TUNNELBRIDGE)) {
    03477         /* ClearPathReservation will not free the wormhole exit
    03478          * if the train has just entered the wormhole. */
    03479         SetTunnelBridgeReservation(GetOtherTunnelBridgeEnd(u->tile), false);
    03480       }
    03481     }
    03482   }
    03483
    03484   /* we may need to update crossing we were approaching */
    03485   TileIndex crossing = TrainApproachingCrossingTile(v);
    03486
    03487   v->u.rail.crash_anim_pos++;
    03488
    03489   InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
    03490   InvalidateWindow(WC_VEHICLE_DETAILS, v->index);
    03491
    03492   if (v->u.rail.track == TRACK_BIT_DEPOT) {
    03493     InvalidateWindow(WC_VEHICLE_DEPOT, v->tile);
    03494   }
    03495
    03496   InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
    03497
    03498   for (; v != NULL; v = v->Next()) {
    03499     v->vehstatus |= VS_CRASHED;
    03500     MarkSingleVehicleDirty(v);
    03501   }
    03502
    03503   /* must be updated after the train has been marked crashed */
    03504   if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
    03505 }
    03506
    03507 static uint CountPassengersInTrain(const Vehicle *v)
    03508 {
    03509   uint num = 0;
    03510
    03511   for (; v != NULL; v = v->Next()) {
    03512     if (IsCargoInClass(v->cargo_type, CC_PASSENGERS)) num += v->cargo.Count();
    03513   }
    03514
    03515   return num;
    03516 }
    03517
    03524 static uint TrainCrashed(Vehicle *v)
    03525 {
    03526   /* do not crash train twice */
    03527   if (v->vehstatus & VS_CRASHED) return 0;
    03528
    03529   /* two drivers + passengers */
    03530   uint num = 2 + CountPassengersInTrain(v);
    03531
    03532   SetVehicleCrashed(v);
    03533   AI::NewEvent(v->owner, new AIEventVehicleCrashed(v->index, v->tile, AIEventVehicleCrashed::CRASH_TRAIN));
    03534
    03535   return num;
    03536 }
    03537
    03538 struct TrainCollideChecker {
    03539   Vehicle *v;
    03540   uint num;
    03541 };
    03542
    03543 static Vehicle *FindTrainCollideEnum(Vehicle *v, void *data)
    03544 {
    03545   TrainCollideChecker *tcc = (TrainCollideChecker*)data;
    03546
    03547   if (v->type != VEH_TRAIN) return NULL;
    03548
    03549   /* get first vehicle now to make most usual checks faster */
    03550   Vehicle *coll = v->First();
    03551
    03552   /* can't collide with own wagons && can't crash in depot && the same height level */
    03553   if (coll != tcc->v && v->u.rail.track != TRACK_BIT_DEPOT && abs(v->z_pos - tcc->v->z_pos) < 6) {
    03554     int x_diff = v->x_pos - tcc->v->x_pos;
    03555     int y_diff = v->y_pos - tcc->v->y_pos;
    03556
    03557     /* needed to disable possible crash of competitor train in station by building diagonal track at its end */
    03558     if (x_diff * x_diff + y_diff * y_diff > 25) return NULL;
    03559
    03560     /* crash both trains */
    03561     tcc->num += TrainCrashed(tcc->v);
    03562     tcc->num += TrainCrashed(coll);
    03563
    03564     /* Try to reserve all tiles directly under the crashed trains.
    03565      * As there might be more than two trains involved, we have to do that for all vehicles */
    03566     const Vehicle *u;
    03567     FOR_ALL_VEHICLES(u) {
    03568       if (u->type == VEH_TRAIN && HASBITS(u->vehstatus, VS_CRASHED) && (u->u.rail.track & TRACK_BIT_DEPOT) == TRACK_BIT_NONE) {
    03569         TrackBits trackbits = u->u.rail.track;
    03570         if ((trackbits & TRACK_BIT_WORMHOLE) == TRACK_BIT_WORMHOLE) {
    03571           /* Vehicle is inside a wormhole, v->u.rail.track contains no useful value then. */
    03572           trackbits |= DiagDirToDiagTrackBits(GetTunnelBridgeDirection(u->tile));
    03573         }
    03574         TryReserveRailTrack(u->tile, TrackBitsToTrack(trackbits));
    03575       }
    03576     }
    03577   }
    03578
    03579   return NULL;
    03580 }
    03581
    03588 static bool CheckTrainCollision(Vehicle *v)
    03589 {
    03590   /* can't collide in depot */
    03591   if (v->u.rail.track == TRACK_BIT_DEPOT) return false;
    03592
    03593   assert(v->u.rail.track == TRACK_BIT_WORMHOLE || TileVirtXY(v->x_pos, v->y_pos) == v->tile);
    03594
    03595   TrainCollideChecker tcc;
    03596   tcc.v = v;
    03597   tcc.num = 0;
    03598
    03599   /* find colliding vehicles */
    03600   if (v->u.rail.track == TRACK_BIT_WORMHOLE) {
    03601     FindVehicleOnPos(v->tile, &tcc, FindTrainCollideEnum);
    03602     FindVehicleOnPos(GetOtherTunnelBridgeEnd(v->tile), &tcc, FindTrainCollideEnum);
    03603   } else {
    03604     FindVehicleOnPosXY(v->x_pos, v->y_pos, &tcc, FindTrainCollideEnum);
    03605   }
    03606
    03607   /* any dead -> no crash */
    03608   if (tcc.num == 0) return false;
    03609
    03610   SetDParam(0, tcc.num);
    03611   AddNewsItem(STR_8868_TRAIN_CRASH_DIE_IN_FIREBALL,
    03612     NS_ACCIDENT_VEHICLE,
    03613     v->index,
    03614     0
    03615   );
    03616
    03617   ModifyStationRatingAround(v->tile, v->owner, -160, 30);
    03618   SndPlayVehicleFx(SND_13_BIG_CRASH, v);
    03619   return true;
    03620 }
    03621
    03622 static Vehicle *CheckVehicleAtSignal(Vehicle *v, void *data)
    03623 {
    03624   DiagDirection exitdir = *(DiagDirection *)data;
    03625
    03626   /* front engine of a train, not inside wormhole or depot, not crashed */
    03627   if (v->type == VEH_TRAIN && IsFrontEngine(v) && (v->u.rail.track & TRACK_BIT_MASK) != 0 && !(v->vehstatus & VS_CRASHED)) {
    03628     if (v->cur_speed <= 5 && TrainExitDir(v->direction, v->u.rail.track) == exitdir) return v;
    03629   }
    03630
    03631   return NULL;
    03632 }
    03633
    03634 static void TrainController(Vehicle *v, Vehicle *nomove, bool update_image)
    03635 {
    03636   Vehicle *prev;
    03637
    03638   /* For every vehicle after and including the given vehicle */
    03639   for (prev = v->Previous(); v != nomove; prev = v, v = v->Next()) {
    03640     DiagDirection enterdir = DIAGDIR_BEGIN;
    03641     bool update_signals_crossing = false; // will we update signals or crossing state?
    03642     BeginVehicleMove(v);
    03643
    03644     GetNewVehiclePosResult gp = GetNewVehiclePos(v);
    03645     if (v->u.rail.track != TRACK_BIT_WORMHOLE) {
    03646       /* Not inside tunnel */
    03647       if (gp.old_tile == gp.new_tile) {
    03648         /* Staying in the old tile */
    03649         if (v->u.rail.track == TRACK_BIT_DEPOT) {
    03650           /* Inside depot */
    03651           gp.x = v->x_pos;
    03652           gp.y = v->y_pos;
    03653         } else {
    03654           /* Not inside depot */
    03655
    03656           /* Reverse when we are at the end of the track already, do not move to the new position */
    03657           if (IsFrontEngine(v) && !TrainCheckIfLineEnds(v)) return;
    03658
    03659           uint32 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
    03660           if (HasBit(r, VETS_CANNOT_ENTER)) {
    03661             goto invalid_rail;
    03662           }
    03663           if (HasBit(r, VETS_ENTERED_STATION)) {
    03664             /* The new position is the end of the platform */
    03665             TrainEnterStation(v, r >> VETS_STATION_ID_OFFSET);
    03666           }
    03667         }
    03668       } else {
    03669         /* A new tile is about to be entered. */
    03670
    03671         /* Determine what direction we're entering the new tile from */
    03672         Direction dir = GetNewVehicleDirectionByTile(gp.new_tile, gp.old_tile);
    03673         enterdir = DirToDiagDir(dir);
    03674         assert(IsValidDiagDirection(enterdir));
    03675
    03676         /* Get the status of the tracks in the new tile and mask
    03677          * away the bits that aren't reachable. */
    03678         TrackStatus ts = GetTileTrackStatus(gp.new_tile, TRANSPORT_RAIL, 0, ReverseDiagDir(enterdir));
    03679         TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(enterdir);
    03680
    03681         TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
    03682         TrackBits red_signals = TrackdirBitsToTrackBits(TrackStatusToRedSignals(ts) & reachable_trackdirs);
    03683
    03684         TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
    03685         if (_settings_game.pf.pathfinder_for_trains != VPF_NTP && _settings_game.pf.forbid_90_deg && prev == NULL) {
    03686           /* We allow wagons to make 90 deg turns, because forbid_90_deg
    03687            * can be switched on halfway a turn */
    03688           bits &= ~TrackCrossesTracks(FindFirstTrack(v->u.rail.track));
    03689         }
    03690
    03691         if (bits == TRACK_BIT_NONE) goto invalid_rail;
    03692
    03693         /* Check if the new tile contrains tracks that are compatible
    03694          * with the current train, if not, bail out. */
    03695         if (!CheckCompatibleRail(v, gp.new_tile)) goto invalid_rail;
    03696
    03697         TrackBits chosen_track;
    03698         if (prev == NULL) {
    03699           /* Currently the locomotive is active. Determine which one of the
    03700            * available tracks to choose */
    03701           chosen_track = TrackToTrackBits(ChooseTrainTrack(v, gp.new_tile, enterdir, bits, false, NULL, true));
    03702           assert(chosen_track & (bits | GetReservedTrackbits(gp.new_tile)));
    03703
    03704           /* Check if it's a red signal and that force proceed is not clicked. */
    03705           if (red_signals & chosen_track && v->u.rail.force_proceed == 0) {
    03706             /* In front of a red signal */
    03707             Trackdir i = FindFirstTrackdir(trackdirbits);
    03708
    03709             /* Don't handle stuck trains here. */
    03710             if (HasBit(v->u.rail.flags, VRF_TRAIN_STUCK)) return;
    03711
    03712             if (!HasSignalOnTrackdir(gp.new_tile, ReverseTrackdir(i))) {
    03713               v->cur_speed = 0;
    03714               v->subspeed = 0;
    03715               v->progress = 255 - 100;
    03716               if (_settings_game.pf.wait_oneway_signal == 255 || ++v->load_unload_time_rem < _settings_game.pf.wait_oneway_signal * 20) return;
    03717             } else if (HasSignalOnTrackdir(gp.new_tile, i)) {
    03718               v->cur_speed = 0;
    03719               v->subspeed = 0;
    03720               v->progress = 255 - 10;
    03721               if (_settings_game.pf.wait_twoway_signal == 255 || ++v->load_unload_time_rem < _settings_game.pf.wait_twoway_signal * 73) {
    03722                 DiagDirection exitdir = TrackdirToExitdir(i);
    03723                 TileIndex o_tile = TileAddByDiagDir(gp.new_tile, exitdir);
    03724
    03725                 exitdir = ReverseDiagDir(exitdir);
    03726
    03727                 /* check if a train is waiting on the other side */
    03728                 if (!HasVehicleOnPos(o_tile, &exitdir, &CheckVehicleAtSignal)) return;
    03729               }
    03730             }
    03731
    03732             /* If we would reverse but are currently in a PBS block and
    03733              * reversing of stuck trains is disabled, don't reverse. */
    03734             if (_settings_game.pf.wait_for_pbs_path == 255 && UpdateSignalsOnSegment(v->tile, enterdir, v->owner) == SIGSEG_PBS) {
    03735               v->load_unload_time_rem = 0;
    03736               return;
    03737             }
    03738             goto reverse_train_direction;
    03739           } else {
    03740             TryReserveRailTrack(gp.new_tile, TrackBitsToTrack(chosen_track));
    03741           }
    03742         } else {
    03743           static const TrackBits _matching_tracks[8] = {
    03744               TRACK_BIT_LEFT  | TRACK_BIT_RIGHT, TRACK_BIT_X,
    03745               TRACK_BIT_UPPER | TRACK_BIT_LOWER, TRACK_BIT_Y,
    03746               TRACK_BIT_LEFT  | TRACK_BIT_RIGHT, TRACK_BIT_X,
    03747               TRACK_BIT_UPPER | TRACK_BIT_LOWER, TRACK_BIT_Y
    03748           };
    03749
    03750           /* The wagon is active, simply follow the prev vehicle. */
    03751           chosen_track = (TrackBits)(byte)(_matching_tracks[GetDirectionToVehicle(prev, gp.x, gp.y)] & bits);
    03752         }
    03753
    03754         /* Make sure chosen track is a valid track */
    03755         assert(
    03756             chosen_track == TRACK_BIT_X     || chosen_track == TRACK_BIT_Y ||
    03757             chosen_track == TRACK_BIT_UPPER || chosen_track == TRACK_BIT_LOWER ||
    03758             chosen_track == TRACK_BIT_LEFT  || chosen_track == TRACK_BIT_RIGHT);
    03759
    03760         /* Update XY to reflect the entrance to the new tile, and select the direction to use */
    03761         const byte *b = _initial_tile_subcoord[FIND_FIRST_BIT(chosen_track)][enterdir];
    03762         gp.x = (gp.x & ~0xF) | b[0];
    03763         gp.y = (gp.y & ~0xF) | b[1];
    03764         Direction chosen_dir = (Direction)b[2];
    03765
    03766         /* Call the landscape function and tell it that the vehicle entered the tile */
    03767         uint32 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
    03768         if (HasBit(r, VETS_CANNOT_ENTER)) {
    03769           goto invalid_rail;
    03770         }
    03771
    03772         if (!HasBit(r, VETS_ENTERED_WORMHOLE)) {
    03773           Track track = FindFirstTrack(chosen_track);
    03774           Trackdir tdir = TrackDirectionToTrackdir(track, chosen_dir);
    03775           if (IsFrontEngine(v) && HasPbsSignalOnTrackdir(gp.new_tile, tdir)) {
    03776             SetSignalStateByTrackdir(gp.new_tile, tdir, SIGNAL_STATE_RED);
    03777             MarkTileDirtyByTile(gp.new_tile);
    03778           }
    03779
    03780           /* Clear any track reservation when the last vehicle leaves the tile */
    03781           if (v->Next() == NULL) ClearPathReservation(v, v->tile, GetVehicleTrackdir(v));
    03782
    03783           v->tile = gp.new_tile;
    03784
    03785           if (GetTileRailType(gp.new_tile) != GetTileRailType(gp.old_tile)) {
    03786             TrainPowerChanged(v->First());
    03787           }
    03788
    03789           v->u.rail.track = chosen_track;
    03790           assert(v->u.rail.track);
    03791         }
    03792
    03793         /* We need to update signal status, but after the vehicle position hash
    03794          * has been updated by AfterSetTrainPos() */
    03795         update_signals_crossing = true;
    03796
    03797         if (prev == NULL) AffectSpeedByDirChange(v, chosen_dir);
    03798
    03799         v->direction = chosen_dir;
    03800
    03801         if (IsFrontEngine(v)) {
    03802           v->load_unload_time_rem = 0;
    03803
    03804           /* If we are approching a crossing that is reserved, play the sound now. */
    03805           TileIndex crossing = TrainApproachingCrossingTile(v);
    03806           if (crossing != INVALID_TILE && GetCrossingReservation(crossing)) SndPlayTileFx(SND_0E_LEVEL_CROSSING, crossing);
    03807
    03808           /* Always try to extend the reservation when entering a tile. */
    03809           CheckNextTrainTile(v);
    03810         }
    03811       }
    03812     } else {
    03813       /* In a tunnel or on a bridge
    03814        * - for tunnels, only the part when the vehicle is not visible (part of enter/exit tile too)
    03815        * - for bridges, only the middle part - without the bridge heads */
    03816       if (!(v->vehstatus & VS_HIDDEN)) {
    03817         v->cur_speed =
    03818           min(v->cur_speed, GetBridgeSpec(GetBridgeType(v->tile))->speed);
    03819       }
    03820
    03821       if (IsTileType(gp.new_tile, MP_TUNNELBRIDGE) && HasBit(VehicleEnterTile(v, gp.new_tile, gp.x, gp.y), VETS_ENTERED_WORMHOLE)) {
    03822         /* Perform look-ahead on tunnel exit. */
    03823         if (IsFrontEngine(v)) {
    03824           TryReserveRailTrack(gp.new_tile, DiagDirToDiagTrack(GetTunnelBridgeDirection(gp.new_tile)));
    03825           CheckNextTrainTile(v);
    03826         }
    03827       } else {
    03828         v->x_pos = gp.x;
    03829         v->y_pos = gp.y;
    03830         VehiclePositionChanged(v);
    03831         if (!(v->vehstatus & VS_HIDDEN)) EndVehicleMove(v);
    03832         continue;
    03833       }
    03834     }
    03835
    03836     /* update image of train, as well as delta XY */
    03837     v->UpdateDeltaXY(v->direction);
    03838     if (update_image) v->cur_image = v->GetImage(v->direction);
    03839
    03840     v->x_pos = gp.x;
    03841     v->y_pos = gp.y;
    03842
    03843     /* update the Z position of the vehicle */
    03844     byte old_z = AfterSetTrainPos(v, (gp.new_tile != gp.old_tile));
    03845
    03846     if (prev == NULL) {
    03847       /* This is the first vehicle in the train */
    03848       AffectSpeedByZChange(v, old_z);
    03849     }
    03850
    03851     if (update_signals_crossing) {
    03852       if (IsFrontEngine(v)) {
    03853         if (TrainMovedChangeSignals(gp.new_tile, enterdir)) {
    03854           /* We are entering a block with PBS signals right now, but
    03855            * not through a PBS signal. This means we don't have a
    03856            * reservation right now. As a conventional signal will only
    03857            * ever be green if no other train is in the block, getting
    03858            * a path should always be possible. If the player built
    03859            * such a strange network that it is not possible, the train
    03860            * will be marked as stuck and the player has to deal with
    03861            * the problem. */
    03862           if ((!HasReservedTracks(gp.new_tile, v->u.rail.track) &&
    03863               !TryReserveRailTrack(gp.new_tile, FindFirstTrack(v->u.rail.track))) ||
    03864               !TryPathReserve(v)) {
    03865             MarkTrainAsStuck(v);
    03866           }
    03867         }
    03868       }
    03869
    03870       /* Signals can only change when the first
    03871        * (above) or the last vehicle moves. */
    03872       if (v->Next() == NULL) {
    03873         TrainMovedChangeSignals(gp.old_tile, ReverseDiagDir(enterdir));
    03874         if (IsLevelCrossingTile(gp.old_tile)) UpdateLevelCrossing(gp.old_tile);
    03875       }
    03876     }
    03877
    03878     /* Do not check on every tick to save some computing time. */
    03879     if (IsFrontEngine(v) && v->tick_counter % _settings_game.pf.path_backoff_interval == 0) CheckNextTrainTile(v);
    03880   }
    03881   return;
    03882
    03883 invalid_rail:
    03884   /* We've reached end of line?? */
    03885   if (prev != NULL) error("Disconnecting train");
    03886
    03887 reverse_train_direction:
    03888   v->load_unload_time_rem = 0;
    03889   v->cur_speed = 0;
    03890   v->subspeed = 0;
    03891   ReverseTrainDirection(v);
    03892 }
    03893
    03899 static Vehicle *CollectTrackbitsFromCrashedVehiclesEnum(Vehicle *v, void *data)
    03900 {
    03901   TrackBits *trackbits = (TrackBits *)data;
    03902
    03903   if (v->type == VEH_TRAIN && (v->vehstatus & VS_CRASHED) != 0) {
    03904     if ((v->u.rail.track & TRACK_BIT_WORMHOLE) == TRACK_BIT_WORMHOLE) {
    03905       /* Vehicle is inside a wormhole, v->u.rail.track contains no useful value then. */
    03906       *trackbits |= DiagDirToDiagTrackBits(GetTunnelBridgeDirection(v->tile));
    03907     } else {
    03908       *trackbits |= v->u.rail.track;
    03909     }
    03910   }
    03911
    03912   return NULL;
    03913 }
    03914
    03922 static void DeleteLastWagon(Vehicle *v)
    03923 {
    03924   Vehicle *first = v->First();
    03925
    03926   /* Go to the last wagon and delete the link pointing there
    03927    * *u is then the one-before-last wagon, and *v the last
    03928    * one which will physicially be removed */
    03929   Vehicle *u = v;
    03930   for (; v->Next() != NULL; v = v->Next()) u = v;
    03931   u->SetNext(NULL);
    03932
    03933   if (first != v) {
    03934     /* Recalculate cached train properties */
    03935     TrainConsistChanged(first, false);
    03936     /* Update the depot window if the first vehicle is in depot -
    03937      * if v == first, then it is updated in PreDestructor() */
    03938     if (first->u.rail.track == TRACK_BIT_DEPOT) {
    03939       InvalidateWindow(WC_VEHICLE_DEPOT, first->tile);
    03940     }
    03941   }
    03942
    03943   /* 'v' shouldn't be accessed after it has been deleted */
    03944   TrackBits trackbits = v->u.rail.track;
    03945   TileIndex tile = v->tile;
    03946   Owner owner = v->owner;
    03947
    03948   delete v;
    03949   v = NULL; // make sure nobody will try to read 'v' anymore
    03950
    03951   if ((trackbits & TRACK_BIT_WORMHOLE) == TRACK_BIT_WORMHOLE) {
    03952     /* Vehicle is inside a wormhole, v->u.rail.track contains no useful value then. */
    03953     trackbits |= DiagDirToDiagTrackBits(GetTunnelBridgeDirection(tile));
    03954   }
    03955
    03956   Track track = TrackBitsToTrack(trackbits);
    03957   if (HasReservedTracks(tile, trackbits)) {
    03958     UnreserveRailTrack(tile, track);
    03959
    03960     /* If there are still crashed vehicles on the tile, give the track reservation to them */
    03961     TrackBits remaining_trackbits = TRACK_BIT_NONE;
    03962     FindVehicleOnPos(tile, &remaining_trackbits, CollectTrackbitsFromCrashedVehiclesEnum);
    03963
    03964     /* It is important that these two are the first in the loop, as reservation cannot deal with every trackbit combination */
    03965     assert(TRACK_BEGIN == TRACK_X && TRACK_Y == TRACK_BEGIN + 1);
    03966     for (Track t = TRACK_BEGIN; t < TRACK_END; t++) {
    03967       if (HasBit(remaining_trackbits, t)) {
    03968         TryReserveRailTrack(tile, t);
    03969       }
    03970     }
    03971   }
    03972
    03973   /* check if the wagon was on a road/rail-crossing */
    03974   if (IsLevelCrossingTile(tile)) UpdateLevelCrossing(tile);
    03975
    03976   /* Update signals */
    03977   if (IsTileType(tile, MP_TUNNELBRIDGE) || IsRailDepotTile(tile)) {
    03978     UpdateSignalsOnSegment(tile, INVALID_DIAGDIR, owner);
    03979   } else {
    03980     SetSignalsOnBothDir(tile, track, owner);
    03981   }
    03982 }
    03983
    03984 static void ChangeTrainDirRandomly(Vehicle *v)
    03985 {
    03986   static const DirDiff delta[] = {
    03987     DIRDIFF_45LEFT, DIRDIFF_SAME, DIRDIFF_SAME, DIRDIFF_45RIGHT
    03988   };
    03989
    03990   do {
    03991     /* We don't need to twist around vehicles if they're not visible */
    03992     if (!(v->vehstatus & VS_HIDDEN)) {
    03993       v->direction = ChangeDir(v->direction, delta[GB(Random(), 0, 2)]);
    03994       BeginVehicleMove(v);
    03995       v->UpdateDeltaXY(v->direction);
    03996       v->cur_image = v->GetImage(v->direction);
    03997       /* Refrain from updating the z position of the vehicle when on
    03998        * a bridge, because AfterSetTrainPos will put the vehicle under
    03999        * the bridge in that case */
    04000       if (v->u.rail.track != TRACK_BIT_WORMHOLE) AfterSetTrainPos(v, false);
    04001     }
    04002   } while ((v = v->Next()) != NULL);
    04003 }
    04004
    04005 static void HandleCrashedTrain(Vehicle *v)
    04006 {
    04007   int state = ++v->u.rail.crash_anim_pos;
    04008
    04009   if (state == 4 && !(v->vehstatus & VS_HIDDEN)) {
    04010     CreateEffectVehicleRel(v, 4, 4, 8, EV_EXPLOSION_LARGE);
    04011   }
    04012
    04013   uint32 r;
    04014   if (state <= 200 && Chance16R(1, 7, r)) {
    04015     int index = (r * 10 >> 16);
    04016
    04017     Vehicle *u = v;
    04018     do {
    04019       if (--index < 0) {
    04020         r = Random();
    04021
    04022         CreateEffectVehicleRel(u,
    04023           GB(r,  8, 3) + 2,
    04024           GB(r, 16, 3) + 2,
    04025           GB(r,  0, 3) + 5,
    04026           EV_EXPLOSION_SMALL);
    04027         break;
    04028       }
    04029     } while ((u = u->Next()) != NULL);
    04030   }
    04031
    04032   if (state <= 240 && !(v->tick_counter & 3)) ChangeTrainDirRandomly(v);
    04033
    04034   if (state >= 4440 && !(v->tick_counter & 0x1F)) {
    04035     DeleteLastWagon(v);
    04036     InvalidateWindow(WC_REPLACE_VEHICLE, (v->group_id << 16) | VEH_TRAIN);
    04037   }
    04038 }
    04039
    04040 static void HandleBrokenTrain(Vehicle *v)
    04041 {
    04042   if (v->breakdown_ctr != 1) {
    04043     v->breakdown_ctr = 1;
    04044     v->cur_speed = 0;
    04045
    04046     if (v->breakdowns_since_last_service != 255)
    04047       v->breakdowns_since_last_service++;
    04048
    04049     InvalidateWindow(WC_VEHICLE_VIEW, v->index);
    04050     InvalidateWindow(WC_VEHICLE_DETAILS, v->index);
    04051
    04052     if (!PlayVehicleSound(v, VSE_BREAKDOWN)) {
    04053       SndPlayVehicleFx((_settings_game.game_creation.landscape != LT_TOYLAND) ?
    04054         SND_10_TRAIN_BREAKDOWN : SND_3A_COMEDY_BREAKDOWN_2, v);
    04055     }
    04056
    04057     if (!(v->vehstatus & VS_HIDDEN)) {
    04058       Vehicle *u = CreateEffectVehicleRel(v, 4, 4, 5, EV_BREAKDOWN_SMOKE);
    04059       if (u != NULL) u->u.effect.animation_state = v->breakdown_delay * 2;
    04060     }
    04061   }
    04062
    04063   if (!(v->tick_counter & 3)) {
    04064     if (!--v->breakdown_delay) {
    04065       v->breakdown_ctr = 0;
    04066       InvalidateWindow(WC_VEHICLE_VIEW, v->index);
    04067     }
    04068   }
    04069 }
    04070
    04072 static const uint16 _breakdown_speeds[16] = {
    04073   225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, 15
    04074 };
    04075
    04076
    04084 static bool TrainApproachingLineEnd(Vehicle *v, bool signal)
    04085 {
    04086   /* Calc position within the current tile */
    04087   uint x = v->x_pos & 0xF;
    04088   uint y = v->y_pos & 0xF;
    04089
    04090   /* for diagonal directions, 'x' will be 0..15 -
    04091    * for other directions, it will be 1, 3, 5, ..., 15 */
    04092   switch (v->direction) {
    04093     case DIR_N : x = ~x + ~y + 25; break;
    04094     case DIR_NW: x = y;            /* FALLTHROUGH */
    04095     case DIR_NE: x = ~x + 16;      break;
    04096     case DIR_E : x = ~x + y + 9;   break;
    04097     case DIR_SE: x = y;            break;
    04098     case DIR_S : x = x + y - 7;    break;
    04099     case DIR_W : x = ~y + x + 9;   break;
    04100     default: break;
    04101   }
    04102
    04103   /* do not reverse when approaching red signal */
    04104   if (!signal && x + (v->u.rail.cached_veh_length + 1) / 2 >= TILE_SIZE) {
    04105     /* we are too near the tile end, reverse now */
    04106     v->cur_speed = 0;
    04107     ReverseTrainDirection(v);
    04108     return false;
    04109   }
    04110
    04111   /* slow down */
    04112   v->vehstatus |= VS_TRAIN_SLOWING;
    04113   uint16 break_speed = _breakdown_speeds[x & 0xF];
    04114   if (break_speed < v->cur_speed) v->cur_speed = break_speed;
    04115
    04116   return true;
    04117 }
    04118
    04119
    04125 static bool TrainCanLeaveTile(const Vehicle *v)
    04126 {
    04127   /* Exit if inside a tunnel/bridge or a depot */
    04128   if (v->u.rail.track == TRACK_BIT_WORMHOLE || v->u.rail.track == TRACK_BIT_DEPOT) return false;
    04129
    04130   TileIndex tile = v->tile;
    04131
    04132   /* entering a tunnel/bridge? */
    04133   if (IsTileType(tile, MP_TUNNELBRIDGE)) {
    04134     DiagDirection dir = GetTunnelBridgeDirection(tile);
    04135     if (DiagDirToDir(dir) == v->direction) return false;
    04136   }
    04137
    04138   /* entering a depot? */
    04139   if (IsRailDepotTile(tile)) {
    04140     DiagDirection dir = ReverseDiagDir(GetRailDepotDirection(tile));
    04141     if (DiagDirToDir(dir) == v->direction) return false;
    04142   }
    04143
    04144   return true;
    04145 }
    04146
    04147
    04155 static TileIndex TrainApproachingCrossingTile(const Vehicle *v)
    04156 {
    04157   assert(IsFrontEngine(v));
    04158   assert(!(v->vehstatus & VS_CRASHED));
    04159
    04160   if (!TrainCanLeaveTile(v)) return INVALID_TILE;
    04161
    04162   DiagDirection dir = TrainExitDir(v->direction, v->u.rail.track);
    04163   TileIndex tile = v->tile + TileOffsByDiagDir(dir);
    04164
    04165   /* not a crossing || wrong axis || unusable rail (wrong type or owner) */
    04166   if (!IsLevelCrossingTile(tile) || DiagDirToAxis(dir) == GetCrossingRoadAxis(tile) ||
    04167       !CheckCompatibleRail(v, tile)) {
    04168     return INVALID_TILE;
    04169   }
    04170
    04171   return tile;
    04172 }
    04173
    04174
    04181 static bool TrainCheckIfLineEnds(Vehicle *v)
    04182 {
    04183   /* First, handle broken down train */
    04184
    04185   int t = v->breakdown_ctr;
    04186   if (t > 1) {
    04187     v->vehstatus |= VS_TRAIN_SLOWING;
    04188
    04189     uint16 break_speed = _breakdown_speeds[GB(~t, 4, 4)];
    04190     if (break_speed < v->cur_speed) v->cur_speed = break_speed;
    04191   } else {
    04192     v->vehstatus &= ~VS_TRAIN_SLOWING;
    04193   }
    04194
    04195   if (!TrainCanLeaveTile(v)) return true;
    04196
    04197   /* Determine the non-diagonal direction in which we will exit this tile */
    04198   DiagDirection dir = TrainExitDir(v->direction, v->u.rail.track);
    04199   /* Calculate next tile */
    04200   TileIndex tile = v->tile + TileOffsByDiagDir(dir);
    04201
    04202   /* Determine the track status on the next tile */
    04203   TrackStatus ts = GetTileTrackStatus(tile, TRANSPORT_RAIL, 0, ReverseDiagDir(dir));
    04204   TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(dir);
    04205
    04206   TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
    04207   TrackdirBits red_signals = TrackStatusToRedSignals(ts) & reachable_trackdirs;
    04208
    04209   /* We are sure the train is not entering a depot, it is detected above */
    04210
    04211   /* mask unreachable track bits if we are forbidden to do 90deg turns */
    04212   TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
    04213   if (_settings_game.pf.pathfinder_for_trains != VPF_NTP && _settings_game.pf.forbid_90_deg) {
    04214     bits &= ~TrackCrossesTracks(FindFirstTrack(v->u.rail.track));
    04215   }
    04216
    04217   /* no suitable trackbits at all || unusable rail (wrong type or owner) */
    04218   if (bits == TRACK_BIT_NONE || !CheckCompatibleRail(v, tile)) {
    04219     return TrainApproachingLineEnd(v, false);
    04220   }
    04221
    04222   /* approaching red signal */
    04223   if ((trackdirbits & red_signals) != 0) return TrainApproachingLineEnd(v, true);
    04224
    04225   /* approaching a rail/road crossing? then make it red */
    04226   if (IsLevelCrossingTile(tile)) MaybeBarCrossingWithSound(tile);
    04227
    04228   return true;
    04229 }
    04230
    04231
    04232 static void TrainLocoHandler(Vehicle *v, bool mode)
    04233 {
    04234   /* train has crashed? */
    04235   if (v->vehstatus & VS_CRASHED) {
    04236     if (!mode) HandleCrashedTrain(v);
    04237     return;
    04238   }
    04239
    04240   if (v->u.rail.force_proceed != 0) {
    04241     v->u.rail.force_proceed--;
    04242     ClrBit(v->u.rail.flags, VRF_TRAIN_STUCK);
    04243     InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
    04244   }
    04245
    04246   /* train is broken down? */
    04247   if (v->breakdown_ctr != 0) {
    04248     if (v->breakdown_ctr <= 2) {
    04249       HandleBrokenTrain(v);
    04250       return;
    04251     }
    04252     if (!v->current_order.IsType(OT_LOADING)) v->breakdown_ctr--;
    04253   }
    04254
    04255   if (HasBit(v->u.rail.flags, VRF_REVERSING) && v->cur_speed == 0) {
    04256     ReverseTrainDirection(v);
    04257   }
    04258
    04259   /* exit if train is stopped */
    04260   if (v->vehstatus & VS_STOPPED && v->cur_speed == 0) return;
    04261
    04262   bool valid_order = v->current_order.IsValid() && v->current_order.GetType() != OT_CONDITIONAL;
    04263   if (ProcessOrders(v) && CheckReverseTrain(v)) {
    04264     v->load_unload_time_rem = 0;
    04265     v->cur_speed = 0;
    04266     v->subspeed = 0;
    04267     ReverseTrainDirection(v);
    04268     return;
    04269   }
    04270
    04271   v->HandleLoading(mode);
    04272
    04273   if (v->current_order.IsType(OT_LOADING)) return;
    04274
    04275   if (CheckTrainStayInDepot(v)) return;
    04276
    04277   if (!mode) HandleLocomotiveSmokeCloud(v);
    04278
    04279   /* We had no order but have an order now, do look ahead. */
    04280   if (!valid_order && v->current_order.IsValid()) {
    04281     CheckNextTrainTile(v);
    04282   }
    04283
    04284   /* Handle stuck trains. */
    04285   if (!mode && HasBit(v->u.rail.flags, VRF_TRAIN_STUCK)) {
    04286     ++v->load_unload_time_rem;
    04287
    04288     /* Should we try reversing this tick if still stuck? */
    04289     bool turn_around = v->load_unload_time_rem % (_settings_game.pf.wait_for_pbs_path * DAY_TICKS) == 0 && _settings_game.pf.wait_for_pbs_path < 255;
    04290
    04291     if (!turn_around && v->load_unload_time_rem % _settings_game.pf.path_backoff_interval != 0 && v->u.rail.force_proceed == 0) return;
    04292     if (!TryPathReserve(v)) {
    04293       /* Still stuck. */
    04294       if (turn_around) ReverseTrainDirection(v);
    04295
    04296       if (HasBit(v->u.rail.flags, VRF_TRAIN_STUCK) && v->load_unload_time_rem > 2 * _settings_game.pf.wait_for_pbs_path * DAY_TICKS) {
    04297         /* Show message to player. */
    04298         if (_settings_client.gui.lost_train_warn && v->owner == _local_company) {
    04299           SetDParam(0, v->index);
    04300           AddNewsItem(
    04301             STR_TRAIN_IS_STUCK,
    04302             NS_ADVICE,
    04303             v->index,
    04304             0);
    04305         }
    04306         v->load_unload_time_rem = 0;
    04307       }
    04308       /* Exit if force proceed not pressed, else reset stuck flag anyway. */
    04309       if (v->u.rail.force_proceed == 0) return;
    04310       ClrBit(v->u.rail.flags, VRF_TRAIN_STUCK);
    04311       v->load_unload_time_rem = 0;
    04312       InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
    04313     }
    04314   }
    04315
    04316   if (v->current_order.IsType(OT_LEAVESTATION)) {
    04317     v->current_order.Free();
    04318     InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
    04319     return;
    04320   }
    04321
    04322   int j = UpdateTrainSpeed(v);
    04323
    04324   /* we need to invalidate the widget if we are stopping from 'Stopping 0 km/h' to 'Stopped' */
    04325   if (v->cur_speed == 0 && v->u.rail.last_speed == 0 && v->vehstatus & VS_STOPPED) {
    04326     InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
    04327   }
    04328
    04329   int adv_spd = (v->direction & 1) ? 192 : 256;
    04330   if (j < adv_spd) {
    04331     /* if the vehicle has speed 0, update the last_speed field. */
    04332     if (v->cur_speed == 0) SetLastSpeed(v, v->cur_speed);
    04333   } else {
    04334     TrainCheckIfLineEnds(v);
    04335     /* Loop until the train has finished moving. */
    04336     do {
    04337       j -= adv_spd;
    04338       TrainController(v, NULL, true);
    04339       /* Don't continue to move if the train crashed. */
    04340       if (CheckTrainCollision(v)) break;
    04341       /* 192 spd used for going straight, 256 for going diagonally. */
    04342       adv_spd = (v->direction & 1) ? 192 : 256;
    04343     } while (j >= adv_spd);
    04344     SetLastSpeed(v, v->cur_speed);
    04345   }
    04346
    04347   if (v->progress == 0) v->progress = j; // Save unused spd for next time, if TrainController didn't set progress
    04348 }
    04349
    04350
    04351
    04352 Money Train::GetRunningCost() const
    04353 {
    04354   Money cost = 0;
    04355   const Vehicle *v = this;
    04356
    04357   do {
    04358     const RailVehicleInfo *rvi = RailVehInfo(v->engine_type);
    04359
    04360     byte cost_factor = GetVehicleProperty(v, 0x0D, rvi->running_cost);
    04361     if (cost_factor == 0) continue;
    04362
    04363     /* Halve running cost for multiheaded parts */
    04364     if (IsMultiheaded(v)) cost_factor /= 2;
    04365
    04366     cost += cost_factor * GetPriceByIndex(rvi->running_cost_class);
    04367   } while ((v = GetNextVehicle(v)) != NULL);
    04368
    04369   return cost;
    04370 }
    04371
    04372
    04373 void Train::Tick()
    04374 {
    04375   if (_age_cargo_skip_counter == 0) this->cargo.AgeCargo();
    04376
    04377   this->tick_counter++;
    04378
    04379   if (IsFrontEngine(this)) {
    04380     if (!(this->vehstatus & VS_STOPPED)) this->running_ticks++;
    04381     this->current_order_time++;
    04382
    04383     TrainLocoHandler(this, false);
    04384
    04385     /* make sure vehicle wasn't deleted. */
    04386     if (this->type == VEH_TRAIN && IsFrontEngine(this))
    04387       TrainLocoHandler(this, true);
    04388   } else if (IsFreeWagon(this) && HASBITS(this->vehstatus, VS_CRASHED)) {
    04389     /* Delete flooded standalone wagon chain */
    04390     if (++this->u.rail.crash_anim_pos >= 4400) delete this;
    04391   }
    04392 }
    04393
    04394 static void CheckIfTrainNeedsService(Vehicle *v)
    04395 {
    04396   static const uint MAX_ACCEPTABLE_DEPOT_DIST = 16;
    04397
    04398   if (_settings_game.vehicle.servint_trains == 0 || !v->NeedsAutomaticServicing()) return;
    04399   if (v->IsInDepot()) {
    04400     VehicleServiceInDepot(v);
    04401     return;
    04402   }
    04403
    04404   TrainFindDepotData tfdd = FindClosestTrainDepot(v, MAX_ACCEPTABLE_DEPOT_DIST);
    04405   /* Only go to the depot if it is not too far out of our way. */
    04406   if (tfdd.best_length == UINT_MAX || tfdd.best_length > MAX_ACCEPTABLE_DEPOT_DIST) {
    04407     if (v->current_order.IsType(OT_GOTO_DEPOT)) {
    04408       /* If we were already heading for a depot but it has
    04409        * suddenly moved farther away, we continue our normal
    04410        * schedule? */
    04411       v->current_order.MakeDummy();
    04412       InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
    04413     }
    04414     return;
    04415   }
    04416
    04417   const Depot *depot = GetDepotByTile(tfdd.tile);
    04418
    04419   if (v->current_order.IsType(OT_GOTO_DEPOT) &&
    04420       v->current_order.GetDestination() != depot->index &&
    04421       !Chance16(3, 16)) {
    04422     return;
    04423   }
    04424
    04425   v->current_order.MakeGoToDepot(depot->index, ODTFB_SERVICE);
    04426   v->dest_tile = tfdd.tile;
    04427   InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
    04428 }
    04429
    04430 void Train::OnNewDay()
    04431 {
    04432   if ((++this->day_counter & 7) == 0) DecreaseVehicleValue(this);
    04433
    04434   if (IsFrontEngine(this)) {
    04435     CheckVehicleBreakdown(this);
    04436     AgeVehicle(this);
    04437
    04438     CheckIfTrainNeedsService(this);
    04439
    04440     CheckOrders(this);
    04441
    04442     /* update destination */
    04443     if (this->current_order.IsType(OT_GOTO_STATION)) {
    04444       TileIndex tile = GetStation(this->current_order.GetDestination())->train_tile;
    04445       if (tile != INVALID_TILE) this->dest_tile = tile;
    04446     }
    04447
    04448     if (this->running_ticks != 0) {
    04449       /* running costs */
    04450       CommandCost cost(EXPENSES_TRAIN_RUN, this->GetRunningCost() * this->running_ticks / (DAYS_IN_YEAR  * DAY_TICKS));
    04451
    04452       this->profit_this_year -= cost.GetCost();
    04453       this->running_ticks = 0;
    04454
    04455       SubtractMoneyFromCompanyFract(this->owner, cost);
    04456
    04457       InvalidateWindow(WC_VEHICLE_DETAILS, this->index);
    04458       InvalidateWindowClasses(WC_TRAINS_LIST);
    04459     }
    04460   } else if (IsTrainEngine(this)) {
    04461     /* Also age engines that aren't front engines */
    04462     AgeVehicle(this);
    04463   }
    04464 }
    04465
    04466 void InitializeTrains()
    04467 {
    04468   _age_cargo_skip_counter = 1;
    04469 }