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 uint16 new_cap = e_u->DetermineCapacity(u);
00204 u->refit_cap = min(new_cap, u->refit_cap);
00205 u->cargo_cap = new_cap;
00206 u->vcache.cached_cargo_age_period = GetVehicleProperty(u, PROP_TRAIN_CARGO_AGE_PERIOD, e_u->info.cargo_age_period);
00207
00208
00209 uint16 veh_len = CALLBACK_FAILED;
00210 if (e_u->GetGRF() != NULL && e_u->GetGRF()->grf_version >= 8) {
00211
00212 veh_len = GetVehicleProperty(u, PROP_TRAIN_SHORTEN_FACTOR, CALLBACK_FAILED);
00213
00214 if (veh_len != CALLBACK_FAILED && veh_len >= VEHICLE_LENGTH) {
00215 ErrorUnknownCallbackResult(e_u->GetGRFID(), CBID_VEHICLE_LENGTH, veh_len);
00216 }
00217 } else if (HasBit(e_u->info.callback_mask, CBM_VEHICLE_LENGTH)) {
00218
00219 veh_len = GetVehicleCallback(CBID_VEHICLE_LENGTH, 0, 0, u->engine_type, u);
00220 }
00221 if (veh_len == CALLBACK_FAILED) veh_len = rvi_u->shorten_factor;
00222 veh_len = VEHICLE_LENGTH - Clamp(veh_len, 0, VEHICLE_LENGTH - 1);
00223
00224
00225 if (same_length && veh_len != u->gcache.cached_veh_length) VehicleLengthChanged(u);
00226
00227
00228 if (!same_length) u->gcache.cached_veh_length = veh_len;
00229
00230 this->gcache.cached_total_length += u->gcache.cached_veh_length;
00231 this->InvalidateNewGRFCache();
00232 u->InvalidateNewGRFCache();
00233 }
00234
00235
00236 this->vcache.cached_max_speed = max_speed;
00237 this->tcache.cached_tilt = train_can_tilt;
00238 this->tcache.cached_max_curve_speed = this->GetCurveSpeedLimit();
00239
00240
00241 this->CargoChanged();
00242
00243 if (this->IsFrontEngine()) {
00244 this->UpdateAcceleration();
00245 SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
00246 InvalidateWindowData(WC_VEHICLE_REFIT, this->index, VIWD_CONSIST_CHANGED);
00247 InvalidateWindowData(WC_VEHICLE_ORDERS, this->index, VIWD_CONSIST_CHANGED);
00248 }
00249 }
00250
00261 int GetTrainStopLocation(StationID station_id, TileIndex tile, const Train *v, int *station_ahead, int *station_length)
00262 {
00263 const Station *st = Station::Get(station_id);
00264 *station_ahead = st->GetPlatformLength(tile, DirToDiagDir(v->direction)) * TILE_SIZE;
00265 *station_length = st->GetPlatformLength(tile) * TILE_SIZE;
00266
00267
00268
00269 OrderStopLocation osl = OSL_PLATFORM_MIDDLE;
00270 if (v->gcache.cached_total_length >= *station_length) {
00271
00272 osl = OSL_PLATFORM_FAR_END;
00273 } else if (v->current_order.IsType(OT_GOTO_STATION) && v->current_order.GetDestination() == station_id) {
00274 osl = v->current_order.GetStopLocation();
00275 }
00276
00277
00278 int stop;
00279 switch (osl) {
00280 default: NOT_REACHED();
00281
00282 case OSL_PLATFORM_NEAR_END:
00283 stop = v->gcache.cached_total_length;
00284 break;
00285
00286 case OSL_PLATFORM_MIDDLE:
00287 stop = *station_length - (*station_length - v->gcache.cached_total_length) / 2;
00288 break;
00289
00290 case OSL_PLATFORM_FAR_END:
00291 stop = *station_length;
00292 break;
00293 }
00294
00295
00296
00297 return stop - (v->gcache.cached_veh_length + 1) / 2;
00298 }
00299
00300
00305 int Train::GetCurveSpeedLimit() const
00306 {
00307 assert(this->First() == this);
00308
00309 static const int absolute_max_speed = UINT16_MAX;
00310 int max_speed = absolute_max_speed;
00311
00312 if (_settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) return max_speed;
00313
00314 int curvecount[2] = {0, 0};
00315
00316
00317 int numcurve = 0;
00318 int sum = 0;
00319 int pos = 0;
00320 int lastpos = -1;
00321 for (const Vehicle *u = this; u->Next() != NULL; u = u->Next(), pos++) {
00322 Direction this_dir = u->direction;
00323 Direction next_dir = u->Next()->direction;
00324
00325 DirDiff dirdiff = DirDifference(this_dir, next_dir);
00326 if (dirdiff == DIRDIFF_SAME) continue;
00327
00328 if (dirdiff == DIRDIFF_45LEFT) curvecount[0]++;
00329 if (dirdiff == DIRDIFF_45RIGHT) curvecount[1]++;
00330 if (dirdiff == DIRDIFF_45LEFT || dirdiff == DIRDIFF_45RIGHT) {
00331 if (lastpos != -1) {
00332 numcurve++;
00333 sum += pos - lastpos;
00334 if (pos - lastpos == 1 && max_speed > 88) {
00335 max_speed = 88;
00336 }
00337 }
00338 lastpos = pos;
00339 }
00340
00341
00342 if (dirdiff == DIRDIFF_90LEFT || dirdiff == DIRDIFF_90RIGHT) {
00343 max_speed = 61;
00344 }
00345 }
00346
00347 if (numcurve > 0 && max_speed > 88) {
00348 if (curvecount[0] == 1 && curvecount[1] == 1) {
00349 max_speed = absolute_max_speed;
00350 } else {
00351 sum /= numcurve;
00352 max_speed = 232 - (13 - Clamp(sum, 1, 12)) * (13 - Clamp(sum, 1, 12));
00353 }
00354 }
00355
00356 if (max_speed != absolute_max_speed) {
00357
00358 const RailtypeInfo *rti = GetRailTypeInfo(this->railtype);
00359 max_speed += (max_speed / 2) * rti->curve_speed;
00360
00361 if (this->tcache.cached_tilt) {
00362
00363 max_speed += max_speed / 5;
00364 }
00365 }
00366
00367 return max_speed;
00368 }
00369
00374 int Train::GetCurrentMaxSpeed() const
00375 {
00376 if (_settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) return min(this->gcache.cached_max_track_speed, this->current_order.max_speed);
00377
00378 int max_speed = this->tcache.cached_max_curve_speed;
00379 if (IsRailStationTile(this->tile)) {
00380 StationID sid = GetStationIndex(this->tile);
00381 if (this->current_order.ShouldStopAtStation(this, sid)) {
00382 int station_ahead;
00383 int station_length;
00384 int stop_at = GetTrainStopLocation(sid, this->tile, this, &station_ahead, &station_length);
00385
00386
00387
00388 int distance_to_go = station_ahead / TILE_SIZE - (station_length - stop_at) / TILE_SIZE;
00389
00390 if (distance_to_go > 0) {
00391 int st_max_speed = 120;
00392
00393 int delta_v = this->cur_speed / (distance_to_go + 1);
00394 if (max_speed > (this->cur_speed - delta_v)) {
00395 st_max_speed = this->cur_speed - (delta_v / 10);
00396 }
00397
00398 st_max_speed = max(st_max_speed, 25 * distance_to_go);
00399 max_speed = min(max_speed, st_max_speed);
00400 }
00401 }
00402 }
00403
00404 for (const Train *u = this; u != NULL; u = u->Next()) {
00405 if (u->track == TRACK_BIT_DEPOT) {
00406 max_speed = min(max_speed, 61);
00407 break;
00408 }
00409
00410
00411 if (u->track == TRACK_BIT_WORMHOLE && !(u->vehstatus & VS_HIDDEN)) {
00412 max_speed = min(max_speed, GetBridgeSpec(GetBridgeType(u->tile))->speed);
00413 }
00414 }
00415
00416 max_speed = min(max_speed, this->current_order.max_speed);
00417 return min(max_speed, this->gcache.cached_max_track_speed);
00418 }
00419
00421 void Train::UpdateAcceleration()
00422 {
00423 assert(this->IsFrontEngine());
00424
00425 uint power = this->gcache.cached_power;
00426 uint weight = this->gcache.cached_weight;
00427 assert(weight != 0);
00428 this->acceleration = Clamp(power / weight * 4, 1, 255);
00429 }
00430
00436 int Train::GetDisplayImageWidth(Point *offset) const
00437 {
00438 int reference_width = TRAININFO_DEFAULT_VEHICLE_WIDTH;
00439 int vehicle_pitch = 0;
00440
00441 const Engine *e = this->GetEngine();
00442 if (e->GetGRF() != NULL && is_custom_sprite(e->u.rail.image_index)) {
00443 reference_width = e->GetGRF()->traininfo_vehicle_width;
00444 vehicle_pitch = e->GetGRF()->traininfo_vehicle_pitch;
00445 }
00446
00447 if (offset != NULL) {
00448 offset->x = reference_width / 2;
00449 offset->y = vehicle_pitch;
00450 }
00451 return this->gcache.cached_veh_length * reference_width / VEHICLE_LENGTH;
00452 }
00453
00454 static SpriteID GetDefaultTrainSprite(uint8 spritenum, Direction direction)
00455 {
00456 return ((direction + _engine_sprite_add[spritenum]) & _engine_sprite_and[spritenum]) + _engine_sprite_base[spritenum];
00457 }
00458
00465 SpriteID Train::GetImage(Direction direction, EngineImageType image_type) const
00466 {
00467 uint8 spritenum = this->spritenum;
00468 SpriteID sprite;
00469
00470 if (HasBit(this->flags, VRF_REVERSE_DIRECTION)) direction = ReverseDir(direction);
00471
00472 if (is_custom_sprite(spritenum)) {
00473 sprite = GetCustomVehicleSprite(this, (Direction)(direction + 4 * IS_CUSTOM_SECONDHEAD_SPRITE(spritenum)), image_type);
00474 if (sprite != 0) return sprite;
00475
00476 spritenum = this->GetEngine()->original_image_index;
00477 }
00478
00479 sprite = GetDefaultTrainSprite(spritenum, direction);
00480
00481 if (this->cargo.Count() >= this->cargo_cap / 2U) sprite += _wagon_full_adder[spritenum];
00482
00483 return sprite;
00484 }
00485
00486 static SpriteID GetRailIcon(EngineID engine, bool rear_head, int &y, EngineImageType image_type)
00487 {
00488 const Engine *e = Engine::Get(engine);
00489 Direction dir = rear_head ? DIR_E : DIR_W;
00490 uint8 spritenum = e->u.rail.image_index;
00491
00492 if (is_custom_sprite(spritenum)) {
00493 SpriteID sprite = GetCustomVehicleIcon(engine, dir, image_type);
00494 if (sprite != 0) {
00495 if (e->GetGRF() != NULL) {
00496 y += e->GetGRF()->traininfo_vehicle_pitch;
00497 }
00498 return sprite;
00499 }
00500
00501 spritenum = Engine::Get(engine)->original_image_index;
00502 }
00503
00504 if (rear_head) spritenum++;
00505
00506 return GetDefaultTrainSprite(spritenum, DIR_W);
00507 }
00508
00509 void DrawTrainEngine(int left, int right, int preferred_x, int y, EngineID engine, PaletteID pal, EngineImageType image_type)
00510 {
00511 if (RailVehInfo(engine)->railveh_type == RAILVEH_MULTIHEAD) {
00512 int yf = y;
00513 int yr = y;
00514
00515 SpriteID spritef = GetRailIcon(engine, false, yf, image_type);
00516 SpriteID spriter = GetRailIcon(engine, true, yr, image_type);
00517 const Sprite *real_spritef = GetSprite(spritef, ST_NORMAL);
00518 const Sprite *real_spriter = GetSprite(spriter, ST_NORMAL);
00519
00520 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);
00521
00522 DrawSprite(spritef, pal, preferred_x - 14, yf);
00523 DrawSprite(spriter, pal, preferred_x + 15, yr);
00524 } else {
00525 SpriteID sprite = GetRailIcon(engine, false, y, image_type);
00526 const Sprite *real_sprite = GetSprite(sprite, ST_NORMAL);
00527 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));
00528 DrawSprite(sprite, pal, preferred_x, y);
00529 }
00530 }
00531
00541 void GetTrainSpriteSize(EngineID engine, uint &width, uint &height, int &xoffs, int &yoffs, EngineImageType image_type)
00542 {
00543 int y = 0;
00544
00545 SpriteID sprite = GetRailIcon(engine, false, y, image_type);
00546 const Sprite *real_sprite = GetSprite(sprite, ST_NORMAL);
00547
00548 width = UnScaleByZoom(real_sprite->width, ZOOM_LVL_GUI);
00549 height = UnScaleByZoom(real_sprite->height, ZOOM_LVL_GUI);
00550 xoffs = UnScaleByZoom(real_sprite->x_offs, ZOOM_LVL_GUI);
00551 yoffs = UnScaleByZoom(real_sprite->y_offs, ZOOM_LVL_GUI);
00552
00553 if (RailVehInfo(engine)->railveh_type == RAILVEH_MULTIHEAD) {
00554 sprite = GetRailIcon(engine, true, y, image_type);
00555 real_sprite = GetSprite(sprite, ST_NORMAL);
00556
00557
00558 width = TRAININFO_DEFAULT_VEHICLE_WIDTH + UnScaleByZoom(real_sprite->width, ZOOM_LVL_GUI) + UnScaleByZoom(real_sprite->x_offs, ZOOM_LVL_GUI) - xoffs;
00559 height = max<uint>(height, UnScaleByZoom(real_sprite->height, ZOOM_LVL_GUI));
00560 xoffs = xoffs - TRAININFO_DEFAULT_VEHICLE_WIDTH / 2;
00561 yoffs = min(yoffs, UnScaleByZoom(real_sprite->y_offs, ZOOM_LVL_GUI));
00562 }
00563 }
00564
00573 static CommandCost CmdBuildRailWagon(TileIndex tile, DoCommandFlag flags, const Engine *e, Vehicle **ret)
00574 {
00575 const RailVehicleInfo *rvi = &e->u.rail;
00576
00577
00578 if (!IsCompatibleRail(rvi->railtype, GetRailType(tile))) return CMD_ERROR;
00579
00580 if (flags & DC_EXEC) {
00581 Train *v = new Train();
00582 *ret = v;
00583 v->spritenum = rvi->image_index;
00584
00585 v->engine_type = e->index;
00586 v->gcache.first_engine = INVALID_ENGINE;
00587
00588 DiagDirection dir = GetRailDepotDirection(tile);
00589
00590 v->direction = DiagDirToDir(dir);
00591 v->tile = tile;
00592
00593 int x = TileX(tile) * TILE_SIZE | _vehicle_initial_x_fract[dir];
00594 int y = TileY(tile) * TILE_SIZE | _vehicle_initial_y_fract[dir];
00595
00596 v->x_pos = x;
00597 v->y_pos = y;
00598 v->z_pos = GetSlopePixelZ(x, y);
00599 v->owner = _current_company;
00600 v->track = TRACK_BIT_DEPOT;
00601 v->vehstatus = VS_HIDDEN | VS_DEFPAL;
00602
00603 v->SetWagon();
00604
00605 v->SetFreeWagon();
00606 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
00607
00608 v->cargo_type = e->GetDefaultCargoType();
00609 v->cargo_cap = rvi->capacity;
00610 v->refit_cap = 0;
00611
00612 v->railtype = rvi->railtype;
00613
00614 v->build_year = _cur_year;
00615 v->cur_image = SPR_IMG_QUERY;
00616 v->random_bits = VehicleRandomBits();
00617
00618 v->group_id = DEFAULT_GROUP;
00619
00620 AddArticulatedParts(v);
00621
00622 _new_vehicle_id = v->index;
00623
00624 VehicleUpdatePosition(v);
00625 v->First()->ConsistChanged(false);
00626 UpdateTrainGroupID(v->First());
00627
00628 CheckConsistencyOfArticulatedVehicle(v);
00629
00630
00631 Train *w;
00632 FOR_ALL_TRAINS(w) {
00633 if (w->tile == tile &&
00634 w->IsFreeWagon() &&
00635 w->engine_type == e->index &&
00636 w->First() != v &&
00637 !(w->vehstatus & VS_CRASHED)) {
00638 DoCommand(0, v->index | 1 << 20, w->Last()->index, DC_EXEC, CMD_MOVE_RAIL_VEHICLE);
00639 break;
00640 }
00641 }
00642 }
00643
00644 return CommandCost();
00645 }
00646
00648 static void NormalizeTrainVehInDepot(const Train *u)
00649 {
00650 const Train *v;
00651 FOR_ALL_TRAINS(v) {
00652 if (v->IsFreeWagon() && v->tile == u->tile &&
00653 v->track == TRACK_BIT_DEPOT) {
00654 if (DoCommand(0, v->index | 1 << 20, u->index, DC_EXEC,
00655 CMD_MOVE_RAIL_VEHICLE).Failed())
00656 break;
00657 }
00658 }
00659 }
00660
00661 static void AddRearEngineToMultiheadedTrain(Train *v)
00662 {
00663 Train *u = new Train();
00664 v->value >>= 1;
00665 u->value = v->value;
00666 u->direction = v->direction;
00667 u->owner = v->owner;
00668 u->tile = v->tile;
00669 u->x_pos = v->x_pos;
00670 u->y_pos = v->y_pos;
00671 u->z_pos = v->z_pos;
00672 u->track = TRACK_BIT_DEPOT;
00673 u->vehstatus = v->vehstatus & ~VS_STOPPED;
00674 u->spritenum = v->spritenum + 1;
00675 u->cargo_type = v->cargo_type;
00676 u->cargo_subtype = v->cargo_subtype;
00677 u->cargo_cap = v->cargo_cap;
00678 u->refit_cap = v->refit_cap;
00679 u->railtype = v->railtype;
00680 u->engine_type = v->engine_type;
00681 u->build_year = v->build_year;
00682 u->cur_image = SPR_IMG_QUERY;
00683 u->random_bits = VehicleRandomBits();
00684 v->SetMultiheaded();
00685 u->SetMultiheaded();
00686 v->SetNext(u);
00687 VehicleUpdatePosition(u);
00688
00689
00690 v->other_multiheaded_part = u;
00691 u->other_multiheaded_part = v;
00692 }
00693
00703 CommandCost CmdBuildRailVehicle(TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **ret)
00704 {
00705 const RailVehicleInfo *rvi = &e->u.rail;
00706
00707 if (rvi->railveh_type == RAILVEH_WAGON) return CmdBuildRailWagon(tile, flags, e, ret);
00708
00709
00710
00711 if (!HasPowerOnRail(rvi->railtype, GetRailType(tile))) return CMD_ERROR;
00712
00713 if (flags & DC_EXEC) {
00714 DiagDirection dir = GetRailDepotDirection(tile);
00715 int x = TileX(tile) * TILE_SIZE + _vehicle_initial_x_fract[dir];
00716 int y = TileY(tile) * TILE_SIZE + _vehicle_initial_y_fract[dir];
00717
00718 Train *v = new Train();
00719 *ret = v;
00720 v->direction = DiagDirToDir(dir);
00721 v->tile = tile;
00722 v->owner = _current_company;
00723 v->x_pos = x;
00724 v->y_pos = y;
00725 v->z_pos = GetSlopePixelZ(x, y);
00726 v->track = TRACK_BIT_DEPOT;
00727 v->vehstatus = VS_HIDDEN | VS_STOPPED | VS_DEFPAL;
00728 v->spritenum = rvi->image_index;
00729 v->cargo_type = e->GetDefaultCargoType();
00730 v->cargo_cap = rvi->capacity;
00731 v->refit_cap = 0;
00732 v->last_station_visited = INVALID_STATION;
00733 v->last_loading_station = INVALID_STATION;
00734
00735 v->engine_type = e->index;
00736 v->gcache.first_engine = INVALID_ENGINE;
00737
00738 v->reliability = e->reliability;
00739 v->reliability_spd_dec = e->reliability_spd_dec;
00740 v->max_age = e->GetLifeLengthInDays();
00741
00742 v->railtype = rvi->railtype;
00743 _new_vehicle_id = v->index;
00744
00745 v->SetServiceInterval(Company::Get(_current_company)->settings.vehicle.servint_trains);
00746 v->date_of_last_service = _date;
00747 v->build_year = _cur_year;
00748 v->cur_image = SPR_IMG_QUERY;
00749 v->random_bits = VehicleRandomBits();
00750
00751 if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) SetBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE);
00752 v->SetServiceIntervalIsPercent(Company::Get(_current_company)->settings.vehicle.servint_ispercent);
00753
00754 v->group_id = DEFAULT_GROUP;
00755
00756 v->SetFrontEngine();
00757 v->SetEngine();
00758
00759 VehicleUpdatePosition(v);
00760
00761 if (rvi->railveh_type == RAILVEH_MULTIHEAD) {
00762 AddRearEngineToMultiheadedTrain(v);
00763 } else {
00764 AddArticulatedParts(v);
00765 }
00766
00767 v->ConsistChanged(false);
00768 UpdateTrainGroupID(v);
00769
00770 if (!HasBit(data, 0) && !(flags & DC_AUTOREPLACE)) {
00771 NormalizeTrainVehInDepot(v);
00772 }
00773
00774 CheckConsistencyOfArticulatedVehicle(v);
00775 }
00776
00777 return CommandCost();
00778 }
00779
00780 static Train *FindGoodVehiclePos(const Train *src)
00781 {
00782 EngineID eng = src->engine_type;
00783 TileIndex tile = src->tile;
00784
00785 Train *dst;
00786 FOR_ALL_TRAINS(dst) {
00787 if (dst->IsFreeWagon() && dst->tile == tile && !(dst->vehstatus & VS_CRASHED)) {
00788
00789 Train *t = dst;
00790 while (t->engine_type == eng) {
00791 t = t->Next();
00792 if (t == NULL) return dst;
00793 }
00794 }
00795 }
00796
00797 return NULL;
00798 }
00799
00801 typedef SmallVector<Train *, 16> TrainList;
00802
00808 static void MakeTrainBackup(TrainList &list, Train *t)
00809 {
00810 for (; t != NULL; t = t->Next()) *list.Append() = t;
00811 }
00812
00817 static void RestoreTrainBackup(TrainList &list)
00818 {
00819
00820 if (list.Length() == 0) return;
00821
00822 Train *prev = NULL;
00823
00824 for (Train **iter = list.Begin(); iter != list.End(); iter++) {
00825 Train *t = *iter;
00826 if (prev != NULL) {
00827 prev->SetNext(t);
00828 } else if (t->Previous() != NULL) {
00829
00830 t->Previous()->SetNext(NULL);
00831 }
00832 prev = t;
00833 }
00834 }
00835
00841 static void RemoveFromConsist(Train *part, bool chain = false)
00842 {
00843 Train *tail = chain ? part->Last() : part->GetLastEnginePart();
00844
00845
00846
00847 if (part->Previous() != NULL) part->Previous()->SetNext(tail->Next());
00848
00849
00850 tail->SetNext(NULL);
00851 }
00852
00858 static void InsertInConsist(Train *dst, Train *chain)
00859 {
00860
00861 assert(dst->Next() == NULL || !dst->Next()->IsArticulatedPart());
00862
00863 chain->Last()->SetNext(dst->Next());
00864 dst->SetNext(chain);
00865 }
00866
00872 static void NormaliseDualHeads(Train *t)
00873 {
00874 for (; t != NULL; t = t->GetNextVehicle()) {
00875 if (!t->IsMultiheaded() || !t->IsEngine()) continue;
00876
00877
00878 Train *u;
00879 for (u = t; u->Next() != NULL && !u->Next()->IsEngine(); u = u->Next()) {}
00880
00881 if (u == t->other_multiheaded_part) continue;
00882
00883
00884 RemoveFromConsist(t->other_multiheaded_part);
00885
00886 InsertInConsist(u, t->other_multiheaded_part);
00887 }
00888 }
00889
00894 static void NormaliseSubtypes(Train *chain)
00895 {
00896
00897 if (chain == NULL) return;
00898
00899
00900 assert(chain->Previous() == NULL);
00901
00902
00903 if (chain->IsWagon()) {
00904 chain->SetFreeWagon();
00905 } else {
00906 assert(chain->IsEngine());
00907 chain->SetFrontEngine();
00908 }
00909
00910
00911 for (Train *t = chain->Next(); t != NULL; t = t->Next()) {
00912 t->ClearFreeWagon();
00913 t->ClearFrontEngine();
00914 }
00915 }
00916
00926 static CommandCost CheckNewTrain(Train *original_dst, Train *dst, Train *original_src, Train *src)
00927 {
00928
00929
00930
00931 if ((src != NULL && src->IsEngine() ? 1 : 0) +
00932 (dst != NULL && dst->IsEngine() ? 1 : 0) -
00933 (original_src != NULL && original_src->IsEngine() ? 1 : 0) -
00934 (original_dst != NULL && original_dst->IsEngine() ? 1 : 0) <= 0) {
00935 return CommandCost();
00936 }
00937
00938
00939
00940 if (GetFreeUnitNumber(VEH_TRAIN) <= _settings_game.vehicle.max_trains) return CommandCost();
00941
00942 return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
00943 }
00944
00950 static CommandCost CheckTrainAttachment(Train *t)
00951 {
00952
00953 if (t == NULL || t->Next() == NULL || !t->IsEngine()) return CommandCost();
00954
00955
00956
00957 int allowed_len = _settings_game.vehicle.max_train_length * TILE_SIZE - t->gcache.cached_veh_length;
00958
00959 Train *head = t;
00960 Train *prev = t;
00961
00962
00963 t = t->Next();
00964 prev->SetNext(NULL);
00965
00966
00967 head->InvalidateNewGRFCache();
00968
00969 while (t != NULL) {
00970 allowed_len -= t->gcache.cached_veh_length;
00971
00972 Train *next = t->Next();
00973
00974
00975
00976 t->SetNext(NULL);
00977
00978
00979 if (!t->IsArticulatedPart() && !t->IsRearDualheaded()) {
00980
00981 EngineID first_engine = t->gcache.first_engine;
00982 t->gcache.first_engine = INVALID_ENGINE;
00983
00984
00985
00986 t->InvalidateNewGRFCache();
00987
00988 uint16 callback = GetVehicleCallbackParent(CBID_TRAIN_ALLOW_WAGON_ATTACH, 0, 0, head->engine_type, t, head);
00989
00990
00991 t->gcache.first_engine = first_engine;
00992
00993
00994 t->InvalidateNewGRFCache();
00995 head->InvalidateNewGRFCache();
00996
00997 if (callback != CALLBACK_FAILED) {
00998
00999 StringID error = STR_NULL;
01000
01001 if (head->GetGRF()->grf_version < 8) {
01002 if (callback == 0xFD) error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
01003 if (callback < 0xFD) error = GetGRFStringID(head->GetGRFID(), 0xD000 + callback);
01004 if (callback >= 0x100) ErrorUnknownCallbackResult(head->GetGRFID(), CBID_TRAIN_ALLOW_WAGON_ATTACH, callback);
01005 } else {
01006 if (callback < 0x400) {
01007 error = GetGRFStringID(head->GetGRFID(), 0xD000 + callback);
01008 } else {
01009 switch (callback) {
01010 case 0x400:
01011 case 0x401:
01012 break;
01013
01014 default:
01015 case 0x402:
01016 error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
01017 break;
01018 }
01019 }
01020 }
01021
01022 if (error != STR_NULL) return_cmd_error(error);
01023 }
01024 }
01025
01026
01027 prev->SetNext(t);
01028 prev = t;
01029 t = next;
01030 }
01031
01032 if (allowed_len < 0) return_cmd_error(STR_ERROR_TRAIN_TOO_LONG);
01033 return CommandCost();
01034 }
01035
01046 static CommandCost ValidateTrains(Train *original_dst, Train *dst, Train *original_src, Train *src, bool check_limit)
01047 {
01048
01049 CommandCost ret = CheckTrainAttachment(src);
01050 if (ret.Failed()) return ret;
01051 ret = CheckTrainAttachment(dst);
01052 if (ret.Failed()) return ret;
01053
01054
01055 return check_limit ? CheckNewTrain(original_dst, dst, original_src, src) : CommandCost();
01056 }
01057
01066 static void ArrangeTrains(Train **dst_head, Train *dst, Train **src_head, Train *src, bool move_chain)
01067 {
01068
01069 if (*src_head == *dst_head) {
01070
01071
01072 *dst_head = NULL;
01073 } else if (*dst_head == NULL) {
01074
01075
01076 *dst_head = src;
01077 }
01078
01079 if (src == *src_head) {
01080
01081
01082
01083
01084
01085
01086 *src_head = move_chain ? NULL :
01087 (src->IsMultiheaded() ? src->GetNextUnit() : src->GetNextVehicle());
01088 }
01089
01090
01091
01092
01093 RemoveFromConsist(src, move_chain);
01094 if (*dst_head != src) InsertInConsist(dst, src);
01095
01096
01097
01098 NormaliseDualHeads(*src_head);
01099 NormaliseDualHeads(*dst_head);
01100 }
01101
01107 static void NormaliseTrainHead(Train *head)
01108 {
01109
01110 if (head == NULL) return;
01111
01112
01113 head->ConsistChanged(false);
01114 UpdateTrainGroupID(head);
01115
01116
01117 if (!head->IsFrontEngine()) return;
01118
01119
01120 InvalidateWindowData(WC_VEHICLE_REFIT, head->index, VIWD_CONSIST_CHANGED);
01121 SetWindowWidgetDirty(WC_VEHICLE_VIEW, head->index, WID_VV_REFIT);
01122
01123
01124 if (head->unitnumber != 0) return;
01125 head->unitnumber = GetFreeUnitNumber(VEH_TRAIN);
01126 }
01127
01140 CommandCost CmdMoveRailVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01141 {
01142 VehicleID s = GB(p1, 0, 20);
01143 VehicleID d = GB(p2, 0, 20);
01144 bool move_chain = HasBit(p1, 20);
01145
01146 Train *src = Train::GetIfValid(s);
01147 if (src == NULL) return CMD_ERROR;
01148
01149 CommandCost ret = CheckOwnership(src->owner);
01150 if (ret.Failed()) return ret;
01151
01152
01153 if (src->vehstatus & VS_CRASHED) return CMD_ERROR;
01154
01155
01156 Train *dst;
01157 if (d == INVALID_VEHICLE) {
01158 dst = src->IsEngine() ? NULL : FindGoodVehiclePos(src);
01159 } else {
01160 dst = Train::GetIfValid(d);
01161 if (dst == NULL) return CMD_ERROR;
01162
01163 CommandCost ret = CheckOwnership(dst->owner);
01164 if (ret.Failed()) return ret;
01165
01166
01167 if (dst->vehstatus & VS_CRASHED) return CMD_ERROR;
01168 }
01169
01170
01171 src = src->GetFirstEnginePart();
01172 if (dst != NULL) {
01173 dst = dst->GetFirstEnginePart();
01174 }
01175
01176
01177 if (src == dst) return CommandCost();
01178
01179
01180 Train *src_head = src->First();
01181 Train *dst_head;
01182 if (dst != NULL) {
01183 dst_head = dst->First();
01184 if (dst_head->tile != src_head->tile) return CMD_ERROR;
01185
01186 dst = dst->GetLastEnginePart();
01187 } else {
01188 dst_head = NULL;
01189 }
01190
01191 if (src->IsRearDualheaded()) return_cmd_error(STR_ERROR_REAR_ENGINE_FOLLOW_FRONT);
01192
01193
01194 if (move_chain && src_head == dst_head) return CommandCost();
01195
01196
01197 if (!move_chain && dst != NULL && dst->IsRearDualheaded() && src == dst->other_multiheaded_part) return CommandCost();
01198
01199
01200 if (!src_head->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
01201
01202
01203 if (dst_head != NULL && !dst_head->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
01204
01205
01206
01207 TrainList original_src;
01208 TrainList original_dst;
01209
01210 MakeTrainBackup(original_src, src_head);
01211 MakeTrainBackup(original_dst, dst_head);
01212
01213
01214
01215
01216 Train *original_src_head = src_head;
01217 Train *original_dst_head = (dst_head == src_head ? NULL : dst_head);
01218
01219
01220 bool original_src_head_front_engine = original_src_head != NULL && original_src_head->IsFrontEngine();
01221 bool original_dst_head_front_engine = original_dst_head != NULL && original_dst_head->IsFrontEngine();
01222
01223
01224 ArrangeTrains(&dst_head, dst, &src_head, src, move_chain);
01225
01226 if ((flags & DC_AUTOREPLACE) == 0) {
01227
01228
01229
01230 CommandCost ret = ValidateTrains(original_dst_head, dst_head, original_src_head, src_head, true);
01231 if (ret.Failed()) {
01232
01233 RestoreTrainBackup(original_src);
01234 RestoreTrainBackup(original_dst);
01235 return ret;
01236 }
01237 }
01238
01239
01240 if (flags & DC_EXEC) {
01241
01242 if (original_src_head_front_engine) GroupStatistics::CountVehicle(original_src_head, -1);
01243 if (original_dst_head_front_engine) GroupStatistics::CountVehicle(original_dst_head, -1);
01244
01245
01246 NormaliseSubtypes(src_head);
01247 NormaliseSubtypes(dst_head);
01248
01249
01250
01251
01252
01253
01254
01255
01256
01257
01258
01259
01260
01261
01262
01263
01264
01265
01266
01267
01268
01269 if (src == original_src_head && src->IsEngine() && !src->IsFrontEngine()) {
01270
01271 DeleteWindowById(WC_VEHICLE_VIEW, src->index);
01272 DeleteWindowById(WC_VEHICLE_ORDERS, src->index);
01273 DeleteWindowById(WC_VEHICLE_REFIT, src->index);
01274 DeleteWindowById(WC_VEHICLE_DETAILS, src->index);
01275 DeleteWindowById(WC_VEHICLE_TIMETABLE, src->index);
01276 SetWindowDirty(WC_COMPANY, _current_company);
01277
01278
01279
01280 DeleteVehicleOrders(src);
01281 RemoveVehicleFromGroup(src);
01282 src->unitnumber = 0;
01283 }
01284
01285
01286
01287 if (original_src_head != src && dst_head == src) {
01288 SetTrainGroupID(src, DEFAULT_GROUP);
01289 SetWindowDirty(WC_COMPANY, _current_company);
01290 }
01291
01292
01293 if (src_head != NULL && src_head->IsFrontEngine()) GroupStatistics::CountVehicle(src_head, 1);
01294 if (dst_head != NULL && dst_head->IsFrontEngine()) GroupStatistics::CountVehicle(dst_head, 1);
01295
01296
01297 NormaliseTrainHead(src_head);
01298 NormaliseTrainHead(dst_head);
01299
01300 if ((flags & DC_NO_CARGO_CAP_CHECK) == 0) {
01301 CheckCargoCapacity(src_head);
01302 CheckCargoCapacity(dst_head);
01303 }
01304
01305
01306 InvalidateWindowData(WC_VEHICLE_DEPOT, src->tile);
01307 InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
01308 } else {
01309
01310 RestoreTrainBackup(original_src);
01311 RestoreTrainBackup(original_dst);
01312 }
01313
01314 return CommandCost();
01315 }
01316
01328 CommandCost CmdSellRailWagon(DoCommandFlag flags, Vehicle *t, uint16 data, uint32 user)
01329 {
01330
01331 Window *w = NULL;
01332
01333
01334 bool sell_chain = HasBit(data, 0);
01335
01336 Train *v = Train::From(t)->GetFirstEnginePart();
01337 Train *first = v->First();
01338
01339 if (v->IsRearDualheaded()) return_cmd_error(STR_ERROR_REAR_ENGINE_FOLLOW_FRONT);
01340
01341
01342
01343 TrainList original;
01344 MakeTrainBackup(original, first);
01345
01346
01347 Train *new_head = first;
01348 Train *sell_head = NULL;
01349
01350
01351 ArrangeTrains(&sell_head, NULL, &new_head, v, sell_chain);
01352
01353
01354 CommandCost ret = ValidateTrains(NULL, NULL, first, new_head, (flags & DC_AUTOREPLACE) == 0);
01355 if (ret.Failed()) {
01356
01357 RestoreTrainBackup(original);
01358 return ret;
01359 }
01360
01361 CommandCost cost(EXPENSES_NEW_VEHICLES);
01362 for (Train *t = sell_head; t != NULL; t = t->Next()) cost.AddCost(-t->value);
01363
01364 if (first->orders.list == NULL && !OrderList::CanAllocateItem()) {
01365 return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
01366 }
01367
01368
01369 if (flags & DC_EXEC) {
01370
01371 NormaliseSubtypes(new_head);
01372
01373 if (v == first && v->IsEngine() && !sell_chain && new_head != NULL && new_head->IsFrontEngine()) {
01374
01375
01376 new_head->orders.list = first->orders.list;
01377 new_head->AddToShared(first);
01378 DeleteVehicleOrders(first);
01379
01380
01381 new_head->CopyVehicleConfigAndStatistics(first);
01382 GroupStatistics::CountVehicle(new_head, 1);
01383
01384
01385 if (IsLocalCompany() && w != NULL) ShowVehicleViewWindow(new_head);
01386 } else if (v->IsPrimaryVehicle() && data & (MAKE_ORDER_BACKUP_FLAG >> 20)) {
01387 OrderBackup::Backup(v, user);
01388 }
01389
01390
01391 NormaliseTrainHead(new_head);
01392
01393
01394 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
01395 InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
01396
01397
01398 delete sell_head;
01399 } else {
01400
01401 RestoreTrainBackup(original);
01402 }
01403
01404 return cost;
01405 }
01406
01407 void Train::UpdateDeltaXY(Direction direction)
01408 {
01409
01410 this->x_offs = -1;
01411 this->y_offs = -1;
01412 this->x_extent = 3;
01413 this->y_extent = 3;
01414 this->z_extent = 6;
01415 this->x_bb_offs = 0;
01416 this->y_bb_offs = 0;
01417
01418 if (!IsDiagonalDirection(direction)) {
01419 static const int _sign_table[] =
01420 {
01421
01422 -1, -1,
01423 -1, 1,
01424 1, 1,
01425 1, -1,
01426 };
01427
01428 int half_shorten = (VEHICLE_LENGTH - this->gcache.cached_veh_length) / 2;
01429
01430
01431 this->x_offs -= half_shorten * _sign_table[direction];
01432 this->y_offs -= half_shorten * _sign_table[direction + 1];
01433 this->x_extent += this->x_bb_offs = half_shorten * _sign_table[direction];
01434 this->y_extent += this->y_bb_offs = half_shorten * _sign_table[direction + 1];
01435 } else {
01436 switch (direction) {
01437
01438
01439 case DIR_NE:
01440 this->x_offs = 1 - (this->gcache.cached_veh_length + 1) / 2;
01441 this->x_extent = this->gcache.cached_veh_length - 1;
01442 this->x_bb_offs = -1;
01443 break;
01444
01445 case DIR_NW:
01446 this->y_offs = 1 - (this->gcache.cached_veh_length + 1) / 2;
01447 this->y_extent = this->gcache.cached_veh_length - 1;
01448 this->y_bb_offs = -1;
01449 break;
01450
01451
01452
01453 case DIR_SW:
01454 this->x_offs = 1 + (this->gcache.cached_veh_length + 1) / 2 - VEHICLE_LENGTH;
01455 this->x_extent = VEHICLE_LENGTH - 1;
01456 this->x_bb_offs = VEHICLE_LENGTH - this->gcache.cached_veh_length - 1;
01457 break;
01458
01459 case DIR_SE:
01460 this->y_offs = 1 + (this->gcache.cached_veh_length + 1) / 2 - VEHICLE_LENGTH;
01461 this->y_extent = VEHICLE_LENGTH - 1;
01462 this->y_bb_offs = VEHICLE_LENGTH - this->gcache.cached_veh_length - 1;
01463 break;
01464
01465 default:
01466 NOT_REACHED();
01467 }
01468 }
01469 }
01470
01475 static void MarkTrainAsStuck(Train *v)
01476 {
01477 if (!HasBit(v->flags, VRF_TRAIN_STUCK)) {
01478
01479 SetBit(v->flags, VRF_TRAIN_STUCK);
01480
01481 v->wait_counter = 0;
01482
01483
01484 v->cur_speed = 0;
01485 v->subspeed = 0;
01486 v->SetLastSpeed();
01487
01488 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
01489 }
01490 }
01491
01499 static void SwapTrainFlags(uint16 *swap_flag1, uint16 *swap_flag2)
01500 {
01501 uint16 flag1 = *swap_flag1;
01502 uint16 flag2 = *swap_flag2;
01503
01504
01505 ClrBit(*swap_flag1, GVF_GOINGUP_BIT);
01506 ClrBit(*swap_flag1, GVF_GOINGDOWN_BIT);
01507 ClrBit(*swap_flag2, GVF_GOINGUP_BIT);
01508 ClrBit(*swap_flag2, GVF_GOINGDOWN_BIT);
01509
01510
01511 if (HasBit(flag1, GVF_GOINGUP_BIT)) {
01512 SetBit(*swap_flag2, GVF_GOINGDOWN_BIT);
01513 } else if (HasBit(flag1, GVF_GOINGDOWN_BIT)) {
01514 SetBit(*swap_flag2, GVF_GOINGUP_BIT);
01515 }
01516 if (HasBit(flag2, GVF_GOINGUP_BIT)) {
01517 SetBit(*swap_flag1, GVF_GOINGDOWN_BIT);
01518 } else if (HasBit(flag2, GVF_GOINGDOWN_BIT)) {
01519 SetBit(*swap_flag1, GVF_GOINGUP_BIT);
01520 }
01521 }
01522
01527 static void UpdateStatusAfterSwap(Train *v)
01528 {
01529
01530 if (v->track != TRACK_BIT_DEPOT) v->direction = ReverseDir(v->direction);
01531
01532
01533 if (v->track != TRACK_BIT_WORMHOLE) {
01534 VehicleEnterTile(v, v->tile, v->x_pos, v->y_pos);
01535 } else {
01536
01537
01538
01539
01540 TileIndex vt = TileVirtXY(v->x_pos, v->y_pos);
01541 if (IsTileType(vt, MP_TUNNELBRIDGE)) {
01542 VehicleEnterTile(v, vt, v->x_pos, v->y_pos);
01543 if (v->track != TRACK_BIT_WORMHOLE && IsBridgeTile(v->tile)) {
01544
01545
01546
01547 VehicleUpdatePosition(v);
01548 v->UpdateInclination(true, true);
01549 return;
01550 }
01551 }
01552 }
01553
01554 VehicleUpdatePosition(v);
01555 v->UpdateViewport(true, true);
01556 }
01557
01564 void ReverseTrainSwapVeh(Train *v, int l, int r)
01565 {
01566 Train *a, *b;
01567
01568
01569 for (a = v; l != 0; l--) a = a->Next();
01570 for (b = v; r != 0; r--) b = b->Next();
01571
01572 if (a != b) {
01573
01574 {
01575 uint16 tmp = (a->vehstatus & ~VS_HIDDEN) | (b->vehstatus & VS_HIDDEN);
01576 b->vehstatus = (b->vehstatus & ~VS_HIDDEN) | (a->vehstatus & VS_HIDDEN);
01577 a->vehstatus = tmp;
01578 }
01579
01580 Swap(a->track, b->track);
01581 Swap(a->direction, b->direction);
01582 Swap(a->x_pos, b->x_pos);
01583 Swap(a->y_pos, b->y_pos);
01584 Swap(a->tile, b->tile);
01585 Swap(a->z_pos, b->z_pos);
01586
01587 SwapTrainFlags(&a->gv_flags, &b->gv_flags);
01588
01589 UpdateStatusAfterSwap(a);
01590 UpdateStatusAfterSwap(b);
01591 } else {
01592
01593
01594
01595 SwapTrainFlags(&a->gv_flags, &a->gv_flags);
01596 UpdateStatusAfterSwap(a);
01597 }
01598 }
01599
01600
01606 static Vehicle *TrainOnTileEnum(Vehicle *v, void *)
01607 {
01608 return (v->type == VEH_TRAIN) ? v : NULL;
01609 }
01610
01611
01618 static Vehicle *TrainApproachingCrossingEnum(Vehicle *v, void *data)
01619 {
01620 if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) return NULL;
01621
01622 Train *t = Train::From(v);
01623 if (!t->IsFrontEngine()) return NULL;
01624
01625 TileIndex tile = *(TileIndex *)data;
01626
01627 if (TrainApproachingCrossingTile(t) != tile) return NULL;
01628
01629 return t;
01630 }
01631
01632
01639 static bool TrainApproachingCrossing(TileIndex tile)
01640 {
01641 assert(IsLevelCrossingTile(tile));
01642
01643 DiagDirection dir = AxisToDiagDir(GetCrossingRailAxis(tile));
01644 TileIndex tile_from = tile + TileOffsByDiagDir(dir);
01645
01646 if (HasVehicleOnPos(tile_from, &tile, &TrainApproachingCrossingEnum)) return true;
01647
01648 dir = ReverseDiagDir(dir);
01649 tile_from = tile + TileOffsByDiagDir(dir);
01650
01651 return HasVehicleOnPos(tile_from, &tile, &TrainApproachingCrossingEnum);
01652 }
01653
01654
01661 void UpdateLevelCrossing(TileIndex tile, bool sound)
01662 {
01663 assert(IsLevelCrossingTile(tile));
01664
01665
01666 bool new_state = HasVehicleOnPos(tile, NULL, &TrainOnTileEnum) || TrainApproachingCrossing(tile) || HasCrossingReservation(tile);
01667
01668 if (new_state != IsCrossingBarred(tile)) {
01669 if (new_state && sound) {
01670 if (_settings_client.sound.ambient) SndPlayTileFx(SND_0E_LEVEL_CROSSING, tile);
01671 }
01672 SetCrossingBarred(tile, new_state);
01673 MarkTileDirtyByTile(tile);
01674 }
01675 }
01676
01677
01683 static inline void MaybeBarCrossingWithSound(TileIndex tile)
01684 {
01685 if (!IsCrossingBarred(tile)) {
01686 BarCrossing(tile);
01687 if (_settings_client.sound.ambient) SndPlayTileFx(SND_0E_LEVEL_CROSSING, tile);
01688 MarkTileDirtyByTile(tile);
01689 }
01690 }
01691
01692
01698 static void AdvanceWagonsBeforeSwap(Train *v)
01699 {
01700 Train *base = v;
01701 Train *first = base;
01702 Train *last = v->Last();
01703 uint length = CountVehiclesInChain(v);
01704
01705 while (length > 2) {
01706 last = last->Previous();
01707 first = first->Next();
01708
01709 int differential = base->CalcNextVehicleOffset() - last->CalcNextVehicleOffset();
01710
01711
01712
01713 for (int i = 0; i < differential; i++) TrainController(first, last->Next());
01714
01715 base = first;
01716 length -= 2;
01717 }
01718 }
01719
01720
01726 static void AdvanceWagonsAfterSwap(Train *v)
01727 {
01728
01729 Train *dep = v;
01730 while (dep->Next() != NULL && (dep->track == TRACK_BIT_DEPOT || dep->Next()->track != TRACK_BIT_DEPOT)) {
01731 dep = dep->Next();
01732 }
01733
01734 Train *leave = dep->Next();
01735
01736 if (leave != NULL) {
01737
01738 int d = TicksToLeaveDepot(dep);
01739
01740 if (d <= 0) {
01741 leave->vehstatus &= ~VS_HIDDEN;
01742 leave->track = TrackToTrackBits(GetRailDepotTrack(leave->tile));
01743 for (int i = 0; i >= d; i--) TrainController(leave, NULL);
01744 }
01745 } else {
01746 dep = NULL;
01747 }
01748
01749 Train *base = v;
01750 Train *first = base;
01751 Train *last = v->Last();
01752 uint length = CountVehiclesInChain(v);
01753
01754
01755
01756 bool nomove = (dep == NULL);
01757
01758 while (length > 2) {
01759
01760
01761 if (base == dep) break;
01762
01763
01764 if (last == dep) nomove = true;
01765
01766 last = last->Previous();
01767 first = first->Next();
01768
01769 int differential = last->CalcNextVehicleOffset() - base->CalcNextVehicleOffset();
01770
01771
01772 for (int i = 0; i < differential; i++) TrainController(first, (nomove ? last->Next() : NULL));
01773
01774 base = first;
01775 length -= 2;
01776 }
01777 }
01778
01783 void ReverseTrainDirection(Train *v)
01784 {
01785 if (IsRailDepotTile(v->tile)) {
01786 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
01787 }
01788
01789
01790 if (!HasBit(v->flags, VRF_TRAIN_STUCK)) FreeTrainTrackReservation(v);
01791
01792
01793 TileIndex crossing = TrainApproachingCrossingTile(v);
01794
01795
01796 int r = CountVehiclesInChain(v) - 1;
01797
01798 AdvanceWagonsBeforeSwap(v);
01799
01800
01801 int l = 0;
01802 do {
01803 ReverseTrainSwapVeh(v, l++, r--);
01804 } while (l <= r);
01805
01806 AdvanceWagonsAfterSwap(v);
01807
01808 if (IsRailDepotTile(v->tile)) {
01809 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
01810 }
01811
01812 ToggleBit(v->flags, VRF_TOGGLE_REVERSE);
01813
01814 ClrBit(v->flags, VRF_REVERSING);
01815
01816
01817 v->ConsistChanged(true);
01818
01819
01820 for (Train *u = v; u != NULL; u = u->Next()) u->UpdateViewport(false, false);
01821
01822
01823 if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
01824
01825
01826 crossing = TrainApproachingCrossingTile(v);
01827 if (crossing != INVALID_TILE) MaybeBarCrossingWithSound(crossing);
01828
01829
01830 if (v->track == TRACK_BIT_DEPOT) {
01831
01832 if (HasBit(v->flags, VRF_TRAIN_STUCK)) SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
01833 ClrBit(v->flags, VRF_TRAIN_STUCK);
01834 return;
01835 }
01836
01837
01838
01839 DiagDirection dir = TrainExitDir(v->direction, v->track);
01840 if (IsRailDepotTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE)) dir = INVALID_DIAGDIR;
01841
01842 if (UpdateSignalsOnSegment(v->tile, dir, v->owner) == SIGSEG_PBS || _settings_game.pf.reserve_paths) {
01843
01844
01845 bool first_tile_okay = !(IsTileType(v->tile, MP_RAILWAY) &&
01846 HasSignalOnTrackdir(v->tile, v->GetVehicleTrackdir()) &&
01847 !IsPbsSignal(GetSignalType(v->tile, FindFirstTrack(v->track))));
01848
01849
01850 if (IsRailDepotTile(v->tile) && TrackdirToExitdir(v->GetVehicleTrackdir()) == GetRailDepotDirection(v->tile)) first_tile_okay = false;
01851
01852 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
01853 if (TryPathReserve(v, false, first_tile_okay)) {
01854
01855 CheckNextTrainTile(v);
01856 } else if (v->current_order.GetType() != OT_LOADING) {
01857
01858 MarkTrainAsStuck(v);
01859 }
01860 } else if (HasBit(v->flags, VRF_TRAIN_STUCK)) {
01861
01862 ClrBit(v->flags, VRF_TRAIN_STUCK);
01863 v->wait_counter = 0;
01864 }
01865 }
01866
01876 CommandCost CmdReverseTrainDirection(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01877 {
01878 Train *v = Train::GetIfValid(p1);
01879 if (v == NULL) return CMD_ERROR;
01880
01881 CommandCost ret = CheckOwnership(v->owner);
01882 if (ret.Failed()) return ret;
01883
01884 if (p2 != 0) {
01885
01886
01887 if (v->IsMultiheaded() || HasBit(EngInfo(v->engine_type)->callback_mask, CBM_VEHICLE_ARTIC_ENGINE)) {
01888 return_cmd_error(STR_ERROR_CAN_T_REVERSE_DIRECTION_RAIL_VEHICLE_MULTIPLE_UNITS);
01889 }
01890 if (!HasBit(EngInfo(v->engine_type)->misc_flags, EF_RAIL_FLIPS)) return CMD_ERROR;
01891
01892 Train *front = v->First();
01893
01894 if (!front->IsStoppedInDepot()) {
01895 return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
01896 }
01897
01898 if (flags & DC_EXEC) {
01899 ToggleBit(v->flags, VRF_REVERSE_DIRECTION);
01900
01901 front->ConsistChanged(false);
01902 SetWindowDirty(WC_VEHICLE_DEPOT, front->tile);
01903 SetWindowDirty(WC_VEHICLE_DETAILS, front->index);
01904 SetWindowDirty(WC_VEHICLE_VIEW, front->index);
01905 SetWindowClassesDirty(WC_TRAINS_LIST);
01906 }
01907 } else {
01908
01909 if ((v->vehstatus & VS_CRASHED) || v->breakdown_ctr != 0) return CMD_ERROR;
01910
01911 if (flags & DC_EXEC) {
01912
01913 if (v->current_order.IsType(OT_LOADING)) {
01914 const Vehicle *last = v;
01915 while (last->Next() != NULL) last = last->Next();
01916
01917
01918 if (!IsTileType(last->tile, MP_STATION) || GetStationIndex(last->tile) != GetStationIndex(v->tile)) {
01919 v->LeaveStation();
01920 }
01921 }
01922
01923
01924 v->force_proceed = TFP_NONE;
01925 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
01926
01927 if (_settings_game.vehicle.train_acceleration_model != AM_ORIGINAL && v->cur_speed != 0) {
01928 ToggleBit(v->flags, VRF_REVERSING);
01929 } else {
01930 v->cur_speed = 0;
01931 v->SetLastSpeed();
01932 HideFillingPercent(&v->fill_percent_te_id);
01933 ReverseTrainDirection(v);
01934 }
01935 }
01936 }
01937 return CommandCost();
01938 }
01939
01949 CommandCost CmdForceTrainProceed(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01950 {
01951 Train *t = Train::GetIfValid(p1);
01952 if (t == NULL) return CMD_ERROR;
01953
01954 if (!t->IsPrimaryVehicle()) return CMD_ERROR;
01955
01956 CommandCost ret = CheckOwnership(t->owner);
01957 if (ret.Failed()) return ret;
01958
01959
01960 if (flags & DC_EXEC) {
01961
01962
01963
01964
01965
01966 t->force_proceed = t->force_proceed == TFP_SIGNAL ? TFP_NONE : HasBit(t->flags, VRF_TRAIN_STUCK) || t->IsChainInDepot() ? TFP_STUCK : TFP_SIGNAL;
01967 SetWindowDirty(WC_VEHICLE_VIEW, t->index);
01968 }
01969
01970 return CommandCost();
01971 }
01972
01980 static FindDepotData FindClosestTrainDepot(Train *v, int max_distance)
01981 {
01982 assert(!(v->vehstatus & VS_CRASHED));
01983
01984 if (IsRailDepotTile(v->tile)) return FindDepotData(v->tile, 0);
01985
01986 PBSTileInfo origin = FollowTrainReservation(v);
01987 if (IsRailDepotTile(origin.tile)) return FindDepotData(origin.tile, 0);
01988
01989 switch (_settings_game.pf.pathfinder_for_trains) {
01990 case VPF_NPF: return NPFTrainFindNearestDepot(v, max_distance);
01991 case VPF_YAPF: return YapfTrainFindNearestDepot(v, max_distance);
01992
01993 default: NOT_REACHED();
01994 }
01995 }
01996
02004 bool Train::FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
02005 {
02006 FindDepotData tfdd = FindClosestTrainDepot(this, 0);
02007 if (tfdd.best_length == UINT_MAX) return false;
02008
02009 if (location != NULL) *location = tfdd.tile;
02010 if (destination != NULL) *destination = GetDepotIndex(tfdd.tile);
02011 if (reverse != NULL) *reverse = tfdd.reverse;
02012
02013 return true;
02014 }
02015
02017 void Train::PlayLeaveStationSound() const
02018 {
02019 static const SoundFx sfx[] = {
02020 SND_04_TRAIN,
02021 SND_0A_TRAIN_HORN,
02022 SND_0A_TRAIN_HORN,
02023 SND_47_MAGLEV_2,
02024 SND_41_MAGLEV
02025 };
02026
02027 if (PlayVehicleSound(this, VSE_START)) return;
02028
02029 EngineID engtype = this->engine_type;
02030 SndPlayVehicleFx(sfx[RailVehInfo(engtype)->engclass], this);
02031 }
02032
02037 static void CheckNextTrainTile(Train *v)
02038 {
02039
02040 if (_settings_game.pf.path_backoff_interval == 255) return;
02041
02042
02043 if (v->track == TRACK_BIT_DEPOT) return;
02044
02045 switch (v->current_order.GetType()) {
02046
02047 case OT_GOTO_DEPOT:
02048 if (v->tile == v->dest_tile) return;
02049 break;
02050
02051 case OT_GOTO_WAYPOINT:
02052
02053 if (IsRailWaypointTile(v->tile) && GetStationIndex(v->tile) == v->current_order.GetDestination()) ProcessOrders(v);
02054 break;
02055
02056 case OT_NOTHING:
02057 case OT_LEAVESTATION:
02058 case OT_LOADING:
02059
02060 if (v->GetNumOrders() > 0) return;
02061 break;
02062
02063 default:
02064 break;
02065 }
02066
02067 if (IsRailStationTile(v->tile) && v->current_order.ShouldStopAtStation(v, GetStationIndex(v->tile))) return;
02068
02069 Trackdir td = v->GetVehicleTrackdir();
02070
02071
02072 if (IsTileType(v->tile, MP_RAILWAY) && HasSignalOnTrackdir(v->tile, td) &&
02073 !IsPbsSignal(GetSignalType(v->tile, TrackdirToTrack(td))) &&
02074 GetSignalStateByTrackdir(v->tile, td) == SIGNAL_STATE_RED) return;
02075
02076 CFollowTrackRail ft(v);
02077 if (!ft.Follow(v->tile, td)) return;
02078
02079 if (!HasReservedTracks(ft.m_new_tile, TrackdirBitsToTrackBits(ft.m_new_td_bits))) {
02080
02081 if (KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE) {
02082 if (HasPbsSignalOnTrackdir(ft.m_new_tile, FindFirstTrackdir(ft.m_new_td_bits))) {
02083
02084 TrackBits tracks = TrackdirBitsToTrackBits(ft.m_new_td_bits);
02085 if (_settings_game.pf.forbid_90_deg) {
02086 tracks &= ~TrackCrossesTracks(TrackdirToTrack(ft.m_old_td));
02087 }
02088 ChooseTrainTrack(v, ft.m_new_tile, ft.m_exitdir, tracks, false, NULL, false);
02089 }
02090 }
02091 }
02092 }
02093
02099 static bool CheckTrainStayInDepot(Train *v)
02100 {
02101
02102 for (const Train *u = v; u != NULL; u = u->Next()) {
02103 if (u->track != TRACK_BIT_DEPOT || u->tile != v->tile) return false;
02104 }
02105
02106
02107 if (v->gcache.cached_power == 0) {
02108 v->vehstatus |= VS_STOPPED;
02109 SetWindowDirty(WC_VEHICLE_DEPOT, v->tile);
02110 return true;
02111 }
02112
02113 SigSegState seg_state;
02114
02115 if (v->force_proceed == TFP_NONE) {
02116
02117 if (++v->wait_counter < 37) {
02118 SetWindowClassesDirty(WC_TRAINS_LIST);
02119 return true;
02120 }
02121
02122 v->wait_counter = 0;
02123
02124 seg_state = _settings_game.pf.reserve_paths ? SIGSEG_PBS : UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
02125 if (seg_state == SIGSEG_FULL || HasDepotReservation(v->tile)) {
02126
02127 SetWindowClassesDirty(WC_TRAINS_LIST);
02128 return true;
02129 }
02130 } else {
02131 seg_state = _settings_game.pf.reserve_paths ? SIGSEG_PBS : UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
02132 }
02133
02134
02135 if (v->current_order.IsType(OT_GOTO_DEPOT) && v->tile == v->dest_tile) {
02136
02137 if (HasDepotReservation(v->tile)) return true;
02138 SetDepotReservation(v->tile, true);
02139 VehicleEnterDepot(v);
02140 return true;
02141 }
02142
02143
02144 if (seg_state == SIGSEG_PBS && !TryPathReserve(v) && v->force_proceed == TFP_NONE) {
02145
02146 SetWindowClassesDirty(WC_TRAINS_LIST);
02147 MarkTrainAsStuck(v);
02148 return true;
02149 }
02150
02151 SetDepotReservation(v->tile, true);
02152 if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(v->tile);
02153
02154 VehicleServiceInDepot(v);
02155 SetWindowClassesDirty(WC_TRAINS_LIST);
02156 v->PlayLeaveStationSound();
02157
02158 v->track = TRACK_BIT_X;
02159 if (v->direction & 2) v->track = TRACK_BIT_Y;
02160
02161 v->vehstatus &= ~VS_HIDDEN;
02162 v->cur_speed = 0;
02163
02164 v->UpdateViewport(true, true);
02165 VehicleUpdatePosition(v);
02166 UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
02167 v->UpdateAcceleration();
02168 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
02169
02170 return false;
02171 }
02172
02179 static void ClearPathReservation(const Train *v, TileIndex tile, Trackdir track_dir)
02180 {
02181 DiagDirection dir = TrackdirToExitdir(track_dir);
02182
02183 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
02184
02185 if (GetTunnelBridgeDirection(tile) == ReverseDiagDir(dir)) {
02186 TileIndex end = GetOtherTunnelBridgeEnd(tile);
02187
02188 if (TunnelBridgeIsFree(tile, end, v).Succeeded()) {
02189
02190 SetTunnelBridgeReservation(tile, false);
02191 SetTunnelBridgeReservation(end, false);
02192
02193 if (_settings_client.gui.show_track_reservation) {
02194 MarkTileDirtyByTile(tile);
02195 MarkTileDirtyByTile(end);
02196 }
02197 }
02198 }
02199 } else if (IsRailStationTile(tile)) {
02200 TileIndex new_tile = TileAddByDiagDir(tile, dir);
02201
02202
02203 if (!IsCompatibleTrainStationTile(new_tile, tile)) {
02204 SetRailStationPlatformReservation(tile, ReverseDiagDir(dir), false);
02205 }
02206 } else {
02207
02208 UnreserveRailTrack(tile, TrackdirToTrack(track_dir));
02209 }
02210 }
02211
02218 void FreeTrainTrackReservation(const Train *v, TileIndex origin, Trackdir orig_td)
02219 {
02220 assert(v->IsFrontEngine());
02221
02222 TileIndex tile = origin != INVALID_TILE ? origin : v->tile;
02223 Trackdir td = orig_td != INVALID_TRACKDIR ? orig_td : v->GetVehicleTrackdir();
02224 bool free_tile = tile != v->tile || !(IsRailStationTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE));
02225 StationID station_id = IsRailStationTile(v->tile) ? GetStationIndex(v->tile) : INVALID_STATION;
02226
02227
02228 if (IsRailDepotTile(tile) && TrackdirToExitdir(td) != GetRailDepotDirection(tile)) return;
02229 if (v->track == TRACK_BIT_DEPOT) {
02230
02231 for (const Train *u = v; u != NULL; u = u->Next()) {
02232 if (u->track != TRACK_BIT_DEPOT || u->tile != v->tile) return;
02233 }
02234 }
02235
02236 if (TracksOverlap(GetReservedTrackbits(tile) | TrackToTrackBits(TrackdirToTrack(td)))) return;
02237
02238 CFollowTrackRail ft(v, GetRailTypeInfo(v->railtype)->compatible_railtypes);
02239 while (ft.Follow(tile, td)) {
02240 tile = ft.m_new_tile;
02241 TrackdirBits bits = ft.m_new_td_bits & TrackBitsToTrackdirBits(GetReservedTrackbits(tile));
02242 td = RemoveFirstTrackdir(&bits);
02243 assert(bits == TRACKDIR_BIT_NONE);
02244
02245 if (!IsValidTrackdir(td)) break;
02246
02247 if (IsTileType(tile, MP_RAILWAY)) {
02248 if (HasSignalOnTrackdir(tile, td) && !IsPbsSignal(GetSignalType(tile, TrackdirToTrack(td)))) {
02249
02250 UnreserveRailTrack(tile, TrackdirToTrack(td));
02251 break;
02252 }
02253 if (HasPbsSignalOnTrackdir(tile, td)) {
02254 if (GetSignalStateByTrackdir(tile, td) == SIGNAL_STATE_RED) {
02255
02256 break;
02257 } else {
02258
02259 SetSignalStateByTrackdir(tile, td, SIGNAL_STATE_RED);
02260 MarkTileDirtyByTile(tile);
02261 }
02262 } else if (HasSignalOnTrackdir(tile, ReverseTrackdir(td)) && IsOnewaySignal(tile, TrackdirToTrack(td))) {
02263 break;
02264 }
02265 }
02266
02267
02268 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);
02269
02270 free_tile = true;
02271 }
02272 }
02273
02274 static const byte _initial_tile_subcoord[6][4][3] = {
02275 {{ 15, 8, 1 }, { 0, 0, 0 }, { 0, 8, 5 }, { 0, 0, 0 }},
02276 {{ 0, 0, 0 }, { 8, 0, 3 }, { 0, 0, 0 }, { 8, 15, 7 }},
02277 {{ 0, 0, 0 }, { 7, 0, 2 }, { 0, 7, 6 }, { 0, 0, 0 }},
02278 {{ 15, 8, 2 }, { 0, 0, 0 }, { 0, 0, 0 }, { 8, 15, 6 }},
02279 {{ 15, 7, 0 }, { 8, 0, 4 }, { 0, 0, 0 }, { 0, 0, 0 }},
02280 {{ 0, 0, 0 }, { 0, 0, 0 }, { 0, 8, 4 }, { 7, 15, 0 }},
02281 };
02282
02295 static Track DoTrainPathfind(const Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool &path_found, bool do_track_reservation, PBSTileInfo *dest)
02296 {
02297 switch (_settings_game.pf.pathfinder_for_trains) {
02298 case VPF_NPF: return NPFTrainChooseTrack(v, tile, enterdir, tracks, path_found, do_track_reservation, dest);
02299 case VPF_YAPF: return YapfTrainChooseTrack(v, tile, enterdir, tracks, path_found, do_track_reservation, dest);
02300
02301 default: NOT_REACHED();
02302 }
02303 }
02304
02310 static PBSTileInfo ExtendTrainReservation(const Train *v, TrackBits *new_tracks, DiagDirection *enterdir)
02311 {
02312 PBSTileInfo origin = FollowTrainReservation(v);
02313
02314 CFollowTrackRail ft(v);
02315
02316 TileIndex tile = origin.tile;
02317 Trackdir cur_td = origin.trackdir;
02318 while (ft.Follow(tile, cur_td)) {
02319 if (KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE) {
02320
02321 if (HasOnewaySignalBlockingTrackdir(ft.m_new_tile, FindFirstTrackdir(ft.m_new_td_bits))) break;
02322 }
02323
02324 if (_settings_game.pf.forbid_90_deg) {
02325 ft.m_new_td_bits &= ~TrackdirCrossesTrackdirs(ft.m_old_td);
02326 if (ft.m_new_td_bits == TRACKDIR_BIT_NONE) break;
02327 }
02328
02329
02330 bool target_seen = ft.m_is_station || (IsTileType(ft.m_new_tile, MP_RAILWAY) && !IsPlainRail(ft.m_new_tile));
02331 if (target_seen || KillFirstBit(ft.m_new_td_bits) != TRACKDIR_BIT_NONE) {
02332
02333
02334
02335
02336
02337
02338 if (HasReservedTracks(ft.m_new_tile, TrackdirBitsToTrackBits(TrackdirReachesTrackdirs(ft.m_old_td)))) break;
02339
02340
02341
02342 if (ft.m_tiles_skipped != 0) ft.m_new_tile -= TileOffsByDiagDir(ft.m_exitdir) * ft.m_tiles_skipped;
02343
02344
02345 if (new_tracks != NULL) *new_tracks = TrackdirBitsToTrackBits(ft.m_new_td_bits);
02346 if (enterdir != NULL) *enterdir = ft.m_exitdir;
02347 return PBSTileInfo(ft.m_new_tile, ft.m_old_td, false);
02348 }
02349
02350 tile = ft.m_new_tile;
02351 cur_td = FindFirstTrackdir(ft.m_new_td_bits);
02352
02353 if (IsSafeWaitingPosition(v, tile, cur_td, true, _settings_game.pf.forbid_90_deg)) {
02354 bool wp_free = IsWaitingPositionFree(v, tile, cur_td, _settings_game.pf.forbid_90_deg);
02355 if (!(wp_free && TryReserveRailTrack(tile, TrackdirToTrack(cur_td)))) break;
02356
02357 return PBSTileInfo(tile, cur_td, true);
02358 }
02359
02360 if (!TryReserveRailTrack(tile, TrackdirToTrack(cur_td))) break;
02361 }
02362
02363 if (ft.m_err == CFollowTrackRail::EC_OWNER || ft.m_err == CFollowTrackRail::EC_NO_WAY) {
02364
02365 return PBSTileInfo(ft.m_old_tile, ft.m_old_td, true);
02366 }
02367
02368
02369 tile = origin.tile;
02370 cur_td = origin.trackdir;
02371 TileIndex stopped = ft.m_old_tile;
02372 Trackdir stopped_td = ft.m_old_td;
02373 while (tile != stopped || cur_td != stopped_td) {
02374 if (!ft.Follow(tile, cur_td)) break;
02375
02376 if (_settings_game.pf.forbid_90_deg) {
02377 ft.m_new_td_bits &= ~TrackdirCrossesTrackdirs(ft.m_old_td);
02378 assert(ft.m_new_td_bits != TRACKDIR_BIT_NONE);
02379 }
02380 assert(KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE);
02381
02382 tile = ft.m_new_tile;
02383 cur_td = FindFirstTrackdir(ft.m_new_td_bits);
02384
02385 UnreserveRailTrack(tile, TrackdirToTrack(cur_td));
02386 }
02387
02388
02389 return PBSTileInfo();
02390 }
02391
02402 static bool TryReserveSafeTrack(const Train *v, TileIndex tile, Trackdir td, bool override_tailtype)
02403 {
02404 switch (_settings_game.pf.pathfinder_for_trains) {
02405 case VPF_NPF: return NPFTrainFindNearestSafeTile(v, tile, td, override_tailtype);
02406 case VPF_YAPF: return YapfTrainFindNearestSafeTile(v, tile, td, override_tailtype);
02407
02408 default: NOT_REACHED();
02409 }
02410 }
02411
02413 class VehicleOrderSaver {
02414 private:
02415 Train *v;
02416 Order old_order;
02417 TileIndex old_dest_tile;
02418 StationID old_last_station_visited;
02419 VehicleOrderID index;
02420 bool suppress_implicit_orders;
02421
02422 public:
02423 VehicleOrderSaver(Train *_v) :
02424 v(_v),
02425 old_order(_v->current_order),
02426 old_dest_tile(_v->dest_tile),
02427 old_last_station_visited(_v->last_station_visited),
02428 index(_v->cur_real_order_index),
02429 suppress_implicit_orders(HasBit(_v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS))
02430 {
02431 }
02432
02433 ~VehicleOrderSaver()
02434 {
02435 this->v->current_order = this->old_order;
02436 this->v->dest_tile = this->old_dest_tile;
02437 this->v->last_station_visited = this->old_last_station_visited;
02438 SB(this->v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS, 1, suppress_implicit_orders ? 1: 0);
02439 }
02440
02446 bool SwitchToNextOrder(bool skip_first)
02447 {
02448 if (this->v->GetNumOrders() == 0) return false;
02449
02450 if (skip_first) ++this->index;
02451
02452 int depth = 0;
02453
02454 do {
02455
02456 if (this->index >= this->v->GetNumOrders()) this->index = 0;
02457
02458 Order *order = this->v->GetOrder(this->index);
02459 assert(order != NULL);
02460
02461 switch (order->GetType()) {
02462 case OT_GOTO_DEPOT:
02463
02464 if ((order->GetDepotOrderType() & ODTFB_SERVICE) && !this->v->NeedsServicing()) break;
02465 case OT_GOTO_STATION:
02466 case OT_GOTO_WAYPOINT:
02467 this->v->current_order = *order;
02468 return UpdateOrderDest(this->v, order, 0, true);
02469 case OT_CONDITIONAL: {
02470 VehicleOrderID next = ProcessConditionalOrder(order, this->v);
02471 if (next != INVALID_VEH_ORDER_ID) {
02472 depth++;
02473 this->index = next;
02474
02475 continue;
02476 }
02477 break;
02478 }
02479 default:
02480 break;
02481 }
02482
02483
02484 ++this->index;
02485 depth++;
02486 } while (this->index != this->v->cur_real_order_index && depth < this->v->GetNumOrders());
02487
02488 return false;
02489 }
02490 };
02491
02492
02493 static Track ChooseTrainTrack(Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool force_res, bool *got_reservation, bool mark_stuck)
02494 {
02495 Track best_track = INVALID_TRACK;
02496 bool do_track_reservation = _settings_game.pf.reserve_paths || force_res;
02497 bool changed_signal = false;
02498
02499 assert((tracks & ~TRACK_BIT_MASK) == 0);
02500
02501 if (got_reservation != NULL) *got_reservation = false;
02502
02503
02504 TrackBits res_tracks = (TrackBits)(GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir));
02505
02506 if (res_tracks != TRACK_BIT_NONE) return FindFirstTrack(res_tracks);
02507
02508
02509 if (KillFirstBit(tracks) == TRACK_BIT_NONE) {
02510 Track track = FindFirstTrack(tracks);
02511
02512 if (track != INVALID_TRACK && HasPbsSignalOnTrackdir(tile, TrackEnterdirToTrackdir(track, enterdir))) {
02513 do_track_reservation = true;
02514 changed_signal = true;
02515 SetSignalStateByTrackdir(tile, TrackEnterdirToTrackdir(track, enterdir), SIGNAL_STATE_GREEN);
02516 } else if (!do_track_reservation) {
02517 return track;
02518 }
02519 best_track = track;
02520 }
02521
02522 PBSTileInfo res_dest(tile, INVALID_TRACKDIR, false);
02523 DiagDirection dest_enterdir = enterdir;
02524 if (do_track_reservation) {
02525 res_dest = ExtendTrainReservation(v, &tracks, &dest_enterdir);
02526 if (res_dest.tile == INVALID_TILE) {
02527
02528 if (mark_stuck) MarkTrainAsStuck(v);
02529 if (changed_signal) SetSignalStateByTrackdir(tile, TrackEnterdirToTrackdir(best_track, enterdir), SIGNAL_STATE_RED);
02530 return FindFirstTrack(tracks);
02531 }
02532 if (res_dest.okay) {
02533
02534 if (got_reservation != NULL) *got_reservation = true;
02535 if (changed_signal) MarkTileDirtyByTile(tile);
02536 TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
02537 return best_track;
02538 }
02539
02540
02541
02542
02543 CheckIfTrainNeedsService(v);
02544 if (v->current_order.IsType(OT_DUMMY) || v->current_order.IsType(OT_CONDITIONAL) || v->current_order.IsType(OT_GOTO_DEPOT)) ProcessOrders(v);
02545 }
02546
02547
02548 VehicleOrderSaver orders(v);
02549
02550
02551
02552
02553
02554
02555
02556 if (v->current_order.IsType(OT_LEAVESTATION)) {
02557 orders.SwitchToNextOrder(false);
02558 } else if (v->current_order.IsType(OT_LOADING) || (!v->current_order.IsType(OT_GOTO_DEPOT) && (
02559 v->current_order.IsType(OT_GOTO_STATION) ?
02560 IsRailStationTile(v->tile) && v->current_order.GetDestination() == GetStationIndex(v->tile) :
02561 v->tile == v->dest_tile))) {
02562 orders.SwitchToNextOrder(true);
02563 }
02564
02565 if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
02566
02567 bool path_found = true;
02568 TileIndex new_tile = res_dest.tile;
02569
02570 Track next_track = DoTrainPathfind(v, new_tile, dest_enterdir, tracks, path_found, do_track_reservation, &res_dest);
02571 if (new_tile == tile) best_track = next_track;
02572 v->HandlePathfindingResult(path_found);
02573 }
02574
02575
02576 if (!do_track_reservation) return best_track;
02577
02578
02579 if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
02580 if (mark_stuck) MarkTrainAsStuck(v);
02581 FreeTrainTrackReservation(v);
02582 return best_track;
02583 }
02584
02585
02586 if (res_dest.tile == INVALID_TILE) {
02587
02588 PBSTileInfo origin = FollowTrainReservation(v);
02589 if (TryReserveSafeTrack(v, origin.tile, origin.trackdir, false)) {
02590 TrackBits res = GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir);
02591 best_track = FindFirstTrack(res);
02592 TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
02593 if (got_reservation != NULL) *got_reservation = true;
02594 if (changed_signal) MarkTileDirtyByTile(tile);
02595 } else {
02596 FreeTrainTrackReservation(v);
02597 if (mark_stuck) MarkTrainAsStuck(v);
02598 }
02599 return best_track;
02600 }
02601
02602 if (got_reservation != NULL) *got_reservation = true;
02603
02604
02605 while (!IsSafeWaitingPosition(v, res_dest.tile, res_dest.trackdir, true, _settings_game.pf.forbid_90_deg)) {
02606
02607 DiagDirection exitdir = TrackdirToExitdir(res_dest.trackdir);
02608 TileIndex next_tile = TileAddByDiagDir(res_dest.tile, exitdir);
02609 TrackBits reachable = TrackdirBitsToTrackBits((TrackdirBits)(GetTileTrackStatus(next_tile, TRANSPORT_RAIL, 0))) & DiagdirReachesTracks(exitdir);
02610 if (_settings_game.pf.forbid_90_deg) {
02611 reachable &= ~TrackCrossesTracks(TrackdirToTrack(res_dest.trackdir));
02612 }
02613
02614
02615 if (orders.SwitchToNextOrder(true)) {
02616 PBSTileInfo cur_dest;
02617 bool path_found;
02618 DoTrainPathfind(v, next_tile, exitdir, reachable, path_found, true, &cur_dest);
02619 if (cur_dest.tile != INVALID_TILE) {
02620 res_dest = cur_dest;
02621 if (res_dest.okay) continue;
02622
02623 FreeTrainTrackReservation(v);
02624 if (mark_stuck) MarkTrainAsStuck(v);
02625 if (got_reservation != NULL) *got_reservation = false;
02626 changed_signal = false;
02627 break;
02628 }
02629 }
02630
02631 if (!TryReserveSafeTrack(v, res_dest.tile, res_dest.trackdir, true)) {
02632 FreeTrainTrackReservation(v);
02633 if (mark_stuck) MarkTrainAsStuck(v);
02634 if (got_reservation != NULL) *got_reservation = false;
02635 changed_signal = false;
02636 }
02637 break;
02638 }
02639
02640 TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
02641
02642 if (changed_signal) MarkTileDirtyByTile(tile);
02643
02644 return best_track;
02645 }
02646
02655 bool TryPathReserve(Train *v, bool mark_as_stuck, bool first_tile_okay)
02656 {
02657 assert(v->IsFrontEngine());
02658
02659
02660
02661
02662 if (v->track == TRACK_BIT_DEPOT) {
02663 if (HasDepotReservation(v->tile)) {
02664 if (mark_as_stuck) MarkTrainAsStuck(v);
02665 return false;
02666 } else {
02667
02668 TileIndex next_tile = TileAddByDiagDir(v->tile, GetRailDepotDirection(v->tile));
02669 if (HasReservedTracks(next_tile, DiagdirReachesTracks(GetRailDepotDirection(v->tile)))) return false;
02670 }
02671 }
02672
02673 Vehicle *other_train = NULL;
02674 PBSTileInfo origin = FollowTrainReservation(v, &other_train);
02675
02676
02677
02678
02679
02680 if (other_train != NULL && other_train->index != v->index) {
02681 if (mark_as_stuck) MarkTrainAsStuck(v);
02682 return false;
02683 }
02684
02685 if (origin.okay && (v->tile != origin.tile || first_tile_okay)) {
02686
02687 if (HasBit(v->flags, VRF_TRAIN_STUCK)) SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
02688 ClrBit(v->flags, VRF_TRAIN_STUCK);
02689 return true;
02690 }
02691
02692
02693 if (v->track == TRACK_BIT_DEPOT) {
02694 SetDepotReservation(v->tile, true);
02695 if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(v->tile);
02696 }
02697
02698 DiagDirection exitdir = TrackdirToExitdir(origin.trackdir);
02699 TileIndex new_tile = TileAddByDiagDir(origin.tile, exitdir);
02700 TrackBits reachable = TrackdirBitsToTrackBits(TrackStatusToTrackdirBits(GetTileTrackStatus(new_tile, TRANSPORT_RAIL, 0)) & DiagdirReachesTrackdirs(exitdir));
02701
02702 if (_settings_game.pf.forbid_90_deg) reachable &= ~TrackCrossesTracks(TrackdirToTrack(origin.trackdir));
02703
02704 bool res_made = false;
02705 ChooseTrainTrack(v, new_tile, exitdir, reachable, true, &res_made, mark_as_stuck);
02706
02707 if (!res_made) {
02708
02709 if (v->track == TRACK_BIT_DEPOT) SetDepotReservation(v->tile, false);
02710 return false;
02711 }
02712
02713 if (HasBit(v->flags, VRF_TRAIN_STUCK)) {
02714 v->wait_counter = 0;
02715 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
02716 }
02717 ClrBit(v->flags, VRF_TRAIN_STUCK);
02718 return true;
02719 }
02720
02721
02722 static bool CheckReverseTrain(const Train *v)
02723 {
02724 if (_settings_game.difficulty.line_reverse_mode != 0 ||
02725 v->track == TRACK_BIT_DEPOT || v->track == TRACK_BIT_WORMHOLE ||
02726 !(v->direction & 1)) {
02727 return false;
02728 }
02729
02730 assert(v->track != TRACK_BIT_NONE);
02731
02732 switch (_settings_game.pf.pathfinder_for_trains) {
02733 case VPF_NPF: return NPFTrainCheckReverse(v);
02734 case VPF_YAPF: return YapfTrainCheckReverse(v);
02735
02736 default: NOT_REACHED();
02737 }
02738 }
02739
02745 TileIndex Train::GetOrderStationLocation(StationID station)
02746 {
02747 if (station == this->last_station_visited) this->last_station_visited = INVALID_STATION;
02748
02749 const Station *st = Station::Get(station);
02750 if (!(st->facilities & FACIL_TRAIN)) {
02751
02752 this->IncrementRealOrderIndex();
02753 return 0;
02754 }
02755
02756 return st->xy;
02757 }
02758
02760 void Train::MarkDirty()
02761 {
02762 Train *v = this;
02763 do {
02764 v->UpdateViewport(false, false);
02765 } while ((v = v->Next()) != NULL);
02766
02767
02768 this->CargoChanged();
02769 this->UpdateAcceleration();
02770 }
02771
02779 int Train::UpdateSpeed()
02780 {
02781 switch (_settings_game.vehicle.train_acceleration_model) {
02782 default: NOT_REACHED();
02783 case AM_ORIGINAL:
02784 return this->DoUpdateSpeed(this->acceleration * (this->GetAccelerationStatus() == AS_BRAKE ? -4 : 2), 0, min(this->gcache.cached_max_track_speed, this->current_order.max_speed));
02785
02786 case AM_REALISTIC:
02787 return this->DoUpdateSpeed(this->GetAcceleration(), this->GetAccelerationStatus() == AS_BRAKE ? 0 : 2, this->GetCurrentMaxSpeed());
02788 }
02789 }
02790
02796 static void TrainEnterStation(Train *v, StationID station)
02797 {
02798 v->last_station_visited = station;
02799
02800
02801 Station *st = Station::Get(station);
02802 if (!(st->had_vehicle_of_type & HVOT_TRAIN)) {
02803 st->had_vehicle_of_type |= HVOT_TRAIN;
02804 SetDParam(0, st->index);
02805 AddVehicleNewsItem(
02806 STR_NEWS_FIRST_TRAIN_ARRIVAL,
02807 v->owner == _local_company ? NT_ARRIVAL_COMPANY : NT_ARRIVAL_OTHER,
02808 v->index,
02809 st->index
02810 );
02811 AI::NewEvent(v->owner, new ScriptEventStationFirstVehicle(st->index, v->index));
02812 Game::NewEvent(new ScriptEventStationFirstVehicle(st->index, v->index));
02813 }
02814
02815 v->force_proceed = TFP_NONE;
02816 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
02817
02818 v->BeginLoading();
02819
02820 TriggerStationRandomisation(st, v->tile, SRT_TRAIN_ARRIVES);
02821 TriggerStationAnimation(st, v->tile, SAT_TRAIN_ARRIVES);
02822 }
02823
02824
02825 static inline bool CheckCompatibleRail(const Train *v, TileIndex tile)
02826 {
02827 return IsTileOwner(tile, v->owner) &&
02828 (!v->IsFrontEngine() || HasBit(v->compatible_railtypes, GetRailType(tile)));
02829 }
02830
02832 struct AccelerationSlowdownParams {
02833 byte small_turn;
02834 byte large_turn;
02835 byte z_up;
02836 byte z_down;
02837 };
02838
02840 static const AccelerationSlowdownParams _accel_slowdown[] = {
02841
02842 {256 / 4, 256 / 2, 256 / 4, 2},
02843 {256 / 4, 256 / 2, 256 / 4, 2},
02844 {0, 256 / 2, 256 / 4, 2},
02845 };
02846
02852 static inline void AffectSpeedByZChange(Train *v, int old_z)
02853 {
02854 if (old_z == v->z_pos || _settings_game.vehicle.train_acceleration_model != AM_ORIGINAL) return;
02855
02856 const AccelerationSlowdownParams *asp = &_accel_slowdown[GetRailTypeInfo(v->railtype)->acceleration_type];
02857
02858 if (old_z < v->z_pos) {
02859 v->cur_speed -= (v->cur_speed * asp->z_up >> 8);
02860 } else {
02861 uint16 spd = v->cur_speed + asp->z_down;
02862 if (spd <= v->gcache.cached_max_track_speed) v->cur_speed = spd;
02863 }
02864 }
02865
02866 static bool TrainMovedChangeSignals(TileIndex tile, DiagDirection dir)
02867 {
02868 if (IsTileType(tile, MP_RAILWAY) &&
02869 GetRailTileType(tile) == RAIL_TILE_SIGNALS) {
02870 TrackdirBits tracks = TrackBitsToTrackdirBits(GetTrackBits(tile)) & DiagdirReachesTrackdirs(dir);
02871 Trackdir trackdir = FindFirstTrackdir(tracks);
02872 if (UpdateSignalsOnSegment(tile, TrackdirToExitdir(trackdir), GetTileOwner(tile)) == SIGSEG_PBS && HasSignalOnTrackdir(tile, trackdir)) {
02873
02874 if (!IsPbsSignal(GetSignalType(tile, TrackdirToTrack(trackdir)))) return true;
02875 }
02876 }
02877 return false;
02878 }
02879
02881 void Train::ReserveTrackUnderConsist() const
02882 {
02883 for (const Train *u = this; u != NULL; u = u->Next()) {
02884 switch (u->track) {
02885 case TRACK_BIT_WORMHOLE:
02886 TryReserveRailTrack(u->tile, DiagDirToDiagTrack(GetTunnelBridgeDirection(u->tile)));
02887 break;
02888 case TRACK_BIT_DEPOT:
02889 break;
02890 default:
02891 TryReserveRailTrack(u->tile, TrackBitsToTrack(u->track));
02892 break;
02893 }
02894 }
02895 }
02896
02903 uint Train::Crash(bool flooded)
02904 {
02905 uint pass = 0;
02906 if (this->IsFrontEngine()) {
02907 pass += 2;
02908
02909
02910
02911 if (!HasBit(this->flags, VRF_TRAIN_STUCK)) FreeTrainTrackReservation(this);
02912 for (const Train *v = this; v != NULL; v = v->Next()) {
02913 ClearPathReservation(v, v->tile, v->GetVehicleTrackdir());
02914 if (IsTileType(v->tile, MP_TUNNELBRIDGE)) {
02915
02916
02917 SetTunnelBridgeReservation(GetOtherTunnelBridgeEnd(v->tile), false);
02918 }
02919 }
02920
02921
02922
02923 TileIndex crossing = TrainApproachingCrossingTile(this);
02924 if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
02925
02926
02927 HideFillingPercent(&this->fill_percent_te_id);
02928 }
02929
02930 pass += this->GroundVehicleBase::Crash(flooded);
02931
02932 this->crash_anim_pos = flooded ? 4000 : 1;
02933 return pass;
02934 }
02935
02942 static uint TrainCrashed(Train *v)
02943 {
02944 uint num = 0;
02945
02946
02947 if (!(v->vehstatus & VS_CRASHED)) {
02948 num = v->Crash();
02949 AI::NewEvent(v->owner, new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_TRAIN));
02950 Game::NewEvent(new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_TRAIN));
02951 }
02952
02953
02954
02955 v->ReserveTrackUnderConsist();
02956
02957 return num;
02958 }
02959
02961 struct TrainCollideChecker {
02962 Train *v;
02963 uint num;
02964 };
02965
02972 static Vehicle *FindTrainCollideEnum(Vehicle *v, void *data)
02973 {
02974 TrainCollideChecker *tcc = (TrainCollideChecker*)data;
02975
02976
02977 if (v->type != VEH_TRAIN || Train::From(v)->track == TRACK_BIT_DEPOT) return NULL;
02978
02979
02980 if (v->owner != tcc->v->owner) return NULL;
02981
02982
02983 Train *coll = Train::From(v)->First();
02984
02985
02986 if (coll == tcc->v) return NULL;
02987
02988 int x_diff = v->x_pos - tcc->v->x_pos;
02989 int y_diff = v->y_pos - tcc->v->y_pos;
02990
02991
02992
02993
02994
02995 uint hash = (y_diff + 7) | (x_diff + 7);
02996 if (hash & ~15) return NULL;
02997
02998
02999 int min_diff = (Train::From(v)->gcache.cached_veh_length + 1) / 2 + (tcc->v->gcache.cached_veh_length + 1) / 2 - 1;
03000 if (x_diff * x_diff + y_diff * y_diff > min_diff * min_diff) return NULL;
03001
03002
03003 if (abs(v->z_pos - tcc->v->z_pos) > 5) return NULL;
03004
03005
03006 tcc->num += TrainCrashed(tcc->v);
03007 tcc->num += TrainCrashed(coll);
03008
03009 return NULL;
03010 }
03011
03019 static bool CheckTrainCollision(Train *v)
03020 {
03021
03022 if (v->track == TRACK_BIT_DEPOT) return false;
03023
03024 assert(v->track == TRACK_BIT_WORMHOLE || TileVirtXY(v->x_pos, v->y_pos) == v->tile);
03025
03026 TrainCollideChecker tcc;
03027 tcc.v = v;
03028 tcc.num = 0;
03029
03030
03031 if (v->track == TRACK_BIT_WORMHOLE) {
03032 FindVehicleOnPos(v->tile, &tcc, FindTrainCollideEnum);
03033 FindVehicleOnPos(GetOtherTunnelBridgeEnd(v->tile), &tcc, FindTrainCollideEnum);
03034 } else {
03035 FindVehicleOnPosXY(v->x_pos, v->y_pos, &tcc, FindTrainCollideEnum);
03036 }
03037
03038
03039 if (tcc.num == 0) return false;
03040
03041 SetDParam(0, tcc.num);
03042 AddVehicleNewsItem(STR_NEWS_TRAIN_CRASH, NT_ACCIDENT, v->index);
03043
03044 ModifyStationRatingAround(v->tile, v->owner, -160, 30);
03045 if (_settings_client.sound.disaster) SndPlayVehicleFx(SND_13_BIG_CRASH, v);
03046 return true;
03047 }
03048
03049 static Vehicle *CheckTrainAtSignal(Vehicle *v, void *data)
03050 {
03051 if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) return NULL;
03052
03053 Train *t = Train::From(v);
03054 DiagDirection exitdir = *(DiagDirection *)data;
03055
03056
03057 if (!t->IsFrontEngine() || !(t->track & TRACK_BIT_MASK)) return NULL;
03058
03059 if (t->cur_speed > 5 || TrainExitDir(t->direction, t->track) != exitdir) return NULL;
03060
03061 return t;
03062 }
03063
03071 bool TrainController(Train *v, Vehicle *nomove, bool reverse)
03072 {
03073 Train *first = v->First();
03074 Train *prev;
03075 bool direction_changed = false;
03076
03077
03078 for (prev = v->Previous(); v != nomove; prev = v, v = v->Next()) {
03079 DiagDirection enterdir = DIAGDIR_BEGIN;
03080 bool update_signals_crossing = false;
03081
03082 GetNewVehiclePosResult gp = GetNewVehiclePos(v);
03083 if (v->track != TRACK_BIT_WORMHOLE) {
03084
03085 if (gp.old_tile == gp.new_tile) {
03086
03087 if (v->track == TRACK_BIT_DEPOT) {
03088
03089 gp.x = v->x_pos;
03090 gp.y = v->y_pos;
03091 } else {
03092
03093
03094
03095 if (v->IsFrontEngine() && !TrainCheckIfLineEnds(v, reverse)) return false;
03096
03097 uint32 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
03098 if (HasBit(r, VETS_CANNOT_ENTER)) {
03099 goto invalid_rail;
03100 }
03101 if (HasBit(r, VETS_ENTERED_STATION)) {
03102
03103 TrainEnterStation(v, r >> VETS_STATION_ID_OFFSET);
03104 }
03105 }
03106 } else {
03107
03108
03109
03110 enterdir = DiagdirBetweenTiles(gp.old_tile, gp.new_tile);
03111 assert(IsValidDiagDirection(enterdir));
03112
03113
03114
03115 TrackStatus ts = GetTileTrackStatus(gp.new_tile, TRANSPORT_RAIL, 0, ReverseDiagDir(enterdir));
03116 TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(enterdir);
03117
03118 TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
03119 TrackBits red_signals = TrackdirBitsToTrackBits(TrackStatusToRedSignals(ts) & reachable_trackdirs);
03120
03121 TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
03122 if (_settings_game.pf.forbid_90_deg && prev == NULL) {
03123
03124
03125 bits &= ~TrackCrossesTracks(FindFirstTrack(v->track));
03126 }
03127
03128 if (bits == TRACK_BIT_NONE) goto invalid_rail;
03129
03130
03131
03132 if (!CheckCompatibleRail(v, gp.new_tile)) goto invalid_rail;
03133
03134 TrackBits chosen_track;
03135 if (prev == NULL) {
03136
03137
03138 chosen_track = TrackToTrackBits(ChooseTrainTrack(v, gp.new_tile, enterdir, bits, false, NULL, true));
03139 assert(chosen_track & (bits | GetReservedTrackbits(gp.new_tile)));
03140
03141 if (v->force_proceed != TFP_NONE && IsPlainRailTile(gp.new_tile) && HasSignals(gp.new_tile)) {
03142
03143
03144
03145
03146 Trackdir dir = FindFirstTrackdir(trackdirbits);
03147 if (GetSignalType(gp.new_tile, TrackdirToTrack(dir)) != SIGTYPE_PBS ||
03148 !HasSignalOnTrackdir(gp.new_tile, ReverseTrackdir(dir))) {
03149
03150
03151 v->force_proceed = (v->force_proceed == TFP_SIGNAL) ? TFP_STUCK : TFP_NONE;
03152 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
03153 }
03154 }
03155
03156
03157 if ((red_signals & chosen_track) && v->force_proceed == TFP_NONE) {
03158
03159 Trackdir i = FindFirstTrackdir(trackdirbits);
03160
03161
03162 if (HasBit(v->flags, VRF_TRAIN_STUCK)) return false;
03163
03164 if (!HasSignalOnTrackdir(gp.new_tile, ReverseTrackdir(i))) {
03165 v->cur_speed = 0;
03166 v->subspeed = 0;
03167 v->progress = 255 - 100;
03168 if (!_settings_game.pf.reverse_at_signals || ++v->wait_counter < _settings_game.pf.wait_oneway_signal * 20) return false;
03169 } else if (HasSignalOnTrackdir(gp.new_tile, i)) {
03170 v->cur_speed = 0;
03171 v->subspeed = 0;
03172 v->progress = 255 - 10;
03173 if (!_settings_game.pf.reverse_at_signals || ++v->wait_counter < _settings_game.pf.wait_twoway_signal * 73) {
03174 DiagDirection exitdir = TrackdirToExitdir(i);
03175 TileIndex o_tile = TileAddByDiagDir(gp.new_tile, exitdir);
03176
03177 exitdir = ReverseDiagDir(exitdir);
03178
03179
03180 if (!HasVehicleOnPos(o_tile, &exitdir, &CheckTrainAtSignal)) return false;
03181 }
03182 }
03183
03184
03185
03186
03187
03188 if (!_settings_game.pf.reverse_at_signals && !HasOnewaySignalBlockingTrackdir(gp.new_tile, i) &&
03189 UpdateSignalsOnSegment(v->tile, enterdir, v->owner) == SIGSEG_PBS) {
03190 v->wait_counter = 0;
03191 return false;
03192 }
03193 goto reverse_train_direction;
03194 } else {
03195 TryReserveRailTrack(gp.new_tile, TrackBitsToTrack(chosen_track), false);
03196 }
03197 } else {
03198
03199 if (prev->tile == gp.new_tile) {
03200
03201 if (prev->track == TRACK_BIT_WORMHOLE) {
03202
03203
03204 assert(IsTunnel(prev->tile));
03205 chosen_track = bits;
03206 } else {
03207 chosen_track = prev->track;
03208 }
03209 } else {
03210
03211
03212
03213
03214
03215
03216
03217 static const TrackBits _connecting_track[DIAGDIR_END][DIAGDIR_END] = {
03218 {TRACK_BIT_X, TRACK_BIT_LOWER, TRACK_BIT_NONE, TRACK_BIT_LEFT },
03219 {TRACK_BIT_UPPER, TRACK_BIT_Y, TRACK_BIT_LEFT, TRACK_BIT_NONE },
03220 {TRACK_BIT_NONE, TRACK_BIT_RIGHT, TRACK_BIT_X, TRACK_BIT_UPPER},
03221 {TRACK_BIT_RIGHT, TRACK_BIT_NONE, TRACK_BIT_LOWER, TRACK_BIT_Y }
03222 };
03223 DiagDirection exitdir = DiagdirBetweenTiles(gp.new_tile, prev->tile);
03224 assert(IsValidDiagDirection(exitdir));
03225 chosen_track = _connecting_track[enterdir][exitdir];
03226 }
03227 chosen_track &= bits;
03228 }
03229
03230
03231 assert(
03232 chosen_track == TRACK_BIT_X || chosen_track == TRACK_BIT_Y ||
03233 chosen_track == TRACK_BIT_UPPER || chosen_track == TRACK_BIT_LOWER ||
03234 chosen_track == TRACK_BIT_LEFT || chosen_track == TRACK_BIT_RIGHT);
03235
03236
03237 const byte *b = _initial_tile_subcoord[FIND_FIRST_BIT(chosen_track)][enterdir];
03238 gp.x = (gp.x & ~0xF) | b[0];
03239 gp.y = (gp.y & ~0xF) | b[1];
03240 Direction chosen_dir = (Direction)b[2];
03241
03242
03243 uint32 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
03244 if (HasBit(r, VETS_CANNOT_ENTER)) {
03245 goto invalid_rail;
03246 }
03247
03248 if (!HasBit(r, VETS_ENTERED_WORMHOLE)) {
03249 Track track = FindFirstTrack(chosen_track);
03250 Trackdir tdir = TrackDirectionToTrackdir(track, chosen_dir);
03251 if (v->IsFrontEngine() && HasPbsSignalOnTrackdir(gp.new_tile, tdir)) {
03252 SetSignalStateByTrackdir(gp.new_tile, tdir, SIGNAL_STATE_RED);
03253 MarkTileDirtyByTile(gp.new_tile);
03254 }
03255
03256
03257 if (v->Next() == NULL) ClearPathReservation(v, v->tile, v->GetVehicleTrackdir());
03258
03259 v->tile = gp.new_tile;
03260
03261 if (GetTileRailType(gp.new_tile) != GetTileRailType(gp.old_tile)) {
03262 v->First()->ConsistChanged(true);
03263 }
03264
03265 v->track = chosen_track;
03266 assert(v->track);
03267 }
03268
03269
03270
03271 update_signals_crossing = true;
03272
03273 if (chosen_dir != v->direction) {
03274 if (prev == NULL && _settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) {
03275 const AccelerationSlowdownParams *asp = &_accel_slowdown[GetRailTypeInfo(v->railtype)->acceleration_type];
03276 DirDiff diff = DirDifference(v->direction, chosen_dir);
03277 v->cur_speed -= (diff == DIRDIFF_45RIGHT || diff == DIRDIFF_45LEFT ? asp->small_turn : asp->large_turn) * v->cur_speed >> 8;
03278 }
03279 direction_changed = true;
03280 v->direction = chosen_dir;
03281 }
03282
03283 if (v->IsFrontEngine()) {
03284 v->wait_counter = 0;
03285
03286
03287 TileIndex crossing = TrainApproachingCrossingTile(v);
03288 if (crossing != INVALID_TILE && HasCrossingReservation(crossing) && _settings_client.sound.new_year) SndPlayTileFx(SND_0E_LEVEL_CROSSING, crossing);
03289
03290
03291 CheckNextTrainTile(v);
03292 }
03293
03294 if (HasBit(r, VETS_ENTERED_STATION)) {
03295
03296 TrainEnterStation(v, r >> VETS_STATION_ID_OFFSET);
03297 }
03298 }
03299 } else {
03300 if (IsTileType(gp.new_tile, MP_TUNNELBRIDGE) && HasBit(VehicleEnterTile(v, gp.new_tile, gp.x, gp.y), VETS_ENTERED_WORMHOLE)) {
03301
03302 if (v->IsFrontEngine()) {
03303 TryReserveRailTrack(gp.new_tile, DiagDirToDiagTrack(GetTunnelBridgeDirection(gp.new_tile)));
03304 CheckNextTrainTile(v);
03305 }
03306
03307
03308 if (gp.old_tile == gp.new_tile) {
03309 gp.old_tile = GetOtherTunnelBridgeEnd(gp.old_tile);
03310 }
03311 } else {
03312 v->x_pos = gp.x;
03313 v->y_pos = gp.y;
03314 VehicleUpdatePosition(v);
03315 if ((v->vehstatus & VS_HIDDEN) == 0) VehicleUpdateViewport(v, true);
03316 continue;
03317 }
03318 }
03319
03320
03321 v->UpdateDeltaXY(v->direction);
03322
03323 v->x_pos = gp.x;
03324 v->y_pos = gp.y;
03325 VehicleUpdatePosition(v);
03326
03327
03328 int old_z = v->UpdateInclination(gp.new_tile != gp.old_tile, false);
03329
03330 if (prev == NULL) {
03331
03332 AffectSpeedByZChange(v, old_z);
03333 }
03334
03335 if (update_signals_crossing) {
03336 if (v->IsFrontEngine()) {
03337 if (TrainMovedChangeSignals(gp.new_tile, enterdir)) {
03338
03339
03340
03341
03342
03343
03344
03345
03346 if ((!HasReservedTracks(gp.new_tile, v->track) &&
03347 !TryReserveRailTrack(gp.new_tile, FindFirstTrack(v->track))) ||
03348 !TryPathReserve(v)) {
03349 MarkTrainAsStuck(v);
03350 }
03351 }
03352 }
03353
03354
03355
03356 if (v->Next() == NULL) {
03357 TrainMovedChangeSignals(gp.old_tile, ReverseDiagDir(enterdir));
03358 if (IsLevelCrossingTile(gp.old_tile)) UpdateLevelCrossing(gp.old_tile);
03359 }
03360 }
03361
03362
03363 if (v->IsFrontEngine() && v->tick_counter % _settings_game.pf.path_backoff_interval == 0) CheckNextTrainTile(v);
03364 }
03365
03366 if (direction_changed) first->tcache.cached_max_curve_speed = first->GetCurveSpeedLimit();
03367
03368 return true;
03369
03370 invalid_rail:
03371
03372 if (prev != NULL) error("Disconnecting train");
03373
03374 reverse_train_direction:
03375 if (reverse) {
03376 v->wait_counter = 0;
03377 v->cur_speed = 0;
03378 v->subspeed = 0;
03379 ReverseTrainDirection(v);
03380 }
03381
03382 return false;
03383 }
03384
03391 static Vehicle *CollectTrackbitsFromCrashedVehiclesEnum(Vehicle *v, void *data)
03392 {
03393 TrackBits *trackbits = (TrackBits *)data;
03394
03395 if (v->type == VEH_TRAIN && (v->vehstatus & VS_CRASHED) != 0) {
03396 TrackBits train_tbits = Train::From(v)->track;
03397 if (train_tbits == TRACK_BIT_WORMHOLE) {
03398
03399 *trackbits |= DiagDirToDiagTrackBits(GetTunnelBridgeDirection(v->tile));
03400 } else if (train_tbits != TRACK_BIT_DEPOT) {
03401 *trackbits |= train_tbits;
03402 }
03403 }
03404
03405 return NULL;
03406 }
03407
03415 static void DeleteLastWagon(Train *v)
03416 {
03417 Train *first = v->First();
03418
03419
03420
03421
03422 Train *u = v;
03423 for (; v->Next() != NULL; v = v->Next()) u = v;
03424 u->SetNext(NULL);
03425
03426 if (first != v) {
03427
03428 first->ConsistChanged(false);
03429
03430
03431 if (first->track == TRACK_BIT_DEPOT) {
03432 SetWindowDirty(WC_VEHICLE_DEPOT, first->tile);
03433 }
03434 }
03435
03436
03437 TrackBits trackbits = v->track;
03438 TileIndex tile = v->tile;
03439 Owner owner = v->owner;
03440
03441 delete v;
03442 v = NULL;
03443
03444 if (trackbits == TRACK_BIT_WORMHOLE) {
03445
03446 trackbits = DiagDirToDiagTrackBits(GetTunnelBridgeDirection(tile));
03447 }
03448
03449 Track track = TrackBitsToTrack(trackbits);
03450 if (HasReservedTracks(tile, trackbits)) {
03451 UnreserveRailTrack(tile, track);
03452
03453
03454 TrackBits remaining_trackbits = TRACK_BIT_NONE;
03455 FindVehicleOnPos(tile, &remaining_trackbits, CollectTrackbitsFromCrashedVehiclesEnum);
03456
03457
03458 assert(TRACK_BEGIN == TRACK_X && TRACK_Y == TRACK_BEGIN + 1);
03459 Track t;
03460 FOR_EACH_SET_TRACK(t, remaining_trackbits) TryReserveRailTrack(tile, t);
03461 }
03462
03463
03464 if (IsLevelCrossingTile(tile)) UpdateLevelCrossing(tile);
03465
03466
03467 if (IsTileType(tile, MP_TUNNELBRIDGE) || IsRailDepotTile(tile)) {
03468 UpdateSignalsOnSegment(tile, INVALID_DIAGDIR, owner);
03469 } else {
03470 SetSignalsOnBothDir(tile, track, owner);
03471 }
03472 }
03473
03478 static void ChangeTrainDirRandomly(Train *v)
03479 {
03480 static const DirDiff delta[] = {
03481 DIRDIFF_45LEFT, DIRDIFF_SAME, DIRDIFF_SAME, DIRDIFF_45RIGHT
03482 };
03483
03484 do {
03485
03486 if (!(v->vehstatus & VS_HIDDEN)) {
03487 v->direction = ChangeDir(v->direction, delta[GB(Random(), 0, 2)]);
03488 v->UpdateDeltaXY(v->direction);
03489 v->cur_image = v->GetImage(v->direction, EIT_ON_MAP);
03490
03491
03492
03493 if (v->track != TRACK_BIT_WORMHOLE) {
03494 VehicleUpdatePosition(v);
03495 v->UpdateInclination(false, false);
03496 }
03497 }
03498 } while ((v = v->Next()) != NULL);
03499 }
03500
03506 static bool HandleCrashedTrain(Train *v)
03507 {
03508 int state = ++v->crash_anim_pos;
03509
03510 if (state == 4 && !(v->vehstatus & VS_HIDDEN)) {
03511 CreateEffectVehicleRel(v, 4, 4, 8, EV_EXPLOSION_LARGE);
03512 }
03513
03514 uint32 r;
03515 if (state <= 200 && Chance16R(1, 7, r)) {
03516 int index = (r * 10 >> 16);
03517
03518 Vehicle *u = v;
03519 do {
03520 if (--index < 0) {
03521 r = Random();
03522
03523 CreateEffectVehicleRel(u,
03524 GB(r, 8, 3) + 2,
03525 GB(r, 16, 3) + 2,
03526 GB(r, 0, 3) + 5,
03527 EV_EXPLOSION_SMALL);
03528 break;
03529 }
03530 } while ((u = u->Next()) != NULL);
03531 }
03532
03533 if (state <= 240 && !(v->tick_counter & 3)) ChangeTrainDirRandomly(v);
03534
03535 if (state >= 4440 && !(v->tick_counter & 0x1F)) {
03536 bool ret = v->Next() != NULL;
03537 DeleteLastWagon(v);
03538 return ret;
03539 }
03540
03541 return true;
03542 }
03543
03545 static const uint16 _breakdown_speeds[16] = {
03546 225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, 15
03547 };
03548
03549
03558 static bool TrainApproachingLineEnd(Train *v, bool signal, bool reverse)
03559 {
03560
03561 uint x = v->x_pos & 0xF;
03562 uint y = v->y_pos & 0xF;
03563
03564
03565
03566 switch (v->direction) {
03567 case DIR_N : x = ~x + ~y + 25; break;
03568 case DIR_NW: x = y;
03569 case DIR_NE: x = ~x + 16; break;
03570 case DIR_E : x = ~x + y + 9; break;
03571 case DIR_SE: x = y; break;
03572 case DIR_S : x = x + y - 7; break;
03573 case DIR_W : x = ~y + x + 9; break;
03574 default: break;
03575 }
03576
03577
03578
03579
03580
03581
03582 if (!signal && x + (v->gcache.cached_veh_length + 1) / 2 * (IsDiagonalDirection(v->direction) ? 1 : 2) >= TILE_SIZE) {
03583
03584 v->cur_speed = 0;
03585 if (reverse) ReverseTrainDirection(v);
03586 return false;
03587 }
03588
03589
03590 v->vehstatus |= VS_TRAIN_SLOWING;
03591 uint16 break_speed = _breakdown_speeds[x & 0xF];
03592 if (break_speed < v->cur_speed) v->cur_speed = break_speed;
03593
03594 return true;
03595 }
03596
03597
03603 static bool TrainCanLeaveTile(const Train *v)
03604 {
03605
03606 if (v->track == TRACK_BIT_WORMHOLE || v->track == TRACK_BIT_DEPOT) return false;
03607
03608 TileIndex tile = v->tile;
03609
03610
03611 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
03612 DiagDirection dir = GetTunnelBridgeDirection(tile);
03613 if (DiagDirToDir(dir) == v->direction) return false;
03614 }
03615
03616
03617 if (IsRailDepotTile(tile)) {
03618 DiagDirection dir = ReverseDiagDir(GetRailDepotDirection(tile));
03619 if (DiagDirToDir(dir) == v->direction) return false;
03620 }
03621
03622 return true;
03623 }
03624
03625
03633 static TileIndex TrainApproachingCrossingTile(const Train *v)
03634 {
03635 assert(v->IsFrontEngine());
03636 assert(!(v->vehstatus & VS_CRASHED));
03637
03638 if (!TrainCanLeaveTile(v)) return INVALID_TILE;
03639
03640 DiagDirection dir = TrainExitDir(v->direction, v->track);
03641 TileIndex tile = v->tile + TileOffsByDiagDir(dir);
03642
03643
03644 if (!IsLevelCrossingTile(tile) || DiagDirToAxis(dir) == GetCrossingRoadAxis(tile) ||
03645 !CheckCompatibleRail(v, tile)) {
03646 return INVALID_TILE;
03647 }
03648
03649 return tile;
03650 }
03651
03652
03660 static bool TrainCheckIfLineEnds(Train *v, bool reverse)
03661 {
03662
03663
03664 int t = v->breakdown_ctr;
03665 if (t > 1) {
03666 v->vehstatus |= VS_TRAIN_SLOWING;
03667
03668 uint16 break_speed = _breakdown_speeds[GB(~t, 4, 4)];
03669 if (break_speed < v->cur_speed) v->cur_speed = break_speed;
03670 } else {
03671 v->vehstatus &= ~VS_TRAIN_SLOWING;
03672 }
03673
03674 if (!TrainCanLeaveTile(v)) return true;
03675
03676
03677 DiagDirection dir = TrainExitDir(v->direction, v->track);
03678
03679 TileIndex tile = v->tile + TileOffsByDiagDir(dir);
03680
03681
03682 TrackStatus ts = GetTileTrackStatus(tile, TRANSPORT_RAIL, 0, ReverseDiagDir(dir));
03683 TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(dir);
03684
03685 TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
03686 TrackdirBits red_signals = TrackStatusToRedSignals(ts) & reachable_trackdirs;
03687
03688
03689
03690
03691 TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
03692 if (_settings_game.pf.forbid_90_deg) {
03693 bits &= ~TrackCrossesTracks(FindFirstTrack(v->track));
03694 }
03695
03696
03697 if (bits == TRACK_BIT_NONE || !CheckCompatibleRail(v, tile)) {
03698 return TrainApproachingLineEnd(v, false, reverse);
03699 }
03700
03701
03702 if ((trackdirbits & red_signals) != 0) return TrainApproachingLineEnd(v, true, reverse);
03703
03704
03705 if (IsLevelCrossingTile(tile)) MaybeBarCrossingWithSound(tile);
03706
03707 return true;
03708 }
03709
03710
03711 static bool TrainLocoHandler(Train *v, bool mode)
03712 {
03713
03714 if (v->vehstatus & VS_CRASHED) {
03715 return mode ? true : HandleCrashedTrain(v);
03716 }
03717
03718 if (v->force_proceed != TFP_NONE) {
03719 ClrBit(v->flags, VRF_TRAIN_STUCK);
03720 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
03721 }
03722
03723
03724 if (v->HandleBreakdown()) return true;
03725
03726 if (HasBit(v->flags, VRF_REVERSING) && v->cur_speed == 0) {
03727 ReverseTrainDirection(v);
03728 }
03729
03730
03731 if ((v->vehstatus & VS_STOPPED) && v->cur_speed == 0) return true;
03732
03733 bool valid_order = !v->current_order.IsType(OT_NOTHING) && v->current_order.GetType() != OT_CONDITIONAL;
03734 if (ProcessOrders(v) && CheckReverseTrain(v)) {
03735 v->wait_counter = 0;
03736 v->cur_speed = 0;
03737 v->subspeed = 0;
03738 ClrBit(v->flags, VRF_LEAVING_STATION);
03739 ReverseTrainDirection(v);
03740 return true;
03741 } else if (HasBit(v->flags, VRF_LEAVING_STATION)) {
03742
03743
03744
03745 DiagDirection dir = TrainExitDir(v->direction, v->track);
03746 if (IsRailDepotTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE)) dir = INVALID_DIAGDIR;
03747
03748 if (UpdateSignalsOnSegment(v->tile, dir, v->owner) == SIGSEG_PBS || _settings_game.pf.reserve_paths) {
03749 TryPathReserve(v, true, true);
03750 }
03751 ClrBit(v->flags, VRF_LEAVING_STATION);
03752 }
03753
03754 v->HandleLoading(mode);
03755
03756 if (v->current_order.IsType(OT_LOADING)) return true;
03757
03758 if (CheckTrainStayInDepot(v)) return true;
03759
03760 if (!mode) v->ShowVisualEffect();
03761
03762
03763 if (!valid_order && !v->current_order.IsType(OT_NOTHING)) {
03764 CheckNextTrainTile(v);
03765 }
03766
03767
03768 if (!mode && HasBit(v->flags, VRF_TRAIN_STUCK)) {
03769 ++v->wait_counter;
03770
03771
03772 bool turn_around = v->wait_counter % (_settings_game.pf.wait_for_pbs_path * DAY_TICKS) == 0 && _settings_game.pf.reverse_at_signals;
03773
03774 if (!turn_around && v->wait_counter % _settings_game.pf.path_backoff_interval != 0 && v->force_proceed == TFP_NONE) return true;
03775 if (!TryPathReserve(v)) {
03776
03777 if (turn_around) ReverseTrainDirection(v);
03778
03779 if (HasBit(v->flags, VRF_TRAIN_STUCK) && v->wait_counter > 2 * _settings_game.pf.wait_for_pbs_path * DAY_TICKS) {
03780
03781 if (_settings_client.gui.lost_vehicle_warn && v->owner == _local_company) {
03782 SetDParam(0, v->index);
03783 AddVehicleAdviceNewsItem(STR_NEWS_TRAIN_IS_STUCK, v->index);
03784 }
03785 v->wait_counter = 0;
03786 }
03787
03788 if (v->force_proceed == TFP_NONE) return true;
03789 ClrBit(v->flags, VRF_TRAIN_STUCK);
03790 v->wait_counter = 0;
03791 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
03792 }
03793 }
03794
03795 if (v->current_order.IsType(OT_LEAVESTATION)) {
03796 v->current_order.Free();
03797 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
03798 return true;
03799 }
03800
03801 int j = v->UpdateSpeed();
03802
03803
03804 if (v->cur_speed == 0 && (v->vehstatus & VS_STOPPED)) {
03805
03806 v->force_proceed = TFP_NONE;
03807 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
03808 }
03809
03810 int adv_spd = v->GetAdvanceDistance();
03811 if (j < adv_spd) {
03812
03813 if (v->cur_speed == 0) v->SetLastSpeed();
03814 } else {
03815 TrainCheckIfLineEnds(v);
03816
03817 for (;;) {
03818 j -= adv_spd;
03819 TrainController(v, NULL);
03820
03821 if (CheckTrainCollision(v)) break;
03822
03823 adv_spd = v->GetAdvanceDistance();
03824
03825
03826 if (j < adv_spd || v->cur_speed == 0) break;
03827
03828 OrderType order_type = v->current_order.GetType();
03829
03830 if ((order_type == OT_GOTO_WAYPOINT || order_type == OT_GOTO_STATION) &&
03831 (v->current_order.GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION) &&
03832 IsTileType(v->tile, MP_STATION) &&
03833 v->current_order.GetDestination() == GetStationIndex(v->tile)) {
03834 ProcessOrders(v);
03835 }
03836 }
03837 v->SetLastSpeed();
03838 }
03839
03840 for (Train *u = v; u != NULL; u = u->Next()) {
03841 if ((u->vehstatus & VS_HIDDEN) != 0) continue;
03842
03843 u->UpdateViewport(false, false);
03844 }
03845
03846 if (v->progress == 0) v->progress = j;
03847
03848 return true;
03849 }
03850
03855 Money Train::GetRunningCost() const
03856 {
03857 Money cost = 0;
03858 const Train *v = this;
03859
03860 do {
03861 const Engine *e = v->GetEngine();
03862 if (e->u.rail.running_cost_class == INVALID_PRICE) continue;
03863
03864 uint cost_factor = GetVehicleProperty(v, PROP_TRAIN_RUNNING_COST_FACTOR, e->u.rail.running_cost);
03865 if (cost_factor == 0) continue;
03866
03867
03868 if (v->IsMultiheaded()) cost_factor /= 2;
03869
03870 cost += GetPrice(e->u.rail.running_cost_class, cost_factor, e->GetGRF());
03871 } while ((v = v->GetNextVehicle()) != NULL);
03872
03873 return cost;
03874 }
03875
03880 bool Train::Tick()
03881 {
03882 this->tick_counter++;
03883
03884 if (this->IsFrontEngine()) {
03885 if (!(this->vehstatus & VS_STOPPED) || this->cur_speed > 0) this->running_ticks++;
03886
03887 this->current_order_time++;
03888
03889 if (!TrainLocoHandler(this, false)) return false;
03890
03891 return TrainLocoHandler(this, true);
03892 } else if (this->IsFreeWagon() && (this->vehstatus & VS_CRASHED)) {
03893
03894 if (++this->crash_anim_pos >= 4400) {
03895 delete this;
03896 return false;
03897 }
03898 }
03899
03900 return true;
03901 }
03902
03907 static void CheckIfTrainNeedsService(Train *v)
03908 {
03909 if (Company::Get(v->owner)->settings.vehicle.servint_trains == 0 || !v->NeedsAutomaticServicing()) return;
03910 if (v->IsChainInDepot()) {
03911 VehicleServiceInDepot(v);
03912 return;
03913 }
03914
03915 uint max_penalty;
03916 switch (_settings_game.pf.pathfinder_for_trains) {
03917 case VPF_NPF: max_penalty = _settings_game.pf.npf.maximum_go_to_depot_penalty; break;
03918 case VPF_YAPF: max_penalty = _settings_game.pf.yapf.maximum_go_to_depot_penalty; break;
03919 default: NOT_REACHED();
03920 }
03921
03922 FindDepotData tfdd = FindClosestTrainDepot(v, max_penalty);
03923
03924 if (tfdd.best_length == UINT_MAX || tfdd.best_length > max_penalty) {
03925 if (v->current_order.IsType(OT_GOTO_DEPOT)) {
03926
03927
03928
03929 v->current_order.MakeDummy();
03930 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
03931 }
03932 return;
03933 }
03934
03935 DepotID depot = GetDepotIndex(tfdd.tile);
03936
03937 if (v->current_order.IsType(OT_GOTO_DEPOT) &&
03938 v->current_order.GetDestination() != depot &&
03939 !Chance16(3, 16)) {
03940 return;
03941 }
03942
03943 SetBit(v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS);
03944 v->current_order.MakeGoToDepot(depot, ODTFB_SERVICE);
03945 v->dest_tile = tfdd.tile;
03946 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
03947 }
03948
03950 void Train::OnNewDay()
03951 {
03952 AgeVehicle(this);
03953
03954 if ((++this->day_counter & 7) == 0) DecreaseVehicleValue(this);
03955
03956 if (this->IsFrontEngine()) {
03957 CheckVehicleBreakdown(this);
03958
03959 CheckIfTrainNeedsService(this);
03960
03961 CheckOrders(this);
03962
03963
03964 if (this->current_order.IsType(OT_GOTO_STATION)) {
03965 TileIndex tile = Station::Get(this->current_order.GetDestination())->train_station.tile;
03966 if (tile != INVALID_TILE) this->dest_tile = tile;
03967 }
03968
03969 if (this->running_ticks != 0) {
03970
03971 CommandCost cost(EXPENSES_TRAIN_RUN, this->GetRunningCost() * this->running_ticks / (DAYS_IN_YEAR * DAY_TICKS));
03972
03973 this->profit_this_year -= cost.GetCost();
03974 this->running_ticks = 0;
03975
03976 SubtractMoneyFromCompanyFract(this->owner, cost);
03977
03978 SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
03979 SetWindowClassesDirty(WC_TRAINS_LIST);
03980 }
03981 }
03982 }
03983
03988 Trackdir Train::GetVehicleTrackdir() const
03989 {
03990 if (this->vehstatus & VS_CRASHED) return INVALID_TRACKDIR;
03991
03992 if (this->track == TRACK_BIT_DEPOT) {
03993
03994 return DiagDirToDiagTrackdir(GetRailDepotDirection(this->tile));
03995 }
03996
03997 if (this->track == TRACK_BIT_WORMHOLE) {
03998
03999 return DiagDirToDiagTrackdir(DirToDiagDir(this->direction));
04000 }
04001
04002 return TrackDirectionToTrackdir(FindFirstTrack(this->track), this->direction);
04003 }