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