# train_cmd.cpp

Go to the documentation of this file.

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