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