OpenTTD Source 20261112-master-gbcbec5e63f
train_cmd.cpp
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
9
10#include "stdafx.h"
11#include "error.h"
13#include "command_func.h"
14#include "error_func.h"
17#include "news_func.h"
18#include "company_func.h"
19#include "newgrf_sound.h"
20#include "newgrf_text.h"
21#include "strings_func.h"
22#include "viewport_func.h"
23#include "vehicle_func.h"
24#include "vehicle_gui.h"
25#include "sound_func.h"
26#include "ai/ai.hpp"
27#include "game/game.hpp"
28#include "newgrf_station.h"
29#include "effectvehicle_func.h"
30#include "core/random_func.hpp"
31#include "company_base.h"
32#include "newgrf.h"
33#include "order_backup.h"
34#include "pbs.h"
35#include "zoom_func.h"
36#include "newgrf_debug.h"
37#include "framerate_type.h"
38#include "station_base.h"
39#include "station_func.h"
40#include "train.h"
41#include "train_cmd.h"
42#include "tunnelbridge_map.h"
43#include "misc_cmd.h"
44#include "script/api/script_event_types.hpp"
47
49
50#include "table/strings.h"
51#include "table/train_sprites.h"
52
53#include "safeguards.h"
54
55static Track ChooseTrainTrack(Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool force_res, bool *got_reservation, bool mark_stuck);
56static bool TrainCheckIfLineEnds(Train *v, bool reverse = true);
57bool TrainController(Train *v, Vehicle *nomove, bool reverse = true); // Also used in vehicle_sl.cpp.
59static void CheckIfTrainNeedsService(Train *v);
60static void CheckNextTrainTile(Train *v);
61
66
68template <>
70{
71 return image_index < lengthof(_engine_sprite_base);
72}
73
74
81{
82 if (!CargoSpec::Get(cargo)->is_freight) return 1;
83 return _settings_game.vehicle.freight_trains;
84}
85
88{
89 bool first = true;
90
91 for (const Train *v : Train::Iterate()) {
92 if (v->First() == v && !v->vehstatus.Test(VehState::Crashed)) {
93 for (const Train *u = v->GetMovingFront(), *w = v->GetMovingNext(); w != nullptr; u = w, w = w->GetMovingNext()) {
94 if (u->track != Track::Depot) {
95 if ((w->track != Track::Depot &&
96 std::max(abs(u->x_pos - w->x_pos), abs(u->y_pos - w->y_pos)) != u->CalcNextVehicleOffset()) ||
97 (w->track == Track::Depot && TicksToLeaveDepot(u) <= 0)) {
98 ShowErrorMessage(GetEncodedString(STR_BROKEN_VEHICLE_LENGTH, v->index, v->owner), {}, WarningLevel::Critical);
99
100 if (!_networking && first) {
101 first = false;
102 Command<Commands::Pause>::Post(PauseMode::Error, true);
103 }
104 /* Break so we warn only once for each train. */
105 break;
106 }
107 }
108 }
109 }
110 }
111}
112
120{
121 uint16_t max_speed = UINT16_MAX;
122
123 assert(this->IsFrontEngine() || this->IsFreeWagon());
124
125 const RailVehicleInfo *rvi_v = RailVehInfo(this->engine_type);
126 EngineID first_engine = this->IsFrontEngine() ? this->engine_type : EngineID::Invalid();
127 this->gcache.cached_total_length = 0;
128 this->compatible_railtypes = {};
129
130 bool train_can_tilt = true;
131 int16_t min_curve_speed_mod = INT16_MAX;
132
133 for (Train *u = this; u != nullptr; u = u->Next()) {
134 const RailVehicleInfo *rvi_u = RailVehInfo(u->engine_type);
135
136 /* Check the this->first cache. */
137 assert(u->First() == this);
138
139 /* update the 'first engine' */
140 u->gcache.first_engine = this == u ? EngineID::Invalid() : first_engine;
141 u->railtypes = rvi_u->railtypes;
142
143 if (u->IsEngine()) first_engine = u->engine_type;
144
145 /* Set user defined data to its default value */
146 u->tcache.user_def_data = rvi_u->user_def_data;
147 this->InvalidateNewGRFCache();
148 u->InvalidateNewGRFCache();
149 }
150
151 for (Train *u = this; u != nullptr; u = u->Next()) {
152 /* Update user defined data (must be done before other properties) */
153 u->tcache.user_def_data = GetVehicleProperty(u, PROP_TRAIN_USER_DATA, u->tcache.user_def_data);
154 this->InvalidateNewGRFCache();
155 u->InvalidateNewGRFCache();
156 }
157
158 for (Train *u = this; u != nullptr; u = u->Next()) {
159 const Engine *e_u = u->GetEngine();
160 const RailVehicleInfo *rvi_u = &e_u->VehInfo<RailVehicleInfo>();
161
162 if (!e_u->info.misc_flags.Test(EngineMiscFlag::RailTilts)) train_can_tilt = false;
163 min_curve_speed_mod = std::min(min_curve_speed_mod, u->GetCurveSpeedModifier());
164
165 /* Cache wagon override sprite group. nullptr is returned if there is none */
166 u->tcache.cached_override = GetWagonOverrideSpriteSet(u->engine_type, u->cargo_type, u->gcache.first_engine);
167
168 /* Reset colour map */
169 u->colourmap = PAL_NONE;
170
171 /* Update powered-wagon-status and visual effect */
172 u->UpdateVisualEffect(true);
173
174 if (rvi_v->pow_wag_power != 0 && rvi_u->railveh_type == RailVehicleType::Wagon &&
175 UsesWagonOverride(u) && !HasBit(u->vcache.cached_vis_effect, VE_DISABLE_WAGON_POWER)) {
176 /* wagon is powered */
177 u->flags.Set(VehicleRailFlag::PoweredWagon); // cache 'powered' status
178 } else {
179 u->flags.Reset(VehicleRailFlag::PoweredWagon);
180 }
181
182 if (!u->IsArticulatedPart()) {
183 /* Do not count powered wagons for the compatible railtypes, as wagons always
184 have railtype normal */
185 if (rvi_u->power > 0) {
186 this->compatible_railtypes.Set(GetAllPoweredRailTypes(u->railtypes));
187 }
188
189 /* Some electric engines can be allowed to run on normal rail. It happens to all
190 * existing electric engines when elrails are disabled and then re-enabled */
191 if (u->flags.Test(VehicleRailFlag::AllowedOnNormalRail)) {
192 u->railtypes.Set(RAILTYPE_RAIL);
193 u->compatible_railtypes.Set(RAILTYPE_RAIL);
194 }
195
196 /* max speed is the minimum of the speed limits of all vehicles in the consist */
197 if ((rvi_u->railveh_type != RailVehicleType::Wagon || _settings_game.vehicle.wagon_speed_limits) && !UsesWagonOverride(u)) {
198 uint16_t speed = GetVehicleProperty(u, PROP_TRAIN_SPEED, rvi_u->max_speed);
199 if (speed != 0) max_speed = std::min(speed, max_speed);
200 }
201 }
202
203 uint16_t new_cap = e_u->DetermineCapacity(u);
204 if (allowed_changes.Test(ConsistChangeFlag::Capacity)) {
205 /* Update vehicle capacity. */
206 if (u->cargo.TotalCount() > new_cap) u->cargo.Truncate(u->cargo.TotalCount() - new_cap);
207 u->refit_cap = std::min(new_cap, u->refit_cap);
208 u->cargo_cap = new_cap;
209 } else {
210 /* Verify capacity hasn't changed. */
211 if (new_cap != u->cargo_cap) ShowNewGrfVehicleError(u->engine_type, STR_NEWGRF_BROKEN, STR_NEWGRF_BROKEN_CAPACITY, GRFBug::VehCapacity, true);
212 }
213 u->vcache.cached_cargo_age_period = GetVehicleProperty(u, PROP_TRAIN_CARGO_AGE_PERIOD, e_u->info.cargo_age_period);
214
215 /* check the vehicle length (callback) */
216 uint16_t veh_len = CALLBACK_FAILED;
217 if (e_u->GetGRF() != nullptr && e_u->GetGRF()->grf_version >= 8) {
218 /* Use callback 36 */
219 veh_len = GetVehicleProperty(u, PROP_TRAIN_SHORTEN_FACTOR, CALLBACK_FAILED);
220
221 if (veh_len != CALLBACK_FAILED && veh_len >= VEHICLE_LENGTH) {
223 }
224 } else if (e_u->info.callback_mask.Test(VehicleCallbackMask::Length)) {
225 /* Use callback 11 */
226 veh_len = GetVehicleCallback(CBID_VEHICLE_LENGTH, 0, 0, u->engine_type, u);
227 }
228 if (veh_len == CALLBACK_FAILED) veh_len = rvi_u->shorten_factor;
229 veh_len = VEHICLE_LENGTH - Clamp(veh_len, 0, VEHICLE_LENGTH - 1);
230
231 if (allowed_changes.Test(ConsistChangeFlag::Length)) {
232 /* Update vehicle length. */
233 u->gcache.cached_veh_length = veh_len;
234 } else {
235 /* Verify length hasn't changed. */
236 if (veh_len != u->gcache.cached_veh_length) VehicleLengthChanged(u);
237 }
238
239 this->gcache.cached_total_length += u->gcache.cached_veh_length;
240 this->InvalidateNewGRFCache();
241 u->InvalidateNewGRFCache();
242 }
243
244 /* store consist weight/max speed in cache */
245 this->vcache.cached_max_speed = max_speed;
246 this->tcache.cached_tilt = train_can_tilt;
247 this->tcache.cached_curve_speed_mod = min_curve_speed_mod;
248 this->tcache.cached_max_curve_speed = this->GetCurveSpeedLimit();
249
250 /* recalculate cached weights and power too (we do this *after* the rest, so it is known which wagons are powered and need extra weight added) */
251 this->CargoChanged();
252
253 if (this->IsFrontEngine()) {
254 this->UpdateAcceleration();
255 SetWindowDirty(WindowClass::VehicleDetails, this->index);
256 InvalidateWindowData(WindowClass::VehicleRefit, this->index, VIWD_CONSIST_CHANGED);
257 InvalidateWindowData(WindowClass::VehicleOrders, this->index, VIWD_CONSIST_CHANGED);
259
260 /* If the consist is changed while in a depot, the vehicle view window must be invalidated to update the availability of refitting. */
261 InvalidateWindowData(WindowClass::VehicleView, this->index, VIWD_CONSIST_CHANGED);
262 }
263}
264
275int GetTrainStopLocation(StationID station_id, TileIndex tile, const Train *moving_front, int *station_ahead, int *station_length)
276{
277 const Train *consist = moving_front->First();
278 const Station *st = Station::Get(station_id);
279 *station_ahead = st->GetPlatformLength(tile, DirToDiagDir(moving_front->GetMovingDirection())) * TILE_SIZE;
280 *station_length = st->GetPlatformLength(tile) * TILE_SIZE;
281
282 /* Default to the middle of the station for stations stops that are not in
283 * the order list like intermediate stations when non-stop is disabled */
285 if (consist->gcache.cached_total_length >= *station_length) {
286 /* The train is longer than the station, make it stop at the far end of the platform */
288 } else if (consist->current_order.IsType(OT_GOTO_STATION) && consist->current_order.GetDestination() == station_id) {
289 osl = consist->current_order.GetStopLocation();
290 }
291
292 /* The stop location of the FRONT! of the train */
293 int stop;
294 switch (osl) {
295 default: NOT_REACHED();
296
298 stop = consist->gcache.cached_total_length;
299 break;
300
302 stop = *station_length - (*station_length - consist->gcache.cached_total_length) / 2;
303 break;
304
306 stop = *station_length;
307 break;
308 }
309
310 /* Subtract half the front vehicle length of the train so we get the real
311 * stop location of the train. */
312 uint8_t rounding = consist->IsDrivingBackwards() ? 2 : 1;
313 return stop - (consist->gcache.cached_veh_length + rounding) / 2;
314}
315
316
322{
323 assert(this->First() == this);
324
325 static const int absolute_max_speed = UINT16_MAX;
326 int max_speed = absolute_max_speed;
327
328 if (_settings_game.vehicle.train_acceleration_model == AccelerationModel::Original) return max_speed;
329
330 int curvecount[2] = {0, 0};
331
332 /* first find the curve speed limit */
333 int numcurve = 0;
334 int sum = 0;
335 int pos = 0;
336 int lastpos = -1;
337 for (const Train *u = this; u->Next() != nullptr; u = u->Next(), pos += u->gcache.cached_veh_length) {
338 Direction this_dir = u->direction;
339 Direction next_dir = u->Next()->direction;
340
341 DirDiff dirdiff = DirDifference(this_dir, next_dir);
342 if (dirdiff == DirDiff::Same) continue;
343
344 if (dirdiff == DirDiff::Left45) curvecount[0]++;
345 if (dirdiff == DirDiff::Right45) curvecount[1]++;
346 if (dirdiff == DirDiff::Left45 || dirdiff == DirDiff::Right45) {
347 if (lastpos != -1) {
348 numcurve++;
349 sum += pos - lastpos;
350 if (pos - lastpos <= static_cast<int>(VEHICLE_LENGTH) && max_speed > 88) {
351 max_speed = 88;
352 }
353 }
354 lastpos = pos;
355 }
356
357 /* if we have a 90 degree turn, fix the speed limit to 60 */
358 if (dirdiff == DirDiff::Left90 || dirdiff == DirDiff::Right90) {
359 max_speed = 61;
360 }
361 }
362
363 if (numcurve > 0 && max_speed > 88) {
364 if (curvecount[0] == 1 && curvecount[1] == 1) {
365 max_speed = absolute_max_speed;
366 } else {
367 sum = CeilDiv(sum, VEHICLE_LENGTH);
368 sum /= numcurve;
369 max_speed = 232 - (13 - Clamp(sum, 1, 12)) * (13 - Clamp(sum, 1, 12));
370 }
371 }
372
373 if (max_speed != absolute_max_speed) {
374 /* Apply the current railtype's curve speed advantage */
375 const RailTypeInfo *rti = GetRailTypeInfo(GetRailType(this->tile));
376 max_speed += (max_speed / 2) * rti->curve_speed;
377
378 if (this->tcache.cached_tilt) {
379 /* Apply max_speed bonus of 20% for a tilting train */
380 max_speed += max_speed / 5;
381 }
382
383 /* Apply max_speed modifier (cached value is fixed-point binary with 8 fractional bits)
384 * and clamp the result to an acceptable range. */
385 max_speed += (max_speed * this->tcache.cached_curve_speed_mod) / 256;
386 max_speed = Clamp(max_speed, 2, absolute_max_speed);
387 }
388
389 return static_cast<uint16_t>(max_speed);
390}
391
397{
398 const Train *moving_front = this->GetMovingFront();
399 int max_speed = _settings_game.vehicle.train_acceleration_model == AccelerationModel::Original ?
400 this->gcache.cached_max_track_speed :
401 this->tcache.cached_max_curve_speed;
402
403 if (_settings_game.vehicle.train_acceleration_model == AccelerationModel::Realistic && IsRailStationTile(moving_front->tile)) {
404 StationID sid = GetStationIndex(moving_front->tile);
405 if (this->current_order.ShouldStopAtStation(this, sid)) {
406 int station_ahead;
407 int station_length;
408 int stop_at = GetTrainStopLocation(sid, moving_front->tile, moving_front, &station_ahead, &station_length);
409
410 /* The distance to go is whatever is still ahead of the train minus the
411 * distance from the train's stop location to the end of the platform */
412 int distance_to_go = station_ahead / TILE_SIZE - (station_length - stop_at) / TILE_SIZE;
413
414 if (distance_to_go > 0) {
415 int st_max_speed = 120;
416
417 int delta_v = this->cur_speed / (distance_to_go + 1);
418 if (max_speed > (this->cur_speed - delta_v)) {
419 st_max_speed = this->cur_speed - (delta_v / 10);
420 }
421
422 st_max_speed = std::max(st_max_speed, 25 * distance_to_go);
423 max_speed = std::min(max_speed, st_max_speed);
424 }
425 }
426 }
427
428 for (const Train *u = this; u != nullptr; u = u->Next()) {
429 if (_settings_game.vehicle.train_acceleration_model == AccelerationModel::Realistic && u->track == Track::Depot) {
430 constexpr int DEPOT_SPEED_LIMIT = 61;
431 max_speed = std::min(max_speed, DEPOT_SPEED_LIMIT);
432 break;
433 }
434
435 /* Vehicle is on the middle part of a bridge. */
436 if (u->track == Track::Wormhole && !u->vehstatus.Test(VehState::Hidden)) {
437 max_speed = std::min<int>(max_speed, GetBridgeSpec(GetBridgeType(u->tile))->speed);
438 }
439 }
440
441 max_speed = std::min<int>(max_speed, this->current_order.GetMaxSpeed());
442
443 /* If the train is going backwards, without a leading cab, restrict its speed. */
444 if (!moving_front->CanLeadTrain()) {
445 constexpr int BACKWARDS_NO_CAB_SPEED_LIMIT = 32;
446 max_speed = std::min<int>(max_speed, BACKWARDS_NO_CAB_SPEED_LIMIT);
447 }
448
449 return std::min<int>(max_speed, this->gcache.cached_max_track_speed);
450}
451
454{
455 assert(this->IsFrontEngine() || this->IsFreeWagon());
456
457 uint power = this->gcache.cached_power;
458 uint weight = this->gcache.cached_weight;
459 assert(weight != 0);
460 this->acceleration = Clamp(power / weight * 4, 1, 255);
461}
462
468{
469 if (this->gcache.cached_veh_length != 8 && this->flags.Test(VehicleRailFlag::Flipped) && !EngInfo(this->engine_type)->misc_flags.Test(EngineMiscFlag::RailFlips)) {
470 int reference_width = TRAININFO_DEFAULT_VEHICLE_WIDTH;
471
472 const Engine *e = this->GetEngine();
473 if (e->GetGRF() != nullptr && IsCustomVehicleSpriteNum(e->VehInfo<RailVehicleInfo>().image_index)) {
474 reference_width = e->GetGRF()->traininfo_vehicle_width;
475 }
476
477 return ScaleSpriteTrad((this->gcache.cached_veh_length - (int)VEHICLE_LENGTH) * reference_width / (int)VEHICLE_LENGTH);
478 }
479 return 0;
480}
481
488{
489 int reference_width = TRAININFO_DEFAULT_VEHICLE_WIDTH;
490 int vehicle_pitch = 0;
491
492 const Engine *e = this->GetEngine();
493 if (e->GetGRF() != nullptr && IsCustomVehicleSpriteNum(e->VehInfo<RailVehicleInfo>().image_index)) {
494 reference_width = e->GetGRF()->traininfo_vehicle_width;
495 vehicle_pitch = e->GetGRF()->traininfo_vehicle_pitch;
496 }
497
498 if (offset != nullptr) {
499 if (this->flags.Test(VehicleRailFlag::Flipped) && !EngInfo(this->engine_type)->misc_flags.Test(EngineMiscFlag::RailFlips)) {
500 offset->x = ScaleSpriteTrad(((int)this->gcache.cached_veh_length - (int)VEHICLE_LENGTH / 2) * reference_width / (int)VEHICLE_LENGTH);
501 } else {
502 offset->x = ScaleSpriteTrad(reference_width) / 2;
503 }
504 offset->y = ScaleSpriteTrad(vehicle_pitch);
505 }
506 return ScaleSpriteTrad(this->gcache.cached_veh_length * reference_width / VEHICLE_LENGTH);
507}
508
509static SpriteID GetDefaultTrainSprite(uint8_t spritenum, Direction direction)
510{
511 assert(IsValidImageIndex<VehicleType::Train>(spritenum));
512 return ((to_underlying(direction) + _engine_sprite_add[spritenum]) & _engine_sprite_and[spritenum]) + _engine_sprite_base[spritenum];
513}
514
522{
523 uint8_t spritenum = this->spritenum;
524
526
527 if (IsCustomVehicleSpriteNum(spritenum)) {
529 GetCustomVehicleSprite(this, direction, image_type, result);
530 if (result->IsValid()) return;
531
533 }
534
536 SpriteID sprite = GetDefaultTrainSprite(spritenum, direction);
537
538 if (this->cargo.StoredCount() >= this->cargo_cap / 2U) sprite += _wagon_full_adder[spritenum];
539
540 result->Set(sprite);
541}
542
543static void GetRailIcon(EngineID engine, bool rear_head, int &y, EngineImageType image_type, VehicleSpriteSeq *result)
544{
545 const Engine *e = Engine::Get(engine);
546 Direction dir = rear_head ? Direction::E : Direction::W;
547 uint8_t spritenum = e->VehInfo<RailVehicleInfo>().image_index;
548
549 if (IsCustomVehicleSpriteNum(spritenum)) {
550 GetCustomVehicleIcon(engine, dir, image_type, result);
551 if (result->IsValid()) {
552 if (e->GetGRF() != nullptr) {
554 }
555 return;
556 }
557
558 spritenum = Engine::Get(engine)->original_image_index;
559 }
560
561 if (rear_head) spritenum++;
562
563 result->Set(GetDefaultTrainSprite(spritenum, Direction::W));
564}
565
566void DrawTrainEngine(int left, int right, int preferred_x, int y, EngineID engine, PaletteID pal, EngineImageType image_type)
567{
568 const GRFFile *grf = Engine::Get(engine)->GetGRF();
569 int vehicle_width = ScaleSpriteTrad(grf == nullptr ? TRAININFO_DEFAULT_VEHICLE_WIDTH : grf->traininfo_vehicle_width);
570
571 if (RailVehInfo(engine)->railveh_type == RailVehicleType::Multihead) {
572 int yf = y;
573 int yr = y;
574
575 VehicleSpriteSeq seqf, seqr;
576 GetRailIcon(engine, false, yf, image_type, &seqf);
577 GetRailIcon(engine, true, yr, image_type, &seqr);
578
579 Rect rectf, rectr;
580 seqf.GetBounds(&rectf);
581 seqr.GetBounds(&rectr);
582
583 preferred_x = Clamp(preferred_x,
584 left - UnScaleGUI(rectf.left) + vehicle_width / 2,
585 right - UnScaleGUI(rectr.right) - (vehicle_width - vehicle_width / 2));
586
587 seqf.Draw(preferred_x - vehicle_width / 2, yf, pal, pal == PALETTE_CRASH);
588 seqr.Draw(preferred_x + (vehicle_width - vehicle_width / 2), yr, pal, pal == PALETTE_CRASH);
589 } else {
591 GetRailIcon(engine, false, y, image_type, &seq);
592
593 Rect rect;
594 seq.GetBounds(&rect);
595 preferred_x = Clamp(preferred_x,
596 left - UnScaleGUI(rect.left),
597 right - UnScaleGUI(rect.right));
598
599 seq.Draw(preferred_x, y, pal, pal == PALETTE_CRASH);
600 }
601}
602
612void GetTrainSpriteSize(EngineID engine, uint &width, uint &height, int &xoffs, int &yoffs, EngineImageType image_type)
613{
614 int y = 0;
615
617 GetRailIcon(engine, false, y, image_type, &seq);
618
619 Rect rect;
620 seq.GetBounds(&rect);
621
622 width = UnScaleGUI(rect.Width());
623 height = UnScaleGUI(rect.Height());
624 xoffs = UnScaleGUI(rect.left);
625 yoffs = UnScaleGUI(rect.top);
626
627 if (RailVehInfo(engine)->railveh_type == RailVehicleType::Multihead) {
628 const GRFFile *grf = Engine::Get(engine)->GetGRF();
629 int vehicle_width = ScaleSpriteTrad(grf == nullptr ? TRAININFO_DEFAULT_VEHICLE_WIDTH : grf->traininfo_vehicle_width);
630
631 GetRailIcon(engine, true, y, image_type, &seq);
632 seq.GetBounds(&rect);
633
634 /* Calculate values relative to an imaginary center between the two sprites. */
635 width = vehicle_width + UnScaleGUI(rect.right) - xoffs;
636 height = std::max<uint>(height, UnScaleGUI(rect.Height()));
637 xoffs = xoffs - vehicle_width / 2;
638 yoffs = std::min(yoffs, UnScaleGUI(rect.top));
639 }
640}
641
647static std::vector<VehicleID> GetFreeWagonsInDepot(TileIndex tile)
648{
649 std::vector<VehicleID> free_wagons;
650
651 for (Vehicle *v : VehiclesOnTile(tile)) {
652 if (v->type != VehicleType::Train) continue;
653 if (v->vehstatus.Test(VehState::Crashed)) continue;
654 if (!Train::From(v)->IsFreeWagon()) continue;
655
656 free_wagons.push_back(v->index);
657 }
658
659 /* Sort by vehicle index for consistency across clients. */
660 std::ranges::sort(free_wagons);
661 return free_wagons;
662}
663
673{
674 const RailVehicleInfo *rvi = &e->VehInfo<RailVehicleInfo>();
675
676 /* Check that the wagon can drive on the track in question */
677 if (!IsCompatibleRail(rvi->railtypes, GetRailType(tile))) return CMD_ERROR;
678
679 if (flags.Test(DoCommandFlag::Execute)) {
680 Train *v = Train::Create();
681 *ret = v;
682 v->spritenum = rvi->image_index;
683
684 v->engine_type = e->index;
685 v->gcache.first_engine = EngineID::Invalid(); // needs to be set before first callback
686
688
689 v->direction = DiagDirToDir(dir);
690 v->tile = tile;
691
692 int x = TileX(tile) * TILE_SIZE | _vehicle_initial_x_fract[dir];
693 int y = TileY(tile) * TILE_SIZE | _vehicle_initial_y_fract[dir];
694
695 v->x_pos = x;
696 v->y_pos = y;
697 v->z_pos = GetSlopePixelZ(x, y, true);
699 v->track = Track::Depot;
701
702 v->SetWagon();
703
704 v->SetFreeWagon();
705 InvalidateWindowData(WindowClass::VehicleDepot, v->tile);
706
708 assert(IsValidCargoType(v->cargo_type));
709 v->cargo_cap = rvi->capacity;
710 v->refit_cap = 0;
711
712 v->railtypes = rvi->railtypes;
714
719 v->random_bits = Random();
720
722
724 if (prob.has_value()) v->flags.Set(VehicleRailFlag::Flipped, prob.value());
726
727 v->UpdatePosition();
730
732
733 /* Try to connect the vehicle to one of free chains of wagons. */
734 for (VehicleID vehicle : GetFreeWagonsInDepot(tile)) {
735 if (vehicle == v->index) continue;
736
737 const Train *w = Train::Get(vehicle);
738 if (w->engine_type != v->engine_type) continue;
739 if (w->First() == v) continue;
740
741 if (Command<Commands::MoveRailVehicle>::Do(DoCommandFlag::Execute, v->index, w->Last()->index, true).Succeeded()) {
742 break;
743 }
744 }
745 }
746
747 return CommandCost();
748}
749
755{
756 assert(u->IsEngine());
757 for (VehicleID vehicle : GetFreeWagonsInDepot(u->tile)) {
758 if (Command<Commands::MoveRailVehicle>::Do(DoCommandFlag::Execute, vehicle, u->index, true).Failed()) {
759 break;
760 }
761 }
762}
763
764static void AddRearEngineToMultiheadedTrain(Train *v)
765{
766 Train *u = Train::Create();
767 v->value >>= 1;
768 u->value = v->value;
769 u->direction = v->direction;
770 u->owner = v->owner;
771 u->tile = v->tile;
772 u->x_pos = v->x_pos;
773 u->y_pos = v->y_pos;
774 u->z_pos = v->z_pos;
775 u->track = Track::Depot;
776 u->vehstatus = v->vehstatus;
778 u->spritenum = v->spritenum + 1;
779 u->cargo_type = v->cargo_type;
781 u->cargo_cap = v->cargo_cap;
782 u->refit_cap = v->refit_cap;
783 u->railtypes = v->railtypes;
784 u->flags.Set(VehicleRailFlag::AllowedOnNormalRail, _settings_game.vehicle.disable_elrails && RailVehInfo(v->engine_type)->intended_railtypes.Test(RAILTYPE_ELECTRIC));
785 u->engine_type = v->engine_type;
788 u->build_year = v->build_year;
790 u->random_bits = Random();
791 v->SetMultiheaded();
792 u->SetMultiheaded();
793 v->SetNext(u);
795 if (prob.has_value()) u->flags.Set(VehicleRailFlag::Flipped, prob.value());
796 u->UpdatePosition();
797
798 /* Now we need to link the front and rear engines together */
801}
802
812{
813 const RailVehicleInfo *rvi = &e->VehInfo<RailVehicleInfo>();
814
815 if (rvi->railveh_type == RailVehicleType::Wagon) return CmdBuildRailWagon(flags, tile, e, ret);
816
817 /* Check if depot and new engine uses the same kind of tracks *
818 * We need to see if the engine got power on the tile to avoid electric engines in non-electric depots */
819 if (!HasPowerOnRail(rvi->railtypes, GetRailType(tile))) return CMD_ERROR;
820
821 if (flags.Test(DoCommandFlag::Execute)) {
823 int x = TileX(tile) * TILE_SIZE + _vehicle_initial_x_fract[dir];
824 int y = TileY(tile) * TILE_SIZE + _vehicle_initial_y_fract[dir];
825
826 Train *v = Train::Create();
827 *ret = v;
828 v->direction = DiagDirToDir(dir);
829 v->tile = tile;
831 v->x_pos = x;
832 v->y_pos = y;
833 v->z_pos = GetSlopePixelZ(x, y, true);
834 v->track = Track::Depot;
836 v->spritenum = rvi->image_index;
838 assert(IsValidCargoType(v->cargo_type));
839 v->cargo_cap = rvi->capacity;
840 v->refit_cap = 0;
841 v->last_station_visited = StationID::Invalid();
842 v->last_loading_station = StationID::Invalid();
843
844 v->engine_type = e->index;
845 v->gcache.first_engine = EngineID::Invalid(); // needs to be set before first callback
846
847 v->reliability = e->reliability;
850
851 v->railtypes = rvi->railtypes;
853
854 v->SetServiceInterval(Company::Get(_current_company)->settings.vehicle.servint_trains);
859 v->random_bits = Random();
860
862 v->SetServiceIntervalIsPercent(Company::Get(_current_company)->settings.vehicle.servint_ispercent);
863
865
866 v->SetFrontEngine();
867 v->SetEngine();
868
870 if (prob.has_value()) v->flags.Set(VehicleRailFlag::Flipped, prob.value());
871 v->UpdatePosition();
872
874 AddRearEngineToMultiheadedTrain(v);
875 } else {
877 }
878
881
883 }
884
885 return CommandCost();
886}
887
888static Train *FindGoodVehiclePos(const Train *src)
889{
890 EngineID eng = src->engine_type;
891
892 for (VehicleID vehicle : GetFreeWagonsInDepot(src->tile)) {
893 Train *dst = Train::Get(vehicle);
894
895 /* check so all vehicles in the line have the same engine. */
896 Train *t = dst;
897 while (t->engine_type == eng) {
898 t = t->Next();
899 if (t == nullptr) return dst;
900 }
901 }
902
903 return nullptr;
904}
905
907typedef std::vector<Train *> TrainList;
908
914static void MakeTrainBackup(TrainList &list, Train *t)
915{
916 for (; t != nullptr; t = t->Next()) list.push_back(t);
917}
918
924{
925 /* No train, nothing to do. */
926 if (list.empty()) return;
927
928 Train *prev = nullptr;
929 /* Iterate over the list and rebuild it. */
930 for (Train *t : list) {
931 if (prev != nullptr) {
932 prev->SetNext(t);
933 } else if (t->Previous() != nullptr) {
934 /* Make sure the head of the train is always the first in the chain. */
935 t->Previous()->SetNext(nullptr);
936 }
937 prev = t;
938 }
939}
940
946static void RemoveFromConsist(Train *part, bool chain = false)
947{
948 Train *tail;
949
950 if (chain) {
951 /* We're moving several vehicles, find the last one in the chain. */
952 tail = part;
953 while (tail->Next() != nullptr) tail = tail->Next();
954 } else {
955 /* We're just moving one vehicle, but make sure we get all the articulated parts. */
956 tail = part->GetLastEnginePart();
957 }
958
959 /* Unlink at the front, but make it point to the next
960 * vehicle after the to be remove part. */
961 if (part->Previous() != nullptr) part->Previous()->SetNext(tail->Next());
962
963 /* Unlink at the back */
964 tail->SetNext(nullptr);
965}
966
972static void InsertInConsist(Train *dst, Train *chain)
973{
974 /* We do not want to add something in the middle of an articulated part. */
975 assert(dst != nullptr && (dst->Next() == nullptr || !dst->Next()->IsArticulatedPart()));
976
977 chain->Last()->SetNext(dst->Next());
978 dst->SetNext(chain);
979}
980
987{
988 for (; t != nullptr; t = t->GetNextVehicle()) {
989 if (!t->IsMultiheaded() || !t->IsEngine()) continue;
990
991 /* Make sure that there are no free cars before next engine */
992 Train *u;
993 for (u = t; u->Next() != nullptr && !u->Next()->IsEngine(); u = u->Next()) {}
994
995 if (u == t->other_multiheaded_part) continue;
996
997 /* Remove the part from the 'wrong' train */
999 /* And add it to the 'right' train */
1001 }
1002}
1003
1008static void NormaliseSubtypes(Train *chain)
1009{
1010 /* Nothing to do */
1011 if (chain == nullptr) return;
1012
1013 /* We must be the first in the chain. */
1014 assert(chain->Previous() == nullptr);
1015
1016 /* Set the appropriate bits for the first in the chain. */
1017 if (chain->IsWagon()) {
1018 chain->SetFreeWagon();
1019 } else {
1020 assert(chain->IsEngine());
1021 chain->SetFrontEngine();
1022 }
1023
1024 /* Now clear the bits for the rest of the chain */
1025 for (Train *t = chain->Next(); t != nullptr; t = t->Next()) {
1026 t->ClearFreeWagon();
1027 t->ClearFrontEngine();
1028 }
1029}
1030
1040static CommandCost CheckNewTrain(Train *original_dst, Train *dst, Train *original_src, Train *src)
1041{
1042 /* Just add 'new' engines and subtract the original ones.
1043 * If that's less than or equal to 0 we can be sure we did
1044 * not add any engines (read: trains) along the way. */
1045 if ((src != nullptr && src->IsEngine() ? 1 : 0) +
1046 (dst != nullptr && dst->IsEngine() ? 1 : 0) -
1047 (original_src != nullptr && original_src->IsEngine() ? 1 : 0) -
1048 (original_dst != nullptr && original_dst->IsEngine() ? 1 : 0) <= 0) {
1049 return CommandCost();
1050 }
1051
1052 /* Get a free unit number and check whether it's within the bounds.
1053 * There will always be a maximum of one new train. */
1054 if (GetFreeUnitNumber(VehicleType::Train) <= _settings_game.vehicle.max_trains) return CommandCost();
1055
1056 return CommandCost(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
1057}
1058
1065{
1066 /* No multi-part train, no need to check. */
1067 if (t == nullptr || t->Next() == nullptr) return CommandCost();
1068
1069 /* The maximum length for a train. For each part we decrease this by one
1070 * and if the result is negative the train is simply too long. */
1071 int allowed_len = _settings_game.vehicle.max_train_length * TILE_SIZE - t->gcache.cached_veh_length;
1072
1073 /* For free-wagon chains, check if they are within the max_train_length limit. */
1074 if (!t->IsEngine()) {
1075 t = t->Next();
1076 while (t != nullptr) {
1077 allowed_len -= t->gcache.cached_veh_length;
1078
1079 t = t->Next();
1080 }
1081
1082 if (allowed_len < 0) return CommandCost(STR_ERROR_TRAIN_TOO_LONG);
1083 return CommandCost();
1084 }
1085
1086 Train *head = t;
1087 Train *prev = t;
1088
1089 /* Break the prev -> t link so it always holds within the loop. */
1090 t = t->Next();
1091 prev->SetNext(nullptr);
1092
1093 /* Make sure the cache is cleared. */
1094 head->InvalidateNewGRFCache();
1095
1096 while (t != nullptr) {
1097 allowed_len -= t->gcache.cached_veh_length;
1098
1099 Train *next = t->Next();
1100
1101 /* Unlink the to-be-added piece; it is already unlinked from the previous
1102 * part due to the fact that the prev -> t link is broken. */
1103 t->SetNext(nullptr);
1104
1105 /* Don't check callback for articulated or rear dual headed parts */
1106 if (!t->IsArticulatedPart() && !t->IsRearDualheaded()) {
1107 /* Back up and clear the first_engine data to avoid using wagon override group */
1108 EngineID first_engine = t->gcache.first_engine;
1109 t->gcache.first_engine = EngineID::Invalid();
1110
1111 /* We don't want the cache to interfere. head's cache is cleared before
1112 * the loop and after each callback does not need to be cleared here. */
1114
1115 std::array<int32_t, 1> regs100;
1116 uint16_t callback = GetVehicleCallbackParent(CBID_TRAIN_ALLOW_WAGON_ATTACH, 0, 0, head->engine_type, t, head, regs100);
1117
1118 /* Restore original first_engine data */
1119 t->gcache.first_engine = first_engine;
1120
1121 /* We do not want to remember any cached variables from the test run */
1123 head->InvalidateNewGRFCache();
1124
1125 if (callback != CALLBACK_FAILED) {
1126 /* A failing callback means everything is okay */
1127 StringID error = STR_NULL;
1128
1129 if (head->GetGRF()->grf_version < 8) {
1130 if (callback == 0xFD) error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
1131 if (callback < 0xFD) error = GetGRFStringID(head->GetGRFID(), GRFSTR_MISC_GRF_TEXT + callback);
1132 if (callback >= 0x100) ErrorUnknownCallbackResult(head->GetGRFID(), CBID_TRAIN_ALLOW_WAGON_ATTACH, callback);
1133 } else {
1134 if (callback < 0x400) {
1135 error = GetGRFStringID(head->GetGRFID(), GRFSTR_MISC_GRF_TEXT + callback);
1136 } else {
1137 switch (callback) {
1138 case 0x400: // allow if railtypes match (always the case for OpenTTD)
1139 case 0x401: // allow
1140 break;
1141
1142 case 0x40F:
1143 error = GetGRFStringID(head->GetGRFID(), static_cast<GRFStringID>(regs100[0]));
1144 break;
1145
1146 default: // unknown reason -> disallow
1147 case 0x402: // disallow attaching
1148 error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
1149 break;
1150 }
1151 }
1152 }
1153
1154 if (error != STR_NULL) return CommandCost(error);
1155 }
1156 }
1157
1158 /* And link it to the new part. */
1159 prev->SetNext(t);
1160 prev = t;
1161 t = next;
1162 }
1163
1164 if (allowed_len < 0) return CommandCost(STR_ERROR_TRAIN_TOO_LONG);
1165 return CommandCost();
1166}
1167
1178static CommandCost ValidateTrains(Train *original_dst, Train *dst, Train *original_src, Train *src, bool check_limit)
1179{
1180 /* Check whether we may actually construct the trains. */
1182 if (ret.Failed()) return ret;
1183 ret = CheckTrainAttachment(dst);
1184 if (ret.Failed()) return ret;
1185
1186 /* Check whether we need to build a new train. */
1187 return check_limit ? CheckNewTrain(original_dst, dst, original_src, src) : CommandCost();
1188}
1189
1198static void ArrangeTrains(Train **dst_head, Train *dst, Train **src_head, Train *src, bool move_chain)
1199{
1200 /* First determine the front of the two resulting trains */
1201 if (*src_head == *dst_head) {
1202 /* If we aren't moving part(s) to a new train, we are just moving the
1203 * front back and there is not destination head. */
1204 *dst_head = nullptr;
1205 } else if (*dst_head == nullptr) {
1206 /* If we are moving to a new train the head of the move train would become
1207 * the head of the new vehicle. */
1208 *dst_head = src;
1209 }
1210
1211 if (src == *src_head) {
1212 /* If we are moving the front of a train then we are, in effect, creating
1213 * a new head for the train. Point to that. Unless we are moving the whole
1214 * train in which case there is not 'source' train anymore.
1215 * In case we are a multiheaded part we want the complete thing to come
1216 * with us, so src->GetNextUnit(), however... when we are e.g. a wagon
1217 * that is followed by a rear multihead we do not want to include that. */
1218 *src_head = move_chain ? nullptr :
1219 (src->IsMultiheaded() ? src->GetNextUnit() : src->GetNextVehicle());
1220 }
1221
1222 /* Now it's just simply removing the part that we are going to move from the
1223 * source train and *if* the destination is a not a new train add the chain
1224 * at the destination location. */
1225 RemoveFromConsist(src, move_chain);
1226 if (*dst_head != src) InsertInConsist(dst, src);
1227
1228 /* Now normalise the dual heads, that is move the dual heads around in such
1229 * a way that the head and rear of a dual head are in the same train */
1230 NormaliseDualHeads(*src_head);
1231 NormaliseDualHeads(*dst_head);
1232}
1233
1239static void NormaliseTrainHead(Train *head)
1240{
1241 /* Not much to do! */
1242 if (head == nullptr) return;
1243
1244 /* Tell the 'world' the train changed. */
1246 UpdateTrainGroupID(head);
1247
1248 /* Not a front engine, i.e. a free wagon chain. No need to do more. */
1249 if (!head->IsFrontEngine()) return;
1250
1251 /* Update the refit button and window */
1252 InvalidateWindowData(WindowClass::VehicleRefit, head->index, VIWD_CONSIST_CHANGED);
1253 SetWindowWidgetDirty(WindowClass::VehicleView, head->index, WID_VV_REFIT);
1254
1255 /* If we don't have a unit number yet, set one. */
1256 if (head->unitnumber != 0) return;
1257 head->unitnumber = Company::Get(head->owner)->freeunits[head->type].UseID(GetFreeUnitNumber(VehicleType::Train));
1258}
1259
1269CommandCost CmdMoveRailVehicle(DoCommandFlags flags, VehicleID src_veh, VehicleID dest_veh, bool move_chain)
1270{
1271 Train *src = Train::GetIfValid(src_veh);
1272 if (src == nullptr) return CMD_ERROR;
1273
1274 CommandCost ret = CheckOwnership(src->owner);
1275 if (ret.Failed()) return ret;
1276
1277 /* Do not allow moving crashed vehicles inside the depot, it is likely to cause asserts later */
1278 if (src->vehstatus.Test(VehState::Crashed)) return CMD_ERROR;
1279
1280 /* if nothing is selected as destination, try and find a matching vehicle to drag to. */
1281 Train *dst;
1282 if (dest_veh == VehicleID::Invalid()) {
1283 dst = (src->IsEngine() || flags.Test(DoCommandFlag::AutoReplace)) ? nullptr : FindGoodVehiclePos(src);
1284 } else {
1285 dst = Train::GetIfValid(dest_veh);
1286 if (dst == nullptr) return CMD_ERROR;
1287
1288 ret = CheckOwnership(dst->owner);
1289 if (ret.Failed()) return ret;
1290
1291 /* Do not allow appending to crashed vehicles, too */
1292 if (dst->vehstatus.Test(VehState::Crashed)) return CMD_ERROR;
1293 }
1294
1295 /* if an articulated part is being handled, deal with its parent vehicle */
1296 src = src->GetFirstEnginePart();
1297 if (dst != nullptr) {
1298 dst = dst->GetFirstEnginePart();
1299 }
1300
1301 /* don't move the same vehicle.. */
1302 if (src == dst) return CommandCost();
1303
1304 /* locate the head of the two chains */
1305 Train *src_head = src->First();
1306 Train *dst_head;
1307 if (dst != nullptr) {
1308 dst_head = dst->First();
1309 if (dst_head->tile != src_head->tile) return CMD_ERROR;
1310 /* Now deal with articulated part of destination wagon */
1311 dst = dst->GetLastEnginePart();
1312 } else {
1313 dst_head = nullptr;
1314 }
1315
1316 if (src->IsRearDualheaded()) return CommandCost(STR_ERROR_REAR_ENGINE_FOLLOW_FRONT);
1317
1318 /* When moving all wagons, we can't have the same src_head and dst_head */
1319 if (move_chain && src_head == dst_head) return CommandCost();
1320
1321 /* When moving a multiheaded part to be place after itself, bail out. */
1322 if (!move_chain && dst != nullptr && dst->IsRearDualheaded() && src == dst->other_multiheaded_part) return CommandCost();
1323
1324 /* Check if all vehicles in the source train are stopped inside a depot. */
1325 if (!src_head->IsStoppedInDepot()) return CommandCost(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
1326
1327 /* Check if all vehicles in the destination train are stopped inside a depot. */
1328 if (dst_head != nullptr && !dst_head->IsStoppedInDepot()) return CommandCost(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
1329
1330 /* First make a backup of the order of the trains. That way we can do
1331 * whatever we want with the order and later on easily revert. */
1332 TrainList original_src;
1333 TrainList original_dst;
1334
1335 MakeTrainBackup(original_src, src_head);
1336 MakeTrainBackup(original_dst, dst_head);
1337
1338 /* Also make backup of the original heads as ArrangeTrains can change them.
1339 * For the destination head we do not care if it is the same as the source
1340 * head because in that case it's just a copy. */
1341 Train *original_src_head = src_head;
1342 Train *original_dst_head = (dst_head == src_head ? nullptr : dst_head);
1343
1344 /* We want this information from before the rearrangement, but execute this after the validation.
1345 * original_src_head can't be nullptr; src is by definition != nullptr, so src_head can't be nullptr as
1346 * src->GetFirst() always yields non-nullptr, so eventually original_src_head != nullptr as well. */
1347 bool original_src_head_front_engine = original_src_head->IsFrontEngine();
1348 bool original_dst_head_front_engine = original_dst_head != nullptr && original_dst_head->IsFrontEngine();
1349
1350 /* (Re)arrange the trains in the wanted arrangement. */
1351 ArrangeTrains(&dst_head, dst, &src_head, src, move_chain);
1352
1353 if (!flags.Test(DoCommandFlag::AutoReplace)) {
1354 /* If the autoreplace flag is set we do not need to test for the validity
1355 * because we are going to revert the train to its original state. As we
1356 * assume the original state was correct autoreplace can skip this. */
1357 ret = ValidateTrains(original_dst_head, dst_head, original_src_head, src_head, true);
1358 if (ret.Failed()) {
1359 /* Restore the train we had. */
1360 RestoreTrainBackup(original_src);
1361 RestoreTrainBackup(original_dst);
1362 return ret;
1363 }
1364 }
1365
1366 /* do it? */
1367 if (flags.Test(DoCommandFlag::Execute)) {
1368 /* Remove old heads from the statistics */
1369 if (original_src_head_front_engine) GroupStatistics::CountVehicle(original_src_head, -1);
1370 if (original_dst_head_front_engine) GroupStatistics::CountVehicle(original_dst_head, -1);
1371
1372 /* First normalise the sub types of the chains. */
1373 NormaliseSubtypes(src_head);
1374 NormaliseSubtypes(dst_head);
1375
1376 /* There are 14 different cases:
1377 * 1) front engine gets moved to a new train, it stays a front engine.
1378 * a) the 'next' part is a wagon that becomes a free wagon chain.
1379 * b) the 'next' part is an engine that becomes a front engine.
1380 * c) there is no 'next' part, nothing else happens
1381 * 2) front engine gets moved to another train, it is not a front engine anymore
1382 * a) the 'next' part is a wagon that becomes a free wagon chain.
1383 * b) the 'next' part is an engine that becomes a front engine.
1384 * c) there is no 'next' part, nothing else happens
1385 * 3) front engine gets moved to later in the current train, it is not a front engine anymore.
1386 * a) the 'next' part is a wagon that becomes a free wagon chain.
1387 * b) the 'next' part is an engine that becomes a front engine.
1388 * 4) free wagon gets moved
1389 * a) the 'next' part is a wagon that becomes a free wagon chain.
1390 * b) the 'next' part is an engine that becomes a front engine.
1391 * c) there is no 'next' part, nothing else happens
1392 * 5) non front engine gets moved and becomes a new train, nothing else happens
1393 * 6) non front engine gets moved within a train / to another train, nothing happens
1394 * 7) wagon gets moved, nothing happens
1395 */
1396 if (src == original_src_head && src->IsEngine() && !src->IsFrontEngine()) {
1397 /* Cases #2 and #3: the front engine gets trashed. */
1398 CloseWindowById(WindowClass::VehicleView, src->index);
1399 CloseWindowById(WindowClass::VehicleOrders, src->index);
1400 CloseWindowById(WindowClass::VehicleRefit, src->index);
1401 CloseWindowById(WindowClass::VehicleDetails, src->index);
1402 CloseWindowById(WindowClass::VehicleTimetable, src->index);
1404 SetWindowDirty(WindowClass::Company, _current_company);
1405
1406 if (src_head != nullptr && src_head->IsFrontEngine()) {
1407 /* Cases #?b: Transfer order, unit number and other stuff
1408 * to the new front engine. */
1409 src_head->orders = src->orders;
1410 if (src_head->orders != nullptr) src_head->AddToShared(src);
1411 src_head->CopyVehicleConfigAndStatistics(src);
1412 }
1413 /* Remove stuff not valid anymore for non-front engines. */
1415 src->ReleaseUnitNumber();
1416 src->name.clear();
1417 }
1418
1419 /* We weren't a front engine but are becoming one. So
1420 * we should be put in the default group. */
1421 if (original_src_head != src && dst_head == src) {
1423 SetWindowDirty(WindowClass::Company, _current_company);
1424 }
1425
1426 /* Handle 'new engine' part of cases #1b, #2b, #3b, #4b and #5 in NormaliseTrainHead. */
1427 NormaliseTrainHead(src_head);
1428 NormaliseTrainHead(dst_head);
1429
1430 /* Add new heads to statistics.
1431 * This should be done after NormaliseTrainHead due to engine total limit checks in GetFreeUnitNumber. */
1432 if (src_head != nullptr && src_head->IsFrontEngine()) GroupStatistics::CountVehicle(src_head, 1);
1433 if (dst_head != nullptr && dst_head->IsFrontEngine()) GroupStatistics::CountVehicle(dst_head, 1);
1434
1436 CheckCargoCapacity(src_head);
1437 CheckCargoCapacity(dst_head);
1438 }
1439
1440 if (src_head != nullptr) src_head->First()->MarkDirty();
1441 if (dst_head != nullptr) dst_head->First()->MarkDirty();
1442
1443 /* We are undoubtedly changing something in the depot and train list. */
1444 InvalidateWindowData(WindowClass::VehicleDepot, src->tile);
1445 InvalidateWindowClassesData(WindowClass::TrainList, 0);
1446 } else {
1447 /* We don't want to execute what we're just tried. */
1448 RestoreTrainBackup(original_src);
1449 RestoreTrainBackup(original_dst);
1450 }
1451
1452 return CommandCost();
1453}
1454
1467CommandCost CmdSellRailWagon(DoCommandFlags flags, Vehicle *t, bool sell_chain, bool backup_order, ClientID user)
1468{
1470 Train *first = v->First();
1471
1472 if (v->IsRearDualheaded()) return CommandCost(STR_ERROR_REAR_ENGINE_FOLLOW_FRONT);
1473
1474 /* First make a backup of the order of the train. That way we can do
1475 * whatever we want with the order and later on easily revert. */
1476 TrainList original;
1477 MakeTrainBackup(original, first);
1478
1479 /* We need to keep track of the new head and the head of what we're going to sell. */
1480 Train *new_head = first;
1481 Train *sell_head = nullptr;
1482
1483 /* Split the train in the wanted way. */
1484 ArrangeTrains(&sell_head, nullptr, &new_head, v, sell_chain);
1485
1486 /* We don't need to validate the second train; it's going to be sold. */
1487 CommandCost ret = ValidateTrains(nullptr, nullptr, first, new_head, !flags.Test(DoCommandFlag::AutoReplace));
1488 if (ret.Failed()) {
1489 /* Restore the train we had. */
1490 RestoreTrainBackup(original);
1491 return ret;
1492 }
1493
1494 if (first->orders == nullptr && !OrderList::CanAllocateItem()) {
1495 /* Restore the train we had. */
1496 RestoreTrainBackup(original);
1497 return CommandCost(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
1498 }
1499
1501 for (Train *part = sell_head; part != nullptr; part = part->Next()) cost.AddCost(-part->value);
1502
1503 /* do it? */
1504 if (flags.Test(DoCommandFlag::Execute)) {
1505 /* First normalise the sub types of the chain. */
1506 NormaliseSubtypes(new_head);
1507
1508 if (v == first && !sell_chain && new_head != nullptr && new_head->IsFrontEngine()) {
1509 if (v->IsEngine()) {
1510 /* We are selling the front engine. In this case we want to
1511 * 'give' the order, unit number and such to the new head. */
1512 new_head->orders = first->orders;
1513 new_head->AddToShared(first);
1514 DeleteVehicleOrders(first);
1515
1516 /* Copy other important data from the front engine */
1517 new_head->CopyVehicleConfigAndStatistics(first);
1518 }
1519 GroupStatistics::CountVehicle(new_head, 1); // after copying over the profit, if required
1520 } else if (v->IsPrimaryVehicle() && backup_order) {
1521 OrderBackup::Backup(v, user);
1522 }
1523
1524 /* We need to update the information about the train. */
1525 NormaliseTrainHead(new_head);
1526
1527 /* We are undoubtedly changing something in the depot and train list. */
1528 InvalidateWindowData(WindowClass::VehicleDepot, v->tile);
1529 InvalidateWindowClassesData(WindowClass::TrainList, 0);
1530
1531 /* Actually delete the sold 'goods' */
1532 delete sell_head;
1533 } else {
1534 /* We don't want to execute what we're just tried. */
1535 RestoreTrainBackup(original);
1536 }
1537
1538 return cost;
1539}
1540
1542{
1543 /* Set common defaults. */
1544 this->bounds = {{-1, -1, 0}, {3, 3, 6}, {}};
1545
1546 /* Set if flipped and engine is NOT flagged with custom flip handling. */
1547 int flipped = this->flags.Test(VehicleRailFlag::Flipped) && !EngInfo(this->engine_type)->misc_flags.Test(EngineMiscFlag::RailFlips);
1548 /* If flipped and vehicle length is odd, we need to adjust the bounding box offset slightly. */
1549 int flip_offs = flipped && (this->gcache.cached_veh_length & 1);
1550
1551 Direction dir = this->direction;
1552 if (flipped) dir = ReverseDir(dir);
1553
1554 if (!IsDiagonalDirection(dir)) {
1555 static constexpr DiagDirectionIndexArray<Point> _sign_table{{{
1556 /* x, y */
1557 {-1, -1}, // DiagDirection::N
1558 {-1, 1}, // DiagDirection::E
1559 { 1, 1}, // DiagDirection::S
1560 { 1, -1}, // DiagDirection::W
1561 }}};
1562
1563 int half_shorten = (VEHICLE_LENGTH - this->gcache.cached_veh_length + flipped) / 2;
1564
1565 /* For all straight directions, move the bound box to the centre of the vehicle, but keep the size. */
1566 this->bounds.offset.x -= half_shorten * _sign_table[DirToDiagDir(dir)].x;
1567 this->bounds.offset.y -= half_shorten * _sign_table[DirToDiagDir(dir)].y;
1568 } else {
1569 switch (dir) {
1570 /* Shorten southern corner of the bounding box according the vehicle length
1571 * and center the bounding box on the vehicle. */
1572 case Direction::NE:
1573 this->bounds.origin.x = -(this->gcache.cached_veh_length + 1) / 2 + flip_offs;
1574 this->bounds.extent.x = this->gcache.cached_veh_length;
1575 this->bounds.offset.x = 1;
1576 break;
1577
1578 case Direction::NW:
1579 this->bounds.origin.y = -(this->gcache.cached_veh_length + 1) / 2 + flip_offs;
1580 this->bounds.extent.y = this->gcache.cached_veh_length;
1581 this->bounds.offset.y = 1;
1582 break;
1583
1584 /* Move northern corner of the bounding box down according to vehicle length
1585 * and center the bounding box on the vehicle. */
1586 case Direction::SW:
1587 this->bounds.origin.x = -(this->gcache.cached_veh_length) / 2 - flip_offs;
1588 this->bounds.extent.x = this->gcache.cached_veh_length;
1589 this->bounds.offset.x = 1 - (VEHICLE_LENGTH - this->gcache.cached_veh_length);
1590 break;
1591
1592 case Direction::SE:
1593 this->bounds.origin.y = -(this->gcache.cached_veh_length) / 2 - flip_offs;
1594 this->bounds.extent.y = this->gcache.cached_veh_length;
1595 this->bounds.offset.y = 1 - (VEHICLE_LENGTH - this->gcache.cached_veh_length);
1596 break;
1597
1598 default:
1599 NOT_REACHED();
1600 }
1601 }
1602}
1603
1608static void MarkTrainAsStuck(Train *consist)
1609{
1610 if (!consist->flags.Test(VehicleRailFlag::Stuck)) {
1611 /* It is the first time the problem occurred, set the "train stuck" flag. */
1613
1614 consist->wait_counter = 0;
1615
1616 /* Stop train */
1617 consist->cur_speed = 0;
1618 consist->subspeed = 0;
1619 consist->SetLastSpeed();
1620
1621 SetWindowWidgetDirty(WindowClass::VehicleView, consist->index, WID_VV_START_STOP);
1622 }
1623}
1624
1632static void SwapTrainFlags(GroundVehicleFlags *swap_flag1, GroundVehicleFlags *swap_flag2)
1633{
1634 GroundVehicleFlags flag1 = *swap_flag1;
1635 GroundVehicleFlags flag2 = *swap_flag2;
1636
1637 /* Reverse the rail-flags (if needed) */
1642}
1643
1649static void UpdateStatusAfterSwap(Train *v, bool reverse = true)
1650{
1651 /* Maybe reverse the direction. */
1652 if (reverse) v->direction = ReverseDir(v->direction);
1653
1654 /* Call the proper EnterTile function unless we are in a wormhole. */
1655 if (v->track != Track::Wormhole) {
1656 VehicleEnterTile(v, v->tile, v->x_pos, v->y_pos);
1657 } else {
1658 /* VehicleEnterTile_TunnelBridge() sets Track::Wormhole when the vehicle
1659 * is on the last bit of the bridge head (frame == TILE_SIZE - 1).
1660 * If we were swapped with such a vehicle, we have set Track::Wormhole,
1661 * when we shouldn't have. Check if this is the case. */
1662 TileIndex vt = TileVirtXY(v->x_pos, v->y_pos);
1664 VehicleEnterTile(v, vt, v->x_pos, v->y_pos);
1665 if (v->track != Track::Wormhole && IsBridgeTile(v->tile)) {
1666 /* We have just left the wormhole, possibly set the
1667 * "goingdown" bit. UpdateInclination() can be used
1668 * because we are at the border of the tile. */
1669 v->UpdatePosition();
1670 v->UpdateInclination(true, true);
1671 return;
1672 }
1673 }
1674 }
1675
1676 v->UpdatePosition();
1677 v->UpdateViewport(true, true);
1678}
1679
1687static void ReverseTrainSwapVeh(Train *v, int l, int r)
1688{
1689 Train *a, *b;
1690
1691 /* locate vehicles to swap */
1692 for (a = v; l != 0; l--) a = a->Next();
1693 for (b = v; r != 0; r--) b = b->Next();
1694
1695 if (a != b) {
1696 /* swap the hidden bits */
1697 {
1698 bool a_hidden = a->vehstatus.Test(VehState::Hidden);
1699 bool b_hidden = b->vehstatus.Test(VehState::Hidden);
1700 b->vehstatus.Set(VehState::Hidden, a_hidden);
1701 a->vehstatus.Set(VehState::Hidden, b_hidden);
1702 }
1703
1704 std::swap(a->track, b->track);
1705 std::swap(a->direction, b->direction);
1706 std::swap(a->x_pos, b->x_pos);
1707 std::swap(a->y_pos, b->y_pos);
1708 std::swap(a->tile, b->tile);
1709 std::swap(a->z_pos, b->z_pos);
1710
1712 } else {
1713 /* Swap GroundVehicleFlag::GoingUp/GroundVehicleFlag::GoingDown.
1714 * This is a little bit redundant way, a->gv_flags will
1715 * be (re)set twice, but it reduces code duplication */
1717 }
1718}
1719
1725{
1726 int r = CountVehiclesInChain(v) - 1; // number of vehicles - 1
1727
1728 /* swap start<>end, start+1<>end-1, ... */
1729 int l = 0;
1730 do {
1731 ReverseTrainSwapVeh(v, l++, r--);
1732 } while (l <= r);
1733
1734 for (Train *u = v; u != nullptr; u = u->Next()) {
1736 }
1737}
1738
1744static bool IsTrain(const Vehicle *v)
1745{
1746 return v->type == VehicleType::Train;
1747}
1748
1756{
1757 assert(IsLevelCrossingTile(tile));
1758
1759 return HasVehicleOnTile(tile, IsTrain);
1760}
1761
1769{
1770 if (v->type != VehicleType::Train || v->vehstatus.Test(VehState::Crashed)) return false;
1771
1772 const Train *t = Train::From(v);
1773 if (!t->IsMovingFront()) return false;
1774
1775 return TrainApproachingCrossingTile(t) == tile;
1776}
1777
1778
1786{
1787 assert(IsLevelCrossingTile(tile));
1788
1790 TileIndex tile_from = tile + TileOffsByDiagDir(dir);
1791
1792 if (HasVehicleOnTile(tile_from, [&](const Vehicle *v) {
1793 return TrainApproachingCrossingEnum(v, tile);
1794 })) return true;
1795
1796 dir = ReverseDiagDir(dir);
1797 tile_from = tile + TileOffsByDiagDir(dir);
1798
1799 return HasVehicleOnTile(tile_from, [&](const Vehicle *v) {
1800 return TrainApproachingCrossingEnum(v, tile);
1801 });
1802}
1803
1809static inline bool CheckLevelCrossing(TileIndex tile)
1810{
1811 /* reserved || train on crossing || train approaching crossing */
1813}
1814
1822static void UpdateLevelCrossingTile(TileIndex tile, bool sound, bool force_barred)
1823{
1824 assert(IsLevelCrossingTile(tile));
1825 bool set_barred;
1826
1827 /* We force the crossing to be barred when an adjacent crossing is barred, otherwise let it decide for itself. */
1828 set_barred = force_barred || CheckLevelCrossing(tile);
1829
1830 /* The state has changed */
1831 if (set_barred != IsCrossingBarred(tile)) {
1832 if (set_barred && sound && _settings_client.sound.ambient) SndPlayTileFx(SND_0E_LEVEL_CROSSING, tile);
1833 SetCrossingBarred(tile, set_barred);
1834 MarkTileDirtyByTile(tile);
1835 }
1836}
1837
1844void UpdateLevelCrossing(TileIndex tile, bool sound, bool force_bar)
1845{
1846 if (!IsLevelCrossingTile(tile)) return;
1847
1848 bool forced_state = force_bar;
1849
1850 Axis axis = GetCrossingRoadAxis(tile);
1851 DiagDirections diagdirs = AxisToDiagDirs(axis);
1852
1853 /* Check if an adjacent crossing is barred. */
1854 for (DiagDirection dir : diagdirs) {
1855 for (TileIndex t = tile; !forced_state && t < Map::Size() && IsLevelCrossingTile(t) && GetCrossingRoadAxis(t) == axis; t = TileAddByDiagDir(t, dir)) {
1856 forced_state |= CheckLevelCrossing(t);
1857 }
1858 }
1859
1860 /* Now that we know whether all tiles in this crossing should be barred or open,
1861 * we need to update those tiles. We start with the tile itself, then look along the road axis. */
1862 UpdateLevelCrossingTile(tile, sound, forced_state);
1863 for (DiagDirection dir : diagdirs) {
1864 for (TileIndex t = TileAddByDiagDir(tile, dir); t < Map::Size() && IsLevelCrossingTile(t) && GetCrossingRoadAxis(t) == axis; t = TileAddByDiagDir(t, dir)) {
1865 UpdateLevelCrossingTile(t, sound, forced_state);
1866 }
1867 }
1868}
1869
1876{
1877 for (DiagDirection dir : AxisToDiagDirs(road_axis)) {
1878 const TileIndex t = TileAddByDiagDir(tile, dir);
1879 if (t < Map::Size() && IsLevelCrossingTile(t) && GetCrossingRoadAxis(t) == road_axis) {
1881 }
1882 }
1883}
1884
1891{
1892 for (DiagDirection dir : AxisToDiagDirs(road_axis)) {
1893 const TileIndexDiff diff = TileOffsByDiagDir(dir);
1894 bool occupied = false;
1895 for (TileIndex t = tile + diff; t < Map::Size() && IsLevelCrossingTile(t) && GetCrossingRoadAxis(t) == road_axis; t += diff) {
1896 occupied |= CheckLevelCrossing(t);
1897 }
1898 if (occupied) {
1899 /* Mark the immediately adjacent tile dirty */
1900 const TileIndex t = tile + diff;
1901 if (t < Map::Size() && IsLevelCrossingTile(t) && GetCrossingRoadAxis(t) == road_axis) {
1903 }
1904 } else {
1905 /* Unbar the crossing tiles in this direction as necessary */
1906 for (TileIndex t = tile + diff; t < Map::Size() && IsLevelCrossingTile(t) && GetCrossingRoadAxis(t) == road_axis; t += diff) {
1907 if (IsCrossingBarred(t)) {
1908 /* The crossing tile is barred, unbar it and continue to check the next tile */
1909 SetCrossingBarred(t, false);
1911 } else {
1912 /* The crossing tile is already unbarred, mark the tile dirty and stop checking */
1914 break;
1915 }
1916 }
1917 }
1918 }
1919}
1920
1926static inline void MaybeBarCrossingWithSound(TileIndex tile)
1927{
1928 if (!IsCrossingBarred(tile)) {
1929 SetCrossingReservation(tile, true);
1930 UpdateLevelCrossing(tile, true);
1931 }
1932}
1933
1934
1940static void AdvanceWagonsBeforeSwap(Train *moving_front)
1941{
1942 Train *base = moving_front;
1943 Train *first = base; // first vehicle to move
1944 Train *last = moving_front->GetMovingBack(); // last vehicle to move
1945 uint length = CountVehiclesInChain(moving_front->First());
1946
1947 while (length > 2) {
1948 last = last->GetMovingPrev();
1949 first = first->GetMovingNext();
1950
1951 int differential = base->CalcNextVehicleOffset() - last->CalcNextVehicleOffset();
1952
1953 /* do not update images now
1954 * negative differential will be handled in AdvanceWagonsAfterSwap() */
1955 for (int i = 0; i < differential; i++) TrainController(first, last->GetMovingNext());
1956
1957 base = first; // == base->GetMovingNext()
1958 length -= 2;
1959 }
1960}
1961
1962
1968static void AdvanceWagonsAfterSwap(Train *moving_front)
1969{
1970 /* first of all, fix the situation when the train was entering a depot */
1971 Train *dep = moving_front; // last vehicle in front of just left depot
1972 while (dep->GetMovingNext() != nullptr && (dep->track == Track::Depot || dep->GetMovingNext()->track != Track::Depot)) {
1973 dep = dep->GetMovingNext(); // find first vehicle outside of a depot, with next vehicle inside a depot
1974 }
1975
1976 Train *leave = dep->GetMovingNext(); // first vehicle in a depot we are leaving now
1977
1978 if (leave != nullptr) {
1979 /* 'pull' next wagon out of the depot, so we won't miss it (it could stay in depot forever) */
1980 int d = TicksToLeaveDepot(dep);
1981
1982 if (d <= 0) {
1983 leave->vehstatus.Reset(VehState::Hidden); // move it out of the depot
1984 leave->track = GetRailDepotTrack(leave->tile);
1985 for (int i = 0; i >= d; i--) TrainController(leave, nullptr); // maybe move it, and maybe let another wagon leave
1986 }
1987 } else {
1988 dep = nullptr; // no vehicle in a depot, so no vehicle leaving a depot
1989 }
1990
1991 Train *base = moving_front;
1992 Train *first = base; // first vehicle to move
1993 Train *last = moving_front->GetMovingBack(); // last vehicle to move
1994 uint length = CountVehiclesInChain(moving_front->First());
1995
1996 /* We have to make sure all wagons that leave a depot because of train reversing are moved correctly
1997 * they have already correct spacing, so we have to make sure they are moved how they should */
1998 bool nomove = (dep == nullptr); // If there is no vehicle leaving a depot, limit the number of wagons moved immediately.
1999
2000 while (length > 2) {
2001 /* we reached vehicle (originally) in front of a depot, stop now
2002 * (we would move wagons that are already moved with new wagon length). */
2003 if (base == dep) break;
2004
2005 /* the last wagon was that one leaving a depot, so do not move it anymore */
2006 if (last == dep) nomove = true;
2007
2008 last = last->GetMovingPrev();
2009 first = first->GetMovingNext();
2010
2011 int differential = last->CalcNextVehicleOffset() - base->CalcNextVehicleOffset();
2012
2013 /* do not update images now */
2014 for (int i = 0; i < differential; i++) TrainController(first, (nomove ? last->GetMovingNext() : nullptr));
2015
2016 base = first; // == base->GetMovingNext()
2017 length -= 2;
2018 }
2019}
2020
2021static bool IsWholeTrainInsideDepot(const Train *v)
2022{
2023 for (const Train *u = v; u != nullptr; u = u->Next()) {
2024 if (u->track != Track::Depot || u->tile != v->tile) return false;
2025 }
2026 return true;
2027}
2028
2033static void ReverseTrainDirection(Train *consist)
2034{
2035 Train *moving_front = consist->GetMovingFront();
2036 if (IsRailDepotTile(moving_front->tile)) {
2037 if (IsWholeTrainInsideDepot(consist)) return;
2038 InvalidateWindowData(WindowClass::VehicleDepot, moving_front->tile);
2039 }
2040
2041 /* Clear path reservation in front if train is not stuck. */
2043
2044 /* Check if we were approaching a rail/road-crossing */
2045 TileIndex crossing = TrainApproachingCrossingTile(moving_front);
2046
2047 /* Check if we should back up or flip the train. */
2048 if (consist->vehicle_flags.Test(VehicleFlag::DrivingBackwards) || _settings_game.difficulty.train_flip_reverse_allowed == TrainFlipReversingAllowed::None || consist->Last()->CanLeadTrain()) {
2049 /* The train will back up. */
2051
2052 for (Train *u = consist; u != nullptr; u = u->Next()) {
2053 /* Invert going up/down */
2054 if (u->gv_flags.Any({GroundVehicleFlag::GoingUp, GroundVehicleFlag::GoingDown})) {
2056 }
2057 UpdateStatusAfterSwap(u, false);
2058 }
2059 /* We may have entered a depot and stopped driving backwards. */
2060 moving_front = consist->GetMovingFront();
2061 } else {
2062 /* The train will flip. */
2063 AdvanceWagonsBeforeSwap(moving_front);
2064
2065 /* swap start<>end, start+1<>end-1, ... */
2066 ReverseTrainSwapVehicles(consist);
2067
2068 AdvanceWagonsAfterSwap(moving_front);
2069 }
2070
2071 if (IsRailDepotTile(moving_front->tile)) {
2072 InvalidateWindowData(WindowClass::VehicleDepot, moving_front->tile);
2073 }
2074
2077
2078 /* recalculate cached data */
2079 consist->ConsistChanged(CCF_TRACK);
2080
2081 /* update all images */
2082 for (Train *u = consist; u != nullptr; u = u->Next()) u->UpdateViewport(false, false);
2083
2084 /* update crossing we were approaching */
2085 if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
2086
2087 /* maybe we are approaching crossing now, after reversal */
2088 crossing = TrainApproachingCrossingTile(moving_front);
2089 if (crossing != INVALID_TILE) MaybeBarCrossingWithSound(crossing);
2090
2091 /* If we are inside a depot after reversing, don't bother with path reserving. */
2092 if (moving_front->track == Track::Depot) {
2093 /* Can't be stuck here as inside a depot is always a safe tile. */
2094 if (consist->flags.Test(VehicleRailFlag::Stuck)) SetWindowWidgetDirty(WindowClass::VehicleView, consist->index, WID_VV_START_STOP);
2096 return;
2097 }
2098
2099 /* VehicleExitDir does not always produce the desired dir for depots and
2100 * tunnels/bridges that is needed for UpdateSignalsOnSegment. */
2101 DiagDirection dir = VehicleExitDir(moving_front->GetMovingDirection(), moving_front->track);
2102 if (IsRailDepotTile(moving_front->tile) || IsTileType(moving_front->tile, TileType::TunnelBridge)) dir = DiagDirection::Invalid;
2103
2104 if (UpdateSignalsOnSegment(moving_front->tile, dir, consist->owner) == SigSegState::Path || _settings_game.pf.reserve_paths) {
2105 /* If we are currently on a tile with conventional signals, we can't treat the
2106 * current tile as a safe tile or we would enter a PBS block without a reservation. */
2107 bool first_tile_okay = !HasBlockSignalOnTrackdir(moving_front->tile, moving_front->GetVehicleTrackdir());
2108
2109 /* If we are on a depot tile facing outwards, do not treat the current tile as safe. */
2110 if (IsRailDepotTile(moving_front->tile) && TrackdirToExitdir(moving_front->GetVehicleTrackdir()) == GetRailDepotDirection(moving_front->tile)) first_tile_okay = false;
2111
2112 if (IsRailStationTile(moving_front->tile)) SetRailStationPlatformReservation(moving_front->tile, TrackdirToExitdir(moving_front->GetVehicleTrackdir()), true);
2113 if (TryPathReserve(consist, false, first_tile_okay)) {
2114 /* Do a look-ahead now in case our current tile was already a safe tile. */
2115 CheckNextTrainTile(consist);
2116 } else if (consist->current_order.GetType() != OT_LOADING) {
2117 /* Do not wait for a way out when we're still loading */
2118 MarkTrainAsStuck(consist);
2119 }
2120 } else if (consist->flags.Test(VehicleRailFlag::Stuck)) {
2121 /* A train not inside a PBS block can't be stuck. */
2123 consist->wait_counter = 0;
2124 }
2125}
2126
2134CommandCost CmdReverseTrainDirection(DoCommandFlags flags, VehicleID veh_id, bool reverse_single_veh)
2135{
2136 Train *v = Train::GetIfValid(veh_id);
2137 if (v == nullptr) return CMD_ERROR;
2138
2140 if (ret.Failed()) return ret;
2141
2142 if (reverse_single_veh) {
2143 /* turn a single unit around */
2144
2145 if (v->IsMultiheaded() || EngInfo(v->engine_type)->callback_mask.Test(VehicleCallbackMask::ArticEngine)) {
2146 return CommandCost(STR_ERROR_CAN_T_REVERSE_DIRECTION_RAIL_VEHICLE_MULTIPLE_UNITS);
2147 }
2148
2149 Train *front = v->First();
2150 /* make sure the vehicle is stopped in the depot */
2151 if (!front->IsStoppedInDepot()) {
2152 return CommandCost(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
2153 }
2154
2155 if (flags.Test(DoCommandFlag::Execute)) {
2157
2159 SetWindowDirty(WindowClass::VehicleDepot, front->tile);
2160 SetWindowDirty(WindowClass::VehicleDetails, front->index);
2161 InvalidateWindowData(WindowClass::VehicleView, front->index);
2162 SetWindowClassesDirty(WindowClass::TrainList);
2163 }
2164 } else {
2165 /* turn the whole train around */
2166 if (!v->IsPrimaryVehicle()) return CMD_ERROR;
2167 if (v->vehstatus.Test(VehState::Crashed) || v->breakdown_ctr != 0) return CMD_ERROR;
2168
2169 if (flags.Test(DoCommandFlag::Execute)) {
2170 /* Properly leave the station if we are loading and won't be loading anymore */
2171 if (v->current_order.IsType(OT_LOADING)) {
2172 const Vehicle *moving_back = v->GetMovingBack();
2173
2174 /* not a station || different station --> leave the station */
2175 if (!IsTileType(moving_back->tile, TileType::Station) || GetStationIndex(moving_back->tile) != GetStationIndex(v->GetMovingFront()->tile)) {
2176 v->LeaveStation();
2177 }
2178 }
2179
2180 /* We cancel any 'skip signal at dangers' here */
2182 InvalidateWindowData(WindowClass::VehicleView, v->index);
2183
2184 if (_settings_game.vehicle.train_acceleration_model != AccelerationModel::Original && v->cur_speed != 0) {
2186 } else {
2187 v->cur_speed = 0;
2188 v->SetLastSpeed();
2191 }
2192
2193 /* Unbunching data is no longer valid. */
2195 }
2196 }
2197 return CommandCost();
2198}
2199
2211{
2214
2215 const Train *moving_front = t->GetMovingFront();
2216 TileIndex next_tile = TileAddByDiagDir(moving_front->tile, TrackdirToExitdir(moving_front->GetVehicleTrackdir()));
2217 if (next_tile == INVALID_TILE || !IsTileType(next_tile, TileType::Railway) || !HasSignals(next_tile)) return TFP_STUCK;
2218 TrackBits new_tracks = DiagdirReachesTracks(TrackdirToExitdir(moving_front->GetVehicleTrackdir())) & GetTrackBits(next_tile);
2219 return new_tracks.Any() && HasSignalOnTrack(next_tile, FindFirstTrack(new_tracks)) ? TFP_SIGNAL : TFP_STUCK;
2220}
2221
2229{
2230 Train *t = Train::GetIfValid(veh_id);
2231 if (t == nullptr) return CMD_ERROR;
2232
2233 if (!t->IsPrimaryVehicle()) return CMD_ERROR;
2234
2236 if (ret.Failed()) return ret;
2237
2238
2239 if (flags.Test(DoCommandFlag::Execute)) {
2241 InvalidateWindowData(WindowClass::VehicleView, t->index);
2242
2243 /* Unbunching data is no longer valid. */
2245 }
2246
2247 return CommandCost();
2248}
2249
2257static FindDepotData FindClosestTrainDepot(Train *v, int max_distance)
2258{
2259 assert(!v->vehstatus.Test(VehState::Crashed));
2260
2261 return YapfTrainFindNearestDepot(v, max_distance);
2262}
2263
2265{
2266 FindDepotData tfdd = FindClosestTrainDepot(this, 0);
2267 if (tfdd.best_length == UINT_MAX) return ClosestDepot();
2268
2269 return ClosestDepot(tfdd.tile, GetDepotIndex(tfdd.tile), tfdd.reverse);
2270}
2271
2272void Train::PlayLeaveStationSound(bool force) const
2273{
2274 static const SoundFx sfx[] = {
2280 };
2281
2282 if (PlayVehicleSound(this, VehicleSoundEvent::Start, force)) return;
2283
2284 SndPlayVehicleFx(sfx[to_underlying(RailVehInfo(this->engine_type)->engclass)], this);
2285}
2286
2291static void CheckNextTrainTile(Train *consist)
2292{
2293 /* Don't do any look-ahead if path_backoff_interval is 255. */
2294 if (_settings_game.pf.path_backoff_interval == 255) return;
2295
2296 const Train *moving_front = consist->GetMovingFront();
2297
2298 /* Exit if we are inside a depot. */
2299 if (moving_front->track == Track::Depot) return;
2300
2301 switch (consist->current_order.GetType()) {
2302 /* Exit if we reached our destination depot. */
2303 case OT_GOTO_DEPOT:
2304 if (moving_front->tile == consist->dest_tile) return;
2305 break;
2306
2307 case OT_GOTO_WAYPOINT:
2308 /* If we reached our waypoint, make sure we see that. */
2309 if (IsRailWaypointTile(moving_front->tile) && GetStationIndex(moving_front->tile) == consist->current_order.GetDestination()) ProcessOrders(consist);
2310 break;
2311
2312 case OT_NOTHING:
2313 case OT_LEAVESTATION:
2314 case OT_LOADING:
2315 /* Exit if the current order doesn't have a destination, but the train has orders. */
2316 if (consist->GetNumOrders() > 0) return;
2317 break;
2318
2319 default:
2320 break;
2321 }
2322 /* Exit if we are on a station tile and are going to stop. */
2323 if (IsRailStationTile(moving_front->tile) && consist->current_order.ShouldStopAtStation(consist, GetStationIndex(moving_front->tile))) return;
2324
2325 Trackdir td = moving_front->GetVehicleTrackdir();
2326
2327 /* On a tile with a red non-pbs signal, don't look ahead. */
2328 if (HasBlockSignalOnTrackdir(moving_front->tile, td) && GetSignalStateByTrackdir(moving_front->tile, td) == SignalState::Red) return;
2329
2330 CFollowTrackRail ft(consist);
2331 if (!ft.Follow(moving_front->tile, td)) return;
2332
2334 /* Next tile is not reserved. */
2335 if (ft.new_td_bits.Count() == 1) {
2337 /* If the next tile is a PBS signal, try to make a reservation. */
2341 }
2342 ChooseTrainTrack(consist, ft.new_tile, ft.exitdir, tracks, false, nullptr, false);
2343 }
2344 }
2345 }
2346}
2347
2354{
2355 /* bail out if not all wagons are in the same depot or not in a depot at all */
2356 for (const Train *u = v; u != nullptr; u = u->Next()) {
2357 if (u->track != Track::Depot || u->tile != v->tile) return false;
2358 }
2359
2360 /* if the train got no power, then keep it in the depot */
2361 if (v->gcache.cached_power == 0) {
2363 SetWindowDirty(WindowClass::VehicleDepot, v->tile);
2364 return true;
2365 }
2366
2367 /* Check if we should wait here for unbunching. */
2368 if (v->IsWaitingForUnbunching()) return true;
2369
2370 SigSegState seg_state;
2371
2372 if (v->force_proceed == TFP_NONE) {
2373 /* force proceed was not pressed */
2374 if (++v->wait_counter < 37) {
2375 SetWindowClassesDirty(WindowClass::TrainList);
2376 return true;
2377 }
2378
2379 v->wait_counter = 0;
2380
2382 if (seg_state == SigSegState::Full || HasDepotReservation(v->tile)) {
2383 /* Full and no PBS signal in block or depot reserved, can't exit. */
2384 SetWindowClassesDirty(WindowClass::TrainList);
2385 return true;
2386 }
2387 } else {
2389 }
2390
2391 /* We are leaving a depot, but have to go to the exact same one; re-enter. */
2392 if (v->current_order.IsType(OT_GOTO_DEPOT) && v->tile == v->dest_tile) {
2393 /* Service when depot has no reservation. */
2395 return true;
2396 }
2397
2398 /* Only leave when we can reserve a path to our destination. */
2399 if (seg_state == SigSegState::Path && !TryPathReserve(v) && v->force_proceed == TFP_NONE) {
2400 /* No path and no force proceed. */
2401 SetWindowClassesDirty(WindowClass::TrainList);
2403 return true;
2404 }
2405
2406 SetDepotReservation(v->tile, true);
2407 if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(v->tile);
2408
2412 SetWindowClassesDirty(WindowClass::TrainList);
2413
2415
2417 v->cur_speed = 0;
2418
2419 v->UpdateViewport(true, true);
2420 v->UpdatePosition();
2422 v->UpdateAcceleration();
2423 InvalidateWindowData(WindowClass::VehicleDepot, v->tile);
2424
2425 return false;
2426}
2427
2434static void ClearPathReservation(const Train *v, TileIndex tile, Trackdir track_dir)
2435{
2436 DiagDirection dir = TrackdirToExitdir(track_dir);
2437
2439 /* Are we just leaving a tunnel/bridge? */
2440 if (GetTunnelBridgeDirection(tile) == ReverseDiagDir(dir)) {
2442
2443 if (TunnelBridgeIsFree(tile, end, v).Succeeded()) {
2444 /* Free the reservation only if no other train is on the tiles. */
2445 SetTunnelBridgeReservation(tile, false);
2446 SetTunnelBridgeReservation(end, false);
2447
2448 if (_settings_client.gui.show_track_reservation) {
2449 if (IsBridge(tile)) {
2450 MarkBridgeDirty(tile);
2451 } else {
2452 MarkTileDirtyByTile(tile);
2454 }
2455 }
2456 }
2457 }
2458 } else if (IsRailStationTile(tile)) {
2459 TileIndex new_tile = TileAddByDiagDir(tile, dir);
2460 /* If the new tile is not a further tile of the same station, we
2461 * clear the reservation for the whole platform. */
2462 if (!IsCompatibleTrainStationTile(new_tile, tile)) {
2464 }
2465 } else {
2466 /* Any other tile */
2467 UnreserveRailTrack(tile, TrackdirToTrack(track_dir));
2468 }
2469}
2470
2476{
2477 assert(consist->IsFrontEngine());
2478
2479 const Train *moving_front = consist->GetMovingFront();
2480 TileIndex tile = moving_front->tile;
2481 Trackdir td = moving_front->GetVehicleTrackdir();
2482 bool free_tile = tile != moving_front->tile || !(IsRailStationTile(moving_front->tile) || IsTileType(moving_front->tile, TileType::TunnelBridge));
2483 StationID station_id = IsRailStationTile(moving_front->tile) ? GetStationIndex(moving_front->tile) : StationID::Invalid();
2484
2485 /* Can't be holding a reservation if we enter a depot. */
2486 if (IsRailDepotTile(tile) && TrackdirToExitdir(td) != GetRailDepotDirection(tile)) return;
2487 if (moving_front->track == Track::Depot) {
2488 /* Front engine is in a depot. We enter if some part is not in the depot. */
2489 for (const Train *u = consist; u != nullptr; u = u->Next()) {
2490 if (u->track != Track::Depot || u->tile != consist->tile) return;
2491 }
2492 }
2493 /* Don't free reservation if it's not ours. */
2494 if (TracksOverlap(GetReservedTrackbits(tile) | TrackdirToTrack(td))) return;
2495
2496 CFollowTrackRail ft(consist, GetAllCompatibleRailTypes(consist->railtypes));
2497 while (ft.Follow(tile, td)) {
2498 tile = ft.new_tile;
2500 td = RemoveFirstTrackdir(bits);
2501 assert(bits.None());
2502
2503 if (!IsValidTrackdir(td)) break;
2504
2505 if (IsTileType(tile, TileType::Railway)) {
2506 if (HasSignalOnTrackdir(tile, td) && !IsPbsSignal(GetSignalType(tile, TrackdirToTrack(td)))) {
2507 /* Conventional signal along trackdir: remove reservation and stop. */
2509 break;
2510 }
2511 if (HasPbsSignalOnTrackdir(tile, td)) {
2512 if (GetSignalStateByTrackdir(tile, td) == SignalState::Red) {
2513 /* Red PBS signal? Can't be our reservation, would be green then. */
2514 break;
2515 } else {
2516 /* Turn the signal back to red. */
2518 MarkTileDirtyByTile(tile);
2519 }
2520 } else if (HasPbsSignalOnTrackdir(tile, ReverseTrackdir(td))) {
2521 /* Reservation passes an opposing path signal. Mark signal for update to re-establish the proper default state. */
2523 } else if (HasSignalOnTrackdir(tile, ReverseTrackdir(td)) && IsOnewaySignal(tile, TrackdirToTrack(td))) {
2524 break;
2525 }
2526 }
2527
2528 /* Don't free first station/bridge/tunnel if we are on it. */
2529 if (free_tile || (!(ft.is_station && GetStationIndex(ft.new_tile) == station_id) && !ft.is_tunnel && !ft.is_bridge)) ClearPathReservation(consist, tile, td);
2530
2531 free_tile = true;
2532 }
2533
2535}
2536
2550static Track DoTrainPathfind(const Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool &path_found, bool do_track_reservation, PBSTileInfo *dest, TileIndex *final_dest)
2551{
2552 if (final_dest != nullptr) *final_dest = INVALID_TILE;
2553 return YapfTrainChooseTrack(v, tile, enterdir, tracks, path_found, do_track_reservation, dest, final_dest);
2554}
2555
2564static PBSTileInfo ExtendTrainReservation(const Train *v, TrackBits *new_tracks, DiagDirection *enterdir)
2565{
2567
2568 CFollowTrackRail ft(v);
2569
2570 std::vector<std::pair<TileIndex, Trackdir>> signals_set_to_red;
2571
2572 TileIndex tile = origin.tile;
2573 Trackdir cur_td = origin.trackdir;
2574 while (ft.Follow(tile, cur_td)) {
2575 if (ft.new_td_bits.Count() == 1) {
2576 /* Possible signal tile. */
2578 }
2579
2582 if (ft.new_td_bits.None()) break;
2583 }
2584
2585 /* Station, depot or waypoint are a possible target. */
2586 bool target_seen = ft.is_station || (IsTileType(ft.new_tile, TileType::Railway) && !IsPlainRail(ft.new_tile));
2587 if (target_seen || ft.new_td_bits.Count() > 1) {
2588 /* Choice found or possible target encountered.
2589 * On finding a possible target, we need to stop and let the pathfinder handle the
2590 * remaining path. This is because we don't know if this target is in one of our
2591 * orders, so we might cause pathfinding to fail later on if we find a choice.
2592 * This failure would cause a bogus call to TryReserveSafePath which might reserve
2593 * a wrong path not leading to our next destination. */
2595
2596 /* If we did skip some tiles, backtrack to the first skipped tile so the pathfinder
2597 * actually starts its search at the first unreserved tile. */
2598 if (ft.tiles_skipped != 0) ft.new_tile -= TileOffsByDiagDir(ft.exitdir) * ft.tiles_skipped;
2599
2600 /* Choice found, path valid but not okay. Save info about the choice tile as well. */
2601 if (new_tracks != nullptr) *new_tracks = TrackdirBitsToTrackBits(ft.new_td_bits);
2602 if (enterdir != nullptr) *enterdir = ft.exitdir;
2603 return PBSTileInfo(ft.new_tile, ft.old_td, false);
2604 }
2605
2606 tile = ft.new_tile;
2607 cur_td = FindFirstTrackdir(ft.new_td_bits);
2608
2609 Trackdir rev_td = ReverseTrackdir(cur_td);
2610 if (IsSafeWaitingPosition(v, tile, cur_td, true, _settings_game.pf.forbid_90_deg)) {
2611 bool wp_free = IsWaitingPositionFree(v, tile, cur_td, _settings_game.pf.forbid_90_deg);
2612 if (!(wp_free && TryReserveRailTrack(tile, TrackdirToTrack(cur_td)))) break;
2613 /* Green path signal opposing the path? Turn to red. */
2614 if (HasPbsSignalOnTrackdir(tile, rev_td) && GetSignalStateByTrackdir(tile, rev_td) == SignalState::Green) {
2615 signals_set_to_red.emplace_back(tile, rev_td);
2617 MarkTileDirtyByTile(tile);
2618 }
2619 /* Safe position is all good, path valid and okay. */
2620 return PBSTileInfo(tile, cur_td, true);
2621 }
2622
2623 if (!TryReserveRailTrack(tile, TrackdirToTrack(cur_td))) break;
2624
2625 /* Green path signal opposing the path? Turn to red. */
2626 if (HasPbsSignalOnTrackdir(tile, rev_td) && GetSignalStateByTrackdir(tile, rev_td) == SignalState::Green) {
2627 signals_set_to_red.emplace_back(tile, rev_td);
2629 MarkTileDirtyByTile(tile);
2630 }
2631 }
2632
2633 if (ft.err == CFollowTrackRail::ErrorCode::Owner || ft.err == CFollowTrackRail::ErrorCode::NoWay) {
2634 /* End of line, path valid and okay. */
2635 return PBSTileInfo(ft.old_tile, ft.old_td, true);
2636 }
2637
2638 /* Sorry, can't reserve path, back out. */
2639 tile = origin.tile;
2640 cur_td = origin.trackdir;
2641 TileIndex stopped = ft.old_tile;
2642 Trackdir stopped_td = ft.old_td;
2643 while (tile != stopped || cur_td != stopped_td) {
2644 if (!ft.Follow(tile, cur_td)) break;
2645
2648 assert(ft.new_td_bits.Any());
2649 }
2650 assert(ft.new_td_bits.Count() == 1);
2651
2652 tile = ft.new_tile;
2653 cur_td = FindFirstTrackdir(ft.new_td_bits);
2654
2655 UnreserveRailTrack(tile, TrackdirToTrack(cur_td));
2656 }
2657
2658 /* Re-instate green signals we turned to red. */
2659 for (auto [sig_tile, td] : signals_set_to_red) {
2661 }
2662
2663 /* Path invalid. */
2664 return PBSTileInfo();
2665}
2666
2677static bool TryReserveSafeTrack(const Train *v, TileIndex tile, Trackdir td, bool override_railtype)
2678{
2679 return YapfTrainFindNearestSafeTile(v, tile, td, override_railtype);
2680}
2681
2683class VehicleOrderSaver {
2684private:
2685 Train *v;
2686 Order old_order;
2687 TileIndex old_dest_tile;
2688 StationID old_last_station_visited;
2689 VehicleOrderID index;
2690 bool suppress_implicit_orders;
2691 bool restored;
2692
2693public:
2694 VehicleOrderSaver(Train *_v) :
2695 v(_v),
2696 old_order(_v->current_order),
2697 old_dest_tile(_v->dest_tile),
2698 old_last_station_visited(_v->last_station_visited),
2699 index(_v->cur_real_order_index),
2700 suppress_implicit_orders(_v->gv_flags.Test(GroundVehicleFlag::SuppressImplicitOrders)),
2701 restored(false)
2702 {
2703 }
2704
2708 void Restore()
2709 {
2710 this->v->current_order = this->old_order;
2711 this->v->dest_tile = this->old_dest_tile;
2712 this->v->last_station_visited = this->old_last_station_visited;
2713 this->v->gv_flags.Set(GroundVehicleFlag::SuppressImplicitOrders, suppress_implicit_orders);
2714 this->restored = true;
2715 }
2716
2721 {
2722 if (!this->restored) this->Restore();
2723 }
2724
2730 bool SwitchToNextOrder(bool skip_first)
2731 {
2732 if (this->v->GetNumOrders() == 0) return false;
2733
2734 if (skip_first) ++this->index;
2735
2736 int depth = 0;
2737
2738 do {
2739 /* Wrap around. */
2740 if (this->index >= this->v->GetNumOrders()) this->index = 0;
2741
2742 Order *order = this->v->GetOrder(this->index);
2743 assert(order != nullptr);
2744
2745 switch (order->GetType()) {
2746 case OT_GOTO_DEPOT:
2747 /* Skip service in depot orders when the train doesn't need service. */
2748 if (order->GetDepotOrderType().Test(OrderDepotTypeFlag::Service) && !this->v->NeedsServicing()) break;
2749 [[fallthrough]];
2750 case OT_GOTO_STATION:
2751 case OT_GOTO_WAYPOINT:
2752 this->v->current_order = *order;
2753 return UpdateOrderDest(this->v, order, 0, true);
2754 case OT_CONDITIONAL: {
2755 VehicleOrderID next = ProcessConditionalOrder(order, this->v);
2756 if (next != INVALID_VEH_ORDER_ID) {
2757 depth++;
2758 this->index = next;
2759 /* Don't increment next, so no break here. */
2760 continue;
2761 }
2762 break;
2763 }
2764 default:
2765 break;
2766 }
2767 /* Don't increment inside the while because otherwise conditional
2768 * orders can lead to an infinite loop. */
2769 ++this->index;
2770 depth++;
2771 } while (this->index != this->v->cur_real_order_index && depth < this->v->GetNumOrders());
2772
2773 return false;
2774 }
2775};
2776
2777/* choose a track */
2778static Track ChooseTrainTrack(Train *consist, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool force_res, bool *got_reservation, bool mark_stuck)
2779{
2780 Track best_track = Track::Invalid;
2781 bool do_track_reservation = _settings_game.pf.reserve_paths || force_res;
2782 bool changed_signal = false;
2783 TileIndex final_dest = INVALID_TILE;
2784
2785 assert(tracks == (tracks & TRACK_BIT_ALL));
2786
2787 if (got_reservation != nullptr) *got_reservation = false;
2788
2789 /* Don't use tracks here as the setting to forbid 90 deg turns might have been switched between reservation and now. */
2790 TrackBits res_tracks = GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir);
2791 /* Do we have a suitable reserved track? */
2792 if (res_tracks.Any()) return FindFirstTrack(res_tracks);
2793
2794 /* Quick return in case only one possible track is available */
2795 if (tracks.Count() == 1) {
2796 Track track = FindFirstTrack(tracks);
2797 /* We need to check for signals only here, as a junction tile can't have signals. */
2798 if (IsValidTrack(track) && HasPbsSignalOnTrackdir(tile, TrackEnterdirToTrackdir(track, enterdir))) {
2799 do_track_reservation = true;
2800 changed_signal = true;
2802 } else if (!do_track_reservation) {
2803 return track;
2804 }
2805 best_track = track;
2806 }
2807
2808 const Train *moving_front = consist->GetMovingFront();
2809
2810 PBSTileInfo res_dest(tile, Trackdir::Invalid, false);
2811 DiagDirection dest_enterdir = enterdir;
2812 if (do_track_reservation) {
2813 res_dest = ExtendTrainReservation(consist, &tracks, &dest_enterdir);
2814 if (res_dest.tile == INVALID_TILE) {
2815 /* Reservation failed? */
2816 if (mark_stuck) MarkTrainAsStuck(consist);
2817 if (changed_signal) SetSignalStateByTrackdir(tile, TrackEnterdirToTrackdir(best_track, enterdir), SignalState::Red);
2818 return FindFirstTrack(tracks);
2819 }
2820 if (res_dest.okay) {
2821 /* Got a valid reservation that ends at a safe target, quick exit. */
2822 if (got_reservation != nullptr) *got_reservation = true;
2823 if (changed_signal) MarkTileDirtyByTile(tile);
2824 TryReserveRailTrack(moving_front->tile, TrackdirToTrack(moving_front->GetVehicleTrackdir()));
2825 return best_track;
2826 }
2827
2828 /* Check if the train needs service here, so it has a chance to always find a depot.
2829 * Also check if the current order is a service order so we don't reserve a path to
2830 * the destination but instead to the next one if service isn't needed. */
2831 CheckIfTrainNeedsService(consist);
2832 if (consist->current_order.IsType(OT_DUMMY) || consist->current_order.IsType(OT_CONDITIONAL) || consist->current_order.IsType(OT_GOTO_DEPOT)) ProcessOrders(consist);
2833 }
2834
2835 /* Save the current train order. The destructor will restore the old order on function exit. */
2836 VehicleOrderSaver orders(consist);
2837
2838 /* If the current tile is the destination of the current order and
2839 * a reservation was requested, advance to the next order.
2840 * Don't advance on a depot order as depots are always safe end points
2841 * for a path and no look-ahead is necessary. This also avoids a
2842 * problem with depot orders not part of the order list when the
2843 * order list itself is empty. */
2844 if (consist->current_order.IsType(OT_LEAVESTATION)) {
2845 orders.SwitchToNextOrder(false);
2846 } else if (consist->current_order.IsType(OT_LOADING) || (!consist->current_order.IsType(OT_GOTO_DEPOT) && (
2847 consist->current_order.IsType(OT_GOTO_STATION) ?
2848 IsRailStationTile(moving_front->tile) && consist->current_order.GetDestination() == GetStationIndex(moving_front->tile) :
2849 moving_front->tile == consist->dest_tile))) {
2850 orders.SwitchToNextOrder(true);
2851 }
2852
2853 if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
2854 /* Pathfinders are able to tell that route was only 'guessed'. */
2855 bool path_found = true;
2856 TileIndex new_tile = res_dest.tile;
2857
2858 Track next_track = DoTrainPathfind(consist, new_tile, dest_enterdir, tracks, path_found, do_track_reservation, &res_dest, &final_dest);
2859 if (new_tile == tile) best_track = next_track;
2860 consist->HandlePathfindingResult(path_found);
2861 }
2862
2863 /* No track reservation requested -> finished. */
2864 if (!do_track_reservation) return best_track;
2865
2866 /* A path was found, but could not be reserved. */
2867 if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
2868 if (mark_stuck) MarkTrainAsStuck(consist);
2870 return best_track;
2871 }
2872
2873 /* No possible reservation target found, we are probably lost. */
2874 if (res_dest.tile == INVALID_TILE) {
2875 /* Try to find any safe destination. */
2876 PBSTileInfo origin = FollowTrainReservation(consist);
2877 if (TryReserveSafeTrack(consist, origin.tile, origin.trackdir, false)) {
2878 TrackBits res = GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir);
2879 best_track = FindFirstTrack(res);
2880 TryReserveRailTrack(moving_front->tile, TrackdirToTrack(moving_front->GetVehicleTrackdir()));
2881 if (got_reservation != nullptr) *got_reservation = true;
2882 if (changed_signal) MarkTileDirtyByTile(tile);
2883 } else {
2885 if (mark_stuck) MarkTrainAsStuck(consist);
2886 }
2887 return best_track;
2888 }
2889
2890 if (got_reservation != nullptr) *got_reservation = true;
2891
2892 /* Reservation target found and free, check if it is safe. */
2893 while (!IsSafeWaitingPosition(consist, res_dest.tile, res_dest.trackdir, true, _settings_game.pf.forbid_90_deg)) {
2894 /* Extend reservation until we have found a safe position. */
2895 DiagDirection exitdir = TrackdirToExitdir(res_dest.trackdir);
2896 TileIndex next_tile = TileAddByDiagDir(res_dest.tile, exitdir);
2898 if (Rail90DegTurnDisallowed(GetTileRailType(res_dest.tile), GetTileRailType(next_tile))) {
2899 reachable.Reset(TrackCrossesTracks(TrackdirToTrack(res_dest.trackdir)));
2900 }
2901
2902 /* Get next order with destination. */
2903 if (orders.SwitchToNextOrder(true)) {
2904 PBSTileInfo cur_dest;
2905 bool path_found;
2906 DoTrainPathfind(consist, next_tile, exitdir, reachable, path_found, true, &cur_dest, nullptr);
2907 if (cur_dest.tile != INVALID_TILE) {
2908 res_dest = cur_dest;
2909 if (res_dest.okay) continue;
2910 /* Path found, but could not be reserved. */
2912 if (mark_stuck) MarkTrainAsStuck(consist);
2913 if (got_reservation != nullptr) *got_reservation = false;
2914 changed_signal = false;
2915 break;
2916 }
2917 }
2918 /* No order or no safe position found, try any position. */
2919 if (!TryReserveSafeTrack(consist, res_dest.tile, res_dest.trackdir, true)) {
2921 if (mark_stuck) MarkTrainAsStuck(consist);
2922 if (got_reservation != nullptr) *got_reservation = false;
2923 changed_signal = false;
2924 }
2925 break;
2926 }
2927
2928 TryReserveRailTrack(moving_front->tile, TrackdirToTrack(moving_front->GetVehicleTrackdir()));
2929
2930 if (changed_signal) MarkTileDirtyByTile(tile);
2931
2932 orders.Restore();
2933 if (consist->current_order.IsType(OT_GOTO_DEPOT) &&
2935 final_dest != INVALID_TILE && IsRailDepotTile(final_dest)) {
2936 consist->current_order.SetDestination(GetDepotIndex(final_dest));
2937 consist->dest_tile = final_dest;
2938 SetWindowWidgetDirty(WindowClass::VehicleView, consist->index, WID_VV_START_STOP);
2939 }
2940
2941 return best_track;
2942}
2943
2952bool TryPathReserve(Train *consist, bool mark_as_stuck, bool first_tile_okay)
2953{
2954 assert(consist->IsFrontEngine());
2955
2956 const Train *moving_front = consist->GetMovingFront();
2957
2958 /* We have to handle depots specially as the track follower won't look
2959 * at the depot tile itself but starts from the next tile. If we are still
2960 * inside the depot, a depot reservation can never be ours. */
2961 if (moving_front->track == Track::Depot) {
2962 if (HasDepotReservation(moving_front->tile)) {
2963 if (mark_as_stuck) MarkTrainAsStuck(consist);
2964 return false;
2965 } else {
2966 /* Depot not reserved, but the next tile might be. */
2967 TileIndex next_tile = TileAddByDiagDir(moving_front->tile, GetRailDepotDirection(moving_front->tile));
2968 if (HasReservedTracks(next_tile, DiagdirReachesTracks(GetRailDepotDirection(moving_front->tile)))) return false;
2969 }
2970 }
2971
2972 Vehicle *other_train = nullptr;
2973 PBSTileInfo origin = FollowTrainReservation(consist, &other_train);
2974 /* The path we are driving on is already blocked by some other train.
2975 * This can only happen in certain situations when mixing path and
2976 * block signals or when changing tracks and/or signals.
2977 * Exit here as doing any further reservations will probably just
2978 * make matters worse. */
2979 if (other_train != nullptr && other_train->index != consist->index) {
2980 if (mark_as_stuck) MarkTrainAsStuck(consist);
2981 return false;
2982 }
2983 /* If we have a reserved path and the path ends at a safe tile, we are finished already. */
2984 if (origin.okay && (moving_front->tile != origin.tile || first_tile_okay)) {
2985 /* Can't be stuck then. */
2986 if (consist->flags.Test(VehicleRailFlag::Stuck)) SetWindowWidgetDirty(WindowClass::VehicleView, consist->index, WID_VV_START_STOP);
2988 return true;
2989 }
2990
2991 /* If we are in a depot, tentatively reserve the depot. */
2992 if (moving_front->track == Track::Depot) {
2993 SetDepotReservation(moving_front->tile, true);
2994 if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(moving_front->tile);
2995 }
2996
2997 DiagDirection exitdir = TrackdirToExitdir(origin.trackdir);
2998 TileIndex new_tile = TileAddByDiagDir(origin.tile, exitdir);
3000
3002
3003 bool res_made = false;
3004 ChooseTrainTrack(consist, new_tile, exitdir, reachable, true, &res_made, mark_as_stuck);
3005
3006 if (!res_made) {
3007 /* Free the depot reservation as well. */
3008 if (moving_front->track == Track::Depot) SetDepotReservation(moving_front->tile, false);
3009 return false;
3010 }
3011
3012 if (consist->flags.Test(VehicleRailFlag::Stuck)) {
3013 consist->wait_counter = 0;
3014 SetWindowWidgetDirty(WindowClass::VehicleView, consist->index, WID_VV_START_STOP);
3015 }
3017 return true;
3018}
3019
3025static bool CheckReverseTrain(const Train *consist)
3026{
3027 const Train *moving_front = consist->GetMovingFront();
3028 if (_settings_game.difficulty.train_flip_reverse_allowed == TrainFlipReversingAllowed::EndOfLineOnly ||
3029 moving_front->track == Track::Depot || moving_front->track == Track::Wormhole ||
3030 !IsDiagonalDirection(moving_front->GetMovingDirection())) {
3031 return false;
3032 }
3033
3034 assert(moving_front->track.Any());
3035
3036 return YapfTrainCheckReverse(consist);
3037}
3038
3045{
3046 if (station == this->last_station_visited) this->last_station_visited = StationID::Invalid();
3047
3048 const Station *st = Station::Get(station);
3050 /* The destination station has no trainstation tiles. */
3052 return TileIndex{};
3053 }
3054
3055 return st->xy;
3056}
3057
3060{
3061 Train *v = this;
3062 do {
3063 v->colourmap = PAL_NONE;
3064 v->UpdateViewport(true, false);
3065 } while ((v = v->Next()) != nullptr);
3066
3067 /* need to update acceleration and cached values since the goods on the train changed. */
3068 this->ConsistChanged({});
3069 this->UpdateAcceleration();
3070}
3071
3080{
3081 switch (_settings_game.vehicle.train_acceleration_model) {
3082 default: NOT_REACHED();
3084 return this->DoUpdateSpeed(this->acceleration * (this->GetAccelerationStatus() == AS_BRAKE ? -4 : 2), 0, this->GetCurrentMaxSpeed());
3085
3087 return this->DoUpdateSpeed(this->GetAcceleration(), this->GetAccelerationStatus() == AS_BRAKE ? 0 : 2, this->GetCurrentMaxSpeed());
3088 }
3089}
3090
3096static void TrainEnterStation(Train *consist, StationID station)
3097{
3098 consist->last_station_visited = station;
3099
3100 /* check if a train ever visited this station before */
3101 Station *st = Station::Get(station);
3102 if (!st->had_vehicle_of_type.Test(StationVehicleType::Train)) {
3103 st->had_vehicle_of_type.Set(StationVehicleType::Train);
3105 GetEncodedString(STR_NEWS_FIRST_TRAIN_ARRIVAL, st->index),
3107 consist->index,
3108 st->index
3109 );
3110 AI::NewEvent(consist->owner, new ScriptEventStationFirstVehicle(st->index, consist->index));
3111 Game::NewEvent(new ScriptEventStationFirstVehicle(st->index, consist->index));
3112 }
3113
3114 consist->force_proceed = TFP_NONE;
3115 InvalidateWindowData(WindowClass::VehicleView, consist->index);
3116
3117 consist->BeginLoading();
3118
3119 TileIndex tile = consist->GetMovingFront()->tile;
3121 TriggerStationAnimation(st, tile, StationAnimationTrigger::VehicleArrives);
3122}
3123
3131static inline bool CheckCompatibleRail(const Train *v, TileIndex tile, bool check_railtype)
3132{
3133 return IsTileOwner(tile, v->owner) &&
3134 (!check_railtype || !v->IsFrontEngine() || v->compatible_railtypes.Test(GetRailType(tile)));
3135}
3136
3139 uint8_t small_turn;
3140 uint8_t large_turn;
3141 uint8_t z_up;
3142 uint8_t z_down;
3143};
3144
3147 /* normal accel */
3148 {256 / 4, 256 / 2, 256 / 4, 2},
3149 {256 / 4, 256 / 2, 256 / 4, 2},
3150 {0, 256 / 2, 256 / 4, 2},
3151};
3152
3158static inline void AffectSpeedByZChange(Train *consist, int z_diff)
3159{
3160 if (z_diff == 0 || _settings_game.vehicle.train_acceleration_model != AccelerationModel::Original) return;
3161
3162 const AccelerationSlowdownParams *asp = &_accel_slowdown[static_cast<int>(consist->GetAccelerationType())];
3163
3164 if (z_diff > 0) {
3165 consist->cur_speed -= (consist->cur_speed * asp->z_up >> 8);
3166 } else {
3167 uint16_t spd = consist->cur_speed + asp->z_down;
3168 if (spd <= consist->gcache.cached_max_track_speed) consist->cur_speed = spd;
3169 }
3170}
3171
3172static bool TrainMovedChangeSignals(TileIndex tile, DiagDirection dir)
3173{
3174 if (IsTileType(tile, TileType::Railway) &&
3177 Trackdir trackdir = FindFirstTrackdir(tracks);
3178 if (UpdateSignalsOnSegment(tile, TrackdirToExitdir(trackdir), GetTileOwner(tile)) == SigSegState::Path && HasSignalOnTrackdir(tile, trackdir)) {
3179 /* A PBS block with a non-PBS signal facing us? */
3180 if (!IsPbsSignal(GetSignalType(tile, TrackdirToTrack(trackdir)))) return true;
3181 }
3182 }
3183 return false;
3184}
3185
3188{
3189 for (const Train *u = this; u != nullptr; u = u->Next()) {
3190 switch (u->track.base()) {
3191 case TrackBits{Track::Wormhole}.base():
3193 break;
3194 case TrackBits{Track::Depot}.base():
3195 break;
3196 default:
3198 break;
3199 }
3200 }
3201}
3202
3209uint Train::Crash(bool flooded)
3210{
3211 uint victims = 0;
3212 if (this->IsFrontEngine()) {
3213 victims += 2; // driver
3214
3215 /* Remove the reserved path in front of the train if it is not stuck.
3216 * Also clear all reserved tracks the train is currently on. */
3218 for (const Train *v = this; v != nullptr; v = v->Next()) {
3221 /* ClearPathReservation will not free the wormhole exit
3222 * if the train has just entered the wormhole. */
3224 }
3225 }
3226
3227 /* we may need to update crossing we were approaching,
3228 * but must be updated after the train has been marked crashed */
3230 if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
3231
3232 /* Remove the loading indicators (if any) */
3234 }
3235
3236 victims += this->GroundVehicleBase::Crash(flooded);
3237
3238 this->crash_anim_pos = flooded ? 4000 : 1; // max 4440, disappear pretty fast when flooded
3239 return victims;
3240}
3241
3248static uint TrainCrashed(Train *v)
3249{
3250 uint victims = 0;
3251
3252 /* do not crash train twice */
3253 if (!v->vehstatus.Test(VehState::Crashed)) {
3254 victims = v->Crash();
3255 TileIndex tile = v->GetMovingFront()->tile;
3256 AI::NewEvent(v->owner, new ScriptEventVehicleCrashed(v->index, tile, ScriptEventVehicleCrashed::CRASH_TRAIN, victims, v->owner));
3257 Game::NewEvent(new ScriptEventVehicleCrashed(v->index, tile, ScriptEventVehicleCrashed::CRASH_TRAIN, victims, v->owner));
3258 }
3259
3260 return victims;
3261}
3262
3269static uint TrainsCrashed(Train *v, Train *u)
3270{
3271 /* Crash both trains. Two statements required to guarantee execution
3272 * order because RandomRange() is involved. */
3273 uint victims = TrainCrashed(v);
3274 victims += TrainCrashed(u);
3275
3276 /* Try to re-reserve track under already crashed train too.
3277 * Crash() in TrainCrashed() clears the reservation! */
3280
3281 return victims;
3282}
3283
3290static uint CheckTrainCollision(Vehicle *v, Train *moving_front)
3291{
3292 /* Make sure we are a train, and are not in a depot. */
3293 if (v->type != VehicleType::Train) return 0;
3294
3295 /* We can't crash into trains in a depot. */
3296 if (Train::From(v)->track == Track::Depot) return 0;
3297
3298 /* Do not crash into trains of another company. */
3299 if (v->owner != moving_front->First()->owner) return 0;
3300
3301 /* Do not collide with our own wagons */
3302 if (v->First() == moving_front->First()) return 0;
3303
3304 int x_diff = v->x_pos - moving_front->x_pos;
3305 int y_diff = v->y_pos - moving_front->y_pos;
3306
3307 /* Do fast calculation to check whether trains are not in close vicinity
3308 * and quickly reject trains distant enough for any collision.
3309 * Differences are shifted by 7, mapping range [-7 .. 8] into [0 .. 15]
3310 * Differences are then ORed and then we check for any higher bits */
3311 uint hash = (y_diff + 7) | (x_diff + 7);
3312 if (hash & ~15) return 0;
3313
3314 /* Slower check using multiplication */
3315 int min_diff = (Train::From(v)->gcache.cached_veh_length + 1) / 2 + (moving_front->gcache.cached_veh_length + 1) / 2 - 1;
3316 if (x_diff * x_diff + y_diff * y_diff > min_diff * min_diff) return 0;
3317
3318 /* Happens when there is a train under bridge next to bridge head */
3319 if (abs(v->z_pos - moving_front->z_pos) > 5) return 0;
3320
3321 return TrainsCrashed(moving_front->First(), Train::From(v)->First());
3322}
3323
3332static bool CheckTrainCollision(Train *moving_front)
3333{
3334 /* can't collide in depot */
3335 if (moving_front->track == Track::Depot) return false;
3336
3337 assert(moving_front->track == Track::Wormhole || TileVirtXY(moving_front->x_pos, moving_front->y_pos) == moving_front->tile);
3338
3339 uint num_victims = 0;
3340
3341 /* find colliding vehicles */
3342 if (moving_front->track == Track::Wormhole) {
3343 for (Vehicle *u : VehiclesOnTile(moving_front->tile)) {
3344 num_victims += CheckTrainCollision(u, moving_front);
3345 }
3346 for (Vehicle *u : VehiclesOnTile(GetOtherTunnelBridgeEnd(moving_front->tile))) {
3347 num_victims += CheckTrainCollision(u, moving_front);
3348 }
3349 } else {
3350 for (Vehicle *u : VehiclesNearTileXY(moving_front->x_pos, moving_front->y_pos, 7)) {
3351 num_victims += CheckTrainCollision(u, moving_front);
3352 }
3353 }
3354
3355 /* any dead -> no crash */
3356 if (num_victims == 0) return false;
3357
3358 AddTileNewsItem(GetEncodedString(STR_NEWS_TRAIN_CRASH, num_victims), NewsType::Accident, moving_front->tile);
3359
3360 ModifyStationRatingAround(moving_front->tile, moving_front->First()->owner, -160, 30);
3361 if (_settings_client.sound.disaster) SndPlayVehicleFx(SND_13_TRAIN_COLLISION, moving_front);
3362 return true;
3363}
3364
3372bool TrainController(Train *v, Vehicle *nomove, bool reverse)
3373{
3374 Train *first = v->First();
3375 Train *prev;
3376 bool direction_changed = false; // has direction of any part changed?
3377
3378 /* For every vehicle after and including the given vehicle */
3379 for (prev = v->GetMovingPrev(); v != nomove; prev = v, v = v->GetMovingNext()) {
3381 bool update_signals_crossing = false; // will we update signals or crossing state?
3382
3384 if (v->track != Track::Wormhole) {
3385 /* Not inside tunnel */
3386 if (gp.old_tile == gp.new_tile) {
3387 /* Staying in the old tile */
3388 if (v->track == Track::Depot) {
3389 /* Inside depot */
3390 gp.x = v->x_pos;
3391 gp.y = v->y_pos;
3392 } else {
3393 /* Not inside depot */
3394
3395 /* Reverse when we are at the end of the track already, do not move to the new position */
3396 if (v->IsMovingFront() && !TrainCheckIfLineEnds(v, reverse)) return false;
3397
3398 auto vets = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
3399 if (vets.Test(VehicleEnterTileState::CannotEnter)) {
3400 goto invalid_rail;
3401 }
3403 /* The new position is the end of the platform */
3405 }
3406 }
3407 } else {
3408 /* A new tile is about to be entered. */
3409
3410 /* Determine what direction we're entering the new tile from */
3411 enterdir = DiagdirBetweenTiles(gp.old_tile, gp.new_tile);
3412 assert(IsValidDiagDirection(enterdir));
3413
3414 /* Get the status of the tracks in the new tile and mask
3415 * away the bits that aren't reachable. */
3417 TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(enterdir);
3418
3419 TrackdirBits trackdirbits = ts.trackdirs & reachable_trackdirs;
3420 TrackBits red_signals = TrackdirBitsToTrackBits(ts.signals & reachable_trackdirs);
3421
3422 TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
3423 if (Rail90DegTurnDisallowed(GetTileRailType(gp.old_tile), GetTileRailType(gp.new_tile)) && prev == nullptr) {
3424 /* We allow wagons to make 90 deg turns, because forbid_90_deg
3425 * can be switched on halfway a turn */
3427 }
3428
3429 if (bits.None()) goto invalid_rail;
3430
3431 /* Check if the new tile constrains tracks that are compatible
3432 * with the current train, if not, bail out. */
3433 if (!CheckCompatibleRail(v->First(), gp.new_tile, v->IsMovingFront())) goto invalid_rail;
3434
3435 TrackBits chosen_track;
3436 if (v->IsMovingFront()) {
3437 /* Currently the locomotive is active. Determine which one of the
3438 * available tracks to choose */
3439 chosen_track = ChooseTrainTrack(first, gp.new_tile, enterdir, bits, false, nullptr, true);
3440 assert(chosen_track.Any(bits | GetReservedTrackbits(gp.new_tile)));
3441
3442 if (first->force_proceed != TFP_NONE && IsPlainRailTile(gp.new_tile) && HasSignals(gp.new_tile)) {
3443 /* For each signal we find decrease the counter by one.
3444 * We start at two, so the first signal we pass decreases
3445 * this to one, then if we reach the next signal it is
3446 * decreased to zero and we won't pass that new signal. */
3447 Trackdir dir = FindFirstTrackdir(trackdirbits);
3448 if (HasSignalOnTrackdir(gp.new_tile, dir) ||
3451 /* However, we do not want to be stopped by PBS signals
3452 * entered via the back. */
3453 first->force_proceed = (first->force_proceed == TFP_SIGNAL) ? TFP_STUCK : TFP_NONE;
3454 InvalidateWindowData(WindowClass::VehicleView, first->index);
3455 }
3456 }
3457
3458 /* Check if it's a red signal and that force proceed is not clicked. */
3459 if (red_signals.Any(chosen_track) && first->force_proceed == TFP_NONE) {
3460 /* In front of a red signal */
3461 Trackdir i = FindFirstTrackdir(trackdirbits);
3462
3463 /* Don't handle stuck trains here. */
3464 if (first->flags.Test(VehicleRailFlag::Stuck)) return false;
3465
3467 first->cur_speed = 0;
3468 first->subspeed = 0;
3469 first->progress = 255; // make sure that every bit of acceleration will hit the signal again, so speed stays 0.
3470 if (!_settings_game.pf.reverse_at_signals || ++first->wait_counter < _settings_game.pf.wait_oneway_signal * Ticks::DAY_TICKS * 2) return false;
3471 } else if (HasSignalOnTrackdir(gp.new_tile, i)) {
3472 first->cur_speed = 0;
3473 first->subspeed = 0;
3474 first->progress = 255; // make sure that every bit of acceleration will hit the signal again, so speed stays 0.
3475 if (!_settings_game.pf.reverse_at_signals || ++first->wait_counter < _settings_game.pf.wait_twoway_signal * Ticks::DAY_TICKS * 2) {
3476 DiagDirection exitdir = TrackdirToExitdir(i);
3477 TileIndex o_tile = TileAddByDiagDir(gp.new_tile, exitdir);
3478
3479 exitdir = ReverseDiagDir(exitdir);
3480
3481 /* check if a train is waiting on the other side */
3482 if (!HasVehicleOnTile(o_tile, [&exitdir](const Vehicle *u) {
3483 if (u->type != VehicleType::Train || u->vehstatus.Test(VehState::Crashed)) return false;
3484 const Train *t = Train::From(u);
3485
3486 /* not front engine of a train, inside wormhole or depot, crashed */
3487 if (!t->IsFrontEngine() || t->track.Any({Track::Wormhole, Track::Depot})) return false;
3488
3489 if (t->cur_speed > 5 || VehicleExitDir(t->direction, t->track) != exitdir) return false;
3490
3491 return true;
3492 })) return false;
3493 }
3494 }
3495
3496 /* If we would reverse but are currently in a PBS block and
3497 * reversing of stuck trains is disabled, don't reverse.
3498 * This does not apply if the reason for reversing is a one-way
3499 * signal blocking us, because a train would then be stuck forever. */
3500 if (!_settings_game.pf.reverse_at_signals && !HasOnewaySignalBlockingTrackdir(gp.new_tile, i) &&
3501 UpdateSignalsOnSegment(v->tile, enterdir, v->owner) == SigSegState::Path) {
3502 first->wait_counter = 0;
3503 return false;
3504 }
3505 goto reverse_train_direction;
3506 } else {
3507 TryReserveRailTrack(gp.new_tile, TrackBitsToTrack(chosen_track), false);
3508 }
3509 } else {
3510 /* The wagon is active, simply follow the prev vehicle. */
3511 if (prev->tile == gp.new_tile) {
3512 /* Choose the same track as prev */
3513 if (prev->track == Track::Wormhole) {
3514 /* Vehicles entering tunnels enter the wormhole earlier than for bridges.
3515 * However, just choose the track into the wormhole. */
3516 assert(IsTunnel(prev->tile));
3517 chosen_track = bits;
3518 } else {
3519 chosen_track = prev->track;
3520 }
3521 } else {
3522 /* Choose the track that leads to the tile where prev is.
3523 * This case is active if 'prev' is already on the second next tile, when 'v' just enters the next tile.
3524 * I.e. when the tile between them has only space for a single vehicle like
3525 * 1) horizontal/vertical track tiles and
3526 * 2) some orientations of tunnel entries, where the vehicle is already inside the wormhole at 8/16 from the tile edge.
3527 * Is also the train just reversing, the wagon inside the tunnel is 'on' the tile of the opposite tunnel entry.
3528 */
3529 static const DiagDirectionIndexArray<DiagDirectionIndexArray<TrackBits>> _connecting_track{{{
3530 {{{Track::X, Track::Lower, {}, Track::Left }}},
3531 {{{Track::Upper, Track::Y, Track::Left, {} }}},
3534 }}};
3535 DiagDirection exitdir = DiagdirBetweenTiles(gp.new_tile, prev->tile);
3536 assert(IsValidDiagDirection(exitdir));
3537 chosen_track = _connecting_track[enterdir][exitdir];
3538 }
3539 chosen_track &= bits;
3540 }
3541
3542 /* Update XY to reflect the entrance to the new tile, and select the direction to use */
3543 Direction chosen_dir = VehicleEnterTileCoordinates(gp, enterdir, TrackBitsToTrack(chosen_track));
3544
3545 /* Call the landscape function and tell it that the vehicle entered the tile */
3546 auto vets = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
3547 if (vets.Test(VehicleEnterTileState::CannotEnter)) {
3548 goto invalid_rail;
3549 }
3550
3552 Track track = FindFirstTrack(chosen_track);
3553 Trackdir tdir = TrackDirectionToTrackdir(track, chosen_dir);
3554 if (v->IsMovingFront() && HasPbsSignalOnTrackdir(gp.new_tile, tdir)) {
3557 }
3558
3559 /* Clear any track reservation when the last vehicle leaves the tile */
3560 if (v->GetMovingNext() == nullptr) ClearPathReservation(v, v->tile, v->GetVehicleTrackdir());
3561
3562 v->tile = gp.new_tile;
3563
3565 first->ConsistChanged(CCF_TRACK);
3566 }
3567
3568 v->track = chosen_track;
3569 assert(v->track.Any());
3570 }
3571
3572 /* We need to update signal status, but after the vehicle position hash
3573 * has been updated by UpdateInclination() */
3574 update_signals_crossing = true;
3575
3576 if (chosen_dir != v->GetMovingDirection()) {
3577 if (prev == nullptr && _settings_game.vehicle.train_acceleration_model == AccelerationModel::Original) {
3578 const AccelerationSlowdownParams *asp = &_accel_slowdown[static_cast<int>(v->GetAccelerationType())];
3579 DirDiff diff = DirDifference(v->direction, chosen_dir);
3580 v->cur_speed -= (diff == DirDiff::Right45 || diff == DirDiff::Left45 ? asp->small_turn : asp->large_turn) * v->cur_speed >> 8;
3581 }
3582 direction_changed = true;
3583 v->SetMovingDirection(chosen_dir);
3584 }
3585
3586 if (v->IsMovingFront()) {
3587 first->wait_counter = 0;
3588
3589 /* If we are approaching a crossing that is reserved, play the sound now. */
3590 TileIndex crossing = TrainApproachingCrossingTile(v); // We know we are the moving front, so we can check v.
3591 if (crossing != INVALID_TILE && HasCrossingReservation(crossing) && _settings_client.sound.ambient) SndPlayTileFx(SND_0E_LEVEL_CROSSING, crossing);
3592
3593 /* Always try to extend the reservation when entering a tile. */
3594 CheckNextTrainTile(first);
3595 }
3596
3598 /* The new position is the location where we want to stop */
3600 }
3601 }
3602 } else {
3604 /* Perform look-ahead on tunnel exit. */
3605 if (v->IsMovingFront()) {
3607 CheckNextTrainTile(first);
3608 }
3609 /* Prevent v->UpdateInclination() being called with wrong parameters.
3610 * This could happen if the train was reversed inside the tunnel/bridge. */
3611 if (gp.old_tile == gp.new_tile) {
3613 }
3614 } else {
3615 v->x_pos = gp.x;
3616 v->y_pos = gp.y;
3617 v->UpdatePosition();
3618 if (!v->vehstatus.Test(VehState::Hidden)) v->Vehicle::UpdateViewport(true);
3619 continue;
3620 }
3621 }
3622
3623 /* update image of train, as well as delta XY */
3624 v->UpdateDeltaXY();
3625
3626 v->x_pos = gp.x;
3627 v->y_pos = gp.y;
3628 v->UpdatePosition();
3629
3630 /* update the Z position of the vehicle */
3631 int old_z = v->UpdateInclination(gp.new_tile != gp.old_tile, false);
3632
3633 if (prev == nullptr) {
3634 /* This is the first vehicle in the train */
3635 AffectSpeedByZChange(first, v->z_pos - old_z);
3636 }
3637
3638 if (update_signals_crossing) {
3639 if (v->IsMovingFront()) {
3640 if (TrainMovedChangeSignals(gp.new_tile, enterdir)) {
3641 /* We are entering a block with PBS signals right now, but
3642 * not through a PBS signal. This means we don't have a
3643 * reservation right now. As a conventional signal will only
3644 * ever be green if no other train is in the block, getting
3645 * a path should always be possible. If the player built
3646 * such a strange network that it is not possible, the train
3647 * will be marked as stuck and the player has to deal with
3648 * the problem. */
3649 if ((!HasReservedTracks(gp.new_tile, v->track) &&
3651 !TryPathReserve(first)) {
3652 MarkTrainAsStuck(first);
3653 }
3654 }
3655 }
3656
3657 /* Signals can only change when the first
3658 * (above) or the last vehicle moves. */
3659 if (v->GetMovingNext() == nullptr) {
3660 TrainMovedChangeSignals(gp.old_tile, ReverseDiagDir(enterdir));
3662 }
3663 }
3664
3665 /* Do not check on every tick to save some computing time. */
3666 if (v->IsMovingFront() && first->tick_counter % _settings_game.pf.path_backoff_interval == 0) CheckNextTrainTile(first);
3667 }
3668
3669 if (direction_changed) first->tcache.cached_max_curve_speed = first->GetCurveSpeedLimit();
3670
3671 return true;
3672
3673invalid_rail:
3674 /* We've reached end of line?? */
3675 if (prev != nullptr) FatalError("Disconnecting train");
3676
3677reverse_train_direction:
3678 if (reverse) {
3679 first->wait_counter = 0;
3680 first->cur_speed = 0;
3681 first->subspeed = 0;
3682 ReverseTrainDirection(first);
3683 }
3684
3685 return false;
3686}
3687
3688static bool IsRailStationPlatformOccupied(TileIndex tile)
3689{
3691
3692 for (TileIndex t = tile; IsCompatibleTrainStationTile(t, tile); t -= delta) {
3693 if (HasVehicleOnTile(t, IsTrain)) return true;
3694 }
3695 for (TileIndex t = tile + delta; IsCompatibleTrainStationTile(t, tile); t += delta) {
3696 if (HasVehicleOnTile(t, IsTrain)) return true;
3697 }
3698
3699 return false;
3700}
3701
3709static void DeleteLastWagon(Train *v)
3710{
3711 Train *first = v->First();
3712
3713 /* Go to the last wagon and delete the link pointing there
3714 * new_last is then the one-before-last wagon, and v the last
3715 * one which will physically be removed */
3716 Train *new_last = v;
3717 for (; v->Next() != nullptr; v = v->Next()) new_last = v;
3718 new_last->SetNext(nullptr);
3719
3720 if (first != v) {
3721 /* Recalculate cached train properties */
3723 /* Update the depot window in case a part of the consist is in a depot. */
3724 SetWindowDirty(WindowClass::VehicleDepot, first->tile);
3725 SetWindowDirty(WindowClass::VehicleDepot, v->tile);
3726 }
3727
3728 /* 'v' shouldn't be accessed after it has been deleted */
3729 TrackBits trackbits = v->track;
3730 TileIndex tile = v->tile;
3731 Owner owner = v->owner;
3732
3733 delete v;
3734 v = nullptr; // make sure nobody will try to read 'v' anymore
3735
3736 if (trackbits == Track::Wormhole) {
3737 /* Vehicle is inside a wormhole, v->track contains no useful value then. */
3739 }
3740
3741 if (trackbits != Track::Depot && HasReservedTracks(tile, trackbits)) {
3742 Track track = TrackBitsToTrack(trackbits);
3743 UnreserveRailTrack(tile, track);
3744
3745 /* If there are still crashed vehicles on the tile, give the track reservation to them */
3746 TrackBits remaining_trackbits{};
3747 for (const Vehicle *u : VehiclesOnTile(tile)) {
3748 if (u->type != VehicleType::Train || !u->vehstatus.Test(VehState::Crashed)) continue;
3749 TrackBits train_tbits = Train::From(u)->track;
3750 if (train_tbits == Track::Wormhole) {
3751 /* Vehicle is inside a wormhole, u->track contains no useful value then. */
3752 remaining_trackbits.Set(DiagDirToDiagTrack(GetTunnelBridgeDirection(u->tile)));
3753 } else if (train_tbits != Track::Depot) {
3754 remaining_trackbits.Set(train_tbits);
3755 }
3756 }
3757
3758 /* It is important that these two are the first in the loop, as reservation cannot deal with every trackbit combination */
3760 for (Track t : remaining_trackbits) TryReserveRailTrack(tile, t);
3761 }
3762
3763 /* check if the wagon was on a road/rail-crossing */
3765
3766 if (IsRailStationTile(tile)) {
3767 bool occupied = IsRailStationPlatformOccupied(tile);
3769 SetRailStationPlatformReservation(tile, dir, occupied);
3771 }
3772
3773 /* Update signals */
3776 } else {
3777 SetSignalsOnBothDir(tile, TrackBitsToTrack(trackbits), owner);
3778 }
3779}
3780
3786{
3787 static const DirDiff delta[] = {
3789 };
3790
3791 do {
3792 /* We don't need to twist around vehicles if they're not visible */
3793 if (!v->vehstatus.Test(VehState::Hidden)) {
3794 v->direction = ChangeDir(v->direction, delta[GB(Random(), 0, 2)]);
3795 /* Refrain from updating the z position of the vehicle when on
3796 * a bridge, because UpdateInclination() will put the vehicle under
3797 * the bridge in that case */
3798 if (v->track != Track::Wormhole) {
3799 v->UpdatePosition();
3800 v->UpdateInclination(false, true);
3801 } else {
3802 v->UpdateViewport(false, true);
3803 }
3804 }
3805 } while ((v = v->Next()) != nullptr);
3806}
3807
3814{
3815 int state = ++v->crash_anim_pos;
3816
3817 if (state == 4 && !v->vehstatus.Test(VehState::Hidden)) {
3819 }
3820
3821 uint32_t r;
3822 if (state <= 200 && Chance16R(1, 7, r)) {
3823 int index = (r * 10 >> 16);
3824
3825 Vehicle *u = v;
3826 do {
3827 if (--index < 0) {
3828 r = Random();
3829
3831 GB(r, 8, 3) + 2,
3832 GB(r, 16, 3) + 2,
3833 GB(r, 0, 3) + 5,
3835 break;
3836 }
3837 } while ((u = u->Next()) != nullptr);
3838 }
3839
3840 if (state <= 240 && !(v->tick_counter & 3)) ChangeTrainDirRandomly(v);
3841
3842 if (state >= 4440 && !(v->tick_counter & 0x1F)) {
3843 bool ret = v->Next() != nullptr;
3844 DeleteLastWagon(v);
3845 return ret;
3846 }
3847
3848 return true;
3849}
3850
3852static const uint16_t _breakdown_speeds[16] = {
3853 225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, 15
3854};
3855
3856
3865static bool TrainApproachingLineEnd(Train *moving_front, bool signal, bool reverse)
3866{
3867 /* Calc position within the current tile */
3868 uint x = moving_front->x_pos & 0xF;
3869 uint y = moving_front->y_pos & 0xF;
3870
3871 Direction vdir = moving_front->GetMovingDirection();
3872
3873 /* for diagonal directions, 'x' will be 0..15 -
3874 * for other directions, it will be 1, 3, 5, ..., 15 */
3875 switch (vdir) {
3876 case Direction::N : x = ~x + ~y + 25; break;
3877 case Direction::NW: x = y; [[fallthrough]];
3878 case Direction::NE: x = ~x + 16; break;
3879 case Direction::E : x = ~x + y + 9; break;
3880 case Direction::SE: x = y; break;
3881 case Direction::S : x = x + y - 7; break;
3882 case Direction::W : x = ~y + x + 9; break;
3883 default: break;
3884 }
3885
3886 Train *consist = moving_front->First();
3887
3888 /* Do not reverse when approaching red signal. Make sure the vehicle's front
3889 * does not cross the tile boundary when we do reverse, but as the vehicle's
3890 * location is based on their center, use half a vehicle's length as offset.
3891 * Multiply the half-length by two for straight directions to compensate that
3892 * we only get odd x offsets there. */
3893 uint8_t rounding = moving_front->IsDrivingBackwards() ? 0 : 1;
3894 if (!signal && x + (moving_front->gcache.cached_veh_length + rounding) / 2 * (IsDiagonalDirection(vdir) ? 1 : 2) >= TILE_SIZE) {
3895 /* we are too near the tile end, reverse now */
3896 consist->cur_speed = 0;
3897 if (reverse) ReverseTrainDirection(consist);
3898 return false;
3899 }
3900
3901 /* slow down */
3903 uint16_t break_speed = _breakdown_speeds[x & 0xF];
3904 if (break_speed < consist->cur_speed) consist->cur_speed = break_speed;
3905
3906 return true;
3907}
3908
3909
3915static bool TrainCanLeaveTile(const Train *moving_front)
3916{
3917 /* Exit if inside a tunnel/bridge or a depot */
3918 if (moving_front->track == Track::Wormhole || moving_front->track == Track::Depot) return false;
3919
3920 TileIndex tile = moving_front->tile;
3921
3922 /* entering a tunnel/bridge? */
3925 if (DiagDirToDir(dir) == moving_front->GetMovingDirection()) return false;
3926 }
3927
3928 /* entering a depot? */
3929 if (IsRailDepotTile(tile)) {
3931 if (DiagDirToDir(dir) == moving_front->GetMovingDirection()) return false;
3932 }
3933
3934 return true;
3935}
3936
3937
3946{
3947 assert(moving_front->IsMovingFront());
3948 assert(!moving_front->First()->vehstatus.Test(VehState::Crashed));
3949
3950 if (!TrainCanLeaveTile(moving_front)) return INVALID_TILE;
3951
3952 DiagDirection dir = VehicleExitDir(moving_front->GetMovingDirection(), moving_front->track);
3953 TileIndex tile = moving_front->tile + TileOffsByDiagDir(dir);
3954
3955 /* not a crossing || wrong axis || unusable rail (wrong type or owner) */
3956 if (!IsLevelCrossingTile(tile) || DiagDirToAxis(dir) == GetCrossingRoadAxis(tile) ||
3957 !CheckCompatibleRail(moving_front->First(), tile, true)) {
3958 return INVALID_TILE;
3959 }
3960
3961 return tile;
3962}
3963
3964
3972static bool TrainCheckIfLineEnds(Train *moving_front, bool reverse)
3973{
3974 /* First, handle broken down train */
3975
3976 Train *consist = moving_front->First();
3977 int t = consist->breakdown_ctr;
3978 if (t > 1) {
3980
3981 uint16_t break_speed = _breakdown_speeds[GB(~t, 4, 4)];
3982 if (break_speed < consist->cur_speed) consist->cur_speed = break_speed;
3983 } else {
3985 }
3986
3987 if (!TrainCanLeaveTile(moving_front)) return true;
3988
3989 /* Determine the non-diagonal direction in which we will exit this tile */
3990 DiagDirection dir = VehicleExitDir(moving_front->GetMovingDirection(), moving_front->track);
3991 /* Calculate next tile */
3992 TileIndex tile = moving_front->tile + TileOffsByDiagDir(dir);
3993
3994 /* Determine the track status on the next tile */
3996 TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(dir);
3997
3998 TrackdirBits trackdirbits = ts.trackdirs & reachable_trackdirs;
3999 TrackdirBits red_signals = ts.signals & reachable_trackdirs;
4000
4001 /* We are sure the train is not entering a depot, it is detected above */
4002
4003 /* mask unreachable track bits if we are forbidden to do 90deg turns */
4004 TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
4005 if (Rail90DegTurnDisallowed(GetTileRailType(moving_front->tile), GetTileRailType(tile))) {
4006 bits.Reset(TrackCrossesTracks(FindFirstTrack(moving_front->track)));
4007 }
4008
4009 /* no suitable trackbits at all || unusable rail (wrong type or owner) */
4010 if (bits.None() || !CheckCompatibleRail(consist, tile, true)) {
4011 return TrainApproachingLineEnd(moving_front, false, reverse);
4012 }
4013
4014 /* approaching red signal */
4015 if (trackdirbits.Any(red_signals)) return TrainApproachingLineEnd(moving_front, true, reverse);
4016
4017 /* approaching a rail/road crossing? then make it red */
4019
4020 return true;
4021}
4022
4029static bool TrainLocoHandler(Train *consist, bool mode)
4030{
4031 /* train has crashed? */
4032 if (consist->vehstatus.Test(VehState::Crashed)) {
4033 return mode ? true : HandleCrashedTrain(consist); // 'this' can be deleted here
4034 }
4035
4036 if (consist->force_proceed != TFP_NONE) {
4038 SetWindowWidgetDirty(WindowClass::VehicleView, consist->index, WID_VV_START_STOP);
4039 }
4040
4041 /* train is broken down? */
4042 if (consist->HandleBreakdown()) return true;
4043
4044 if (consist->flags.Test(VehicleRailFlag::Reversing) && consist->cur_speed == 0) {
4045 ReverseTrainDirection(consist);
4046 }
4047
4048 /* exit if train is stopped */
4049 if (consist->vehstatus.Test(VehState::Stopped) && consist->cur_speed == 0) return true;
4050
4051 bool valid_order = !consist->current_order.IsType(OT_NOTHING) && consist->current_order.GetType() != OT_CONDITIONAL;
4052 if (ProcessOrders(consist) && CheckReverseTrain(consist)) {
4053 consist->wait_counter = 0;
4054 consist->cur_speed = 0;
4055 consist->subspeed = 0;
4057 ReverseTrainDirection(consist);
4058 return true;
4059 } else if (consist->flags.Test(VehicleRailFlag::LeavingStation)) {
4060 /* Try to reserve a path when leaving the station as we
4061 * might not be marked as wanting a reservation, e.g.
4062 * when an overlength train gets turned around in a station. */
4063 const Train *moving_front = consist->GetMovingFront();
4064 DiagDirection dir = VehicleExitDir(moving_front->GetMovingDirection(), moving_front->track);
4065 if (IsRailDepotTile(moving_front->tile) || IsTileType(moving_front->tile, TileType::TunnelBridge)) dir = DiagDirection::Invalid;
4066
4067 if (UpdateSignalsOnSegment(moving_front->tile, dir, consist->owner) == SigSegState::Path || _settings_game.pf.reserve_paths) {
4068 TryPathReserve(consist, true, true);
4069 }
4071 }
4072
4073 consist->HandleLoading(mode);
4074
4075 if (consist->current_order.IsType(OT_LOADING)) return true;
4076
4077 if (CheckTrainStayInDepot(consist)) return true;
4078
4079 if (!mode) consist->ShowVisualEffect();
4080
4081 /* We had no order but have an order now, do look ahead. */
4082 if (!valid_order && !consist->current_order.IsType(OT_NOTHING)) {
4083 CheckNextTrainTile(consist);
4084 }
4085
4086 /* Handle stuck trains. */
4087 if (!mode && consist->flags.Test(VehicleRailFlag::Stuck)) {
4088 ++consist->wait_counter;
4089
4090 /* Should we try reversing this tick if still stuck? */
4091 bool turn_around = consist->wait_counter % (_settings_game.pf.wait_for_pbs_path * Ticks::DAY_TICKS) == 0 && _settings_game.pf.reverse_at_signals;
4092
4093 if (!turn_around && consist->wait_counter % _settings_game.pf.path_backoff_interval != 0 && consist->force_proceed == TFP_NONE) return true;
4094 if (!TryPathReserve(consist)) {
4095 /* Still stuck. */
4096 if (turn_around) ReverseTrainDirection(consist);
4097
4098 if (consist->flags.Test(VehicleRailFlag::Stuck) && consist->wait_counter > 2 * _settings_game.pf.wait_for_pbs_path * Ticks::DAY_TICKS) {
4099 /* Show message to player. */
4100 if (_settings_client.gui.lost_vehicle_warn && consist->owner == _local_company) {
4101 AddVehicleAdviceNewsItem(AdviceType::TrainStuck, GetEncodedString(STR_NEWS_TRAIN_IS_STUCK, consist->index), consist->index);
4102 }
4103 consist->wait_counter = 0;
4104 }
4105 /* Exit if force proceed not pressed, else reset stuck flag anyway. */
4106 if (consist->force_proceed == TFP_NONE) return true;
4108 consist->wait_counter = 0;
4109 SetWindowWidgetDirty(WindowClass::VehicleView, consist->index, WID_VV_START_STOP);
4110 }
4111 }
4112
4113 if (consist->current_order.IsType(OT_LEAVESTATION)) {
4114 consist->current_order.Free();
4115 SetWindowWidgetDirty(WindowClass::VehicleView, consist->index, WID_VV_START_STOP);
4116 return true;
4117 }
4118
4119 int j = consist->UpdateSpeed();
4120
4121 /* we need to invalidate the widget if we are stopping from 'Stopping 0 km/h' to 'Stopped' */
4122 if (consist->cur_speed == 0 && consist->vehstatus.Test(VehState::Stopped)) {
4123 /* If we manually stopped, we're not force-proceeding anymore. */
4124 consist->force_proceed = TFP_NONE;
4125 InvalidateWindowData(WindowClass::VehicleView, consist->index);
4126 }
4127
4128 Train* moving_front = consist->GetMovingFront();
4129 int adv_spd = moving_front->GetAdvanceDistance();
4130 if (j < adv_spd) {
4131 /* if the vehicle has speed 0, update the last_speed field. */
4132 if (consist->cur_speed == 0) consist->SetLastSpeed();
4133 } else if (!TrainCheckIfLineEnds(moving_front)) {
4134 /* Train reversed, discard any further motion, to prevent uncommanded movement in the reverse direction. */
4135 j = 0;
4136 } else {
4137 /* Loop until the train has finished moving. */
4138 for (;;) {
4139 j -= adv_spd;
4140 TrainController(moving_front, nullptr);
4141 moving_front = moving_front->GetMovingFront();
4142 /* Don't continue to move if the train crashed. */
4143 if (CheckTrainCollision(moving_front)) break;
4144 /* Determine distance to next map position */
4145 adv_spd = moving_front->GetAdvanceDistance();
4146
4147 /* No more moving this tick */
4148 if (j < adv_spd || consist->cur_speed == 0) break;
4149
4150 OrderType order_type = consist->current_order.GetType();
4151 /* Do not skip waypoints (incl. 'via' stations) when passing through at full speed. */
4152 if ((order_type == OT_GOTO_WAYPOINT || order_type == OT_GOTO_STATION) &&
4154 IsTileType(moving_front->tile, TileType::Station) &&
4155 consist->current_order.GetDestination() == GetStationIndex(moving_front->tile)) {
4156 ProcessOrders(consist);
4157 }
4158 }
4159 consist->SetLastSpeed();
4160 }
4161
4162 for (Train *u = consist; u != nullptr; u = u->Next()) {
4163 if (u->vehstatus.Test(VehState::Hidden)) continue;
4164
4165 u->UpdateViewport(false, false);
4166 }
4167
4168 if (consist->progress == 0) consist->progress = j; // Save unused spd for next time, if TrainController didn't set progress
4169
4170 return true;
4171}
4172
4178{
4179 Money cost = 0;
4180 const Train *v = this;
4181
4182 do {
4183 const Engine *e = v->GetEngine();
4184 if (e->VehInfo<RailVehicleInfo>().running_cost_class == Price::Invalid) continue;
4185
4186 uint cost_factor = GetVehicleProperty(v, PROP_TRAIN_RUNNING_COST_FACTOR, e->VehInfo<RailVehicleInfo>().running_cost);
4187 if (cost_factor == 0) continue;
4188
4189 /* Halve running cost for multiheaded parts */
4190 if (v->IsMultiheaded()) cost_factor /= 2;
4191
4192 cost += GetPrice(e->VehInfo<RailVehicleInfo>().running_cost_class, cost_factor, e->GetGRF());
4193 } while ((v = v->GetNextVehicle()) != nullptr);
4194
4195 return cost;
4196}
4197
4203{
4204 this->tick_counter++;
4205
4206 if (this->IsFrontEngine()) {
4208
4209 if (!this->vehstatus.Test(VehState::Stopped) || this->cur_speed > 0) this->running_ticks++;
4210
4211 this->current_order_time++;
4212
4213 if (!TrainLocoHandler(this, false)) return false;
4214
4215 return TrainLocoHandler(this, true);
4216 } else if (this->IsFreeWagon() && this->vehstatus.Test(VehState::Crashed)) {
4217 /* Delete flooded standalone wagon chain */
4218 if (++this->crash_anim_pos >= 4400) {
4219 delete this;
4220 return false;
4221 }
4222 }
4223
4224 return true;
4225}
4226
4232{
4233 if (Company::Get(v->owner)->settings.vehicle.servint_trains == 0 || !v->NeedsAutomaticServicing()) return;
4234 if (v->IsChainInDepot()) {
4236 return;
4237 }
4238
4239 uint max_penalty = _settings_game.pf.yapf.maximum_go_to_depot_penalty;
4240
4241 FindDepotData tfdd = FindClosestTrainDepot(v, max_penalty);
4242 /* Only go to the depot if it is not too far out of our way. */
4243 if (tfdd.best_length == UINT_MAX || tfdd.best_length > max_penalty) {
4244 if (v->current_order.IsType(OT_GOTO_DEPOT)) {
4245 /* If we were already heading for a depot but it has
4246 * suddenly moved farther away, we continue our normal
4247 * schedule? */
4249 SetWindowWidgetDirty(WindowClass::VehicleView, v->index, WID_VV_START_STOP);
4250 }
4251 return;
4252 }
4253
4254 DepotID depot = GetDepotIndex(tfdd.tile);
4255
4256 if (v->current_order.IsType(OT_GOTO_DEPOT) &&
4257 v->current_order.GetDestination() != depot &&
4258 !Chance16(3, 16)) {
4259 return;
4260 }
4261
4264 v->dest_tile = tfdd.tile;
4265 SetWindowWidgetDirty(WindowClass::VehicleView, v->index, WID_VV_START_STOP);
4266}
4267
4270{
4271 AgeVehicle(this);
4272}
4273
4276{
4277 EconomyAgeVehicle(this);
4278
4279 if ((++this->day_counter & 7) == 0) DecreaseVehicleValue(this);
4280
4281 if (this->IsFrontEngine()) {
4283
4285
4286 CheckOrders(this);
4287
4288 /* update destination */
4289 if (this->current_order.IsType(OT_GOTO_STATION)) {
4290 TileIndex tile = Station::Get(this->current_order.GetDestination().ToStationID())->train_station.tile;
4291 if (tile != INVALID_TILE) this->dest_tile = tile;
4292 }
4293
4294 if (this->running_ticks != 0) {
4295 /* running costs */
4297
4298 this->profit_this_year -= cost.GetCost();
4299 this->running_ticks = 0;
4300
4302
4303 SetWindowDirty(WindowClass::VehicleDetails, this->index);
4304 SetWindowClassesDirty(WindowClass::TrainList);
4305 }
4306 }
4307}
4308
4314{
4315 if (this->vehstatus.Test(VehState::Crashed)) return Trackdir::Invalid;
4316
4317 if (this->track == Track::Depot) {
4318 /* We'll assume the train is facing outwards */
4319 return DiagDirToDiagTrackdir(GetRailDepotDirection(this->tile)); // Train in depot
4320 }
4321
4322 if (this->track == Track::Wormhole) {
4323 /* train in tunnel or on bridge, so just use its direction and assume a diagonal track */
4325 }
4326
4327 return TrackDirectionToTrackdir(FindFirstTrack(this->track), this->GetMovingDirection());
4328}
4329
4330uint16_t Train::GetMaxWeight() const
4331{
4332 uint16_t weight = CargoSpec::Get(this->cargo_type)->WeightOfNUnitsInTrain(this->GetEngine()->DetermineCapacity(this));
4333
4334 /* Vehicle weight is not added for articulated parts. */
4335 if (!this->IsArticulatedPart()) {
4336 weight += GetVehicleProperty(this, PROP_TRAIN_WEIGHT, RailVehInfo(this->engine_type)->weight);
4337 }
4338
4339 /* Powered wagons have extra weight added. */
4340 if (this->flags.Test(VehicleRailFlag::PoweredWagon)) {
4341 weight += RailVehInfo(this->gcache.first_engine)->pow_wag_weight;
4342 }
4343
4344 return weight;
4345}
Base functions for all AIs.
void AddArticulatedParts(Vehicle *first)
Add the remaining articulated parts to the given vehicle.
void CheckConsistencyOfArticulatedVehicle(const Vehicle *v)
Checks whether the specs of freshly build articulated vehicles are consistent with the information sp...
Functions related to articulated vehicles.
void CheckCargoCapacity(Vehicle *v)
Check the capacity of all vehicles in a chain and spread cargo if needed.
@ BuiltAsPrototype
Vehicle is a prototype (accepted as exclusive preview).
@ DrivingBackwards
Vehicle is driving backwards.
static constexpr uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
constexpr bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
const BridgeSpec * GetBridgeSpec(BridgeType i)
Get the specification of a bridge type.
Definition bridge.h:63
bool IsBridgeTile(Tile t)
checks if there is a bridge on this tile
Definition bridge_map.h:35
BridgeType GetBridgeType(Tile t)
Determines the type of bridge on a tile.
Definition bridge_map.h:56
bool IsBridge(Tile t)
Checks if this is a bridge, instead of a tunnel.
Definition bridge_map.h:24
bool IsValidCargoType(CargoType cargo)
Test whether cargo type is not INVALID_CARGO.
Definition cargo_type.h:112
CargoType
Cargo slots to indicate a cargo type within a game.
Definition cargo_type.h:22
static void NewEvent(CompanyID company, ScriptEvent *event)
Queue a new event for an AI.
Definition ai_core.cpp:231
uint Count() const
Count the number of set bits.
constexpr bool Test(Tvalue_type value) const
Test if the value-th bit is set.
constexpr Tstorage base() const noexcept
Retrieve the raw value behind this bit set.
constexpr bool None() const
Test if none of the values are set.
constexpr Timpl & Flip()
Flip all bits.
constexpr Timpl & Reset()
Reset all bits.
constexpr Timpl & Set()
Set all bits.
constexpr bool Any(const Timpl &other) const
Test if any of the given values are set.
Common return value for all commands.
void AddCost(const Money &cost)
Adds the given cost to the cost of the command.
Money GetCost() const
The costs as made up to this moment.
bool Failed() const
Did this command fail?
uint16_t reliability_spd_dec
Speed of reliability decay between services (per day).
Definition engine_base.h:52
const GRFFile * GetGRF() const
Retrieve the NewGRF the engine is tied to.
GrfID GetGRFID() const
Retrieve the GRF ID of the NewGRF the engine is tied to.
Definition engine.cpp:185
uint DetermineCapacity(const Vehicle *v, uint16_t *mail_capacity=nullptr) const
Determines capacity of a given vehicle from scratch.
Definition engine.cpp:229
EngineFlags flags
Flags of the engine.
Definition engine_base.h:59
uint8_t original_image_index
Original vehicle image index, thus the image index of the overridden vehicle.
Definition engine_base.h:63
TimerGameCalendar::Date GetLifeLengthInDays() const
Returns the vehicle's (not model's!) life length in days.
Definition engine.cpp:471
CargoType GetDefaultCargoType() const
Determines the default cargo type of an engine.
Definition engine_base.h:96
uint16_t reliability
Current reliability of the engine.
Definition engine_base.h:51
static void NewEvent(class ScriptEvent *event)
Queue a new event for the game script.
TileIndex tile
The base tile of the area.
RAII class for measuring multi-step elements of performance.
This struct contains all the info that is needed to draw and construct tracks.
Definition rail.h:134
uint8_t curve_speed
Multiplier for curve maximum speed advantage.
Definition rail.h:214
static constexpr TimerGameTick::Ticks DAY_TICKS
1 day is 74 ticks; TimerGameCalendar::date_fract used to be uint16_t and incremented by 885.
static Date date
Current date in days (day counter).
static Year year
Current year, starting at 0.
static Date date
Current date in days (day counter).
This class will save the current order of a vehicle and restore it on destruction.
void Restore()
Restore the saved order to the vehicle.
~VehicleOrderSaver()
Restore the saved order to the vehicle, if Restore() has not already been called.
bool SwitchToNextOrder(bool skip_first)
Set the current vehicle order to the next order in the order list.
Iterate over all vehicles near a given world coordinate.
Iterate over all vehicles on a tile.
Functions related to commands.
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
@ Execute
execute the given command
@ NoCargoCapacityCheck
when autoreplace/autorenew is in progress, this shall prevent truncating the amount of cargo in the v...
@ AutoReplace
autoreplace/autorenew is in progress, this shall disable vehicle limits when building,...
EnumBitSet< DoCommandFlag, uint16_t > DoCommandFlags
Bitset of DoCommandFlag elements.
Definition of stuff that is very close to a company, like the company struct itself.
CommandCost CheckOwnership(Owner owner, TileIndex tile)
Check whether the current owner owns something.
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
CompanyID _current_company
Company currently doing an action.
void SubtractMoneyFromCompanyFract(CompanyID company, const CommandCost &cst)
Subtract money from a company, including the money fraction.
Functions related to companies.
DepotID GetDepotIndex(Tile t)
Get the index of which depot is attached to the tile.
Definition depot_map.h:56
PoolID< uint16_t, struct DepotIDTag, 64000, 0xFFFF > DepotID
Type for the unique identifier of depots.
Definition depot_type.h:15
DirDiff DirDifference(Direction d0, Direction d1)
Calculate the difference between two directions.
Direction DiagDirToDir(DiagDirection dir)
Convert a DiagDirection to a Direction.
DiagDirection ReverseDiagDir(DiagDirection d)
Returns the reverse direction of the given DiagDirection.
DiagDirections AxisToDiagDirs(Axis a)
Converts an Axis to DiagDirections.
Direction ReverseDir(Direction d)
Return the reverse of a direction.
bool IsValidDiagDirection(DiagDirection d)
Checks if an integer value is a valid DiagDirection.
Direction ChangeDir(Direction d, DirDiff delta)
Change a direction by a given difference.
DiagDirection AxisToDiagDir(Axis a)
Converts an Axis to a DiagDirection.
bool IsDiagonalDirection(Direction dir)
Checks if a given Direction is diagonal.
Axis DiagDirToAxis(DiagDirection d)
Convert a DiagDirection to the axis.
DiagDirection DirToDiagDir(Direction dir)
Convert a Direction to a DiagDirection.
DirDiff
Enumeration for the difference between two directions.
@ Left45
Angle of 45 degrees left.
@ Left90
Angle of 90 degrees left.
@ Same
Both directions faces to the same direction.
@ Right45
Angle of 45 degrees right.
@ Right90
Angle of 90 degrees right.
EnumIndexArray< T, DiagDirection, DiagDirection::End > DiagDirectionIndexArray
Array with DiagDirection as index.
Direction
Defines the 8 directions on the map.
@ SW
Southwest.
@ NW
Northwest.
@ NE
Northeast.
@ SE
Southeast.
Axis
Enumeration for the two axis X and Y.
DiagDirection
Enumeration for diagonal directions.
@ Begin
Used for iterations.
@ Invalid
Flag for an invalid DiagDirection.
EnumBitSet< DiagDirection, uint8_t > DiagDirections
Bitset of DiagDirection elements.
Money GetPrice(Price index, uint cost_factor, const GRFFile *grf_file, int shift)
Determine a certain price.
Definition economy.cpp:941
@ TrainRun
Running costs trains.
@ NewVehicles
New vehicles.
@ Invalid
Invalid base price.
EffectVehicle * CreateEffectVehicleRel(const Vehicle *v, int x, int y, int z, EffectVehicleType type)
Create an effect vehicle above a particular vehicle.
Functions related to effect vehicles.
@ EV_EXPLOSION_SMALL
Various explosions.
@ EV_EXPLOSION_LARGE
Various explosions.
@ RailFlips
Rail vehicle has old depot-flip handling.
@ RailTilts
Rail vehicle tilts in curves.
@ VE_DISABLE_WAGON_POWER
Flag to disable wagon power.
Definition engine_type.h:67
PoolID< uint16_t, struct EngineIDTag, 64000, 0xFFFF > EngineID
Unique identification number of an engine.
Definition engine_type.h:25
@ ExclusivePreview
This vehicle is in the exclusive preview stage, either being used or being offered to a company.
@ Multihead
indicates a combination of two locomotives
Definition engine_type.h:32
@ Wagon
simple wagon, not motorized
Definition engine_type.h:33
constexpr std::underlying_type_t< enum_type > to_underlying(enum_type e)
Implementation of std::to_underlying (from C++23).
Definition enum_type.hpp:21
Functions related to errors.
@ Critical
Critical errors, the MessageBox is shown in all cases.
Definition error.h:25
void ShowErrorMessage(EncodedString &&summary_msg, int x, int y, CommandCost &cc)
Display an error message in a window.
Error reporting related functions.
fluid_settings_t * settings
FluidSynth settings handle.
Template function for track followers.
Types for recording game performance data.
@ GameLoopTrains
Time spent processing trains.
Base functions for all Games.
uint32_t SpriteID
The number of a sprite, without mapping bits and colourtables.
Definition gfx_type.h:17
uint32_t PaletteID
The number of the palette.
Definition gfx_type.h:18
@ AS_BRAKE
We want to stop.
void UpdateTrainGroupID(Train *v)
Recalculates the groupID of a train.
void SetTrainGroupID(Train *v, GroupID grp)
Affect the groupID of a train to new_g.
void MarkTileDirtyByTile(TileIndex tile, int bridge_level_offset, int tile_height_override)
Mark a tile given by its index dirty for repaint.
static constexpr GroupID DEFAULT_GROUP
Ungrouped vehicles are in this group.
Definition group_type.h:18
TrackStatus GetTileTrackStatus(TileIndex tile, TransportType mode, RoadTramType sub_mode, DiagDirection side)
Returns information about trackdirs and signal states.
int GetSlopePixelZ(int x, int y, bool ground_vehicle)
Return world Z coordinate of a given point of a tile.
#define Rect
Macro that prevents name conflicts between included headers.
#define Point
Macro that prevents name conflicts between included headers.
DiagDirection DiagdirBetweenTiles(TileIndex tile_from, TileIndex tile_to)
Determines the DiagDirection to get from one tile to another.
Definition map_func.h:627
static TileIndex TileVirtXY(uint x, uint y)
Get a tile from the virtual XY-coordinate.
Definition map_func.h:407
TileIndex TileAddByDiagDir(TileIndex tile, DiagDirection dir)
Adds a DiagDir to a tile.
Definition map_func.h:615
TileIndexDiff TileOffsByAxis(Axis axis)
Convert an Axis to a TileIndexDiff.
Definition map_func.h:559
static uint TileY(TileIndex tile)
Get the Y component of a tile.
Definition map_func.h:429
static uint TileX(TileIndex tile)
Get the X component of a tile.
Definition map_func.h:419
TileIndexDiff TileOffsByDiagDir(DiagDirection dir)
Convert a DiagDirection to a TileIndexDiff.
Definition map_func.h:574
int32_t TileIndexDiff
An offset value between two tiles.
Definition map_type.h:23
constexpr T abs(const T a)
Returns the absolute value of (scalar) variable.
Definition math_func.hpp:23
constexpr uint CeilDiv(uint a, uint b)
Computes ceil(a / b) for non-negative a and b.
constexpr T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Definition math_func.hpp:79
Miscellaneous command definitions.
void HideFillingPercent(TextEffectID *te_id)
Hide vehicle loading indicators.
Definition misc_gui.cpp:582
bool _networking
are we in networking mode?
Definition network.cpp:63
ClientID
'Unique' identifier to be given to clients
Base for the NewGRF implementation.
@ Trains
Trains feature.
Definition newgrf.h:82
@ ArticEngine
Add articulated engines (trains and road vehicles).
@ Length
Vehicle length (trains and road vehicles).
@ CBID_VEHICLE_LENGTH
Vehicle length, returns the amount of 1/8's the vehicle is shorter for trains and RVs.
@ CBID_TRAIN_ALLOW_WAGON_ATTACH
Determine whether a wagon can be attached to an already existing train.
static const uint CALLBACK_FAILED
Different values for Callback result evaluations.
void ErrorUnknownCallbackResult(GrfID grfid, uint16_t cbid, uint16_t cb_res)
Record that a NewGRF returned an unknown/invalid callback result.
@ VehCapacity
Capacity of vehicle changes when not refitting or arranging.
Functions/types related to NewGRF debugging.
void InvalidateNewGRFInspectWindow(GrfSpecFeature feature, uint index)
Invalidate the inspect window for a given feature and index.
void DeleteNewGRFInspectWindow(GrfSpecFeature feature, uint index)
Delete inspect window for a given feature and index.
uint16_t GetVehicleCallbackParent(CallbackID callback, uint32_t param1, uint32_t param2, EngineID engine, const Vehicle *v, const Vehicle *parent, std::span< int32_t > regs100)
Evaluate a newgrf callback for vehicles with a different vehicle for parent scope.
bool UsesWagonOverride(const Vehicle *v)
Check if a wagon is currently using a wagon override.
uint16_t GetVehicleCallback(CallbackID callback, uint32_t param1, uint32_t param2, EngineID engine, const Vehicle *v, std::span< int32_t > regs100)
Evaluate a newgrf callback for vehicles.
std::optional< bool > TestVehicleBuildProbability(Vehicle *v, BuildProbabilityType type)
Test for vehicle build probability type.
@ Reversed
Change the rail vehicle should be reversed when purchased.
@ PROP_TRAIN_SHORTEN_FACTOR
Shorter vehicles.
@ PROP_TRAIN_USER_DATA
User defined data for vehicle variable 0x42.
@ PROP_TRAIN_WEIGHT
Weight in t (if dualheaded: for each single vehicle).
@ PROP_TRAIN_CARGO_AGE_PERIOD
Number of ticks before carried cargo is aged.
@ PROP_TRAIN_RUNNING_COST_FACTOR
Yearly runningcost (if dualheaded: sum of both vehicles).
@ PROP_TRAIN_SPEED
Max. speed: 1 unit = 1/1.6 mph = 1 km-ish/h.
bool PlayVehicleSound(const Vehicle *v, VehicleSoundEvent event, bool force)
Checks whether a NewGRF wants to play a different vehicle sound effect.
Functions related to NewGRF provided sounds.
@ Start
Vehicle starting, i.e. leaving, the station.
void TriggerStationRandomisation(BaseStation *st, TileIndex trigger_tile, StationRandomTrigger trigger, CargoType cargo_type)
Trigger station randomisation.
Header file for NewGRF stations.
StringID GetGRFStringID(GrfID grfid, GRFStringID stringid)
Returns the index for this stringid associated with its grfID.
Header of Action 04 "universal holder" structure and functions.
StrongType::Typedef< uint32_t, struct GRFStringIDTag, StrongType::Compare, StrongType::Integer > GRFStringID
Type for GRF-internal string IDs.
static constexpr GRFStringID GRFSTR_MISC_GRF_TEXT
Miscellaneous GRF text range.
Functions related to news.
void AddVehicleNewsItem(EncodedString &&headline, NewsType type, VehicleID vehicle, StationID station=StationID::Invalid())
Adds a newsitem referencing a vehicle.
Definition news_func.h:32
void AddVehicleAdviceNewsItem(AdviceType advice_type, EncodedString &&headline, VehicleID vehicle)
Adds a vehicle-advice news item.
Definition news_func.h:43
@ ArrivalCompany
First vehicle arrived for company.
Definition news_type.h:31
@ ArrivalOther
First vehicle arrived for competitor.
Definition news_type.h:32
@ Accident
An accident or disaster has occurred.
Definition news_type.h:33
@ TrainStuck
The train got stuck and needs to be unstuck manually.
Definition news_type.h:59
@ Error
A game paused because a (critical) error.
Definition openttd.h:75
Functions related to order backups.
bool ProcessOrders(Vehicle *v)
Handle the orders of a vehicle and determine the next place to go to if needed.
bool UpdateOrderDest(Vehicle *v, const Order *order, int conditional_depth, bool pbs_look_ahead)
Update the vehicle's destination tile from an order.
void CheckOrders(const Vehicle *v)
Check the orders of a vehicle, to see if there are invalid orders and stuff.
void DeleteVehicleOrders(Vehicle *v, bool keep_orderlist, bool reset_order_indices)
Delete all orders from a vehicle.
VehicleOrderID ProcessConditionalOrder(const Order *order, const Vehicle *v)
Process a conditional order and determine the next order.
OrderStopLocation
Where to stop the trains.
Definition order_type.h:98
@ NearEnd
Stop at the near end of the platform.
Definition order_type.h:99
@ FarEnd
Stop at the far end of the platform.
Definition order_type.h:101
@ Middle
Stop at the middle of the platform.
Definition order_type.h:100
@ NonStop
The vehicle will not stop at any stations it passes except the destination, aka non-stop.
Definition order_type.h:88
@ GoVia
The vehicle will stop at any station it passes except the destination, aka via.
Definition order_type.h:89
uint8_t VehicleOrderID
The index of an order within its current vehicle (not pool related).
Definition order_type.h:18
@ NearestDepot
Send the vehicle to the nearest depot.
Definition order_type.h:121
@ Service
This depot order is because of the servicing limit.
Definition order_type.h:109
static const VehicleOrderID INVALID_VEH_ORDER_ID
Invalid vehicle order index (sentinel).
Definition order_type.h:39
OrderType
Order types.
Definition order_type.h:50
void SetRailStationPlatformReservation(TileIndex start, DiagDirection dir, bool b)
Set the reservation for a complete station platform.
Definition pbs.cpp:57
TrackBits GetReservedTrackbits(TileIndex t)
Get the reserved trackbits for any tile, regardless of type.
Definition pbs.cpp:24
bool TryReserveRailTrack(TileIndex tile, Track t, bool trigger_stations)
Try to reserve a specific track on a tile.
Definition pbs.cpp:80
bool IsWaitingPositionFree(const Train *v, TileIndex tile, Trackdir trackdir, bool forbid_90deg)
Check if a safe position is free.
Definition pbs.cpp:439
void UnreserveRailTrack(TileIndex tile, Track t)
Lift the reservation of a specific track on a tile.
Definition pbs.cpp:144
PBSTileInfo FollowTrainReservation(const Train *consist, Vehicle **train_on_res)
Follow a train reservation to the last tile.
Definition pbs.cpp:301
bool IsSafeWaitingPosition(const Train *v, TileIndex tile, Trackdir trackdir, bool include_line_end, bool forbid_90deg)
Determine whether a certain track on a tile is a safe position to end a path.
Definition pbs.cpp:395
PBS support routines.
bool HasReservedTracks(TileIndex tile, TrackBits tracks)
Check whether some of tracks is reserved on a tile.
Definition pbs.h:58
RailType GetTileRailType(Tile tile)
Return the rail type of tile, or INVALID_RAILTYPE if this is no rail tile.
Definition rail.cpp:39
int TicksToLeaveDepot(const Train *v)
Compute number of ticks when next wagon will leave a depot.
RailTypes GetAllPoweredRailTypes(RailTypes railtypes)
Returns all powered railtypes for a set of railtypes.
Definition rail.h:344
bool IsCompatibleRail(RailType enginetype, RailType tiletype)
Checks if an engine of the given RailType can drive on a tile with a given RailType.
Definition rail.h:371
bool HasPowerOnRail(RailType enginetype, RailType tiletype)
Checks if an engine of the given RailType got power on a tile with a given RailType.
Definition rail.h:396
bool Rail90DegTurnDisallowed(RailType rt1, RailType rt2, bool def=_settings_game.pf.forbid_90_deg)
Test if 90 degree turns are disallowed between two railtypes.
Definition rail.h:430
const RailTypeInfo * GetRailTypeInfo(RailType railtype)
Returns a pointer to the Railtype information for a given railtype.
Definition rail.h:320
RailTypes GetAllCompatibleRailTypes(RailTypes railtypes)
Returns all compatible railtypes for a set of railtypes.
Definition rail.h:332
std::vector< Train * > TrainList
Helper type for lists/vectors of trains.
Definition rail_cmd.cpp:43
bool HasOnewaySignalBlockingTrackdir(Tile tile, Trackdir td)
Is a one-way signal blocking the trackdir?
Definition rail_map.h:547
static RailTileType GetRailTileType(Tile t)
Returns the RailTileType (normal with or without signals, waypoint or depot).
Definition rail_map.h:36
static bool IsPlainRail(Tile t)
Returns whether this is plain rails, with or without signals.
Definition rail_map.h:49
RailType GetRailType(Tile t)
Gets the rail type of the given tile.
Definition rail_map.h:115
bool HasSignalOnTrackdir(Tile tile, Trackdir trackdir)
Checks for the presence of signals along the given trackdir on the given rail tile.
Definition rail_map.h:490
TrackBits GetTrackBits(Tile tile)
Gets the track bits of the given tile.
Definition rail_map.h:136
static bool IsPlainRailTile(Tile t)
Checks whether the tile is a rail tile or rail tile with signals.
Definition rail_map.h:60
bool IsPbsSignal(SignalType s)
Checks whether the given signal is a path based signal.
Definition rail_map.h:291
@ Signals
Normal rail tile with signals.
Definition rail_map.h:25
Track GetRailDepotTrack(Tile t)
Returns the track of a depot, ignoring direction.
Definition rail_map.h:182
DiagDirection GetRailDepotDirection(Tile t)
Returns the direction the depot is facing to.
Definition rail_map.h:171
void SetSignalStateByTrackdir(Tile tile, Trackdir trackdir, SignalState state)
Sets the state of the signal along the given trackdir.
Definition rail_map.h:519
bool HasSignalOnTrack(Tile tile, Track track)
Checks for the presence of signals (either way) on the given track on the given rail tile.
Definition rail_map.h:474
bool HasPbsSignalOnTrackdir(Tile tile, Trackdir td)
Is a pbs signal present along the trackdir?
Definition rail_map.h:534
bool IsOnewaySignal(Tile t, Track track)
Is the signal at the given track on a tile a one way signal?
Definition rail_map.h:357
SignalType GetSignalType(Tile t, Track track)
Get the signal type for a track on a tile.
Definition rail_map.h:303
void SetDepotReservation(Tile t, bool b)
Set the reservation state of the depot.
Definition rail_map.h:268
bool HasDepotReservation(Tile t)
Get the reservation state of the depot.
Definition rail_map.h:256
bool HasSignals(Tile t)
Checks if a rail tile has signals.
Definition rail_map.h:72
SignalState GetSignalStateByTrackdir(Tile tile, Trackdir trackdir)
Gets the state of the signal along the given trackdir.
Definition rail_map.h:505
static bool IsRailDepotTile(Tile t)
Is this tile rail tile and a rail depot?
Definition rail_map.h:105
bool HasBlockSignalOnTrackdir(Tile tile, Trackdir td)
Check whether a block signal is present along the trackdir.
Definition rail_map.h:559
@ RAILTYPE_ELECTRIC
Electric rails.
Definition rail_type.h:29
@ RAILTYPE_RAIL
Standard non-electric rails.
Definition rail_type.h:28
Pseudo random number generator.
bool Chance16(const uint32_t a, const uint32_t b, const std::source_location location=std::source_location::current())
Flips a coin with given probability.
bool Chance16R(const uint32_t a, const uint32_t b, uint32_t &r, const std::source_location location=std::source_location::current())
Flips a coin with a given probability and saves the randomize-number in a variable.
void UpdateLevelCrossing(TileIndex tile, bool sound=true, bool force_bar=false)
Update a level crossing to barred or open (crossing may include multiple adjacent tiles).
bool HasCrossingReservation(Tile t)
Get the reservation state of the rail crossing.
Definition road_map.h:390
bool IsLevelCrossingTile(Tile t)
Return whether a tile is a level crossing tile.
Definition road_map.h:79
Axis GetCrossingRoadAxis(Tile t)
Get the road axis of a level crossing.
Definition road_map.h:346
void SetCrossingBarred(Tile t, bool barred)
Set the bar state of a level crossing.
Definition road_map.h:438
Axis GetCrossingRailAxis(Tile t)
Get the rail axis of a level crossing.
Definition road_map.h:358
bool IsCrossingBarred(Tile t)
Check if the level crossing is barred.
Definition road_map.h:426
void SetCrossingReservation(Tile t, bool b)
Set the reservation state of the rail crossing.
Definition road_map.h:403
@ Invalid
Invalid marker.
Definition road_type.h:42
A number of safeguards to prevent using unsafe methods.
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition settings.cpp:61
ClientSettings _settings_client
The current settings for this game.
Definition settings.cpp:60
@ EndOfLineOnly
Trains can only flip when the track ends.
@ None
Trains cannot flip anywhere and must back up if the track ends.
SigSegState UpdateSignalsOnSegment(TileIndex tile, DiagDirection side, Owner owner)
Update signals, starting at one side of a tile Will check tile next to this at opposite side too.
Definition signal.cpp:655
void UpdateSignalsInBuffer()
Update signals in buffer Called from 'outside'.
Definition signal.cpp:581
void AddSideToSignalBuffer(TileIndex tile, DiagDirection side, Owner owner)
Add side of tile to signal update buffer.
Definition signal.cpp:629
void SetSignalsOnBothDir(TileIndex tile, Track track, Owner owner)
Update signals at segments that are at both ends of given (existent or non-existent) track.
Definition signal.cpp:673
SigSegState
State of the signal segment.
Definition signal_func.h:55
@ Path
Segment is a path segment.
Definition signal_func.h:58
@ Full
Occupied by a train.
Definition signal_func.h:57
@ Path
normal path signal.
Definition signal_type.h:27
@ Green
The signal is green.
Definition signal_type.h:40
@ Red
The signal is red.
Definition signal_type.h:39
Functions related to sound.
SoundFx
Sound effects from baseset.
Definition sound_type.h:45
@ SND_04_DEPARTURE_STEAM
2 == 0x02 Station departure: steam engine
Definition sound_type.h:49
@ SND_41_DEPARTURE_MAGLEV
65 == 0x41 Station departure: maglev engine
Definition sound_type.h:112
@ SND_13_TRAIN_COLLISION
15 == 0x11 Train+train crash
Definition sound_type.h:64
@ SND_0E_LEVEL_CROSSING
12 == 0x0C Train passes through level crossing
Definition sound_type.h:59
@ SND_0A_DEPARTURE_TRAIN
8 == 0x08 Station departure: diesel and electric engine
Definition sound_type.h:55
@ SND_47_DEPARTURE_MONORAIL
71 == 0x47 Station departure: monorail engine
Definition sound_type.h:118
static const PaletteID PALETTE_CRASH
Recolour sprite greying of crashed vehicles.
Definition sprites.h:1794
static const SpriteID SPR_IMG_QUERY
Definition sprites.h:1275
Base classes/functions for stations.
void ModifyStationRatingAround(TileIndex tile, Owner owner, int amount, uint radius)
Forcibly modify station ratings near a given tile.
Functions related to stations.
bool IsRailWaypointTile(Tile t)
Is this tile a station tile and a rail waypoint?
bool IsCompatibleTrainStationTile(Tile test_tile, Tile station_tile)
Check if a tile is a valid continuation to a railstation tile.
bool IsRailStationTile(Tile t)
Is this tile a station tile and a rail station?
StationID GetStationIndex(Tile t)
Get StationID from a tile.
Definition station_map.h:26
Axis GetRailStationAxis(Tile t)
Get the rail direction of a rail station.
@ Train
Station with train station.
@ VehicleArrives
Trigger platform when train arrives.
@ VehicleArrives
Trigger platform when train arrives.
@ Train
Station has seen a train.
Definition of base types and functions in a cross-platform compatible way.
#define lengthof(array)
Return the length of an fixed size array.
Definition stdafx.h:261
EncodedString GetEncodedString(StringID str)
Encode a string with no parameters into an encoded string.
Definition strings.cpp:89
Functions related to OTTD's strings.
StrongType::Typedef< uint32_t, struct StringIDTag, StrongType::Compare, StrongType::Integer > StringID
Numeric value that represents a string, independent of the selected language.
Data structure for storing engine speed changes of an acceleration type.
uint8_t large_turn
Speed change due to a large turn.
uint8_t z_up
Fraction to remove when moving up.
uint8_t small_turn
Speed change due to a small turn.
uint8_t z_down
Fraction to add when moving down.
std::string name
Name of vehicle.
TimerGameTick::Ticks current_order_time
How many ticks have passed since this order started.
VehicleOrderID cur_real_order_index
The index to the current real (non-implicit) order.
VehicleFlags vehicle_flags
Used for gradual loading and other miscellaneous things (.
void ResetDepotUnbunching()
Resets all the data used for depot unbunching.
TileIndex xy
Base tile of the station.
StationFacilities facilities
The facilities that this station has.
TileArea train_station
Tile area the train 'station' part covers.
VehicleType type
Type of vehicle.
uint16_t speed
maximum travel speed (1 unit = 1/1.6 mph = 1 km-ish/h)
Definition bridge.h:41
bool Follow(TileIndex old_tile, Trackdir old_td)
Main follower routine.
bool is_tunnel
last turn passed tunnel
bool is_bridge
last turn passed bridge ramp
int tiles_skipped
number of skipped tunnel or station tiles
DiagDirection exitdir
exit direction (leaving the old tile)
TrackdirBits new_td_bits
the new set of available trackdirs
TileIndex new_tile
the new tile (the vehicle has entered)
Trackdir old_td
the trackdir (the vehicle was on) before move
bool is_station
last turn passed station
TileIndex old_tile
the origin (vehicle moved from) before move
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo type.
Definition cargotype.h:140
uint64_t WeightOfNUnitsInTrain(uint32_t n) const
Calculate the weight of n units of cargo inside a train wagon.
Structure to return information about the closest depot location, and whether it could be found.
T y
Y coordinate.
T x
X coordinate.
uint16_t cargo_age_period
Number of ticks before carried cargo is aged.
EngineMiscFlags misc_flags
Miscellaneous flags.
VehicleCallbackMasks callback_mask
Bitmask of vehicle callbacks that have to be called.
Helper container to find a depot.
uint best_length
The distance towards the depot in penalty, or UINT_MAX if not found.
bool reverse
True if reversing is necessary for the train to get to this depot.
TileIndex tile
The tile of the depot.
Dynamic data of a loaded NewGRF.
Definition newgrf.h:126
uint8_t grf_version
GRF version (See https://newgrf-specs.tt-wiki.net/wiki/Version_numbers#GRF_version).
Definition newgrf.h:129
uint traininfo_vehicle_width
Width (in pixels) of a 8/8 train vehicle in depot GUI and vehicle details.
Definition newgrf.h:167
int traininfo_vehicle_pitch
Vertical offset for drawing train images in depot GUI and vehicle details.
Definition newgrf.h:166
Position information of a vehicle after it moved.
TileIndex new_tile
Tile of the vehicle after moving.
int y
x and y position of the vehicle after moving
TileIndex old_tile
Current tile of the vehicle.
EngineID first_engine
Cached EngineID of the front vehicle. EngineID::Invalid() for the front vehicle itself.
uint32_t cached_power
Total power of the consist (valid only for the first engine).
uint16_t cached_total_length
Length of the whole vehicle (valid only for the first engine).
uint8_t cached_veh_length
Length of this vehicle in units of 1/VEHICLE_LENGTH of normal length. It is cached because this can b...
bool IsChainInDepot() const override
Check whether the whole vehicle chain is in the depot.
void SetFreeWagon()
Set a vehicle as a free wagon.
int UpdateInclination(bool new_tile, bool update_delta)
Checks if the vehicle is in a slope and sets the required flags in that case.
bool CanLeadTrain() const
Check if this vehicle can lead a train.
void SetMultiheaded()
Set a vehicle as a multiheaded engine.
bool IsEngine() const
Check if a vehicle is an engine (can be first in a consist).
bool IsRearDualheaded() const
Tell if we are dealing with the rear end of a multiheaded engine.
bool IsMultiheaded() const
Check if the vehicle is a multiheaded engine.
void SetEngine()
Set engine status.
void SetWagon()
Set a vehicle to be a wagon.
void SetFrontEngine()
Set front engine state.
void ClearFreeWagon()
Clear a vehicle from being a free wagon.
bool IsWagon() const
Check if a vehicle is a wagon.
GroundVehicleFlags gv_flags
uint Crash(bool flooded) override
Common code executed for crashed ground vehicles.
uint DoUpdateSpeed(uint accel, int min_speed, int max_speed)
void ClearFrontEngine()
Remove the front engine state.
void SetLastSpeed()
Update the GUI variant of the current speed of the vehicle.
static void CountVehicle(const Vehicle *v, int delta)
Update num_vehicle when adding or removing a vehicle.
static uint Size()
Get the size of the map.
Definition map_func.h:280
VehicleSpriteSeq sprite_seq
Vehicle appearance.
static void Backup(const Vehicle *v, ClientID user)
Create an order backup for the given vehicle.
If you change this, keep in mind that it is also saved in 2 other places:
Definition order_base.h:33
OrderDepotTypeFlags GetDepotOrderType() const
What caused us going to the depot?
Definition order_base.h:169
DestinationID GetDestination() const
Gets the destination of this order.
Definition order_base.h:99
bool IsType(OrderType type) const
Check whether this order is of the given type.
Definition order_base.h:66
OrderStopLocation GetStopLocation() const
Where must we stop at the platform?
Definition order_base.h:163
OrderType GetType() const
Get the type of order of this order.
Definition order_base.h:72
void MakeDummy()
Makes this order a Dummy order.
void SetDestination(DestinationID destination)
Sets the destination of this order.
Definition order_base.h:106
OrderDepotActionFlags GetDepotActionType() const
What are we going to do when in the depot.
Definition order_base.h:175
void Free()
'Free' the order
Definition order_cmd.cpp:48
bool ShouldStopAtStation(const Vehicle *v, StationID station) const
Check whether the given vehicle should stop at the given station based on this order and the non-stop...
void MakeGoToDepot(DestinationID destination, OrderDepotTypeFlags order, OrderNonStopFlags non_stop_type=OrderNonStopFlag::NonStop, OrderDepotActionFlags action={}, CargoType cargo=CARGO_NO_REFIT)
Makes this order a Go To Depot order.
Definition order_cmd.cpp:74
OrderNonStopFlags GetNonStopType() const
At which stations must we stop?
Definition order_base.h:157
This struct contains information about the end of a reserved path.
Definition pbs.h:26
Trackdir trackdir
The reserved trackdir on the tile.
Definition pbs.h:28
TileIndex tile
Tile the path ends, INVALID_TILE if no valid path was found.
Definition pbs.h:27
bool okay
True if tile is a safe waiting position, false otherwise.
Definition pbs.h:29
static Pool::IterateWrapper< Vehicle > Iterate(size_t from=0)
static T * Create(Targs &&... args)
static Engine * Get(auto index)
static Vehicle * GetIfValid(auto index)
Information about a rail vehicle.
Definition engine_type.h:73
uint16_t power
Power of engine (hp); For multiheaded engines the sum of both engine powers.
Definition engine_type.h:81
uint8_t user_def_data
Property 0x25: "User-defined bit mask" Used only for (very few) NewGRF vehicles.
Definition engine_type.h:93
uint8_t running_cost
Running cost of engine; For multiheaded engines the sum of both running costs.
Definition engine_type.h:83
uint8_t shorten_factor
length on main map for this type is 8 - shorten_factor
Definition engine_type.h:90
RailTypes railtypes
Railtypes, mangled if elrail is disabled.
Definition engine_type.h:77
uint16_t pow_wag_power
Extra power applied to consist if wagon should be powered.
Definition engine_type.h:87
uint16_t max_speed
Maximum speed (1 unit = 1/1.6 mph = 1 km-ish/h).
Definition engine_type.h:80
RailVehicleType railveh_type
Type of rail vehicle.
Definition engine_type.h:75
uint8_t capacity
Cargo capacity of vehicle; For multiheaded engines the capacity of each single engine.
Definition engine_type.h:86
RailTypes intended_railtypes
Intended railtypes, regardless of elrail being enabled or disabled.
Definition engine_type.h:78
int Width() const
Get width of Rect.
int Height() const
Get height of Rect.
static Station * Get(auto index)
T * GetMovingFront() const
Get the moving front of the vehicle chain.
T * GetMovingPrev() const
Get the previous vehicle in the vehicle chain, relative to its current movement.
T * Next() const
Get next vehicle in the chain.
T * Previous() const
Get previous vehicle in the chain.
static Train * From(Vehicle *v)
T * First() const
Get the first vehicle in the chain.
T * GetNextVehicle() const
Get the next real (non-articulated part) vehicle in the consist.
void UpdateViewport(bool force_update, bool update_delta)
Update vehicle sprite- and position caches.
T * GetMovingNext() const
Get the next vehicle in the vehicle chain, relative to its current movement.
T * GetLastEnginePart()
Get the last part of an articulated engine.
T * GetFirstEnginePart()
Get the first part of an articulated engine.
T * Last()
Get the last vehicle in the chain.
T * GetMovingBack() const
Get the moving back of the vehicle chain.
Station data structure.
uint GetPlatformLength(TileIndex tile, DiagDirection dir) const override
Determines the REMAINING length of a platform, starting at (and including) the given tile.
Definition station.cpp:292
Track status of a tile.
Definition track_type.h:105
TrackdirBits signals
Red signals on the tile.
Definition track_type.h:107
TrackdirBits trackdirs
Trackdirs present on the tile.
Definition track_type.h:106
uint16_t cached_max_curve_speed
max consist speed limited by curves
Definition train.h:84
'Train' is either a loco or a wagon.
Definition train.h:97
void PlayLeaveStationSound(bool force=false) const override
Play the sound associated with leaving the station.
void UpdateAcceleration()
Update acceleration of the train from the cached power and weight.
void OnNewCalendarDay() override
Calendar day handler.
Train * GetNextUnit() const
Get the next real (non-articulated part and non rear part of dualheaded engine) vehicle in the consis...
Definition train.h:156
Trackdir GetVehicleTrackdir() const override
Get the tracks of the train vehicle.
void GetImage(Direction direction, EngineImageType image_type, VehicleSpriteSeq *result) const override
Get the sprite to display the train.
Train * other_multiheaded_part
Link between the two ends of a multiheaded engine.
Definition train.h:105
RailTypes railtypes
On which rail types the train can run.
Definition train.h:108
uint16_t crash_anim_pos
Crash animation counter.
Definition train.h:99
bool Tick() override
Update train vehicle data for a tick.
void ReserveTrackUnderConsist() const
Tries to reserve track under whole train consist.
TileIndex GetOrderStationLocation(StationID station) override
Get the location of the next station to visit.
TrainForceProceeding force_proceed
How the train should behave when it encounters next obstacle.
Definition train.h:111
int GetDisplayImageWidth(Point *offset=nullptr) const
Get the width of a train vehicle image in the GUI.
ClosestDepot FindClosestDepot() override
Find the closest depot for this vehicle and tell us the location, DestinationID and whether we should...
TrackBits track
On which track the train currently is.
Definition train.h:110
void UpdateDeltaXY() override
Updates the x and y offsets and the size of the sprite used for this vehicle.
VehicleRailFlags flags
Which flags has this train currently set.
Definition train.h:98
int CalcNextVehicleOffset() const
Calculate the offset from this vehicle's center to the following center taking the vehicle lengths in...
Definition train.h:180
uint16_t GetMaxWeight() const override
Calculates the weight value that this vehicle will have when fully loaded with its current cargo.
uint16_t GetCurveSpeedLimit() const
Computes train speed limit caused by curves.
bool IsPrimaryVehicle() const override
Whether this is the primary vehicle in the chain.
Definition train.h:124
void MarkDirty() override
Goods at the consist have changed, update the graphics, cargo, and acceleration.
int UpdateSpeed()
This function looks at the vehicle and updates its speed (cur_speed and subspeed) variables.
uint Crash(bool flooded=false) override
The train vehicle crashed!
VehicleAccelerationModel GetAccelerationType() const
Allows to know the acceleration type of a vehicle.
Definition train.h:194
Train(VehicleID index)
Create new Train object.
Definition train.h:114
AccelStatus GetAccelerationStatus() const
Checks the current acceleration status of this vehicle.
Definition train.h:291
TrainCache tcache
Set of cached variables, recalculated on load and each time a vehicle is added to/removed from the co...
Definition train.h:102
void OnNewEconomyDay() override
Economy day handler.
int GetCursorImageOffset() const
Get the offset for train image when it is used as cursor.
void ConsistChanged(ConsistChangeFlags allowed_changes)
Recalculates the cached stuff of a train.
Money GetRunningCost() const override
Get running cost for the train consist.
RailTypes compatible_railtypes
With which rail types the train is compatible.
Definition train.h:107
uint16_t wait_counter
Ticks waiting in front of a signal, ticks being stuck or a counter for forced proceeding through sign...
Definition train.h:100
int GetCurrentMaxSpeed() const override
Calculates the maximum speed of the vehicle under its current conditions.
Sprite sequence for a vehicle part.
bool IsValid() const
Check whether the sequence contains any sprites.
void GetBounds(Rect *bounds) const
Determine shared bounds of all sprites.
Definition vehicle.cpp:125
void Set(SpriteID sprite)
Assign a single sprite to the sequence.
void Draw(int x, int y, PaletteID default_pal, bool force_pal) const
Draw the sprite sequence.
Definition vehicle.cpp:153
Vehicle data structure.
EngineID engine_type
The type of engine used for this vehicle.
int32_t z_pos
z coordinate.
Direction direction
facing
const Engine * GetEngine() const
Retrieves the engine of the vehicle.
Definition vehicle.cpp:750
Direction GetMovingDirection() const
Get the moving direction of this vehicle chain.
void IncrementRealOrderIndex()
Advanced cur_real_order_index to the next real order, keeps care of the wrap-around and invalidates t...
bool IsStoppedInDepot() const
Check whether the vehicle is in the depot and stopped.
bool IsMovingFront() const
Is this vehicle the moving front of the vehicle chain?
Order * GetOrder(int index) const
Returns order 'index' of a vehicle or nullptr when it doesn't exists.
void LeaveStation()
Perform all actions when leaving a station.
Definition vehicle.cpp:2373
void AddToShared(Vehicle *shared_chain)
Adds this vehicle to a shared vehicle chain.
Definition vehicle.cpp:3024
VehicleCargoList cargo
The cargo this vehicle is carrying.
TimerGameEconomy::Date date_of_last_service
Last economy date the vehicle had a service at a depot.
uint16_t cargo_cap
total capacity
StationID last_loading_station
Last station the vehicle has stopped at and could possibly leave from with any cargo loaded.
VehicleOrderID GetNumOrders() const
Get the number of orders this vehicle has.
void SetMovingDirection(Direction d)
Set the movement direction of this vehicle chain.
uint16_t random_bits
Bits used for randomized variational spritegroups.
void ReleaseUnitNumber()
Release the vehicle's unit number.
Definition vehicle.cpp:2443
uint8_t day_counter
Increased by one for each day.
void HandleLoading(bool mode=false)
Handle the loading of the vehicle; when not it skips through dummy orders and does nothing in all oth...
Definition vehicle.cpp:2454
Money profit_this_year
Profit this year << 8, low 8 bits are fract.
SpriteID colourmap
NOSAVE: cached colour mapping.
uint8_t breakdown_ctr
Counter for managing breakdown events.
uint GetAdvanceDistance()
Determines the vehicle "progress" needed for moving a step.
GroupID group_id
Index of group Pool array.
VehStates vehstatus
Status.
TimerGameCalendar::Date date_of_last_service_newgrf
Last calendar date the vehicle had a service at a depot, unchanged by the date cheat to protect again...
uint8_t subspeed
fractional speed
bool IsArticulatedPart() const
Check if the vehicle is an articulated part of an engine.
void LeaveUnbunchingDepot()
Leave an unbunching depot and calculate the next departure time for shared order vehicles.
Definition vehicle.cpp:2534
CargoType cargo_type
type of cargo this vehicle is carrying
uint8_t acceleration
used by train & aircraft
Vehicle * First() const
Get the first vehicle of this vehicle chain.
Order current_order
The current order (+ status, like: loading).
void HandlePathfindingResult(bool path_found)
Handle the pathfinding result, especially the lost status.
Definition vehicle.cpp:794
Vehicle * Next() const
Get the next vehicle of this vehicle.
int32_t y_pos
y coordinate.
int32_t x_pos
x coordinate.
const GRFFile * GetGRF() const
Retrieve the NewGRF the vehicle is tied to.
Definition vehicle.cpp:760
OrderList * orders
Pointer to the order list for this vehicle.
Money value
Value of the vehicle.
uint16_t refit_cap
Capacity left over from before last refit.
void InvalidateNewGRFCache()
Invalidates cached NewGRF variables.
VehicleCache vcache
Cache of often used vehicle values.
SpriteBounds bounds
Bounding box of vehicle.
void BeginLoading()
Prepare everything to begin the loading when arriving at a station.
Definition vehicle.cpp:2229
uint8_t spritenum
currently displayed sprite index 0xfd == custom sprite, 0xfe == custom second head sprite 0xff == res...
uint16_t cur_speed
current speed
uint8_t cargo_subtype
Used for livery refits (NewGRF variations).
bool IsFrontEngine() const
Check if the vehicle is a front engine.
bool IsWaitingForUnbunching() const
Check whether a vehicle inside a depot is waiting for unbunching.
Definition vehicle.cpp:2581
TextEffectID fill_percent_te_id
a text-effect id to a loading indicator object
void SetNext(Vehicle *next)
Set the next vehicle of this vehicle.
Definition vehicle.cpp:2988
TimerGameCalendar::Date max_age
Maximum age.
MutableSpriteCache sprite_cache
Cache of sprites and values related to recalculating them, see MutableSpriteCache.
uint16_t reliability
Reliability.
bool HandleBreakdown()
Handle all of the aspects of a vehicle breakdown This includes adding smoke and sounds,...
Definition vehicle.cpp:1376
uint8_t progress
The percentage (if divided by 256) this vehicle already crossed the tile unit.
uint16_t reliability_spd_dec
Reliability decrease speed.
uint8_t tick_counter
Increased by one for each tick.
TileIndex tile
Current tile index.
TileIndex dest_tile
Heading for this tile.
void CopyVehicleConfigAndStatistics(Vehicle *src)
Copy certain configurations and statistics of a vehicle after successful autoreplace/renew The functi...
void UpdatePosition()
Update the position of the vehicle.
Definition vehicle.cpp:1701
StationID last_station_visited
The last station we stopped at.
bool IsDrivingBackwards() const
Is this vehicle moving backwards?
void ShowVisualEffect() const
Draw visual effects (smoke and/or sparks) for a vehicle chain.
Definition vehicle.cpp:2836
TimerGameCalendar::Year build_year
Year the vehicle has been built.
Owner owner
Which company owns the vehicle?
UnitID unitnumber
unit number, for display purposes only
bool NeedsAutomaticServicing() const
Checks if the current order should be interrupted for a service-in-depot order.
Definition vehicle.cpp:294
uint8_t running_ticks
Number of ticks this vehicle was not stopped this day.
GrfID GetGRFID() const
Retrieve the GRF ID of the NewGRF the vehicle is tied to.
Definition vehicle.cpp:770
@ EnteredStation
The vehicle entered a station.
Definition tile_cmd.h:25
@ CannotEnter
The vehicle cannot enter the tile.
Definition tile_cmd.h:27
@ EnteredWormhole
The vehicle either entered a bridge, tunnel or depot tile (this includes the last tile of the bridge/...
Definition tile_cmd.h:26
VehicleEnterTileStates VehicleEnterTile(Vehicle *v, TileIndex tile, int x, int y)
Call the tile callback function for a vehicle entering a tile.
Definition vehicle.cpp:1865
static bool IsTileType(Tile tile, TileType type)
Checks if a tile is a given tiletype.
Definition tile_map.h:150
bool IsTileOwner(Tile tile, Owner owner)
Checks if a tile belongs to the given owner.
Definition tile_map.h:214
Owner GetTileOwner(Tile tile)
Returns the owner of a tile.
Definition tile_map.h:178
StrongType::Typedef< uint32_t, struct TileIndexTag, StrongType::Compare, StrongType::Integer, StrongType::Compatible< int32_t >, StrongType::Compatible< int64_t > > TileIndex
The index/ID of a Tile.
Definition tile_type.h:92
constexpr TileIndex INVALID_TILE
The very nice invalid tile marker.
Definition tile_type.h:100
static constexpr uint TILE_SIZE
Tile size in world coordinates.
Definition tile_type.h:15
@ TunnelBridge
Tunnel entry/exit and bridge heads.
Definition tile_type.h:58
@ Station
A tile of a station or airport.
Definition tile_type.h:54
@ Railway
A tile with railway.
Definition tile_type.h:50
Definition of the game-calendar-timer.
Definition of the game-economy-timer.
Track TrackdirToTrack(Trackdir trackdir)
Returns the Track that a given Trackdir represents.
Definition track_func.h:235
TrackdirBits TrackBitsToTrackdirBits(TrackBits bits)
Converts TrackBits to TrackdirBits while allowing both directions.
Definition track_func.h:292
DiagDirection VehicleExitDir(Direction direction, TrackBits track)
Determine the side in which the vehicle will leave the tile.
Definition track_func.h:609
Track TrackBitsToTrack(TrackBits tracks)
Converts TrackBits to Track.
Definition track_func.h:166
TrackBits TrackCrossesTracks(Track track)
Maps a track to all tracks that make 90 deg turns with it.
Definition track_func.h:324
Trackdir ReverseTrackdir(Trackdir trackdir)
Maps a trackdir to the reverse trackdir.
Definition track_func.h:220
bool TracksOverlap(TrackBits bits)
Checks if the given tracks overlap, ie form a crossing.
Definition track_func.h:540
Trackdir TrackDirectionToTrackdir(Track track, Direction dir)
Maps a track and a full (8-way) direction to the trackdir that represents the track running in the gi...
Definition track_func.h:405
bool IsValidTrackdir(Trackdir trackdir)
Checks if a Trackdir is valid for non-road vehicles.
Definition track_func.h:48
Trackdir FindFirstTrackdir(TrackdirBits trackdirs)
Returns first Trackdir from TrackdirBits or Trackdir::Invalid.
Definition track_func.h:184
TrackdirBits TrackdirCrossesTrackdirs(Trackdir trackdir)
Maps a trackdir to all trackdirs that make 90 deg turns with it.
Definition track_func.h:501
TrackdirBits TrackdirReachesTrackdirs(Trackdir trackdir)
Maps a trackdir to the trackdirs that can be reached from it (ie, when entering the next tile.
Definition track_func.h:479
TrackdirBits DiagdirReachesTrackdirs(DiagDirection diagdir)
Returns all trackdirs that can be reached when entering a tile from a given (diagonal) direction.
Definition track_func.h:450
bool IsValidTrack(Track track)
Checks if a Track is valid.
Definition track_func.h:24
Track FindFirstTrack(TrackBits tracks)
Returns first Track from TrackBits or Track::Invalid.
Definition track_func.h:150
Trackdir RemoveFirstTrackdir(TrackdirBits &trackdirs)
Removes first Trackdir from TrackdirBits and returns it.
Definition track_func.h:130
Trackdir TrackEnterdirToTrackdir(Track track, DiagDirection diagdir)
Maps a track and an (4-way) dir to the trackdir that represents the track with the entry in the given...
Definition track_func.h:390
TrackBits DiagdirReachesTracks(DiagDirection diagdir)
Returns all tracks that can be reached when entering a tile from a given (diagonal) direction.
Definition track_func.h:468
Trackdir DiagDirToDiagTrackdir(DiagDirection diagdir)
Maps a (4-way) direction to the diagonal trackdir that runs in that direction.
Definition track_func.h:432
Track AxisToTrack(Axis a)
Convert an Axis to the corresponding Track Axis::X -> Track::X Axis::Y -> Track::Y Uses the fact that...
Definition track_func.h:62
DiagDirection TrackdirToExitdir(Trackdir trackdir)
Maps a trackdir to the (4-way) direction the tile is exited when following that trackdir.
Definition track_func.h:343
Track DiagDirToDiagTrack(DiagDirection diagdir)
Maps a DiagDirection to the associated diagonal Track.
Definition track_func.h:419
TrackBits TrackdirBitsToTrackBits(TrackdirBits bits)
Discards all directional information from a TrackdirBits value.
Definition track_func.h:281
EnumBitSet< Trackdir, uint16_t > TrackdirBits
Bitset of Trackdir elements.
Definition track_type.h:93
EnumBitSet< Track, uint8_t > TrackBits
Bitset of Track elements.
Definition track_type.h:43
static constexpr TrackBits TRACK_BIT_ALL
All possible tracks.
Definition track_type.h:52
Trackdir
Enumeration for tracks and directions.
Definition track_type.h:63
@ Invalid
Flag for an invalid trackdir.
Definition track_type.h:82
Track
These are used to specify a single track.
Definition track_type.h:19
@ X
Track along the x-axis (north-east to south-west).
Definition track_type.h:21
@ Upper
Track in the upper corner of the tile (north).
Definition track_type.h:23
@ Begin
Used for iterations.
Definition track_type.h:20
@ Invalid
Flag for an invalid track.
Definition track_type.h:32
@ Y
Track along the y-axis (north-west to south-east).
Definition track_type.h:22
@ Right
Track in the right corner of the tile (east).
Definition track_type.h:26
@ Left
Track in the left corner of the tile (west).
Definition track_type.h:25
@ Depot
Special flag indicating a vehicle is inside a depot.
Definition track_type.h:30
@ Lower
Track in the lower corner of the tile (south).
Definition track_type.h:24
@ Wormhole
Special flag indicating vehicle is inside a bridge or tunnel.
Definition track_type.h:29
Base for the train class.
@ Capacity
Allow vehicles to change capacity.
Definition train.h:48
@ Length
Allow vehicles to change length.
Definition train.h:47
EnumBitSet< ConsistChangeFlag, uint8_t > ConsistChangeFlags
Bitset of the ConsistChangeFlag elements.
Definition train.h:51
static constexpr ConsistChangeFlags CCF_TRACK
Valid changes while vehicle is driving, and possibly changing tracks.
Definition train.h:53
bool TryPathReserve(Train *v, bool mark_as_stuck=false, bool first_tile_okay=false)
Try to reserve a path to a safe position.
int GetTrainStopLocation(StationID station_id, TileIndex tile, const Train *moving_front, int *station_ahead, int *station_length)
Get the stop location of (the center) of the front vehicle of a train at a platform of a station.
void FreeTrainTrackReservation(const Train *v)
Free the reserved path in front of a vehicle.
@ Reversed
Used for vehicle var 0xFE bit 8 (toggled each time the train is reversed, accurate for first vehicle ...
Definition train.h:31
@ LeavingStation
Train is just leaving a station.
Definition train.h:33
@ PoweredWagon
Wagon is powered.
Definition train.h:27
@ Reversing
Train is slowing down to reverse.
Definition train.h:26
@ Stuck
Train can't get a path reservation.
Definition train.h:32
@ AllowedOnNormalRail
Electric train engine is allowed to run on normal rail. *‍/.
Definition train.h:30
@ Flipped
Reverse the visible direction of the vehicle.
Definition train.h:28
TrainForceProceeding
Modes for ignoring signals.
Definition train.h:39
@ TFP_SIGNAL
Ignore next signal, after the signal ignore being stuck.
Definition train.h:42
@ TFP_NONE
Normal operation.
Definition train.h:40
@ TFP_STUCK
Proceed till next signal, but ignore being stuck till then. This includes force leaving depots.
Definition train.h:41
static constexpr ConsistChangeFlags CCF_ARRANGE
Valid changes for arranging the consist in a depot.
Definition train.h:57
static CommandCost CmdBuildRailWagon(DoCommandFlags flags, TileIndex tile, const Engine *e, Vehicle **ret)
Build a railroad wagon.
void FreeTrainTrackReservation(const Train *consist)
Free the reserved path in front of a vehicle.
static void NormaliseTrainHead(Train *head)
Normalise the head of the train again, i.e.
static CommandCost ValidateTrains(Train *original_dst, Train *dst, Train *original_src, Train *src, bool check_limit)
Validate whether we are going to create valid trains.
static bool CheckTrainStayInDepot(Train *v)
Will the train stay in the depot the next tick?
static FindDepotData FindClosestTrainDepot(Train *v, int max_distance)
Try to find a depot nearby.
CommandCost CmdForceTrainProceed(DoCommandFlags flags, VehicleID veh_id)
Force a train through a red signal.
void UpdateLevelCrossing(TileIndex tile, bool sound, bool force_bar)
Update a level crossing to barred or open (crossing may include multiple adjacent tiles).
int GetTrainStopLocation(StationID station_id, TileIndex tile, const Train *moving_front, int *station_ahead, int *station_length)
Get the stop location of (the center) of the front vehicle of a train at a platform of a station.
static uint TrainsCrashed(Train *v, Train *u)
Marks trains as crashed and creates an script events.
static bool CheckCompatibleRail(const Train *v, TileIndex tile, bool check_railtype)
Check if the vehicle is compatible with the specified tile.
static void AdvanceWagonsBeforeSwap(Train *moving_front)
Advances wagons for train reversing, needed for variable length wagons.
static void MakeTrainBackup(TrainList &list, Train *t)
Make a backup of a train into a train list.
static void ArrangeTrains(Train **dst_head, Train *dst, Train **src_head, Train *src, bool move_chain)
Arrange the trains in the wanted way.
static bool TryReserveSafeTrack(const Train *v, TileIndex tile, Trackdir td, bool override_railtype)
Try to reserve any path to a safe tile, ignoring the vehicle's destination.
static const uint16_t _breakdown_speeds[16]
Maximum speeds for train that is broken down or approaching line end.
static void InsertInConsist(Train *dst, Train *chain)
Inserts a chain into the train at dst.
void UpdateAdjacentLevelCrossingTilesOnLevelCrossingRemoval(TileIndex tile, Axis road_axis)
Update adjacent level crossing tiles in this multi-track crossing, due to removal of a level crossing...
static constexpr DiagDirectionIndexArray< uint8_t > _vehicle_initial_y_fract
Initial y subtile coordinate of rail vehicles for each direction.
Definition train_cmd.cpp:65
static void MarkTrainAsStuck(Train *consist)
Mark a train as stuck and stop it if it isn't stopped right now.
static void UpdateLevelCrossingTile(TileIndex tile, bool sound, bool force_barred)
Sets a level crossing tile to the correct state.
static constexpr DiagDirectionIndexArray< uint8_t > _vehicle_initial_x_fract
Initial x subtile coordinate of rail vehicles for each direction.
Definition train_cmd.cpp:63
static void CheckNextTrainTile(Train *v)
Check if the train is on the last reserved tile and try to extend the path then.
static bool HandleCrashedTrain(Train *v)
Handle a crashed train.
void NormalizeTrainVehInDepot(const Train *u)
Move all free vehicles in the depot to the train.
CommandCost CmdReverseTrainDirection(DoCommandFlags flags, VehicleID veh_id, bool reverse_single_veh)
Reverse train.
static bool CheckLevelCrossing(TileIndex tile)
Check if a level crossing should be barred.
static CommandCost CheckNewTrain(Train *original_dst, Train *dst, Train *original_src, Train *src)
Check/validate whether we may actually build a new train.
CommandCost CmdBuildRailVehicle(DoCommandFlags flags, TileIndex tile, const Engine *e, Vehicle **ret)
Build a railroad vehicle.
static void UpdateStatusAfterSwap(Train *v, bool reverse=true)
Updates some variables after swapping the vehicle.
uint8_t FreightWagonMult(CargoType cargo)
Return the cargo weight multiplier to use for a rail vehicle.
Definition train_cmd.cpp:80
static uint CheckTrainCollision(Vehicle *v, Train *moving_front)
Collision test function.
bool TryPathReserve(Train *consist, bool mark_as_stuck, bool first_tile_okay)
Try to reserve a path to a safe position.
static uint TrainCrashed(Train *v)
Marks train as crashed and creates an AI event.
static void NormaliseDualHeads(Train *t)
Normalise the dual heads in the train, i.e.
static CommandCost CheckTrainAttachment(Train *t)
Check whether the train parts can be attached.
static const AccelerationSlowdownParams _accel_slowdown[]
Speed update fractions for each acceleration type.
CommandCost CmdMoveRailVehicle(DoCommandFlags flags, VehicleID src_veh, VehicleID dest_veh, bool move_chain)
Move a rail vehicle around inside the depot.
void ReverseTrainSwapVehicles(Train *v)
Swap vehicles in chain starting from v, and reverse their direction.
static Track DoTrainPathfind(const Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool &path_found, bool do_track_reservation, PBSTileInfo *dest, TileIndex *final_dest)
Perform pathfinding for a train.
static void TrainEnterStation(Train *consist, StationID station)
Trains enters a station, send out a news item if it is the first train, and start loading.
static bool TrainLocoHandler(Train *consist, bool mode)
Per-tick handler of each front engine.
static bool TrainCanLeaveTile(const Train *moving_front)
Determines whether train would like to leave the tile.
static void AffectSpeedByZChange(Train *consist, int z_diff)
Modify the speed of the vehicle due to a change in altitude.
static void ReverseTrainSwapVeh(Train *v, int l, int r)
Swap vehicles l and r in consist v, and reverse their direction.
static void ClearPathReservation(const Train *v, TileIndex tile, Trackdir track_dir)
Clear the reservation of tile that was just left by a wagon on track_dir.
static void ReverseTrainDirection(Train *consist)
Turn a train around.
static bool IsTrain(const Vehicle *v)
Check if the vehicle is a train.
void CheckTrainsLengths()
Checks if lengths of all rail vehicles are valid.
Definition train_cmd.cpp:87
static bool CheckReverseTrain(const Train *consist)
Can the train reverse?
static void MaybeBarCrossingWithSound(TileIndex tile)
Bars crossing and plays ding-ding sound if not barred already.
bool TrainOnCrossing(TileIndex tile)
Check if a level crossing tile has a train on it.
static void ChangeTrainDirRandomly(Train *v)
Rotate all vehicles of a (crashed) train chain randomly to animate the crash.
void MarkDirtyAdjacentLevelCrossingTiles(TileIndex tile, Axis road_axis)
Find adjacent level crossing tiles in this multi-track crossing and mark them dirty.
static void NormaliseSubtypes(Train *chain)
Normalise the sub types of the parts in this chain.
bool TrainController(Train *v, Vehicle *nomove, bool reverse=true)
Move a vehicle chain one movement stop forwards.
CommandCost CmdSellRailWagon(DoCommandFlags flags, Vehicle *t, bool sell_chain, bool backup_order, ClientID user)
Sell a (single) train wagon/engine.
bool IsValidImageIndex< VehicleType::Train >(uint8_t image_index)
Helper to check whether an image index is valid for a particular vehicle.
Definition train_cmd.cpp:69
static TrainForceProceeding DetermineNextTrainForceProceeding(const Train *t)
Determine to what force_proceed should be changed.
static void RemoveFromConsist(Train *part, bool chain=false)
Remove the given wagon from its consist.
static bool TrainCheckIfLineEnds(Train *v, bool reverse=true)
Checks for line end.
static void RestoreTrainBackup(TrainList &list)
Restore the train from the backup list.
static void DeleteLastWagon(Train *v)
Deletes/Clears the last wagon of a crashed train.
static bool TrainApproachingLineEnd(Train *moving_front, bool signal, bool reverse)
Train is approaching line end, slow down and possibly reverse.
static bool TrainApproachingCrossing(TileIndex tile)
Finds a vehicle approaching rail-road crossing.
static void SwapTrainFlags(GroundVehicleFlags *swap_flag1, GroundVehicleFlags *swap_flag2)
Swap the two up/down flags in two ways:
static PBSTileInfo ExtendTrainReservation(const Train *v, TrackBits *new_tracks, DiagDirection *enterdir)
Extend a train path as far as possible.
static TileIndex TrainApproachingCrossingTile(const Train *v)
Determines whether train is approaching a rail-road crossing (thus making it barred).
static void AdvanceWagonsAfterSwap(Train *moving_front)
Advances wagons for train reversing, needed for variable length wagons.
void GetTrainSpriteSize(EngineID engine, uint &width, uint &height, int &xoffs, int &yoffs, EngineImageType image_type)
Get the size of the sprite of a train sprite heading west, or both heads (used for lists).
static void CheckIfTrainNeedsService(Train *v)
Check whether a train needs service, and if so, find a depot or service it.
static bool TrainApproachingCrossingEnum(const Vehicle *v, TileIndex tile)
Checks if a train is approaching a rail-road crossing.
static std::vector< VehicleID > GetFreeWagonsInDepot(TileIndex tile)
Get a list of free wagons in a depot.
Command definitions related to trains.
Sprites to use for trains.
static const uint8_t _engine_sprite_and[]
For how many directions do we have sprites?
static const uint8_t _engine_sprite_add[]
Non-zero for multihead trains.
@ Rail
Transport by train.
bool IsTunnel(Tile t)
Is this a tunnel (entrance)?
Definition tunnel_map.h:23
void MarkBridgeDirty(TileIndex begin, TileIndex end, DiagDirection direction, uint bridge_height)
Mark bridge tiles dirty.
Functions that have tunnels and bridges in common.
DiagDirection GetTunnelBridgeDirection(Tile t)
Get the direction pointing to the other end.
TileIndex GetOtherTunnelBridgeEnd(Tile t)
Determines type of the wormhole and returns its other end.
void SetTunnelBridgeReservation(Tile t, bool b)
Set the reservation state of the rail tunnel/bridge.
void ShowNewGrfVehicleError(EngineID engine, StringID part1, StringID part2, GRFBug bug_type, bool critical)
Displays a "NewGrf Bug" error message for a engine, and pauses the game if not networking.
Definition vehicle.cpp:339
void VehicleEnterDepot(Vehicle *v)
Vehicle entirely entered the depot, update its status, orders, vehicle windows, service it,...
Definition vehicle.cpp:1564
UnitID GetFreeUnitNumber(VehicleType type)
Get an unused unit number for a vehicle (if allowed).
Definition vehicle.cpp:1922
void VehicleLengthChanged(const Vehicle *u)
Logs a bug in GRF and shows a warning message if this is for the first time this happened.
Definition vehicle.cpp:365
void VehicleServiceInDepot(Vehicle *v)
Service a vehicle and all subsequent vehicles in the consist.
Definition vehicle.cpp:189
void CheckVehicleBreakdown(Vehicle *v)
Periodic check for a vehicle to maybe break down.
Definition vehicle.cpp:1320
GetNewVehiclePosResult GetNewVehiclePos(const Vehicle *v)
Get position information of a vehicle when moving one pixel in the direction it is facing.
Definition vehicle.cpp:1804
void DecreaseVehicleValue(Vehicle *v)
Decrease the value of a vehicle.
Definition vehicle.cpp:1299
void EconomyAgeVehicle(Vehicle *v)
Update economy age of a vehicle.
Definition vehicle.cpp:1442
CommandCost TunnelBridgeIsFree(TileIndex tile, TileIndex endtile, const Vehicle *ignore)
Finds vehicle in tunnel / bridge.
Definition vehicle.cpp:583
void AgeVehicle(Vehicle *v)
Update age of a vehicle.
Definition vehicle.cpp:1454
Direction VehicleEnterTileCoordinates(GetNewVehiclePosResult &gp, DiagDirection enterdir, Track track)
Lookup new subposition coordinates and direction to use when entering a new tile, applying the subcoo...
Definition vehicle.cpp:3413
@ Crashed
Vehicle is crashed.
@ TrainSlowing
Train is slowing down.
@ Hidden
Vehicle is not visible.
@ DefaultPalette
Use default vehicle palette.
@ Stopped
Vehicle is stopped by the player.
Functions related to vehicles.
bool IsValidImageIndex(uint8_t image_index)
Helper to check whether an image index is valid for a particular vehicle.
@ CUSTOM_VEHICLE_SPRITENUM_REVERSED
Vehicle sprite from NewGRF with reverse driving direction (from articulation callback).
bool HasVehicleOnTile(TileIndex tile, UnaryPred &&predicate)
Loop over vehicles on a tile, and check whether a predicate is true for any of them.
Functions related to the vehicle's GUIs.
@ VIWD_CONSIST_CHANGED
Vehicle composition was changed.
Definition vehicle_gui.h:36
EngineImageType
Visualisation contexts of vehicles and engines.
PoolID< uint32_t, struct VehicleIDTag, 0xFF000, 0xFFFFF > VehicleID
The type all our vehicle IDs have.
@ Train
Train vehicle type.
@ Original
Original acceleration model.
@ Realistic
"Realistic" acceleration model.
EnumBitSet< GroundVehicleFlag, uint16_t > GroundVehicleFlags
Bitset of GroundVehicleFlag elements.
@ GoingUp
Vehicle is currently going uphill. (Cached track information for acceleration).
@ SuppressImplicitOrders
Disable insertion and removal of automatic orders until the vehicle completes the real order.
@ GoingDown
Vehicle is currently going downhill. (Cached track information for acceleration).
static const uint VEHICLE_LENGTH
The length of a vehicle in tile units.
Types related to the vehicle widgets.
@ WID_VV_REFIT
Open the refit window.
@ WID_VV_START_STOP
Start or stop this vehicle, and show information about the current state.
Functions related to (drawing on) viewports.
void CloseWindowById(WindowClass cls, WindowNumber number, bool force, int data)
Close a window by its class and window number (if it is open).
Definition window.cpp:1242
void SetWindowClassesDirty(WindowClass cls)
Mark all windows of a particular class as dirty (in need of repainting).
Definition window.cpp:3285
void InvalidateWindowData(WindowClass cls, WindowNumber number, int data, bool gui_scope)
Mark window data of the window of a given class and specific window number as invalid (in need of re-...
Definition window.cpp:3377
void SetWindowWidgetDirty(WindowClass cls, WindowNumber number, WidgetID widget_index)
Mark a particular widget in a particular window as dirty (in need of repainting).
Definition window.cpp:3271
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting).
Definition window.cpp:3255
void InvalidateWindowClassesData(WindowClass cls, int data, bool gui_scope)
Mark window data of all windows of a given class as invalid (in need of re-computing) Note that by de...
Definition window.cpp:3395
Entry point for OpenTTD to YAPF.
FindDepotData YapfTrainFindNearestDepot(const Train *v, int max_distance)
Used when user sends train to the nearest depot or if train needs servicing using YAPF.
bool YapfTrainFindNearestSafeTile(const Train *v, TileIndex tile, Trackdir td, bool override_railtype)
Try to extend the reserved path of a train to the nearest safe tile using YAPF.
bool YapfTrainCheckReverse(const Train *v)
Returns true if it is better to reverse the train before leaving station using YAPF.
Track YapfTrainChooseTrack(const Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool &path_found, bool reserve_track, struct PBSTileInfo *target, TileIndex *dest)
Finds the best path for given train using YAPF.
Functions related to zooming.
int ScaleSpriteTrad(int value)
Scale traditional pixel dimensions to GUI zoom level, for drawing sprites.
Definition zoom_func.h:107
int UnScaleGUI(int value)
Short-hand to apply GUI zoom level.
Definition zoom_func.h:77