00001
00002
00003
00004
00005
00006
00007
00008
00009
00012 #include "stdafx.h"
00013 #include "gui.h"
00014 #include "articulated_vehicles.h"
00015 #include "command_func.h"
00016 #include "pathfinder/npf/npf_func.h"
00017 #include "pathfinder/yapf/yapf.hpp"
00018 #include "news_func.h"
00019 #include "company_func.h"
00020 #include "vehicle_gui.h"
00021 #include "newgrf_sound.h"
00022 #include "newgrf_text.h"
00023 #include "group.h"
00024 #include "strings_func.h"
00025 #include "functions.h"
00026 #include "window_func.h"
00027 #include "vehicle_func.h"
00028 #include "sound_func.h"
00029 #include "ai/ai.hpp"
00030 #include "newgrf_station.h"
00031 #include "effectvehicle_func.h"
00032 #include "gamelog.h"
00033 #include "network/network.h"
00034 #include "spritecache.h"
00035 #include "core/random_func.hpp"
00036 #include "company_base.h"
00037 #include "newgrf.h"
00038 #include "order_backup.h"
00039
00040 #include "table/strings.h"
00041 #include "table/train_cmd.h"
00042
00043 static Track ChooseTrainTrack(Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool force_res, bool *got_reservation, bool mark_stuck);
00044 static bool TrainCheckIfLineEnds(Train *v);
00045 static void TrainController(Train *v, Vehicle *nomove);
00046 static TileIndex TrainApproachingCrossingTile(const Train *v);
00047 static void CheckIfTrainNeedsService(Train *v);
00048 static void CheckNextTrainTile(Train *v);
00049
00050 static const byte _vehicle_initial_x_fract[4] = {10, 8, 4, 8};
00051 static const byte _vehicle_initial_y_fract[4] = { 8, 4, 8, 10};
00052
00053
00061 static inline DiagDirection TrainExitDir(Direction direction, TrackBits track)
00062 {
00063 static const TrackBits state_dir_table[DIAGDIR_END] = { TRACK_BIT_RIGHT, TRACK_BIT_LOWER, TRACK_BIT_LEFT, TRACK_BIT_UPPER };
00064
00065 DiagDirection diagdir = DirToDiagDir(direction);
00066
00067
00068 if (!HasBit(direction, 0) && track != state_dir_table[diagdir]) {
00069 diagdir = ChangeDiagDir(diagdir, DIAGDIRDIFF_90LEFT);
00070 }
00071
00072 return diagdir;
00073 }
00074
00075
00081 byte FreightWagonMult(CargoID cargo)
00082 {
00083 if (!CargoSpec::Get(cargo)->is_freight) return 1;
00084 return _settings_game.vehicle.freight_trains;
00085 }
00086
00092 static void RailVehicleLengthChanged(const Train *u)
00093 {
00094
00095 const Engine *engine = Engine::Get(u->engine_type);
00096 uint32 grfid = engine->grf_prop.grffile->grfid;
00097 GRFConfig *grfconfig = GetGRFConfig(grfid);
00098 if (GamelogGRFBugReverse(grfid, engine->grf_prop.local_id) || !HasBit(grfconfig->grf_bugs, GBUG_VEH_LENGTH)) {
00099 ShowNewGrfVehicleError(u->engine_type, STR_NEWGRF_BROKEN, STR_NEWGRF_BROKEN_VEHICLE_LENGTH, GBUG_VEH_LENGTH, true);
00100 }
00101 }
00102
00104 void CheckTrainsLengths()
00105 {
00106 const Train *v;
00107
00108 FOR_ALL_TRAINS(v) {
00109 if (v->First() == v && !(v->vehstatus & VS_CRASHED)) {
00110 for (const Train *u = v, *w = v->Next(); w != NULL; u = w, w = w->Next()) {
00111 if (u->track != TRACK_BIT_DEPOT) {
00112 if ((w->track != TRACK_BIT_DEPOT &&
00113 max(abs(u->x_pos - w->x_pos), abs(u->y_pos - w->y_pos)) != u->gcache.cached_veh_length) ||
00114 (w->track == TRACK_BIT_DEPOT && TicksToLeaveDepot(u) <= 0)) {
00115 SetDParam(0, v->index);
00116 SetDParam(1, v->owner);
00117 ShowErrorMessage(STR_BROKEN_VEHICLE_LENGTH, INVALID_STRING_ID, WL_CRITICAL);
00118
00119 if (!_networking) DoCommandP(0, PM_PAUSED_ERROR, 1, CMD_PAUSE);
00120 }
00121 }
00122 }
00123 }
00124 }
00125 }
00126
00131 void Train::RailtypeChanged()
00132 {
00133 for (Train *u = this; u != NULL; u = u->Next()) {
00134
00135 u->UpdateVisualEffect(false);
00136 }
00137 this->PowerChanged();
00138 if (this->IsFrontEngine()) this->UpdateAcceleration();
00139 }
00140
00147 void Train::ConsistChanged(bool same_length)
00148 {
00149 uint16 max_speed = UINT16_MAX;
00150
00151 assert(this->IsFrontEngine() || this->IsFreeWagon());
00152
00153 const RailVehicleInfo *rvi_v = RailVehInfo(this->engine_type);
00154 EngineID first_engine = this->IsFrontEngine() ? this->engine_type : INVALID_ENGINE;
00155 this->gcache.cached_total_length = 0;
00156 this->compatible_railtypes = RAILTYPES_NONE;
00157
00158 bool train_can_tilt = true;
00159
00160 for (Train *u = this; u != NULL; u = u->Next()) {
00161 const RailVehicleInfo *rvi_u = RailVehInfo(u->engine_type);
00162
00163
00164 assert(u->First() == this);
00165
00166
00167 u->gcache.first_engine = this == u ? INVALID_ENGINE : first_engine;
00168 u->railtype = rvi_u->railtype;
00169
00170 if (u->IsEngine()) first_engine = u->engine_type;
00171
00172
00173 u->tcache.user_def_data = rvi_u->user_def_data;
00174 this->InvalidateNewGRFCache();
00175 u->InvalidateNewGRFCache();
00176 }
00177
00178 for (Train *u = this; u != NULL; u = u->Next()) {
00179
00180 u->tcache.user_def_data = GetVehicleProperty(u, PROP_TRAIN_USER_DATA, u->tcache.user_def_data);
00181 this->InvalidateNewGRFCache();
00182 u->InvalidateNewGRFCache();
00183 }
00184
00185 for (Train *u = this; u != NULL; u = u->Next()) {
00186 const Engine *e_u = Engine::Get(u->engine_type);
00187 const RailVehicleInfo *rvi_u = &e_u->u.rail;
00188
00189 if (!HasBit(e_u->info.misc_flags, EF_RAIL_TILTS)) train_can_tilt = false;
00190
00191
00192 u->tcache.cached_override = GetWagonOverrideSpriteSet(u->engine_type, u->cargo_type, u->gcache.first_engine);
00193
00194
00195 u->colourmap = PAL_NONE;
00196
00197
00198 u->UpdateVisualEffect(true);
00199
00200 if (rvi_v->pow_wag_power != 0 && rvi_u->railveh_type == RAILVEH_WAGON &&
00201 UsesWagonOverride(u) && !HasBit(u->vcache.cached_vis_effect, VE_DISABLE_WAGON_POWER)) {
00202
00203 SetBit(u->flags, VRF_POWEREDWAGON);
00204 } else {
00205 ClrBit(u->flags, VRF_POWEREDWAGON);
00206 }
00207
00208 if (!u->IsArticulatedPart()) {
00209
00210
00211 if (rvi_u->power > 0) {
00212 this->compatible_railtypes |= GetRailTypeInfo(u->railtype)->powered_railtypes;
00213 }
00214
00215
00216
00217 if (HasBit(u->flags, VRF_EL_ENGINE_ALLOWED_NORMAL_RAIL)) {
00218 u->railtype = RAILTYPE_RAIL;
00219 u->compatible_railtypes |= RAILTYPES_RAIL;
00220 }
00221
00222
00223 if ((rvi_u->railveh_type != RAILVEH_WAGON || _settings_game.vehicle.wagon_speed_limits) && !UsesWagonOverride(u)) {
00224 uint16 speed = GetVehicleProperty(u, PROP_TRAIN_SPEED, rvi_u->max_speed);
00225 if (speed != 0) max_speed = min(speed, max_speed);
00226 }
00227 }
00228
00229 u->cargo_cap = GetVehicleCapacity(u);
00230
00231
00232 uint16 veh_len = CALLBACK_FAILED;
00233 if (HasBit(e_u->info.callback_mask, CBM_VEHICLE_LENGTH)) {
00234 veh_len = GetVehicleCallback(CBID_VEHICLE_LENGTH, 0, 0, u->engine_type, u);
00235 }
00236 if (veh_len == CALLBACK_FAILED) veh_len = rvi_u->shorten_factor;
00237 veh_len = 8 - Clamp(veh_len, 0, 7);
00238
00239
00240 if (same_length && veh_len != u->gcache.cached_veh_length) RailVehicleLengthChanged(u);
00241
00242
00243 if (!same_length) u->gcache.cached_veh_length = veh_len;
00244
00245 this->gcache.cached_total_length += u->gcache.cached_veh_length;
00246 this->InvalidateNewGRFCache();
00247 u->InvalidateNewGRFCache();
00248 }
00249
00250
00251 this->vcache.cached_max_speed = max_speed;
00252 this->tcache.cached_tilt = train_can_tilt;
00253 this->tcache.cached_max_curve_speed = this->GetCurveSpeedLimit();
00254
00255
00256 this->CargoChanged();
00257
00258 if (this->IsFrontEngine()) {
00259 this->UpdateAcceleration();
00260 SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
00261 InvalidateWindowData(WC_VEHICLE_REFIT, this->index);
00262 }
00263 }
00264
00275 int GetTrainStopLocation(StationID station_id, TileIndex tile, const Train *v, int *station_ahead, int *station_length)
00276 {
00277 const Station *st = Station::Get(station_id);
00278 *station_ahead = st->GetPlatformLength(tile, DirToDiagDir(v->direction)) * TILE_SIZE;
00279 *station_length = st->GetPlatformLength(tile) * TILE_SIZE;
00280
00281
00282
00283 OrderStopLocation osl = OSL_PLATFORM_MIDDLE;
00284 if (v->gcache.cached_total_length >= *station_length) {
00285
00286 osl = OSL_PLATFORM_FAR_END;
00287 } else if (v->current_order.IsType(OT_GOTO_STATION) && v->current_order.GetDestination() == station_id) {
00288 osl = v->current_order.GetStopLocation();
00289 }
00290
00291
00292 int stop;
00293 switch (osl) {
00294 default: NOT_REACHED();
00295
00296 case OSL_PLATFORM_NEAR_END:
00297 stop = v->gcache.cached_total_length;
00298 break;
00299
00300 case OSL_PLATFORM_MIDDLE:
00301 stop = *station_length - (*station_length - v->gcache.cached_total_length) / 2;
00302 break;
00303
00304 case OSL_PLATFORM_FAR_END:
00305 stop = *station_length;
00306 break;
00307 }
00308
00309
00310
00311 return stop - (v->gcache.cached_veh_length + 1) / 2;
00312 }
00313
00314
00319 int Train::GetCurveSpeedLimit() const
00320 {
00321 assert(this->First() == this);
00322
00323 static const int absolute_max_speed = UINT16_MAX;
00324 int max_speed = absolute_max_speed;
00325
00326 if (_settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) return max_speed;
00327
00328 int curvecount[2] = {0, 0};
00329
00330
00331 int numcurve = 0;
00332 int sum = 0;
00333 int pos = 0;
00334 int lastpos = -1;
00335 for (const Vehicle *u = this; u->Next() != NULL; u = u->Next(), pos++) {
00336 Direction this_dir = u->direction;
00337 Direction next_dir = u->Next()->direction;
00338
00339 DirDiff dirdiff = DirDifference(this_dir, next_dir);
00340 if (dirdiff == DIRDIFF_SAME) continue;
00341
00342 if (dirdiff == DIRDIFF_45LEFT) curvecount[0]++;
00343 if (dirdiff == DIRDIFF_45RIGHT) curvecount[1]++;
00344 if (dirdiff == DIRDIFF_45LEFT || dirdiff == DIRDIFF_45RIGHT) {
00345 if (lastpos != -1) {
00346 numcurve++;
00347 sum += pos - lastpos;
00348 if (pos - lastpos == 1) {
00349 max_speed = 88;
00350 }
00351 }
00352 lastpos = pos;
00353 }
00354
00355
00356 if (dirdiff == DIRDIFF_90LEFT || dirdiff == DIRDIFF_90RIGHT) {
00357 max_speed = 61;
00358 }
00359 }
00360
00361 if (numcurve > 0 && max_speed > 88) {
00362 if (curvecount[0] == 1 && curvecount[1] == 1) {
00363 max_speed = absolute_max_speed;
00364 } else {
00365 sum /= numcurve;
00366 max_speed = 232 - (13 - Clamp(sum, 1, 12)) * (13 - Clamp(sum, 1, 12));
00367 }
00368 }
00369
00370 if (max_speed != absolute_max_speed) {
00371
00372 const RailtypeInfo *rti = GetRailTypeInfo(this->railtype);
00373 max_speed += (max_speed / 2) * rti->curve_speed;
00374
00375 if (this->tcache.cached_tilt) {
00376
00377 max_speed += max_speed / 5;
00378 }
00379 }
00380
00381 return max_speed;
00382 }
00383
00388 int Train::GetCurrentMaxSpeed() const
00389 {
00390 int max_speed = this->tcache.cached_max_curve_speed;
00391 assert(max_speed == this->GetCurveSpeedLimit());
00392
00393 if (IsRailStationTile(this->tile)) {
00394 StationID sid = GetStationIndex(this->tile);
00395 if (this->current_order.ShouldStopAtStation(this, sid)) {
00396 int station_ahead;
00397 int station_length;
00398 int stop_at = GetTrainStopLocation(sid, this->tile, this, &station_ahead, &station_length);
00399
00400
00401
00402 int distance_to_go = station_ahead / TILE_SIZE - (station_length - stop_at) / TILE_SIZE;
00403
00404 if (distance_to_go > 0) {
00405 int st_max_speed = 120;
00406
00407 int delta_v = this->cur_speed / (distance_to_go + 1);
00408 if (max_speed > (this->cur_speed - delta_v)) {
00409 st_max_speed = this->cur_speed - (delta_v / 10);
00410 }
00411
00412 st_max_speed = max(st_max_speed, 25 * distance_to_go);
00413 max_speed = min(max_speed, st_max_speed);
00414 }
00415 }
00416 }
00417
00418 for (const Train *u = this; u != NULL; u = u->Next()) {
00419 if (u->track == TRACK_BIT_DEPOT) {
00420 max_speed = min(max_speed, 61);
00421 break;
00422 }
00423 }
00424
00425 return min(max_speed, this->gcache.cached_max_track_speed);
00426 }
00427
00428 void Train::UpdateAcceleration()
00429 {
00430 assert(this->IsFrontEngine());
00431
00432 uint power = this->gcache.cached_power;
00433 uint weight = this->gcache.cached_weight;
00434 assert(weight != 0);
00435 this->acceleration = Clamp(power / weight * 4, 1, 255);
00436 }
00437
00443 int Train::GetDisplayImageWidth(Point *offset) const
00444 {
00445 int reference_width = TRAININFO_DEFAULT_VEHICLE_WIDTH;
00446 int vehicle_pitch = 0;
00447
00448 const Engine *e = Engine::Get(this->engine_type);
00449 if (e->grf_prop.grffile != NULL && is_custom_sprite(e->u.rail.image_index)) {
00450 reference_width = e->grf_prop.grffile->traininfo_vehicle_width;
00451 vehicle_pitch = e->grf_prop.grffile->traininfo_vehicle_pitch;
00452 }
00453
00454 if (offset != NULL) {
00455 offset->x = reference_width / 2;
00456 offset->y = vehicle_pitch;
00457 }
00458 return this->gcache.cached_veh_length * reference_width / 8;
00459 }
00460
00461 static SpriteID GetDefaultTrainSprite(uint8 spritenum, Direction direction)
00462 {
00463 return ((direction + _engine_sprite_add[spritenum]) & _engine_sprite_and[spritenum]) + _engine_sprite_base[spritenum];
00464 }
00465
00466 SpriteID Train::GetImage(Direction direction) const
00467 {
00468 uint8 spritenum = this->spritenum;
00469 SpriteID sprite;
00470
00471 if (HasBit(this->flags, VRF_REVERSE_DIRECTION)) direction = ReverseDir(direction);
00472
00473 if (is_custom_sprite(spritenum)) {
00474 sprite = GetCustomVehicleSprite(this, (Direction)(direction + 4 * IS_CUSTOM_SECONDHEAD_SPRITE(spritenum)));
00475 if (sprite != 0) return sprite;
00476
00477 spritenum = Engine::Get(this->engine_type)->original_image_index;
00478 }
00479
00480 sprite = GetDefaultTrainSprite(spritenum, direction);
00481
00482 if (this->cargo.Count() >= this->cargo_cap / 2U) sprite += _wagon_full_adder[spritenum];
00483
00484 return sprite;
00485 }
00486
00487 static SpriteID GetRailIcon(EngineID engine, bool rear_head, int &y)
00488 {
00489 const Engine *e = Engine::Get(engine);
00490 Direction dir = rear_head ? DIR_E : DIR_W;
00491 uint8 spritenum = e->u.rail.image_index;
00492
00493 if (is_custom_sprite(spritenum)) {
00494 SpriteID sprite = GetCustomVehicleIcon(engine, dir);
00495 if (sprite != 0) {
00496 if (e->grf_prop.grffile != NULL) {
00497 y += e->grf_prop.grffile->traininfo_vehicle_pitch;
00498 }
00499 return sprite;
00500 }
00501
00502 spritenum = Engine::Get(engine)->original_image_index;
00503 }
00504
00505 if (rear_head) spritenum++;
00506
00507 return GetDefaultTrainSprite(spritenum, DIR_W);
00508 }
00509
00510 void DrawTrainEngine(int left, int right, int preferred_x, int y, EngineID engine, PaletteID pal)
00511 {
00512 if (RailVehInfo(engine)->railveh_type == RAILVEH_MULTIHEAD) {
00513 int yf = y;
00514 int yr = y;
00515
00516 SpriteID spritef = GetRailIcon(engine, false, yf);
00517 SpriteID spriter = GetRailIcon(engine, true, yr);
00518 const Sprite *real_spritef = GetSprite(spritef, ST_NORMAL);
00519 const Sprite *real_spriter = GetSprite(spriter, ST_NORMAL);
00520
00521 preferred_x = Clamp(preferred_x, left - real_spritef->x_offs + 14, right - real_spriter->width - real_spriter->x_offs - 15);
00522
00523 DrawSprite(spritef, pal, preferred_x - 14, yf);
00524 DrawSprite(spriter, pal, preferred_x + 15, yr);
00525 } else {
00526 SpriteID sprite = GetRailIcon(engine, false, y);
00527 const Sprite *real_sprite = GetSprite(sprite, ST_NORMAL);
00528 preferred_x = Clamp(preferred_x, left - real_sprite->x_offs, right - real_sprite->width - real_sprite->x_offs);
00529 DrawSprite(sprite, pal, preferred_x, y);
00530 }
00531 }
00532
00541 static CommandCost CmdBuildRailWagon(TileIndex tile, DoCommandFlag flags, const Engine *e, Vehicle **ret)
00542 {
00543 const RailVehicleInfo *rvi = &e->u.rail;
00544
00545
00546 if (!IsCompatibleRail(rvi->railtype, GetRailType(tile))) return CMD_ERROR;
00547
00548 if (flags & DC_EXEC) {
00549 Train *v = new Train();
00550 *ret = v;
00551 v->spritenum = rvi->image_index;
00552
00553 v->engine_type = e->index;
00554 v->gcache.first_engine = INVALID_ENGINE;
00555
00556 DiagDirection dir = GetRailDepotDirection(tile);
00557
00558 v->direction = DiagDirToDir(dir);
00559 v->tile = tile;
00560
00561 int x = TileX(tile) * TILE_SIZE | _vehicle_initial_x_fract[dir];
00562 int y = TileY(tile) * TILE_SIZE | _vehicle_initial_y_fract[dir];
00563
00564 v->x_pos = x;
00565 v->y_pos = y;
00566 v->z_pos = GetSlopeZ(x, y);
00567 v->owner = _current_company;
00568 v->track = TRACK_BIT_DEPOT;
00569 v->vehstatus = VS_HIDDEN | VS_DEFPAL;
00570
00571 v->SetWagon();
00572
00573 v->SetFreeWagon();
00574 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
00575
00576 v->cargo_type = e->GetDefaultCargoType();
00577 v->cargo_cap = rvi->capacity;
00578
00579 v->railtype = rvi->railtype;
00580
00581 v->build_year = _cur_year;
00582 v->cur_image = SPR_IMG_QUERY;
00583 v->random_bits = VehicleRandomBits();
00584
00585 v->group_id = DEFAULT_GROUP;
00586
00587 AddArticulatedParts(v);
00588
00589 _new_vehicle_id = v->index;
00590
00591 VehicleMove(v, false);
00592 v->First()->ConsistChanged(false);
00593 UpdateTrainGroupID(v->First());
00594
00595 CheckConsistencyOfArticulatedVehicle(v);
00596
00597
00598 Train *w;
00599 FOR_ALL_TRAINS(w) {
00600 if (w->tile == tile &&
00601 w->IsFreeWagon() &&
00602 w->engine_type == e->index &&
00603 w->First() != v &&
00604 !(w->vehstatus & VS_CRASHED)) {
00605 DoCommand(0, v->index | 1 << 20, w->Last()->index, DC_EXEC, CMD_MOVE_RAIL_VEHICLE);
00606 break;
00607 }
00608 }
00609 }
00610
00611 return CommandCost();
00612 }
00613
00615 static void NormalizeTrainVehInDepot(const Train *u)
00616 {
00617 const Train *v;
00618 FOR_ALL_TRAINS(v) {
00619 if (v->IsFreeWagon() && v->tile == u->tile &&
00620 v->track == TRACK_BIT_DEPOT) {
00621 if (DoCommand(0, v->index | 1 << 20, u->index, DC_EXEC,
00622 CMD_MOVE_RAIL_VEHICLE).Failed())
00623 break;
00624 }
00625 }
00626 }
00627
00628 static void AddRearEngineToMultiheadedTrain(Train *v)
00629 {
00630 Train *u = new Train();
00631 v->value >>= 1;
00632 u->value = v->value;
00633 u->direction = v->direction;
00634 u->owner = v->owner;
00635 u->tile = v->tile;
00636 u->x_pos = v->x_pos;
00637 u->y_pos = v->y_pos;
00638 u->z_pos = v->z_pos;
00639 u->track = TRACK_BIT_DEPOT;
00640 u->vehstatus = v->vehstatus & ~VS_STOPPED;
00641 u->spritenum = v->spritenum + 1;
00642 u->cargo_type = v->cargo_type;
00643 u->cargo_subtype = v->cargo_subtype;
00644 u->cargo_cap = v->cargo_cap;
00645 u->railtype = v->railtype;
00646 u->engine_type = v->engine_type;
00647 u->build_year = v->build_year;
00648 u->cur_image = SPR_IMG_QUERY;
00649 u->random_bits = VehicleRandomBits();
00650 v->SetMultiheaded();
00651 u->SetMultiheaded();
00652 v->SetNext(u);
00653 VehicleMove(u, false);
00654
00655
00656 v->other_multiheaded_part = u;
00657 u->other_multiheaded_part = v;
00658 }
00659
00669 CommandCost CmdBuildRailVehicle(TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **ret)
00670 {
00671 const RailVehicleInfo *rvi = &e->u.rail;
00672
00673 if (rvi->railveh_type == RAILVEH_WAGON) return CmdBuildRailWagon(tile, flags, e, ret);
00674
00675
00676
00677 if (!HasPowerOnRail(rvi->railtype, GetRailType(tile))) return CMD_ERROR;
00678
00679 if (flags & DC_EXEC) {
00680 DiagDirection dir = GetRailDepotDirection(tile);
00681 int x = TileX(tile) * TILE_SIZE + _vehicle_initial_x_fract[dir];
00682 int y = TileY(tile) * TILE_SIZE + _vehicle_initial_y_fract[dir];
00683
00684 Train *v = new Train();
00685 *ret = v;
00686 v->direction = DiagDirToDir(dir);
00687 v->tile = tile;
00688 v->owner = _current_company;
00689 v->x_pos = x;
00690 v->y_pos = y;
00691 v->z_pos = GetSlopeZ(x, y);
00692 v->track = TRACK_BIT_DEPOT;
00693 v->vehstatus = VS_HIDDEN | VS_STOPPED | VS_DEFPAL;
00694 v->spritenum = rvi->image_index;
00695 v->cargo_type = e->GetDefaultCargoType();
00696 v->cargo_cap = rvi->capacity;
00697 v->last_station_visited = INVALID_STATION;
00698
00699 v->engine_type = e->index;
00700 v->gcache.first_engine = INVALID_ENGINE;
00701
00702 v->reliability = e->reliability;
00703 v->reliability_spd_dec = e->reliability_spd_dec;
00704 v->max_age = e->GetLifeLengthInDays();
00705
00706 v->railtype = rvi->railtype;
00707 _new_vehicle_id = v->index;
00708
00709 v->service_interval = Company::Get(_current_company)->settings.vehicle.servint_trains;
00710 v->date_of_last_service = _date;
00711 v->build_year = _cur_year;
00712 v->cur_image = SPR_IMG_QUERY;
00713 v->random_bits = VehicleRandomBits();
00714
00715 if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) SetBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE);
00716
00717 v->group_id = DEFAULT_GROUP;
00718
00719 v->SetFrontEngine();
00720 v->SetEngine();
00721
00722 VehicleMove(v, false);
00723
00724 if (rvi->railveh_type == RAILVEH_MULTIHEAD) {
00725 AddRearEngineToMultiheadedTrain(v);
00726 } else {
00727 AddArticulatedParts(v);
00728 }
00729
00730 v->ConsistChanged(false);
00731 UpdateTrainGroupID(v);
00732
00733 if (!HasBit(data, 0) && !(flags & DC_AUTOREPLACE)) {
00734 NormalizeTrainVehInDepot(v);
00735 }
00736
00737 CheckConsistencyOfArticulatedVehicle(v);
00738 }
00739
00740 return CommandCost();
00741 }
00742
00743
00744 bool Train::IsInDepot() const
00745 {
00746
00747 if (!IsRailDepotTile(this->tile) || this->cur_speed != 0) return false;
00748
00749
00750 for (const Train *v = this; v != NULL; v = v->Next()) {
00751 if (v->track != TRACK_BIT_DEPOT || v->tile != this->tile) return false;
00752 }
00753
00754 return true;
00755 }
00756
00757 bool Train::IsStoppedInDepot() const
00758 {
00759
00760 if (this->IsFrontEngine() && !(this->vehstatus & VS_STOPPED)) return false;
00761 return this->IsInDepot();
00762 }
00763
00764 static Train *FindGoodVehiclePos(const Train *src)
00765 {
00766 EngineID eng = src->engine_type;
00767 TileIndex tile = src->tile;
00768
00769 Train *dst;
00770 FOR_ALL_TRAINS(dst) {
00771 if (dst->IsFreeWagon() && dst->tile == tile && !(dst->vehstatus & VS_CRASHED)) {
00772
00773 Train *t = dst;
00774 while (t->engine_type == eng) {
00775 t = t->Next();
00776 if (t == NULL) return dst;
00777 }
00778 }
00779 }
00780
00781 return NULL;
00782 }
00783
00785 typedef SmallVector<Train *, 16> TrainList;
00786
00792 static void MakeTrainBackup(TrainList &list, Train *t)
00793 {
00794 for (; t != NULL; t = t->Next()) *list.Append() = t;
00795 }
00796
00801 static void RestoreTrainBackup(TrainList &list)
00802 {
00803
00804 if (list.Length() == 0) return;
00805
00806 Train *prev = NULL;
00807
00808 for (Train **iter = list.Begin(); iter != list.End(); iter++) {
00809 Train *t = *iter;
00810 if (prev != NULL) {
00811 prev->SetNext(t);
00812 } else if (t->Previous() != NULL) {
00813
00814 t->Previous()->SetNext(NULL);
00815 }
00816 prev = t;
00817 }
00818 }
00819
00825 static void RemoveFromConsist(Train *part, bool chain = false)
00826 {
00827 Train *tail = chain ? part->Last() : part->GetLastEnginePart();
00828
00829
00830
00831 if (part->Previous() != NULL) part->Previous()->SetNext(tail->Next());
00832
00833
00834 tail->SetNext(NULL);
00835 }
00836
00842 static void InsertInConsist(Train *dst, Train *chain)
00843 {
00844
00845 assert(dst->Next() == NULL || !dst->Next()->IsArticulatedPart());
00846
00847 chain->Last()->SetNext(dst->Next());
00848 dst->SetNext(chain);
00849 }
00850
00856 static void NormaliseDualHeads(Train *t)
00857 {
00858 for (; t != NULL; t = t->GetNextVehicle()) {
00859 if (!t->IsMultiheaded() || !t->IsEngine()) continue;
00860
00861
00862 Train *u;
00863 for (u = t; u->Next() != NULL && !u->Next()->IsEngine(); u = u->Next()) {}
00864
00865 if (u == t->other_multiheaded_part) continue;
00866
00867
00868 RemoveFromConsist(t->other_multiheaded_part);
00869
00870 InsertInConsist(u, t->other_multiheaded_part);
00871 }
00872 }
00873
00878 static void NormaliseSubtypes(Train *chain)
00879 {
00880
00881 if (chain == NULL) return;
00882
00883
00884 assert(chain->Previous() == NULL);
00885
00886
00887 if (chain->IsWagon()) {
00888 chain->SetFreeWagon();
00889 } else {
00890 assert(chain->IsEngine());
00891 chain->SetFrontEngine();
00892 }
00893
00894
00895 for (Train *t = chain->Next(); t != NULL; t = t->Next()) {
00896 t->ClearFreeWagon();
00897 t->ClearFrontEngine();
00898 }
00899 }
00900
00910 static CommandCost CheckNewTrain(Train *original_dst, Train *dst, Train *original_src, Train *src)
00911 {
00912
00913
00914
00915 if ((src != NULL && src->IsEngine() ? 1 : 0) +
00916 (dst != NULL && dst->IsEngine() ? 1 : 0) -
00917 (original_src != NULL && original_src->IsEngine() ? 1 : 0) -
00918 (original_dst != NULL && original_dst->IsEngine() ? 1 : 0) <= 0) {
00919 return CommandCost();
00920 }
00921
00922
00923
00924 if (GetFreeUnitNumber(VEH_TRAIN) <= _settings_game.vehicle.max_trains) return CommandCost();
00925
00926 return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
00927 }
00928
00934 static CommandCost CheckTrainAttachment(Train *t)
00935 {
00936
00937 if (t == NULL || t->Next() == NULL || !t->IsEngine()) return CommandCost();
00938
00939
00940
00941 int allowed_len = _settings_game.vehicle.mammoth_trains ? 100 : 10;
00942
00943 Train *head = t;
00944 Train *prev = t;
00945
00946
00947 t = t->Next();
00948 allowed_len--;
00949 prev->SetNext(NULL);
00950
00951
00952 head->InvalidateNewGRFCache();
00953
00954 while (t != NULL) {
00955 Train *next = t->Next();
00956
00957
00958
00959 t->SetNext(NULL);
00960
00961
00962 if (!t->IsArticulatedPart() && !t->IsRearDualheaded()) {
00963 allowed_len--;
00964
00965
00966 EngineID first_engine = t->gcache.first_engine;
00967 t->gcache.first_engine = INVALID_ENGINE;
00968
00969
00970
00971 t->InvalidateNewGRFCache();
00972
00973 uint16 callback = GetVehicleCallbackParent(CBID_TRAIN_ALLOW_WAGON_ATTACH, 0, 0, head->engine_type, t, head);
00974
00975
00976 t->gcache.first_engine = first_engine;
00977
00978
00979 t->InvalidateNewGRFCache();
00980 head->InvalidateNewGRFCache();
00981
00982 if (callback != CALLBACK_FAILED) {
00983
00984 StringID error = STR_NULL;
00985
00986 if (callback == 0xFD) error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
00987 if (callback < 0xFD) error = GetGRFStringID(GetEngineGRFID(head->engine_type), 0xD000 + callback);
00988
00989 if (error != STR_NULL) return_cmd_error(error);
00990 }
00991 }
00992
00993
00994 prev->SetNext(t);
00995 prev = t;
00996 t = next;
00997 }
00998
00999 if (allowed_len <= 0) return_cmd_error(STR_ERROR_TRAIN_TOO_LONG);
01000 return CommandCost();
01001 }
01002
01013 static CommandCost ValidateTrains(Train *original_dst, Train *dst, Train *original_src, Train *src, bool check_limit)
01014 {
01015
01016 CommandCost ret = CheckTrainAttachment(src);
01017 if (ret.Failed()) return ret;
01018 ret = CheckTrainAttachment(dst);
01019 if (ret.Failed()) return ret;
01020
01021
01022 return check_limit ? CheckNewTrain(original_dst, dst, original_src, src) : CommandCost();
01023 }
01024
01033 static void ArrangeTrains(Train **dst_head, Train *dst, Train **src_head, Train *src, bool move_chain)
01034 {
01035
01036 if (*src_head == *dst_head) {
01037
01038
01039 *dst_head = NULL;
01040 } else if (*dst_head == NULL) {
01041
01042
01043 *dst_head = src;
01044 }
01045
01046 if (src == *src_head) {
01047
01048
01049
01050
01051
01052
01053 *src_head = move_chain ? NULL :
01054 (src->IsMultiheaded() ? src->GetNextUnit() : src->GetNextVehicle());
01055 }
01056
01057
01058
01059
01060 RemoveFromConsist(src, move_chain);
01061 if (*dst_head != src) InsertInConsist(dst, src);
01062
01063
01064
01065 NormaliseDualHeads(*src_head);
01066 NormaliseDualHeads(*dst_head);
01067 }
01068
01074 static void NormaliseTrainHead(Train *head)
01075 {
01076
01077 if (head == NULL) return;
01078
01079
01080 head->ConsistChanged(false);
01081 UpdateTrainGroupID(head);
01082
01083
01084 if (!head->IsFrontEngine()) return;
01085
01086
01087 InvalidateWindowData(WC_VEHICLE_REFIT, head->index);
01088 SetWindowWidgetDirty(WC_VEHICLE_VIEW, head->index, VVW_WIDGET_REFIT_VEH);
01089
01090
01091 if (head->unitnumber != 0) return;
01092 head->unitnumber = GetFreeUnitNumber(VEH_TRAIN);
01093 }
01094
01107 CommandCost CmdMoveRailVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01108 {
01109 VehicleID s = GB(p1, 0, 20);
01110 VehicleID d = GB(p2, 0, 20);
01111 bool move_chain = HasBit(p1, 20);
01112
01113 Train *src = Train::GetIfValid(s);
01114 if (src == NULL) return CMD_ERROR;
01115
01116 CommandCost ret = CheckOwnership(src->owner);
01117 if (ret.Failed()) return ret;
01118
01119
01120 if (src->vehstatus & VS_CRASHED) return CMD_ERROR;
01121
01122
01123 Train *dst;
01124 if (d == INVALID_VEHICLE) {
01125 dst = src->IsEngine() ? NULL : FindGoodVehiclePos(src);
01126 } else {
01127 dst = Train::GetIfValid(d);
01128 if (dst == NULL) return CMD_ERROR;
01129
01130 CommandCost ret = CheckOwnership(dst->owner);
01131 if (ret.Failed()) return ret;
01132
01133
01134 if (dst->vehstatus & VS_CRASHED) return CMD_ERROR;
01135 }
01136
01137
01138 src = src->GetFirstEnginePart();
01139 if (dst != NULL) {
01140 dst = dst->GetFirstEnginePart();
01141 }
01142
01143
01144 if (src == dst) return CommandCost();
01145
01146
01147 Train *src_head = src->First();
01148 Train *dst_head;
01149 if (dst != NULL) {
01150 dst_head = dst->First();
01151 if (dst_head->tile != src_head->tile) return CMD_ERROR;
01152
01153 dst = dst->GetLastEnginePart();
01154 } else {
01155 dst_head = NULL;
01156 }
01157
01158 if (src->IsRearDualheaded()) return_cmd_error(STR_ERROR_REAR_ENGINE_FOLLOW_FRONT);
01159
01160
01161 if (move_chain && src_head == dst_head) return CommandCost();
01162
01163
01164 if (!move_chain && dst != NULL && dst->IsRearDualheaded() && src == dst->other_multiheaded_part) return CommandCost();
01165
01166
01167 if (!src_head->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
01168
01169
01170 if (dst_head != NULL && !dst_head->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
01171
01172
01173
01174 TrainList original_src;
01175 TrainList original_dst;
01176
01177 MakeTrainBackup(original_src, src_head);
01178 MakeTrainBackup(original_dst, dst_head);
01179
01180
01181
01182
01183 Train *original_src_head = src_head;
01184 Train *original_dst_head = (dst_head == src_head ? NULL : dst_head);
01185
01186
01187 ArrangeTrains(&dst_head, dst, &src_head, src, move_chain);
01188
01189 if ((flags & DC_AUTOREPLACE) == 0) {
01190
01191
01192
01193 CommandCost ret = ValidateTrains(original_dst_head, dst_head, original_src_head, src_head, true);
01194 if (ret.Failed()) {
01195
01196 RestoreTrainBackup(original_src);
01197 RestoreTrainBackup(original_dst);
01198 return ret;
01199 }
01200 }
01201
01202
01203 if (flags & DC_EXEC) {
01204
01205 NormaliseSubtypes(src_head);
01206 NormaliseSubtypes(dst_head);
01207
01208
01209
01210
01211
01212
01213
01214
01215
01216
01217
01218
01219
01220
01221
01222
01223
01224
01225
01226
01227
01228 if (src == original_src_head && src->IsEngine() && !src->IsFrontEngine()) {
01229
01230 DeleteWindowById(WC_VEHICLE_VIEW, src->index);
01231 DeleteWindowById(WC_VEHICLE_ORDERS, src->index);
01232 DeleteWindowById(WC_VEHICLE_REFIT, src->index);
01233 DeleteWindowById(WC_VEHICLE_DETAILS, src->index);
01234 DeleteWindowById(WC_VEHICLE_TIMETABLE, src->index);
01235
01236
01237
01238 if (dst_head != NULL && dst_head != src && (src_head == NULL || !src_head->IsFrontEngine())) {
01239 DecreaseGroupNumVehicle(src->group_id);
01240 }
01241
01242
01243
01244 if (dst_head == NULL && !src_head->IsFrontEngine()) {
01245 DecreaseGroupNumVehicle(src->group_id);
01246 }
01247
01248
01249
01250 DeleteVehicleOrders(src);
01251 RemoveVehicleFromGroup(src);
01252 src->unitnumber = 0;
01253 }
01254
01255
01256
01257 if (original_src_head == src && dst_head == src) {
01258 IncreaseGroupNumVehicle(src->group_id);
01259 }
01260
01261
01262
01263 if (original_src_head != src && dst_head == src) {
01264 SetTrainGroupID(src, DEFAULT_GROUP);
01265 }
01266
01267
01268 NormaliseTrainHead(src_head);
01269 NormaliseTrainHead(dst_head);
01270
01271
01272 InvalidateWindowData(WC_VEHICLE_DEPOT, src->tile);
01273 InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
01274 } else {
01275
01276 RestoreTrainBackup(original_src);
01277 RestoreTrainBackup(original_dst);
01278 }
01279
01280 return CommandCost();
01281 }
01282
01294 CommandCost CmdSellRailWagon(DoCommandFlag flags, Vehicle *t, uint16 data, uint32 user)
01295 {
01296
01297 Window *w = NULL;
01298
01299
01300 bool sell_chain = HasBit(data, 0);
01301
01302 Train *v = Train::From(t)->GetFirstEnginePart();
01303 Train *first = v->First();
01304
01305 if (v->IsRearDualheaded()) return_cmd_error(STR_ERROR_REAR_ENGINE_FOLLOW_FRONT);
01306
01307
01308
01309 TrainList original;
01310 MakeTrainBackup(original, first);
01311
01312
01313 Train *new_head = first;
01314 Train *sell_head = NULL;
01315
01316
01317 ArrangeTrains(&sell_head, NULL, &new_head, v, sell_chain);
01318
01319
01320 CommandCost ret = ValidateTrains(NULL, NULL, first, new_head, (flags & DC_AUTOREPLACE) == 0);
01321 if (ret.Failed()) {
01322
01323 RestoreTrainBackup(original);
01324 return ret;
01325 }
01326
01327 CommandCost cost(EXPENSES_NEW_VEHICLES);
01328 for (Train *t = sell_head; t != NULL; t = t->Next()) cost.AddCost(-t->value);
01329
01330
01331 if (flags & DC_EXEC) {
01332
01333 NormaliseSubtypes(new_head);
01334
01335 if (v == first && v->IsEngine() && !sell_chain && new_head != NULL && new_head->IsFrontEngine()) {
01336
01337
01338 new_head->orders.list = first->orders.list;
01339 new_head->AddToShared(first);
01340 DeleteVehicleOrders(first);
01341
01342
01343 new_head->CopyVehicleConfigAndStatistics(first);
01344 IncreaseGroupNumVehicle(new_head->group_id);
01345
01346
01347 if (IsLocalCompany() && w != NULL) ShowVehicleViewWindow(new_head);
01348 } else if (v->IsPrimaryVehicle() && data & (MAKE_ORDER_BACKUP_FLAG >> 20)) {
01349 OrderBackup::Backup(v, user);
01350 }
01351
01352
01353 NormaliseTrainHead(new_head);
01354
01355
01356 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
01357 InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
01358
01359
01360 delete sell_head;
01361 } else {
01362
01363 RestoreTrainBackup(original);
01364 }
01365
01366 return cost;
01367 }
01368
01369 void Train::UpdateDeltaXY(Direction direction)
01370 {
01371 #define MKIT(a, b, c, d) ((a & 0xFF) << 24) | ((b & 0xFF) << 16) | ((c & 0xFF) << 8) | ((d & 0xFF) << 0)
01372 static const uint32 _delta_xy_table[8] = {
01373 MKIT(3, 3, -1, -1),
01374 MKIT(3, 7, -1, -3),
01375 MKIT(3, 3, -1, -1),
01376 MKIT(7, 3, -3, -1),
01377 MKIT(3, 3, -1, -1),
01378 MKIT(3, 7, -1, -3),
01379 MKIT(3, 3, -1, -1),
01380 MKIT(7, 3, -3, -1),
01381 };
01382 #undef MKIT
01383
01384 uint32 x = _delta_xy_table[direction];
01385 this->x_offs = GB(x, 0, 8);
01386 this->y_offs = GB(x, 8, 8);
01387 this->x_extent = GB(x, 16, 8);
01388 this->y_extent = GB(x, 24, 8);
01389 this->z_extent = 6;
01390 }
01391
01392 static inline void SetLastSpeed(Train *v, int spd)
01393 {
01394 int old = v->tcache.last_speed;
01395 if (spd != old) {
01396 v->tcache.last_speed = spd;
01397 if (_settings_client.gui.vehicle_speed || (old == 0) != (spd == 0)) {
01398 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
01399 }
01400 }
01401 }
01402
01404 static void MarkTrainAsStuck(Train *v)
01405 {
01406 if (!HasBit(v->flags, VRF_TRAIN_STUCK)) {
01407
01408 SetBit(v->flags, VRF_TRAIN_STUCK);
01409
01410 v->wait_counter = 0;
01411
01412
01413 v->cur_speed = 0;
01414 v->subspeed = 0;
01415 SetLastSpeed(v, 0);
01416
01417 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
01418 }
01419 }
01420
01421 static void SwapTrainFlags(uint16 *swap_flag1, uint16 *swap_flag2)
01422 {
01423 uint16 flag1 = *swap_flag1;
01424 uint16 flag2 = *swap_flag2;
01425
01426
01427 ClrBit(*swap_flag1, GVF_GOINGUP_BIT);
01428 ClrBit(*swap_flag1, GVF_GOINGDOWN_BIT);
01429 ClrBit(*swap_flag2, GVF_GOINGUP_BIT);
01430 ClrBit(*swap_flag2, GVF_GOINGDOWN_BIT);
01431
01432
01433 if (HasBit(flag1, GVF_GOINGUP_BIT)) {
01434 SetBit(*swap_flag2, GVF_GOINGDOWN_BIT);
01435 } else if (HasBit(flag1, GVF_GOINGDOWN_BIT)) {
01436 SetBit(*swap_flag2, GVF_GOINGUP_BIT);
01437 }
01438 if (HasBit(flag2, GVF_GOINGUP_BIT)) {
01439 SetBit(*swap_flag1, GVF_GOINGDOWN_BIT);
01440 } else if (HasBit(flag2, GVF_GOINGDOWN_BIT)) {
01441 SetBit(*swap_flag1, GVF_GOINGUP_BIT);
01442 }
01443 }
01444
01449 static void UpdateStatusAfterSwap(Train *v)
01450 {
01451
01452 if (v->track != TRACK_BIT_DEPOT) v->direction = ReverseDir(v->direction);
01453
01454
01455 if (v->track != TRACK_BIT_WORMHOLE) {
01456 VehicleEnterTile(v, v->tile, v->x_pos, v->y_pos);
01457 } else {
01458
01459
01460
01461
01462 TileIndex vt = TileVirtXY(v->x_pos, v->y_pos);
01463 if (IsTileType(vt, MP_TUNNELBRIDGE)) {
01464 VehicleEnterTile(v, vt, v->x_pos, v->y_pos);
01465 if (v->track != TRACK_BIT_WORMHOLE && IsBridgeTile(v->tile)) {
01466
01467
01468
01469 v->UpdateInclination(true, true);
01470 return;
01471 }
01472 }
01473 }
01474
01475 v->UpdateViewport(true, true);
01476 }
01477
01478 static void ReverseTrainSwapVeh(Train *v, int l, int r)
01479 {
01480 Train *a, *b;
01481
01482
01483 for (a = v; l != 0; l--) a = a->Next();
01484 for (b = v; r != 0; r--) b = b->Next();
01485
01486 if (a != b) {
01487
01488 {
01489 uint16 tmp = (a->vehstatus & ~VS_HIDDEN) | (b->vehstatus & VS_HIDDEN);
01490 b->vehstatus = (b->vehstatus & ~VS_HIDDEN) | (a->vehstatus & VS_HIDDEN);
01491 a->vehstatus = tmp;
01492 }
01493
01494 Swap(a->track, b->track);
01495 Swap(a->direction, b->direction);
01496 Swap(a->x_pos, b->x_pos);
01497 Swap(a->y_pos, b->y_pos);
01498 Swap(a->tile, b->tile);
01499 Swap(a->z_pos, b->z_pos);
01500
01501 SwapTrainFlags(&a->gv_flags, &b->gv_flags);
01502
01503 UpdateStatusAfterSwap(a);
01504 UpdateStatusAfterSwap(b);
01505 } else {
01506
01507
01508
01509 SwapTrainFlags(&a->gv_flags, &a->gv_flags);
01510 UpdateStatusAfterSwap(a);
01511 }
01512
01513
01514 v->RailtypeChanged();
01515 }
01516
01517
01523 static Vehicle *TrainOnTileEnum(Vehicle *v, void *)
01524 {
01525 return (v->type == VEH_TRAIN) ? v : NULL;
01526 }
01527
01528
01535 static Vehicle *TrainApproachingCrossingEnum(Vehicle *v, void *data)
01536 {
01537 if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) return NULL;
01538
01539 Train *t = Train::From(v);
01540 if (!t->IsFrontEngine()) return NULL;
01541
01542 TileIndex tile = *(TileIndex *)data;
01543
01544 if (TrainApproachingCrossingTile(t) != tile) return NULL;
01545
01546 return t;
01547 }
01548
01549
01556 static bool TrainApproachingCrossing(TileIndex tile)
01557 {
01558 assert(IsLevelCrossingTile(tile));
01559
01560 DiagDirection dir = AxisToDiagDir(GetCrossingRailAxis(tile));
01561 TileIndex tile_from = tile + TileOffsByDiagDir(dir);
01562
01563 if (HasVehicleOnPos(tile_from, &tile, &TrainApproachingCrossingEnum)) return true;
01564
01565 dir = ReverseDiagDir(dir);
01566 tile_from = tile + TileOffsByDiagDir(dir);
01567
01568 return HasVehicleOnPos(tile_from, &tile, &TrainApproachingCrossingEnum);
01569 }
01570
01571
01578 void UpdateLevelCrossing(TileIndex tile, bool sound)
01579 {
01580 assert(IsLevelCrossingTile(tile));
01581
01582
01583 bool new_state = HasVehicleOnPos(tile, NULL, &TrainOnTileEnum) || TrainApproachingCrossing(tile) || HasCrossingReservation(tile);
01584
01585 if (new_state != IsCrossingBarred(tile)) {
01586 if (new_state && sound) {
01587 SndPlayTileFx(SND_0E_LEVEL_CROSSING, tile);
01588 }
01589 SetCrossingBarred(tile, new_state);
01590 MarkTileDirtyByTile(tile);
01591 }
01592 }
01593
01594
01600 static inline void MaybeBarCrossingWithSound(TileIndex tile)
01601 {
01602 if (!IsCrossingBarred(tile)) {
01603 BarCrossing(tile);
01604 SndPlayTileFx(SND_0E_LEVEL_CROSSING, tile);
01605 MarkTileDirtyByTile(tile);
01606 }
01607 }
01608
01609
01615 static void AdvanceWagonsBeforeSwap(Train *v)
01616 {
01617 Train *base = v;
01618 Train *first = base;
01619 Train *last = v->Last();
01620 uint length = CountVehiclesInChain(v);
01621
01622 while (length > 2) {
01623 last = last->Previous();
01624 first = first->Next();
01625
01626 int differential = base->gcache.cached_veh_length - last->gcache.cached_veh_length;
01627
01628
01629
01630 for (int i = 0; i < differential; i++) TrainController(first, last->Next());
01631
01632 base = first;
01633 length -= 2;
01634 }
01635 }
01636
01637
01643 static void AdvanceWagonsAfterSwap(Train *v)
01644 {
01645
01646 Train *dep = v;
01647 while (dep->Next() != NULL && (dep->track == TRACK_BIT_DEPOT || dep->Next()->track != TRACK_BIT_DEPOT)) {
01648 dep = dep->Next();
01649 }
01650
01651 Train *leave = dep->Next();
01652
01653 if (leave != NULL) {
01654
01655 int d = TicksToLeaveDepot(dep);
01656
01657 if (d <= 0) {
01658 leave->vehstatus &= ~VS_HIDDEN;
01659 leave->track = TrackToTrackBits(GetRailDepotTrack(leave->tile));
01660 for (int i = 0; i >= d; i--) TrainController(leave, NULL);
01661 }
01662 } else {
01663 dep = NULL;
01664 }
01665
01666 Train *base = v;
01667 Train *first = base;
01668 Train *last = v->Last();
01669 uint length = CountVehiclesInChain(v);
01670
01671
01672
01673 bool nomove = (dep == NULL);
01674
01675 while (length > 2) {
01676
01677
01678 if (base == dep) break;
01679
01680
01681 if (last == dep) nomove = true;
01682
01683 last = last->Previous();
01684 first = first->Next();
01685
01686 int differential = last->gcache.cached_veh_length - base->gcache.cached_veh_length;
01687
01688
01689 for (int i = 0; i < differential; i++) TrainController(first, (nomove ? last->Next() : NULL));
01690
01691 base = first;
01692 length -= 2;
01693 }
01694 }
01695
01696
01697 static void ReverseTrainDirection(Train *v)
01698 {
01699 if (IsRailDepotTile(v->tile)) {
01700 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
01701 }
01702
01703
01704 if (!HasBit(v->flags, VRF_TRAIN_STUCK)) FreeTrainTrackReservation(v);
01705
01706
01707 TileIndex crossing = TrainApproachingCrossingTile(v);
01708
01709
01710 int r = CountVehiclesInChain(v) - 1;
01711
01712 AdvanceWagonsBeforeSwap(v);
01713
01714
01715 int l = 0;
01716 do {
01717 ReverseTrainSwapVeh(v, l++, r--);
01718 } while (l <= r);
01719
01720 AdvanceWagonsAfterSwap(v);
01721
01722 if (IsRailDepotTile(v->tile)) {
01723 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
01724 }
01725
01726 ToggleBit(v->flags, VRF_TOGGLE_REVERSE);
01727
01728 ClrBit(v->flags, VRF_REVERSING);
01729
01730
01731 v->ConsistChanged(true);
01732
01733
01734 for (Train *u = v; u != NULL; u = u->Next()) u->UpdateViewport(false, false);
01735
01736
01737 if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
01738
01739
01740 crossing = TrainApproachingCrossingTile(v);
01741 if (crossing != INVALID_TILE) MaybeBarCrossingWithSound(crossing);
01742
01743
01744 if (v->track == TRACK_BIT_DEPOT) {
01745
01746 if (HasBit(v->flags, VRF_TRAIN_STUCK)) SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
01747 ClrBit(v->flags, VRF_TRAIN_STUCK);
01748 return;
01749 }
01750
01751
01752
01753 DiagDirection dir = TrainExitDir(v->direction, v->track);
01754 if (IsRailDepotTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE)) dir = INVALID_DIAGDIR;
01755
01756 if (UpdateSignalsOnSegment(v->tile, dir, v->owner) == SIGSEG_PBS || _settings_game.pf.reserve_paths) {
01757
01758
01759 bool first_tile_okay = !(IsTileType(v->tile, MP_RAILWAY) &&
01760 HasSignalOnTrackdir(v->tile, v->GetVehicleTrackdir()) &&
01761 !IsPbsSignal(GetSignalType(v->tile, FindFirstTrack(v->track))));
01762
01763 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
01764 if (TryPathReserve(v, false, first_tile_okay)) {
01765
01766 CheckNextTrainTile(v);
01767 } else if (v->current_order.GetType() != OT_LOADING) {
01768
01769 MarkTrainAsStuck(v);
01770 }
01771 } else if (HasBit(v->flags, VRF_TRAIN_STUCK)) {
01772
01773 ClrBit(v->flags, VRF_TRAIN_STUCK);
01774 v->wait_counter = 0;
01775 }
01776 }
01777
01787 CommandCost CmdReverseTrainDirection(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01788 {
01789 Train *v = Train::GetIfValid(p1);
01790 if (v == NULL) return CMD_ERROR;
01791
01792 CommandCost ret = CheckOwnership(v->owner);
01793 if (ret.Failed()) return ret;
01794
01795 if (p2 != 0) {
01796
01797
01798 if (v->IsMultiheaded() || HasBit(EngInfo(v->engine_type)->callback_mask, CBM_VEHICLE_ARTIC_ENGINE)) {
01799 return_cmd_error(STR_ERROR_CAN_T_REVERSE_DIRECTION_RAIL_VEHICLE_MULTIPLE_UNITS);
01800 }
01801
01802 Train *front = v->First();
01803
01804 if (!front->IsStoppedInDepot()) {
01805 return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
01806 }
01807
01808 if (flags & DC_EXEC) {
01809 ToggleBit(v->flags, VRF_REVERSE_DIRECTION);
01810 SetWindowDirty(WC_VEHICLE_DEPOT, v->tile);
01811 SetWindowDirty(WC_VEHICLE_DETAILS, v->index);
01812
01813 v->force_proceed = TFP_NONE;
01814 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
01815 }
01816 } else {
01817
01818 if ((v->vehstatus & VS_CRASHED) || v->breakdown_ctr != 0) return CMD_ERROR;
01819
01820 if (flags & DC_EXEC) {
01821
01822 if (v->current_order.IsType(OT_LOADING)) {
01823 const Vehicle *last = v;
01824 while (last->Next() != NULL) last = last->Next();
01825
01826
01827 if (!IsTileType(last->tile, MP_STATION) || GetStationIndex(last->tile) != GetStationIndex(v->tile)) {
01828 v->LeaveStation();
01829 }
01830 }
01831
01832
01833 v->force_proceed = TFP_NONE;
01834 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
01835
01836 if (_settings_game.vehicle.train_acceleration_model != AM_ORIGINAL && v->cur_speed != 0) {
01837 ToggleBit(v->flags, VRF_REVERSING);
01838 } else {
01839 v->cur_speed = 0;
01840 SetLastSpeed(v, 0);
01841 HideFillingPercent(&v->fill_percent_te_id);
01842 ReverseTrainDirection(v);
01843 }
01844 }
01845 }
01846 return CommandCost();
01847 }
01848
01858 CommandCost CmdForceTrainProceed(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01859 {
01860 Train *t = Train::GetIfValid(p1);
01861 if (t == NULL) return CMD_ERROR;
01862
01863 CommandCost ret = CheckOwnership(t->owner);
01864 if (ret.Failed()) return ret;
01865
01866
01867 if (flags & DC_EXEC) {
01868
01869
01870
01871
01872
01873 t->force_proceed = t->force_proceed == TFP_SIGNAL ? TFP_NONE : HasBit(t->flags, VRF_TRAIN_STUCK) || t->IsInDepot() ? TFP_STUCK : TFP_SIGNAL;
01874 SetWindowDirty(WC_VEHICLE_VIEW, t->index);
01875 }
01876
01877 return CommandCost();
01878 }
01879
01884 static FindDepotData FindClosestTrainDepot(Train *v, int max_distance)
01885 {
01886 assert(!(v->vehstatus & VS_CRASHED));
01887
01888 if (IsRailDepotTile(v->tile)) return FindDepotData(v->tile, 0);
01889
01890 PBSTileInfo origin = FollowTrainReservation(v);
01891 if (IsRailDepotTile(origin.tile)) return FindDepotData(origin.tile, 0);
01892
01893 switch (_settings_game.pf.pathfinder_for_trains) {
01894 case VPF_NPF: return NPFTrainFindNearestDepot(v, max_distance);
01895 case VPF_YAPF: return YapfTrainFindNearestDepot(v, max_distance);
01896
01897 default: NOT_REACHED();
01898 }
01899 }
01900
01901 bool Train::FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
01902 {
01903 FindDepotData tfdd = FindClosestTrainDepot(this, 0);
01904 if (tfdd.best_length == UINT_MAX) return false;
01905
01906 if (location != NULL) *location = tfdd.tile;
01907 if (destination != NULL) *destination = GetDepotIndex(tfdd.tile);
01908 if (reverse != NULL) *reverse = tfdd.reverse;
01909
01910 return true;
01911 }
01912
01913 void Train::PlayLeaveStationSound() const
01914 {
01915 static const SoundFx sfx[] = {
01916 SND_04_TRAIN,
01917 SND_0A_TRAIN_HORN,
01918 SND_0A_TRAIN_HORN,
01919 SND_47_MAGLEV_2,
01920 SND_41_MAGLEV
01921 };
01922
01923 if (PlayVehicleSound(this, VSE_START)) return;
01924
01925 EngineID engtype = this->engine_type;
01926 SndPlayVehicleFx(sfx[RailVehInfo(engtype)->engclass], this);
01927 }
01928
01930 static void CheckNextTrainTile(Train *v)
01931 {
01932
01933 if (_settings_game.pf.path_backoff_interval == 255) return;
01934
01935
01936 if (v->track == TRACK_BIT_DEPOT) return;
01937
01938 switch (v->current_order.GetType()) {
01939
01940 case OT_GOTO_DEPOT:
01941 if (v->tile == v->dest_tile) return;
01942 break;
01943
01944 case OT_GOTO_WAYPOINT:
01945
01946 if (IsRailWaypointTile(v->tile) && GetStationIndex(v->tile) == v->current_order.GetDestination()) ProcessOrders(v);
01947 break;
01948
01949 case OT_NOTHING:
01950 case OT_LEAVESTATION:
01951 case OT_LOADING:
01952
01953 if (v->GetNumOrders() > 0) return;
01954 break;
01955
01956 default:
01957 break;
01958 }
01959
01960 if (IsRailStationTile(v->tile) && v->current_order.ShouldStopAtStation(v, GetStationIndex(v->tile))) return;
01961
01962 Trackdir td = v->GetVehicleTrackdir();
01963
01964
01965 if (IsTileType(v->tile, MP_RAILWAY) && HasSignalOnTrackdir(v->tile, td) &&
01966 !IsPbsSignal(GetSignalType(v->tile, TrackdirToTrack(td))) &&
01967 GetSignalStateByTrackdir(v->tile, td) == SIGNAL_STATE_RED) return;
01968
01969 CFollowTrackRail ft(v);
01970 if (!ft.Follow(v->tile, td)) return;
01971
01972 if (!HasReservedTracks(ft.m_new_tile, TrackdirBitsToTrackBits(ft.m_new_td_bits))) {
01973
01974 if (KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE) {
01975 if (HasPbsSignalOnTrackdir(ft.m_new_tile, FindFirstTrackdir(ft.m_new_td_bits))) {
01976
01977 TrackBits tracks = TrackdirBitsToTrackBits(ft.m_new_td_bits);
01978 if (_settings_game.pf.forbid_90_deg) {
01979 tracks &= ~TrackCrossesTracks(TrackdirToTrack(ft.m_old_td));
01980 }
01981 ChooseTrainTrack(v, ft.m_new_tile, ft.m_exitdir, tracks, false, NULL, false);
01982 }
01983 }
01984 }
01985 }
01986
01987 static bool CheckTrainStayInDepot(Train *v)
01988 {
01989
01990 for (const Train *u = v; u != NULL; u = u->Next()) {
01991 if (u->track != TRACK_BIT_DEPOT || u->tile != v->tile) return false;
01992 }
01993
01994
01995 if (v->gcache.cached_power == 0) {
01996 v->vehstatus |= VS_STOPPED;
01997 SetWindowDirty(WC_VEHICLE_DEPOT, v->tile);
01998 return true;
01999 }
02000
02001 SigSegState seg_state;
02002
02003 if (v->force_proceed == TFP_NONE) {
02004
02005 if (++v->wait_counter < 37) {
02006 SetWindowClassesDirty(WC_TRAINS_LIST);
02007 return true;
02008 }
02009
02010 v->wait_counter = 0;
02011
02012 seg_state = _settings_game.pf.reserve_paths ? SIGSEG_PBS : UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
02013 if (seg_state == SIGSEG_FULL || HasDepotReservation(v->tile)) {
02014
02015 SetWindowClassesDirty(WC_TRAINS_LIST);
02016 return true;
02017 }
02018 } else {
02019 seg_state = _settings_game.pf.reserve_paths ? SIGSEG_PBS : UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
02020 }
02021
02022
02023 if (v->current_order.IsType(OT_GOTO_DEPOT) && v->tile == v->dest_tile) {
02024
02025 if (HasDepotReservation(v->tile)) return true;
02026 SetDepotReservation(v->tile, true);
02027 VehicleEnterDepot(v);
02028 return true;
02029 }
02030
02031
02032 if (seg_state == SIGSEG_PBS && !TryPathReserve(v) && v->force_proceed == TFP_NONE) {
02033
02034 SetWindowClassesDirty(WC_TRAINS_LIST);
02035 MarkTrainAsStuck(v);
02036 return true;
02037 }
02038
02039 SetDepotReservation(v->tile, true);
02040 if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(v->tile);
02041
02042 VehicleServiceInDepot(v);
02043 SetWindowClassesDirty(WC_TRAINS_LIST);
02044 v->PlayLeaveStationSound();
02045
02046 v->track = TRACK_BIT_X;
02047 if (v->direction & 2) v->track = TRACK_BIT_Y;
02048
02049 v->vehstatus &= ~VS_HIDDEN;
02050 v->cur_speed = 0;
02051
02052 v->UpdateDeltaXY(v->direction);
02053 v->cur_image = v->GetImage(v->direction);
02054 VehicleMove(v, false);
02055 UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
02056 v->UpdateAcceleration();
02057 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
02058
02059 return false;
02060 }
02061
02063 static void ClearPathReservation(const Train *v, TileIndex tile, Trackdir track_dir)
02064 {
02065 DiagDirection dir = TrackdirToExitdir(track_dir);
02066
02067 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
02068
02069 if (GetTunnelBridgeDirection(tile) == ReverseDiagDir(dir)) {
02070 TileIndex end = GetOtherTunnelBridgeEnd(tile);
02071
02072 if (TunnelBridgeIsFree(tile, end, v).Succeeded()) {
02073
02074 SetTunnelBridgeReservation(tile, false);
02075 SetTunnelBridgeReservation(end, false);
02076
02077 if (_settings_client.gui.show_track_reservation) {
02078 MarkTileDirtyByTile(tile);
02079 MarkTileDirtyByTile(end);
02080 }
02081 }
02082 }
02083 } else if (IsRailStationTile(tile)) {
02084 TileIndex new_tile = TileAddByDiagDir(tile, dir);
02085
02086
02087 if (!IsCompatibleTrainStationTile(new_tile, tile)) {
02088 SetRailStationPlatformReservation(tile, ReverseDiagDir(dir), false);
02089 }
02090 } else {
02091
02092 UnreserveRailTrack(tile, TrackdirToTrack(track_dir));
02093 }
02094 }
02095
02097 void FreeTrainTrackReservation(const Train *v, TileIndex origin, Trackdir orig_td)
02098 {
02099 assert(v->IsFrontEngine());
02100
02101 TileIndex tile = origin != INVALID_TILE ? origin : v->tile;
02102 Trackdir td = orig_td != INVALID_TRACKDIR ? orig_td : v->GetVehicleTrackdir();
02103 bool free_tile = tile != v->tile || !(IsRailStationTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE));
02104 StationID station_id = IsRailStationTile(v->tile) ? GetStationIndex(v->tile) : INVALID_STATION;
02105
02106
02107 if (TracksOverlap(GetReservedTrackbits(tile) | TrackToTrackBits(TrackdirToTrack(td)))) return;
02108
02109 CFollowTrackRail ft(v, GetRailTypeInfo(v->railtype)->compatible_railtypes);
02110 while (ft.Follow(tile, td)) {
02111 tile = ft.m_new_tile;
02112 TrackdirBits bits = ft.m_new_td_bits & TrackBitsToTrackdirBits(GetReservedTrackbits(tile));
02113 td = RemoveFirstTrackdir(&bits);
02114 assert(bits == TRACKDIR_BIT_NONE);
02115
02116 if (!IsValidTrackdir(td)) break;
02117
02118 if (IsTileType(tile, MP_RAILWAY)) {
02119 if (HasSignalOnTrackdir(tile, td) && !IsPbsSignal(GetSignalType(tile, TrackdirToTrack(td)))) {
02120
02121 UnreserveRailTrack(tile, TrackdirToTrack(td));
02122 break;
02123 }
02124 if (HasPbsSignalOnTrackdir(tile, td)) {
02125 if (GetSignalStateByTrackdir(tile, td) == SIGNAL_STATE_RED) {
02126
02127 break;
02128 } else {
02129
02130 SetSignalStateByTrackdir(tile, td, SIGNAL_STATE_RED);
02131 MarkTileDirtyByTile(tile);
02132 }
02133 } else if (HasSignalOnTrackdir(tile, ReverseTrackdir(td)) && IsOnewaySignal(tile, TrackdirToTrack(td))) {
02134 break;
02135 }
02136 }
02137
02138
02139 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);
02140
02141 free_tile = true;
02142 }
02143 }
02144
02145 static const byte _initial_tile_subcoord[6][4][3] = {
02146 {{ 15, 8, 1 }, { 0, 0, 0 }, { 0, 8, 5 }, { 0, 0, 0 }},
02147 {{ 0, 0, 0 }, { 8, 0, 3 }, { 0, 0, 0 }, { 8, 15, 7 }},
02148 {{ 0, 0, 0 }, { 7, 0, 2 }, { 0, 7, 6 }, { 0, 0, 0 }},
02149 {{ 15, 8, 2 }, { 0, 0, 0 }, { 0, 0, 0 }, { 8, 15, 6 }},
02150 {{ 15, 7, 0 }, { 8, 0, 4 }, { 0, 0, 0 }, { 0, 0, 0 }},
02151 {{ 0, 0, 0 }, { 0, 0, 0 }, { 0, 8, 4 }, { 7, 15, 0 }},
02152 };
02153
02166 static Track DoTrainPathfind(const Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool &path_found, bool do_track_reservation, PBSTileInfo *dest)
02167 {
02168 switch (_settings_game.pf.pathfinder_for_trains) {
02169 case VPF_NPF: return NPFTrainChooseTrack(v, tile, enterdir, tracks, path_found, do_track_reservation, dest);
02170 case VPF_YAPF: return YapfTrainChooseTrack(v, tile, enterdir, tracks, path_found, do_track_reservation, dest);
02171
02172 default: NOT_REACHED();
02173 }
02174 }
02175
02181 static PBSTileInfo ExtendTrainReservation(const Train *v, TrackBits *new_tracks, DiagDirection *enterdir)
02182 {
02183 PBSTileInfo origin = FollowTrainReservation(v);
02184
02185 CFollowTrackRail ft(v);
02186
02187 TileIndex tile = origin.tile;
02188 Trackdir cur_td = origin.trackdir;
02189 while (ft.Follow(tile, cur_td)) {
02190 if (KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE) {
02191
02192 if (HasOnewaySignalBlockingTrackdir(ft.m_new_tile, FindFirstTrackdir(ft.m_new_td_bits))) break;
02193 }
02194
02195 if (_settings_game.pf.forbid_90_deg) {
02196 ft.m_new_td_bits &= ~TrackdirCrossesTrackdirs(ft.m_old_td);
02197 if (ft.m_new_td_bits == TRACKDIR_BIT_NONE) break;
02198 }
02199
02200
02201 bool target_seen = ft.m_is_station || (IsTileType(ft.m_new_tile, MP_RAILWAY) && !IsPlainRail(ft.m_new_tile));
02202 if (target_seen || KillFirstBit(ft.m_new_td_bits) != TRACKDIR_BIT_NONE) {
02203
02204
02205
02206
02207
02208
02209 if (HasReservedTracks(ft.m_new_tile, TrackdirBitsToTrackBits(TrackdirReachesTrackdirs(ft.m_old_td)))) break;
02210
02211
02212
02213 if (ft.m_tiles_skipped != 0) ft.m_new_tile -= TileOffsByDiagDir(ft.m_exitdir) * ft.m_tiles_skipped;
02214
02215
02216 if (new_tracks) *new_tracks = TrackdirBitsToTrackBits(ft.m_new_td_bits);
02217 if (enterdir) *enterdir = ft.m_exitdir;
02218 return PBSTileInfo(ft.m_new_tile, ft.m_old_td, false);
02219 }
02220
02221 tile = ft.m_new_tile;
02222 cur_td = FindFirstTrackdir(ft.m_new_td_bits);
02223
02224 if (IsSafeWaitingPosition(v, tile, cur_td, true, _settings_game.pf.forbid_90_deg)) {
02225 bool wp_free = IsWaitingPositionFree(v, tile, cur_td, _settings_game.pf.forbid_90_deg);
02226 if (!(wp_free && TryReserveRailTrack(tile, TrackdirToTrack(cur_td)))) break;
02227
02228 return PBSTileInfo(tile, cur_td, true);
02229 }
02230
02231 if (!TryReserveRailTrack(tile, TrackdirToTrack(cur_td))) break;
02232 }
02233
02234 if (ft.m_err == CFollowTrackRail::EC_OWNER || ft.m_err == CFollowTrackRail::EC_NO_WAY) {
02235
02236 return PBSTileInfo(ft.m_old_tile, ft.m_old_td, true);
02237 }
02238
02239
02240 tile = origin.tile;
02241 cur_td = origin.trackdir;
02242 TileIndex stopped = ft.m_old_tile;
02243 Trackdir stopped_td = ft.m_old_td;
02244 while (tile != stopped || cur_td != stopped_td) {
02245 if (!ft.Follow(tile, cur_td)) break;
02246
02247 if (_settings_game.pf.forbid_90_deg) {
02248 ft.m_new_td_bits &= ~TrackdirCrossesTrackdirs(ft.m_old_td);
02249 assert(ft.m_new_td_bits != TRACKDIR_BIT_NONE);
02250 }
02251 assert(KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE);
02252
02253 tile = ft.m_new_tile;
02254 cur_td = FindFirstTrackdir(ft.m_new_td_bits);
02255
02256 UnreserveRailTrack(tile, TrackdirToTrack(cur_td));
02257 }
02258
02259
02260 return PBSTileInfo();
02261 }
02262
02273 static bool TryReserveSafeTrack(const Train *v, TileIndex tile, Trackdir td, bool override_tailtype)
02274 {
02275 switch (_settings_game.pf.pathfinder_for_trains) {
02276 case VPF_NPF: return NPFTrainFindNearestSafeTile(v, tile, td, override_tailtype);
02277 case VPF_YAPF: return YapfTrainFindNearestSafeTile(v, tile, td, override_tailtype);
02278
02279 default: NOT_REACHED();
02280 }
02281 }
02282
02284 class VehicleOrderSaver
02285 {
02286 private:
02287 Vehicle *v;
02288 Order old_order;
02289 TileIndex old_dest_tile;
02290 StationID old_last_station_visited;
02291 VehicleOrderID index;
02292
02293 public:
02294 VehicleOrderSaver(Vehicle *_v) :
02295 v(_v),
02296 old_order(_v->current_order),
02297 old_dest_tile(_v->dest_tile),
02298 old_last_station_visited(_v->last_station_visited),
02299 index(_v->cur_order_index)
02300 {
02301 }
02302
02303 ~VehicleOrderSaver()
02304 {
02305 this->v->current_order = this->old_order;
02306 this->v->dest_tile = this->old_dest_tile;
02307 this->v->last_station_visited = this->old_last_station_visited;
02308 }
02309
02315 bool SwitchToNextOrder(bool skip_first)
02316 {
02317 if (this->v->GetNumOrders() == 0) return false;
02318
02319 if (skip_first) ++this->index;
02320
02321 int conditional_depth = 0;
02322
02323 do {
02324
02325 if (this->index >= this->v->GetNumOrders()) this->index = 0;
02326
02327 Order *order = this->v->GetOrder(this->index);
02328 assert(order != NULL);
02329
02330 switch (order->GetType()) {
02331 case OT_GOTO_DEPOT:
02332
02333 if ((order->GetDepotOrderType() & ODTFB_SERVICE) && !this->v->NeedsServicing()) break;
02334 case OT_GOTO_STATION:
02335 case OT_GOTO_WAYPOINT:
02336 this->v->current_order = *order;
02337 UpdateOrderDest(this->v, order);
02338 return true;
02339 case OT_CONDITIONAL: {
02340 if (conditional_depth > this->v->GetNumOrders()) return false;
02341 VehicleOrderID next = ProcessConditionalOrder(order, this->v);
02342 if (next != INVALID_VEH_ORDER_ID) {
02343 conditional_depth++;
02344 this->index = next;
02345
02346 continue;
02347 }
02348 break;
02349 }
02350 default:
02351 break;
02352 }
02353
02354
02355 ++this->index;
02356 } while (this->index != this->v->cur_order_index);
02357
02358 return false;
02359 }
02360 };
02361
02362
02363 static Track ChooseTrainTrack(Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool force_res, bool *got_reservation, bool mark_stuck)
02364 {
02365 Track best_track = INVALID_TRACK;
02366 bool do_track_reservation = _settings_game.pf.reserve_paths || force_res;
02367 bool changed_signal = false;
02368
02369 assert((tracks & ~TRACK_BIT_MASK) == 0);
02370
02371 if (got_reservation != NULL) *got_reservation = false;
02372
02373
02374 TrackBits res_tracks = (TrackBits)(GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir));
02375
02376 if (res_tracks != TRACK_BIT_NONE) return FindFirstTrack(res_tracks);
02377
02378
02379 if (KillFirstBit(tracks) == TRACK_BIT_NONE) {
02380 Track track = FindFirstTrack(tracks);
02381
02382 if (track != INVALID_TRACK && HasPbsSignalOnTrackdir(tile, TrackEnterdirToTrackdir(track, enterdir))) {
02383 do_track_reservation = true;
02384 changed_signal = true;
02385 SetSignalStateByTrackdir(tile, TrackEnterdirToTrackdir(track, enterdir), SIGNAL_STATE_GREEN);
02386 } else if (!do_track_reservation) {
02387 return track;
02388 }
02389 best_track = track;
02390 }
02391
02392 PBSTileInfo res_dest(tile, INVALID_TRACKDIR, false);
02393 DiagDirection dest_enterdir = enterdir;
02394 if (do_track_reservation) {
02395
02396
02397
02398 CheckIfTrainNeedsService(v);
02399 if (v->current_order.IsType(OT_DUMMY) || v->current_order.IsType(OT_CONDITIONAL) || v->current_order.IsType(OT_GOTO_DEPOT)) ProcessOrders(v);
02400
02401 res_dest = ExtendTrainReservation(v, &tracks, &dest_enterdir);
02402 if (res_dest.tile == INVALID_TILE) {
02403
02404 if (mark_stuck) MarkTrainAsStuck(v);
02405 if (changed_signal) SetSignalStateByTrackdir(tile, TrackEnterdirToTrackdir(best_track, enterdir), SIGNAL_STATE_RED);
02406 return FindFirstTrack(tracks);
02407 }
02408 }
02409
02410
02411 VehicleOrderSaver orders(v);
02412
02413
02414
02415
02416
02417
02418
02419 if (v->current_order.IsType(OT_LEAVESTATION)) {
02420 orders.SwitchToNextOrder(false);
02421 } else if (v->current_order.IsType(OT_LOADING) || (!v->current_order.IsType(OT_GOTO_DEPOT) && (
02422 v->current_order.IsType(OT_GOTO_STATION) ?
02423 IsRailStationTile(v->tile) && v->current_order.GetDestination() == GetStationIndex(v->tile) :
02424 v->tile == v->dest_tile))) {
02425 orders.SwitchToNextOrder(true);
02426 }
02427
02428 if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
02429
02430 bool path_found = true;
02431 TileIndex new_tile = res_dest.tile;
02432
02433 Track next_track = DoTrainPathfind(v, new_tile, dest_enterdir, tracks, path_found, do_track_reservation, &res_dest);
02434 if (new_tile == tile) best_track = next_track;
02435 v->HandlePathfindingResult(path_found);
02436 }
02437
02438
02439 if (!do_track_reservation) return best_track;
02440
02441
02442 if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
02443 if (mark_stuck) MarkTrainAsStuck(v);
02444 FreeTrainTrackReservation(v);
02445 return best_track;
02446 }
02447
02448
02449 if (res_dest.tile == INVALID_TILE) {
02450
02451 PBSTileInfo origin = FollowTrainReservation(v);
02452 if (TryReserveSafeTrack(v, origin.tile, origin.trackdir, false)) {
02453 TrackBits res = GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir);
02454 best_track = FindFirstTrack(res);
02455 TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
02456 if (got_reservation != NULL) *got_reservation = true;
02457 if (changed_signal) MarkTileDirtyByTile(tile);
02458 } else {
02459 FreeTrainTrackReservation(v);
02460 if (mark_stuck) MarkTrainAsStuck(v);
02461 }
02462 return best_track;
02463 }
02464
02465 if (got_reservation != NULL) *got_reservation = true;
02466
02467
02468 while (!IsSafeWaitingPosition(v, res_dest.tile, res_dest.trackdir, true, _settings_game.pf.forbid_90_deg)) {
02469
02470 DiagDirection exitdir = TrackdirToExitdir(res_dest.trackdir);
02471 TileIndex next_tile = TileAddByDiagDir(res_dest.tile, exitdir);
02472 TrackBits reachable = TrackdirBitsToTrackBits((TrackdirBits)(GetTileTrackStatus(next_tile, TRANSPORT_RAIL, 0))) & DiagdirReachesTracks(exitdir);
02473 if (_settings_game.pf.forbid_90_deg) {
02474 reachable &= ~TrackCrossesTracks(TrackdirToTrack(res_dest.trackdir));
02475 }
02476
02477
02478 if (orders.SwitchToNextOrder(true)) {
02479 PBSTileInfo cur_dest;
02480 bool path_found;
02481 DoTrainPathfind(v, next_tile, exitdir, reachable, path_found, true, &cur_dest);
02482 if (cur_dest.tile != INVALID_TILE) {
02483 res_dest = cur_dest;
02484 if (res_dest.okay) continue;
02485
02486 FreeTrainTrackReservation(v);
02487 if (mark_stuck) MarkTrainAsStuck(v);
02488 if (got_reservation != NULL) *got_reservation = false;
02489 changed_signal = false;
02490 break;
02491 }
02492 }
02493
02494 if (!TryReserveSafeTrack(v, res_dest.tile, res_dest.trackdir, true)) {
02495 FreeTrainTrackReservation(v);
02496 if (mark_stuck) MarkTrainAsStuck(v);
02497 if (got_reservation != NULL) *got_reservation = false;
02498 changed_signal = false;
02499 }
02500 break;
02501 }
02502
02503 TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
02504
02505 if (changed_signal) MarkTileDirtyByTile(tile);
02506
02507 return best_track;
02508 }
02509
02518 bool TryPathReserve(Train *v, bool mark_as_stuck, bool first_tile_okay)
02519 {
02520 assert(v->IsFrontEngine());
02521
02522
02523
02524
02525 if (v->track == TRACK_BIT_DEPOT) {
02526 if (HasDepotReservation(v->tile)) {
02527 if (mark_as_stuck) MarkTrainAsStuck(v);
02528 return false;
02529 } else {
02530
02531 TileIndex next_tile = TileAddByDiagDir(v->tile, GetRailDepotDirection(v->tile));
02532 if (HasReservedTracks(next_tile, DiagdirReachesTracks(GetRailDepotDirection(v->tile)))) return false;
02533 }
02534 }
02535
02536 Vehicle *other_train = NULL;
02537 PBSTileInfo origin = FollowTrainReservation(v, &other_train);
02538
02539
02540
02541
02542
02543 if (other_train != NULL && other_train->index != v->index) {
02544 if (mark_as_stuck) MarkTrainAsStuck(v);
02545 return false;
02546 }
02547
02548 if (origin.okay && (v->tile != origin.tile || first_tile_okay)) {
02549
02550 if (HasBit(v->flags, VRF_TRAIN_STUCK)) SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
02551 ClrBit(v->flags, VRF_TRAIN_STUCK);
02552 return true;
02553 }
02554
02555
02556 if (v->track == TRACK_BIT_DEPOT) {
02557 SetDepotReservation(v->tile, true);
02558 if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(v->tile);
02559 }
02560
02561 DiagDirection exitdir = TrackdirToExitdir(origin.trackdir);
02562 TileIndex new_tile = TileAddByDiagDir(origin.tile, exitdir);
02563 TrackBits reachable = TrackdirBitsToTrackBits(TrackStatusToTrackdirBits(GetTileTrackStatus(new_tile, TRANSPORT_RAIL, 0)) & DiagdirReachesTrackdirs(exitdir));
02564
02565 if (_settings_game.pf.forbid_90_deg) reachable &= ~TrackCrossesTracks(TrackdirToTrack(origin.trackdir));
02566
02567 bool res_made = false;
02568 ChooseTrainTrack(v, new_tile, exitdir, reachable, true, &res_made, mark_as_stuck);
02569
02570 if (!res_made) {
02571
02572 if (v->track == TRACK_BIT_DEPOT) SetDepotReservation(v->tile, false);
02573 return false;
02574 }
02575
02576 if (HasBit(v->flags, VRF_TRAIN_STUCK)) {
02577 v->wait_counter = 0;
02578 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
02579 }
02580 ClrBit(v->flags, VRF_TRAIN_STUCK);
02581 return true;
02582 }
02583
02584
02585 static bool CheckReverseTrain(const Train *v)
02586 {
02587 if (_settings_game.difficulty.line_reverse_mode != 0 ||
02588 v->track == TRACK_BIT_DEPOT || v->track == TRACK_BIT_WORMHOLE ||
02589 !(v->direction & 1)) {
02590 return false;
02591 }
02592
02593 assert(v->track != TRACK_BIT_NONE);
02594
02595 switch (_settings_game.pf.pathfinder_for_trains) {
02596 case VPF_NPF: return NPFTrainCheckReverse(v);
02597 case VPF_YAPF: return YapfTrainCheckReverse(v);
02598
02599 default: NOT_REACHED();
02600 }
02601 }
02602
02603 TileIndex Train::GetOrderStationLocation(StationID station)
02604 {
02605 if (station == this->last_station_visited) this->last_station_visited = INVALID_STATION;
02606
02607 const Station *st = Station::Get(station);
02608 if (!(st->facilities & FACIL_TRAIN)) {
02609
02610 this->IncrementOrderIndex();
02611 return 0;
02612 }
02613
02614 return st->xy;
02615 }
02616
02617 void Train::MarkDirty()
02618 {
02619 Train *v = this;
02620 do {
02621 v->UpdateViewport(false, false);
02622 } while ((v = v->Next()) != NULL);
02623
02624
02625 this->CargoChanged();
02626 this->UpdateAcceleration();
02627 }
02628
02636 int Train::UpdateSpeed()
02637 {
02638 uint accel;
02639 uint16 max_speed;
02640
02641 switch (_settings_game.vehicle.train_acceleration_model) {
02642 default: NOT_REACHED();
02643 case AM_ORIGINAL:
02644 max_speed = this->gcache.cached_max_track_speed;
02645 accel = this->acceleration * (this->GetAccelerationStatus() == AS_BRAKE ? -4 : 2);
02646 break;
02647 case AM_REALISTIC:
02648 max_speed = this->GetCurrentMaxSpeed();
02649 accel = this->GetAcceleration();
02650 break;
02651 }
02652
02653 uint spd = this->subspeed + accel;
02654 this->subspeed = (byte)spd;
02655 {
02656 int tempmax = max_speed;
02657 if (this->cur_speed > max_speed) {
02658 tempmax = max(this->cur_speed - (this->cur_speed / 10) - 1, tempmax);
02659 }
02660
02661 int min_speed = (_settings_game.vehicle.train_acceleration_model == AM_ORIGINAL || this->GetAccelerationStatus() == AS_BRAKE) ? 0 : 2;
02662 this->cur_speed = spd = Clamp(this->cur_speed + ((int)spd >> 8), min_speed, tempmax);
02663 }
02664
02665 int scaled_spd = this->GetAdvanceSpeed(spd);
02666
02667 scaled_spd += this->progress;
02668 this->progress = 0;
02669 return scaled_spd;
02670 }
02671
02677 static void TrainEnterStation(Train *v, StationID station)
02678 {
02679 v->last_station_visited = station;
02680
02681
02682 Station *st = Station::Get(station);
02683 if (!(st->had_vehicle_of_type & HVOT_TRAIN)) {
02684 st->had_vehicle_of_type |= HVOT_TRAIN;
02685 SetDParam(0, st->index);
02686 AddVehicleNewsItem(
02687 STR_NEWS_FIRST_TRAIN_ARRIVAL,
02688 v->owner == _local_company ? NS_ARRIVAL_COMPANY : NS_ARRIVAL_OTHER,
02689 v->index,
02690 st->index
02691 );
02692 AI::NewEvent(v->owner, new AIEventStationFirstVehicle(st->index, v->index));
02693 }
02694
02695 v->force_proceed = TFP_NONE;
02696 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
02697
02698 v->BeginLoading();
02699
02700 TriggerStationAnimation(st, v->tile, SAT_TRAIN_ARRIVES);
02701 }
02702
02703
02704 static inline bool CheckCompatibleRail(const Train *v, TileIndex tile)
02705 {
02706 return IsTileOwner(tile, v->owner) &&
02707 (!v->IsFrontEngine() || HasBit(v->compatible_railtypes, GetRailType(tile)));
02708 }
02709
02710 struct RailtypeSlowdownParams {
02711 byte small_turn, large_turn;
02712 byte z_up;
02713 byte z_down;
02714 };
02715
02716 static const RailtypeSlowdownParams _railtype_slowdown[] = {
02717
02718 {256 / 4, 256 / 2, 256 / 4, 2},
02719 {256 / 4, 256 / 2, 256 / 4, 2},
02720 {256 / 4, 256 / 2, 256 / 4, 2},
02721 {0, 256 / 2, 256 / 4, 2},
02722 };
02723
02725 static inline void AffectSpeedByZChange(Train *v, byte old_z)
02726 {
02727 if (old_z == v->z_pos || _settings_game.vehicle.train_acceleration_model != AM_ORIGINAL) return;
02728
02729 const RailtypeSlowdownParams *rsp = &_railtype_slowdown[v->railtype];
02730
02731 if (old_z < v->z_pos) {
02732 v->cur_speed -= (v->cur_speed * rsp->z_up >> 8);
02733 } else {
02734 uint16 spd = v->cur_speed + rsp->z_down;
02735 if (spd <= v->gcache.cached_max_track_speed) v->cur_speed = spd;
02736 }
02737 }
02738
02739 static bool TrainMovedChangeSignals(TileIndex tile, DiagDirection dir)
02740 {
02741 if (IsTileType(tile, MP_RAILWAY) &&
02742 GetRailTileType(tile) == RAIL_TILE_SIGNALS) {
02743 TrackdirBits tracks = TrackBitsToTrackdirBits(GetTrackBits(tile)) & DiagdirReachesTrackdirs(dir);
02744 Trackdir trackdir = FindFirstTrackdir(tracks);
02745 if (UpdateSignalsOnSegment(tile, TrackdirToExitdir(trackdir), GetTileOwner(tile)) == SIGSEG_PBS && HasSignalOnTrackdir(tile, trackdir)) {
02746
02747 if (!IsPbsSignal(GetSignalType(tile, TrackdirToTrack(trackdir)))) return true;
02748 }
02749 }
02750 return false;
02751 }
02752
02756 void Train::ReserveTrackUnderConsist() const
02757 {
02758 for (const Train *u = this; u != NULL; u = u->Next()) {
02759 switch (u->track) {
02760 case TRACK_BIT_WORMHOLE:
02761 TryReserveRailTrack(u->tile, DiagDirToDiagTrack(GetTunnelBridgeDirection(u->tile)));
02762 break;
02763 case TRACK_BIT_DEPOT:
02764 break;
02765 default:
02766 TryReserveRailTrack(u->tile, TrackBitsToTrack(u->track));
02767 break;
02768 }
02769 }
02770 }
02771
02772 uint Train::Crash(bool flooded)
02773 {
02774 uint pass = 0;
02775 if (this->IsFrontEngine()) {
02776 pass += 2;
02777
02778
02779
02780 if (!HasBit(this->flags, VRF_TRAIN_STUCK)) FreeTrainTrackReservation(this);
02781 for (const Train *v = this; v != NULL; v = v->Next()) {
02782 ClearPathReservation(v, v->tile, v->GetVehicleTrackdir());
02783 if (IsTileType(v->tile, MP_TUNNELBRIDGE)) {
02784
02785
02786 SetTunnelBridgeReservation(GetOtherTunnelBridgeEnd(v->tile), false);
02787 }
02788 }
02789
02790
02791
02792 TileIndex crossing = TrainApproachingCrossingTile(this);
02793 if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
02794
02795
02796 HideFillingPercent(&this->fill_percent_te_id);
02797 }
02798
02799 pass += this->GroundVehicleBase::Crash(flooded);
02800
02801 this->crash_anim_pos = flooded ? 4000 : 1;
02802 return pass;
02803 }
02804
02811 static uint TrainCrashed(Train *v)
02812 {
02813 uint num = 0;
02814
02815
02816 if (!(v->vehstatus & VS_CRASHED)) {
02817 num = v->Crash();
02818 AI::NewEvent(v->owner, new AIEventVehicleCrashed(v->index, v->tile, AIEventVehicleCrashed::CRASH_TRAIN));
02819 }
02820
02821
02822
02823 v->ReserveTrackUnderConsist();
02824
02825 return num;
02826 }
02827
02828 struct TrainCollideChecker {
02829 Train *v;
02830 uint num;
02831 };
02832
02833 static Vehicle *FindTrainCollideEnum(Vehicle *v, void *data)
02834 {
02835 TrainCollideChecker *tcc = (TrainCollideChecker*)data;
02836
02837
02838 if (v->type != VEH_TRAIN || Train::From(v)->track == TRACK_BIT_DEPOT) return NULL;
02839
02840
02841 if (v->owner != tcc->v->owner) return NULL;
02842
02843
02844 Train *coll = Train::From(v)->First();
02845
02846
02847 if (coll == tcc->v) return NULL;
02848
02849 int x_diff = v->x_pos - tcc->v->x_pos;
02850 int y_diff = v->y_pos - tcc->v->y_pos;
02851
02852
02853
02854
02855
02856 uint hash = (y_diff + 7) | (x_diff + 7);
02857 if (hash & ~15) return NULL;
02858
02859
02860 if (x_diff * x_diff + y_diff * y_diff > 25) return NULL;
02861
02862
02863 if (abs(v->z_pos - tcc->v->z_pos) > 5) return NULL;
02864
02865
02866 tcc->num += TrainCrashed(tcc->v);
02867 tcc->num += TrainCrashed(coll);
02868
02869 return NULL;
02870 }
02871
02878 static bool CheckTrainCollision(Train *v)
02879 {
02880
02881 if (v->track == TRACK_BIT_DEPOT) return false;
02882
02883 assert(v->track == TRACK_BIT_WORMHOLE || TileVirtXY(v->x_pos, v->y_pos) == v->tile);
02884
02885 TrainCollideChecker tcc;
02886 tcc.v = v;
02887 tcc.num = 0;
02888
02889
02890 if (v->track == TRACK_BIT_WORMHOLE) {
02891 FindVehicleOnPos(v->tile, &tcc, FindTrainCollideEnum);
02892 FindVehicleOnPos(GetOtherTunnelBridgeEnd(v->tile), &tcc, FindTrainCollideEnum);
02893 } else {
02894 FindVehicleOnPosXY(v->x_pos, v->y_pos, &tcc, FindTrainCollideEnum);
02895 }
02896
02897
02898 if (tcc.num == 0) return false;
02899
02900 SetDParam(0, tcc.num);
02901 AddVehicleNewsItem(STR_NEWS_TRAIN_CRASH,
02902 NS_ACCIDENT,
02903 v->index
02904 );
02905
02906 ModifyStationRatingAround(v->tile, v->owner, -160, 30);
02907 SndPlayVehicleFx(SND_13_BIG_CRASH, v);
02908 return true;
02909 }
02910
02911 static Vehicle *CheckTrainAtSignal(Vehicle *v, void *data)
02912 {
02913 if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) return NULL;
02914
02915 Train *t = Train::From(v);
02916 DiagDirection exitdir = *(DiagDirection *)data;
02917
02918
02919 if (!t->IsFrontEngine() || !(t->track & TRACK_BIT_MASK)) return NULL;
02920
02921 if (t->cur_speed > 5 || TrainExitDir(t->direction, t->track) != exitdir) return NULL;
02922
02923 return t;
02924 }
02925
02926 static void TrainController(Train *v, Vehicle *nomove)
02927 {
02928 Train *first = v->First();
02929 Train *prev;
02930 bool direction_changed = false;
02931
02932
02933 for (prev = v->Previous(); v != nomove; prev = v, v = v->Next()) {
02934 DiagDirection enterdir = DIAGDIR_BEGIN;
02935 bool update_signals_crossing = false;
02936
02937 GetNewVehiclePosResult gp = GetNewVehiclePos(v);
02938 if (v->track != TRACK_BIT_WORMHOLE) {
02939
02940 if (gp.old_tile == gp.new_tile) {
02941
02942 if (v->track == TRACK_BIT_DEPOT) {
02943
02944 gp.x = v->x_pos;
02945 gp.y = v->y_pos;
02946 } else {
02947
02948
02949
02950 if (v->IsFrontEngine() && !TrainCheckIfLineEnds(v)) return;
02951
02952 uint32 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
02953 if (HasBit(r, VETS_CANNOT_ENTER)) {
02954 goto invalid_rail;
02955 }
02956 if (HasBit(r, VETS_ENTERED_STATION)) {
02957
02958 TrainEnterStation(v, r >> VETS_STATION_ID_OFFSET);
02959 }
02960 }
02961 } else {
02962
02963
02964
02965 enterdir = DiagdirBetweenTiles(gp.old_tile, gp.new_tile);
02966 assert(IsValidDiagDirection(enterdir));
02967
02968
02969
02970 TrackStatus ts = GetTileTrackStatus(gp.new_tile, TRANSPORT_RAIL, 0, ReverseDiagDir(enterdir));
02971 TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(enterdir);
02972
02973 TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
02974 TrackBits red_signals = TrackdirBitsToTrackBits(TrackStatusToRedSignals(ts) & reachable_trackdirs);
02975
02976 TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
02977 if (_settings_game.pf.forbid_90_deg && prev == NULL) {
02978
02979
02980 bits &= ~TrackCrossesTracks(FindFirstTrack(v->track));
02981 }
02982
02983 if (bits == TRACK_BIT_NONE) goto invalid_rail;
02984
02985
02986
02987 if (!CheckCompatibleRail(v, gp.new_tile)) goto invalid_rail;
02988
02989 TrackBits chosen_track;
02990 if (prev == NULL) {
02991
02992
02993 chosen_track = TrackToTrackBits(ChooseTrainTrack(v, gp.new_tile, enterdir, bits, false, NULL, true));
02994 assert(chosen_track & (bits | GetReservedTrackbits(gp.new_tile)));
02995
02996 if (v->force_proceed != TFP_NONE && IsPlainRailTile(gp.new_tile) && HasSignals(gp.new_tile)) {
02997
02998
02999
03000
03001 Trackdir dir = FindFirstTrackdir(trackdirbits);
03002 if (GetSignalType(gp.new_tile, TrackdirToTrack(dir)) != SIGTYPE_PBS ||
03003 !HasSignalOnTrackdir(gp.new_tile, ReverseTrackdir(dir))) {
03004
03005
03006 v->force_proceed = (v->force_proceed == TFP_SIGNAL) ? TFP_STUCK : TFP_NONE;
03007 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
03008 }
03009 }
03010
03011
03012 if ((red_signals & chosen_track) && v->force_proceed == TFP_NONE) {
03013
03014 Trackdir i = FindFirstTrackdir(trackdirbits);
03015
03016
03017 if (HasBit(v->flags, VRF_TRAIN_STUCK)) return;
03018
03019 if (!HasSignalOnTrackdir(gp.new_tile, ReverseTrackdir(i))) {
03020 v->cur_speed = 0;
03021 v->subspeed = 0;
03022 v->progress = 255 - 100;
03023 if (_settings_game.pf.wait_oneway_signal == 255 || ++v->wait_counter < _settings_game.pf.wait_oneway_signal * 20) return;
03024 } else if (HasSignalOnTrackdir(gp.new_tile, i)) {
03025 v->cur_speed = 0;
03026 v->subspeed = 0;
03027 v->progress = 255 - 10;
03028 if (_settings_game.pf.wait_twoway_signal == 255 || ++v->wait_counter < _settings_game.pf.wait_twoway_signal * 73) {
03029 DiagDirection exitdir = TrackdirToExitdir(i);
03030 TileIndex o_tile = TileAddByDiagDir(gp.new_tile, exitdir);
03031
03032 exitdir = ReverseDiagDir(exitdir);
03033
03034
03035 if (!HasVehicleOnPos(o_tile, &exitdir, &CheckTrainAtSignal)) return;
03036 }
03037 }
03038
03039
03040
03041
03042
03043 if (_settings_game.pf.wait_for_pbs_path == 255 && !HasOnewaySignalBlockingTrackdir(gp.new_tile, i) &&
03044 UpdateSignalsOnSegment(v->tile, enterdir, v->owner) == SIGSEG_PBS) {
03045 v->wait_counter = 0;
03046 return;
03047 }
03048 goto reverse_train_direction;
03049 } else {
03050 TryReserveRailTrack(gp.new_tile, TrackBitsToTrack(chosen_track));
03051 }
03052 } else {
03053
03054 if (prev->tile == gp.new_tile) {
03055
03056 if (prev->track == TRACK_BIT_WORMHOLE) {
03057
03058
03059 assert(IsTunnel(prev->tile));
03060 chosen_track = bits;
03061 } else {
03062 chosen_track = prev->track;
03063 }
03064 } else {
03065
03066
03067
03068
03069
03070
03071
03072 static const TrackBits _connecting_track[DIAGDIR_END][DIAGDIR_END] = {
03073 {TRACK_BIT_X, TRACK_BIT_LOWER, TRACK_BIT_NONE, TRACK_BIT_LEFT },
03074 {TRACK_BIT_UPPER, TRACK_BIT_Y, TRACK_BIT_LEFT, TRACK_BIT_NONE },
03075 {TRACK_BIT_NONE, TRACK_BIT_RIGHT, TRACK_BIT_X, TRACK_BIT_UPPER},
03076 {TRACK_BIT_RIGHT, TRACK_BIT_NONE, TRACK_BIT_LOWER, TRACK_BIT_Y }
03077 };
03078 DiagDirection exitdir = DiagdirBetweenTiles(gp.new_tile, prev->tile);
03079 assert(IsValidDiagDirection(exitdir));
03080 chosen_track = _connecting_track[enterdir][exitdir];
03081 }
03082 chosen_track &= bits;
03083 }
03084
03085
03086 assert(
03087 chosen_track == TRACK_BIT_X || chosen_track == TRACK_BIT_Y ||
03088 chosen_track == TRACK_BIT_UPPER || chosen_track == TRACK_BIT_LOWER ||
03089 chosen_track == TRACK_BIT_LEFT || chosen_track == TRACK_BIT_RIGHT);
03090
03091
03092 const byte *b = _initial_tile_subcoord[FIND_FIRST_BIT(chosen_track)][enterdir];
03093 gp.x = (gp.x & ~0xF) | b[0];
03094 gp.y = (gp.y & ~0xF) | b[1];
03095 Direction chosen_dir = (Direction)b[2];
03096
03097
03098 uint32 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
03099 if (HasBit(r, VETS_CANNOT_ENTER)) {
03100 goto invalid_rail;
03101 }
03102
03103 if (!HasBit(r, VETS_ENTERED_WORMHOLE)) {
03104 Track track = FindFirstTrack(chosen_track);
03105 Trackdir tdir = TrackDirectionToTrackdir(track, chosen_dir);
03106 if (v->IsFrontEngine() && HasPbsSignalOnTrackdir(gp.new_tile, tdir)) {
03107 SetSignalStateByTrackdir(gp.new_tile, tdir, SIGNAL_STATE_RED);
03108 MarkTileDirtyByTile(gp.new_tile);
03109 }
03110
03111
03112 if (v->Next() == NULL) ClearPathReservation(v, v->tile, v->GetVehicleTrackdir());
03113
03114 v->tile = gp.new_tile;
03115
03116 if (GetTileRailType(gp.new_tile) != GetTileRailType(gp.old_tile)) {
03117 v->First()->RailtypeChanged();
03118 }
03119
03120 v->track = chosen_track;
03121 assert(v->track);
03122 }
03123
03124
03125
03126 update_signals_crossing = true;
03127
03128 if (chosen_dir != v->direction) {
03129 if (prev == NULL && _settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) {
03130 const RailtypeSlowdownParams *rsp = &_railtype_slowdown[v->railtype];
03131 DirDiff diff = DirDifference(v->direction, chosen_dir);
03132 v->cur_speed -= (diff == DIRDIFF_45RIGHT || diff == DIRDIFF_45LEFT ? rsp->small_turn : rsp->large_turn) * v->cur_speed >> 8;
03133 }
03134 direction_changed = true;
03135 v->direction = chosen_dir;
03136 }
03137
03138 if (v->IsFrontEngine()) {
03139 v->wait_counter = 0;
03140
03141
03142 TileIndex crossing = TrainApproachingCrossingTile(v);
03143 if (crossing != INVALID_TILE && HasCrossingReservation(crossing)) SndPlayTileFx(SND_0E_LEVEL_CROSSING, crossing);
03144
03145
03146 CheckNextTrainTile(v);
03147 }
03148
03149 if (HasBit(r, VETS_ENTERED_STATION)) {
03150
03151 TrainEnterStation(v, r >> VETS_STATION_ID_OFFSET);
03152 }
03153 }
03154 } else {
03155
03156
03157
03158 if (!(v->vehstatus & VS_HIDDEN)) {
03159 Train *first = v->First();
03160 first->cur_speed = min(first->cur_speed, GetBridgeSpec(GetBridgeType(v->tile))->speed);
03161 }
03162
03163 if (IsTileType(gp.new_tile, MP_TUNNELBRIDGE) && HasBit(VehicleEnterTile(v, gp.new_tile, gp.x, gp.y), VETS_ENTERED_WORMHOLE)) {
03164
03165 if (v->IsFrontEngine()) {
03166 TryReserveRailTrack(gp.new_tile, DiagDirToDiagTrack(GetTunnelBridgeDirection(gp.new_tile)));
03167 CheckNextTrainTile(v);
03168 }
03169
03170
03171 if (gp.old_tile == gp.new_tile) {
03172 gp.old_tile = GetOtherTunnelBridgeEnd(gp.old_tile);
03173 }
03174 } else {
03175 v->x_pos = gp.x;
03176 v->y_pos = gp.y;
03177 VehicleMove(v, !(v->vehstatus & VS_HIDDEN));
03178 continue;
03179 }
03180 }
03181
03182
03183 v->UpdateDeltaXY(v->direction);
03184
03185 v->x_pos = gp.x;
03186 v->y_pos = gp.y;
03187
03188
03189 byte old_z = v->UpdateInclination(gp.new_tile != gp.old_tile, false);
03190
03191 if (prev == NULL) {
03192
03193 AffectSpeedByZChange(v, old_z);
03194 }
03195
03196 if (update_signals_crossing) {
03197 if (v->IsFrontEngine()) {
03198 if (TrainMovedChangeSignals(gp.new_tile, enterdir)) {
03199
03200
03201
03202
03203
03204
03205
03206
03207 if ((!HasReservedTracks(gp.new_tile, v->track) &&
03208 !TryReserveRailTrack(gp.new_tile, FindFirstTrack(v->track))) ||
03209 !TryPathReserve(v)) {
03210 MarkTrainAsStuck(v);
03211 }
03212 }
03213 }
03214
03215
03216
03217 if (v->Next() == NULL) {
03218 TrainMovedChangeSignals(gp.old_tile, ReverseDiagDir(enterdir));
03219 if (IsLevelCrossingTile(gp.old_tile)) UpdateLevelCrossing(gp.old_tile);
03220 }
03221 }
03222
03223
03224 if (v->IsFrontEngine() && v->tick_counter % _settings_game.pf.path_backoff_interval == 0) CheckNextTrainTile(v);
03225 }
03226
03227 if (direction_changed) first->tcache.cached_max_curve_speed = first->GetCurveSpeedLimit();
03228
03229 return;
03230
03231 invalid_rail:
03232
03233 if (prev != NULL) error("Disconnecting train");
03234
03235 reverse_train_direction:
03236 v->wait_counter = 0;
03237 v->cur_speed = 0;
03238 v->subspeed = 0;
03239 ReverseTrainDirection(v);
03240 }
03241
03248 static Vehicle *CollectTrackbitsFromCrashedVehiclesEnum(Vehicle *v, void *data)
03249 {
03250 TrackBits *trackbits = (TrackBits *)data;
03251
03252 if (v->type == VEH_TRAIN && (v->vehstatus & VS_CRASHED) != 0) {
03253 TrackBits train_tbits = Train::From(v)->track;
03254 if (train_tbits == TRACK_BIT_WORMHOLE) {
03255
03256 *trackbits |= DiagDirToDiagTrackBits(GetTunnelBridgeDirection(v->tile));
03257 } else if (train_tbits != TRACK_BIT_DEPOT) {
03258 *trackbits |= train_tbits;
03259 }
03260 }
03261
03262 return NULL;
03263 }
03264
03272 static void DeleteLastWagon(Train *v)
03273 {
03274 Train *first = v->First();
03275
03276
03277
03278
03279 Train *u = v;
03280 for (; v->Next() != NULL; v = v->Next()) u = v;
03281 u->SetNext(NULL);
03282
03283 if (first != v) {
03284
03285 first->ConsistChanged(false);
03286
03287
03288 if (first->track == TRACK_BIT_DEPOT) {
03289 SetWindowDirty(WC_VEHICLE_DEPOT, first->tile);
03290 }
03291 }
03292
03293
03294 TrackBits trackbits = v->track;
03295 TileIndex tile = v->tile;
03296 Owner owner = v->owner;
03297
03298 delete v;
03299 v = NULL;
03300
03301 if (trackbits == TRACK_BIT_WORMHOLE) {
03302
03303 trackbits = DiagDirToDiagTrackBits(GetTunnelBridgeDirection(tile));
03304 }
03305
03306 Track track = TrackBitsToTrack(trackbits);
03307 if (HasReservedTracks(tile, trackbits)) {
03308 UnreserveRailTrack(tile, track);
03309
03310
03311 TrackBits remaining_trackbits = TRACK_BIT_NONE;
03312 FindVehicleOnPos(tile, &remaining_trackbits, CollectTrackbitsFromCrashedVehiclesEnum);
03313
03314
03315 assert(TRACK_BEGIN == TRACK_X && TRACK_Y == TRACK_BEGIN + 1);
03316 Track t;
03317 FOR_EACH_SET_TRACK(t, remaining_trackbits) TryReserveRailTrack(tile, t);
03318 }
03319
03320
03321 if (IsLevelCrossingTile(tile)) UpdateLevelCrossing(tile);
03322
03323
03324 if (IsTileType(tile, MP_TUNNELBRIDGE) || IsRailDepotTile(tile)) {
03325 UpdateSignalsOnSegment(tile, INVALID_DIAGDIR, owner);
03326 } else {
03327 SetSignalsOnBothDir(tile, track, owner);
03328 }
03329 }
03330
03331 static void ChangeTrainDirRandomly(Train *v)
03332 {
03333 static const DirDiff delta[] = {
03334 DIRDIFF_45LEFT, DIRDIFF_SAME, DIRDIFF_SAME, DIRDIFF_45RIGHT
03335 };
03336
03337 do {
03338
03339 if (!(v->vehstatus & VS_HIDDEN)) {
03340 v->direction = ChangeDir(v->direction, delta[GB(Random(), 0, 2)]);
03341 v->UpdateDeltaXY(v->direction);
03342 v->cur_image = v->GetImage(v->direction);
03343
03344
03345
03346 if (v->track != TRACK_BIT_WORMHOLE) v->UpdateInclination(false, false);
03347 }
03348 } while ((v = v->Next()) != NULL);
03349 }
03350
03351 static bool HandleCrashedTrain(Train *v)
03352 {
03353 int state = ++v->crash_anim_pos;
03354
03355 if (state == 4 && !(v->vehstatus & VS_HIDDEN)) {
03356 CreateEffectVehicleRel(v, 4, 4, 8, EV_EXPLOSION_LARGE);
03357 }
03358
03359 uint32 r;
03360 if (state <= 200 && Chance16R(1, 7, r)) {
03361 int index = (r * 10 >> 16);
03362
03363 Vehicle *u = v;
03364 do {
03365 if (--index < 0) {
03366 r = Random();
03367
03368 CreateEffectVehicleRel(u,
03369 GB(r, 8, 3) + 2,
03370 GB(r, 16, 3) + 2,
03371 GB(r, 0, 3) + 5,
03372 EV_EXPLOSION_SMALL);
03373 break;
03374 }
03375 } while ((u = u->Next()) != NULL);
03376 }
03377
03378 if (state <= 240 && !(v->tick_counter & 3)) ChangeTrainDirRandomly(v);
03379
03380 if (state >= 4440 && !(v->tick_counter & 0x1F)) {
03381 bool ret = v->Next() != NULL;
03382 DeleteLastWagon(v);
03383 return ret;
03384 }
03385
03386 return true;
03387 }
03388
03390 static const uint16 _breakdown_speeds[16] = {
03391 225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, 15
03392 };
03393
03394
03402 static bool TrainApproachingLineEnd(Train *v, bool signal)
03403 {
03404
03405 uint x = v->x_pos & 0xF;
03406 uint y = v->y_pos & 0xF;
03407
03408
03409
03410 switch (v->direction) {
03411 case DIR_N : x = ~x + ~y + 25; break;
03412 case DIR_NW: x = y;
03413 case DIR_NE: x = ~x + 16; break;
03414 case DIR_E : x = ~x + y + 9; break;
03415 case DIR_SE: x = y; break;
03416 case DIR_S : x = x + y - 7; break;
03417 case DIR_W : x = ~y + x + 9; break;
03418 default: break;
03419 }
03420
03421
03422 if (!signal && x + (v->gcache.cached_veh_length + 1) / 2 >= TILE_SIZE) {
03423
03424 v->cur_speed = 0;
03425 ReverseTrainDirection(v);
03426 return false;
03427 }
03428
03429
03430 v->vehstatus |= VS_TRAIN_SLOWING;
03431 uint16 break_speed = _breakdown_speeds[x & 0xF];
03432 if (break_speed < v->cur_speed) v->cur_speed = break_speed;
03433
03434 return true;
03435 }
03436
03437
03443 static bool TrainCanLeaveTile(const Train *v)
03444 {
03445
03446 if (v->track == TRACK_BIT_WORMHOLE || v->track == TRACK_BIT_DEPOT) return false;
03447
03448 TileIndex tile = v->tile;
03449
03450
03451 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
03452 DiagDirection dir = GetTunnelBridgeDirection(tile);
03453 if (DiagDirToDir(dir) == v->direction) return false;
03454 }
03455
03456
03457 if (IsRailDepotTile(tile)) {
03458 DiagDirection dir = ReverseDiagDir(GetRailDepotDirection(tile));
03459 if (DiagDirToDir(dir) == v->direction) return false;
03460 }
03461
03462 return true;
03463 }
03464
03465
03473 static TileIndex TrainApproachingCrossingTile(const Train *v)
03474 {
03475 assert(v->IsFrontEngine());
03476 assert(!(v->vehstatus & VS_CRASHED));
03477
03478 if (!TrainCanLeaveTile(v)) return INVALID_TILE;
03479
03480 DiagDirection dir = TrainExitDir(v->direction, v->track);
03481 TileIndex tile = v->tile + TileOffsByDiagDir(dir);
03482
03483
03484 if (!IsLevelCrossingTile(tile) || DiagDirToAxis(dir) == GetCrossingRoadAxis(tile) ||
03485 !CheckCompatibleRail(v, tile)) {
03486 return INVALID_TILE;
03487 }
03488
03489 return tile;
03490 }
03491
03492
03499 static bool TrainCheckIfLineEnds(Train *v)
03500 {
03501
03502
03503 int t = v->breakdown_ctr;
03504 if (t > 1) {
03505 v->vehstatus |= VS_TRAIN_SLOWING;
03506
03507 uint16 break_speed = _breakdown_speeds[GB(~t, 4, 4)];
03508 if (break_speed < v->cur_speed) v->cur_speed = break_speed;
03509 } else {
03510 v->vehstatus &= ~VS_TRAIN_SLOWING;
03511 }
03512
03513 if (!TrainCanLeaveTile(v)) return true;
03514
03515
03516 DiagDirection dir = TrainExitDir(v->direction, v->track);
03517
03518 TileIndex tile = v->tile + TileOffsByDiagDir(dir);
03519
03520
03521 TrackStatus ts = GetTileTrackStatus(tile, TRANSPORT_RAIL, 0, ReverseDiagDir(dir));
03522 TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(dir);
03523
03524 TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
03525 TrackdirBits red_signals = TrackStatusToRedSignals(ts) & reachable_trackdirs;
03526
03527
03528
03529
03530 TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
03531 if (_settings_game.pf.forbid_90_deg) {
03532 bits &= ~TrackCrossesTracks(FindFirstTrack(v->track));
03533 }
03534
03535
03536 if (bits == TRACK_BIT_NONE || !CheckCompatibleRail(v, tile)) {
03537 return TrainApproachingLineEnd(v, false);
03538 }
03539
03540
03541 if ((trackdirbits & red_signals) != 0) return TrainApproachingLineEnd(v, true);
03542
03543
03544 if (IsLevelCrossingTile(tile)) MaybeBarCrossingWithSound(tile);
03545
03546 return true;
03547 }
03548
03549
03550 static bool TrainLocoHandler(Train *v, bool mode)
03551 {
03552
03553 if (v->vehstatus & VS_CRASHED) {
03554 return mode ? true : HandleCrashedTrain(v);
03555 }
03556
03557 if (v->force_proceed != TFP_NONE) {
03558 ClrBit(v->flags, VRF_TRAIN_STUCK);
03559 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
03560 }
03561
03562
03563 if (v->HandleBreakdown()) return true;
03564
03565 if (HasBit(v->flags, VRF_REVERSING) && v->cur_speed == 0) {
03566 ReverseTrainDirection(v);
03567 }
03568
03569
03570 if ((v->vehstatus & VS_STOPPED) && v->cur_speed == 0) return true;
03571
03572 bool valid_order = !v->current_order.IsType(OT_NOTHING) && v->current_order.GetType() != OT_CONDITIONAL;
03573 if (ProcessOrders(v) && CheckReverseTrain(v)) {
03574 v->wait_counter = 0;
03575 v->cur_speed = 0;
03576 v->subspeed = 0;
03577 ClrBit(v->flags, VRF_LEAVING_STATION);
03578 ReverseTrainDirection(v);
03579 return true;
03580 } else if (HasBit(v->flags, VRF_LEAVING_STATION)) {
03581
03582
03583
03584 DiagDirection dir = TrainExitDir(v->direction, v->track);
03585 if (IsRailDepotTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE)) dir = INVALID_DIAGDIR;
03586
03587 if (UpdateSignalsOnSegment(v->tile, dir, v->owner) == SIGSEG_PBS || _settings_game.pf.reserve_paths) {
03588 TryPathReserve(v, true, true);
03589 }
03590 ClrBit(v->flags, VRF_LEAVING_STATION);
03591 }
03592
03593 v->HandleLoading(mode);
03594
03595 if (v->current_order.IsType(OT_LOADING)) return true;
03596
03597 if (CheckTrainStayInDepot(v)) return true;
03598
03599 if (!mode) v->ShowVisualEffect();
03600
03601
03602 if (!valid_order && !v->current_order.IsType(OT_NOTHING)) {
03603 CheckNextTrainTile(v);
03604 }
03605
03606
03607 if (!mode && HasBit(v->flags, VRF_TRAIN_STUCK)) {
03608 ++v->wait_counter;
03609
03610
03611 bool turn_around = v->wait_counter % (_settings_game.pf.wait_for_pbs_path * DAY_TICKS) == 0 && _settings_game.pf.wait_for_pbs_path < 255;
03612
03613 if (!turn_around && v->wait_counter % _settings_game.pf.path_backoff_interval != 0 && v->force_proceed == TFP_NONE) return true;
03614 if (!TryPathReserve(v)) {
03615
03616 if (turn_around) ReverseTrainDirection(v);
03617
03618 if (HasBit(v->flags, VRF_TRAIN_STUCK) && v->wait_counter > 2 * _settings_game.pf.wait_for_pbs_path * DAY_TICKS) {
03619
03620 if (_settings_client.gui.lost_vehicle_warn && v->owner == _local_company) {
03621 SetDParam(0, v->index);
03622 AddVehicleNewsItem(
03623 STR_NEWS_TRAIN_IS_STUCK,
03624 NS_ADVICE,
03625 v->index
03626 );
03627 }
03628 v->wait_counter = 0;
03629 }
03630
03631 if (v->force_proceed == TFP_NONE) return true;
03632 ClrBit(v->flags, VRF_TRAIN_STUCK);
03633 v->wait_counter = 0;
03634 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
03635 }
03636 }
03637
03638 if (v->current_order.IsType(OT_LEAVESTATION)) {
03639 v->current_order.Free();
03640 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
03641 return true;
03642 }
03643
03644 int j = v->UpdateSpeed();
03645
03646
03647 if (v->cur_speed == 0 && (v->vehstatus & VS_STOPPED)) {
03648
03649 v->force_proceed = TFP_NONE;
03650 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
03651 }
03652
03653 int adv_spd = v->GetAdvanceDistance();
03654 if (j < adv_spd) {
03655
03656 if (v->cur_speed == 0) SetLastSpeed(v, v->cur_speed);
03657 } else {
03658 TrainCheckIfLineEnds(v);
03659
03660 for (;;) {
03661 j -= adv_spd;
03662 TrainController(v, NULL);
03663
03664 if (CheckTrainCollision(v)) break;
03665
03666 adv_spd = v->GetAdvanceDistance();
03667
03668
03669 if (j < adv_spd || v->cur_speed == 0) break;
03670
03671 OrderType order_type = v->current_order.GetType();
03672
03673 if ((order_type == OT_GOTO_WAYPOINT || order_type == OT_GOTO_STATION) &&
03674 (v->current_order.GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION) &&
03675 IsTileType(v->tile, MP_STATION) &&
03676 v->current_order.GetDestination() == GetStationIndex(v->tile)) {
03677 ProcessOrders(v);
03678 }
03679 }
03680 SetLastSpeed(v, v->cur_speed);
03681 }
03682
03683 for (Train *u = v; u != NULL; u = u->Next()) {
03684 if ((u->vehstatus & VS_HIDDEN) != 0) continue;
03685
03686 u->UpdateViewport(false, false);
03687 }
03688
03689 if (v->progress == 0) v->progress = j;
03690
03691 return true;
03692 }
03693
03694
03695
03696 Money Train::GetRunningCost() const
03697 {
03698 Money cost = 0;
03699 const Train *v = this;
03700
03701 do {
03702 const Engine *e = Engine::Get(v->engine_type);
03703 if (e->u.rail.running_cost_class == INVALID_PRICE) continue;
03704
03705 uint cost_factor = GetVehicleProperty(v, PROP_TRAIN_RUNNING_COST_FACTOR, e->u.rail.running_cost);
03706 if (cost_factor == 0) continue;
03707
03708
03709 if (v->IsMultiheaded()) cost_factor /= 2;
03710
03711 cost += GetPrice(e->u.rail.running_cost_class, cost_factor, e->grf_prop.grffile);
03712 } while ((v = v->GetNextVehicle()) != NULL);
03713
03714 return cost;
03715 }
03716
03717
03718 bool Train::Tick()
03719 {
03720 this->tick_counter++;
03721
03722 if (this->IsFrontEngine()) {
03723 if (!(this->vehstatus & VS_STOPPED) || this->cur_speed > 0) this->running_ticks++;
03724
03725 this->current_order_time++;
03726
03727 if (!TrainLocoHandler(this, false)) return false;
03728
03729 return TrainLocoHandler(this, true);
03730 } else if (this->IsFreeWagon() && (this->vehstatus & VS_CRASHED)) {
03731
03732 if (++this->crash_anim_pos >= 4400) {
03733 delete this;
03734 return false;
03735 }
03736 }
03737
03738 return true;
03739 }
03740
03741 static void CheckIfTrainNeedsService(Train *v)
03742 {
03743 if (Company::Get(v->owner)->settings.vehicle.servint_trains == 0 || !v->NeedsAutomaticServicing()) return;
03744 if (v->IsInDepot()) {
03745 VehicleServiceInDepot(v);
03746 return;
03747 }
03748
03749 uint max_penalty;
03750 switch (_settings_game.pf.pathfinder_for_trains) {
03751 case VPF_NPF: max_penalty = _settings_game.pf.npf.maximum_go_to_depot_penalty; break;
03752 case VPF_YAPF: max_penalty = _settings_game.pf.yapf.maximum_go_to_depot_penalty; break;
03753 default: NOT_REACHED();
03754 }
03755
03756 FindDepotData tfdd = FindClosestTrainDepot(v, max_penalty);
03757
03758 if (tfdd.best_length == UINT_MAX || tfdd.best_length > max_penalty) {
03759 if (v->current_order.IsType(OT_GOTO_DEPOT)) {
03760
03761
03762
03763 v->current_order.MakeDummy();
03764 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
03765 }
03766 return;
03767 }
03768
03769 DepotID depot = GetDepotIndex(tfdd.tile);
03770
03771 if (v->current_order.IsType(OT_GOTO_DEPOT) &&
03772 v->current_order.GetDestination() != depot &&
03773 !Chance16(3, 16)) {
03774 return;
03775 }
03776
03777 v->current_order.MakeGoToDepot(depot, ODTFB_SERVICE);
03778 v->dest_tile = tfdd.tile;
03779 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
03780 }
03781
03782 void Train::OnNewDay()
03783 {
03784 if ((++this->day_counter & 7) == 0) DecreaseVehicleValue(this);
03785
03786 if (this->IsFrontEngine()) {
03787 CheckVehicleBreakdown(this);
03788 AgeVehicle(this);
03789
03790 CheckIfTrainNeedsService(this);
03791
03792 CheckOrders(this);
03793
03794
03795 if (this->current_order.IsType(OT_GOTO_STATION)) {
03796 TileIndex tile = Station::Get(this->current_order.GetDestination())->train_station.tile;
03797 if (tile != INVALID_TILE) this->dest_tile = tile;
03798 }
03799
03800 if (this->running_ticks != 0) {
03801
03802 CommandCost cost(EXPENSES_TRAIN_RUN, this->GetRunningCost() * this->running_ticks / (DAYS_IN_YEAR * DAY_TICKS));
03803
03804 this->profit_this_year -= cost.GetCost();
03805 this->running_ticks = 0;
03806
03807 SubtractMoneyFromCompanyFract(this->owner, cost);
03808
03809 SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
03810 SetWindowClassesDirty(WC_TRAINS_LIST);
03811 }
03812 } else if (this->IsEngine()) {
03813
03814 AgeVehicle(this);
03815 }
03816 }
03817
03818 Trackdir Train::GetVehicleTrackdir() const
03819 {
03820 if (this->vehstatus & VS_CRASHED) return INVALID_TRACKDIR;
03821
03822 if (this->track == TRACK_BIT_DEPOT) {
03823
03824 return DiagDirToDiagTrackdir(GetRailDepotDirection(this->tile));
03825 }
03826
03827 if (this->track == TRACK_BIT_WORMHOLE) {
03828
03829 return DiagDirToDiagTrackdir(DirToDiagDir(this->direction));
03830 }
03831
03832 return TrackDirectionToTrackdir(FindFirstTrack(this->track), this->direction);
03833 }