OpenTTD Source 20250528-master-g3aca5d62a8
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 <http://www.gnu.org/licenses/>.
6 */
7
10#include "stdafx.h"
11#include "error.h"
13#include "command_func.h"
14#include "error_func.h"
16#include "news_func.h"
17#include "company_func.h"
18#include "newgrf_sound.h"
19#include "newgrf_text.h"
20#include "strings_func.h"
21#include "viewport_func.h"
22#include "vehicle_func.h"
23#include "sound_func.h"
24#include "ai/ai.hpp"
25#include "game/game.hpp"
26#include "newgrf_station.h"
27#include "effectvehicle_func.h"
28#include "network/network.h"
29#include "spritecache.h"
30#include "core/random_func.hpp"
31#include "company_base.h"
32#include "newgrf.h"
33#include "order_backup.h"
34#include "zoom_func.h"
35#include "newgrf_debug.h"
36#include "framerate_type.h"
37#include "train_cmd.h"
38#include "misc_cmd.h"
41
42#include "table/strings.h"
43#include "table/train_sprites.h"
44
45#include "safeguards.h"
46
47static Track ChooseTrainTrack(Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool force_res, bool *got_reservation, bool mark_stuck);
48static bool TrainCheckIfLineEnds(Train *v, bool reverse = true);
49bool TrainController(Train *v, Vehicle *nomove, bool reverse = true); // Also used in vehicle_sl.cpp.
51static void CheckIfTrainNeedsService(Train *v);
52static void CheckNextTrainTile(Train *v);
53
54static const uint8_t _vehicle_initial_x_fract[4] = {10, 8, 4, 8};
55static const uint8_t _vehicle_initial_y_fract[4] = { 8, 4, 8, 10};
56
57template <>
58bool IsValidImageIndex<VEH_TRAIN>(uint8_t image_index)
59{
60 return image_index < lengthof(_engine_sprite_base);
61}
62
63
70{
71 if (!CargoSpec::Get(cargo)->is_freight) return 1;
73}
74
77{
78 bool first = true;
79
80 for (const Train *v : Train::Iterate()) {
81 if (v->First() == v && !v->vehstatus.Test(VehState::Crashed)) {
82 for (const Train *u = v, *w = v->Next(); w != nullptr; u = w, w = w->Next()) {
83 if (u->track != TRACK_BIT_DEPOT) {
84 if ((w->track != TRACK_BIT_DEPOT &&
85 std::max(abs(u->x_pos - w->x_pos), abs(u->y_pos - w->y_pos)) != u->CalcNextVehicleOffset()) ||
86 (w->track == TRACK_BIT_DEPOT && TicksToLeaveDepot(u) <= 0)) {
87 ShowErrorMessage(GetEncodedString(STR_BROKEN_VEHICLE_LENGTH, v->index, v->owner), {}, WL_CRITICAL);
88
89 if (!_networking && first) {
90 first = false;
92 }
93 /* Break so we warn only once for each train. */
94 break;
95 }
96 }
97 }
98 }
99 }
100}
101
109{
110 uint16_t max_speed = UINT16_MAX;
111
112 assert(this->IsFrontEngine() || this->IsFreeWagon());
113
114 const RailVehicleInfo *rvi_v = RailVehInfo(this->engine_type);
115 EngineID first_engine = this->IsFrontEngine() ? this->engine_type : EngineID::Invalid();
116 this->gcache.cached_total_length = 0;
117 this->compatible_railtypes = {};
118
119 bool train_can_tilt = true;
120 int16_t min_curve_speed_mod = INT16_MAX;
121
122 for (Train *u = this; u != nullptr; u = u->Next()) {
123 const RailVehicleInfo *rvi_u = RailVehInfo(u->engine_type);
124
125 /* Check the this->first cache. */
126 assert(u->First() == this);
127
128 /* update the 'first engine' */
129 u->gcache.first_engine = this == u ? EngineID::Invalid() : first_engine;
130 u->railtype = rvi_u->railtype;
131
132 if (u->IsEngine()) first_engine = u->engine_type;
133
134 /* Set user defined data to its default value */
135 u->tcache.user_def_data = rvi_u->user_def_data;
136 this->InvalidateNewGRFCache();
137 u->InvalidateNewGRFCache();
138 }
139
140 for (Train *u = this; u != nullptr; u = u->Next()) {
141 /* Update user defined data (must be done before other properties) */
142 u->tcache.user_def_data = GetVehicleProperty(u, PROP_TRAIN_USER_DATA, u->tcache.user_def_data);
143 this->InvalidateNewGRFCache();
144 u->InvalidateNewGRFCache();
145 }
146
147 for (Train *u = this; u != nullptr; u = u->Next()) {
148 const Engine *e_u = u->GetEngine();
149 const RailVehicleInfo *rvi_u = &e_u->u.rail;
150
151 if (!e_u->info.misc_flags.Test(EngineMiscFlag::RailTilts)) train_can_tilt = false;
152 min_curve_speed_mod = std::min(min_curve_speed_mod, u->GetCurveSpeedModifier());
153
154 /* Cache wagon override sprite group. nullptr is returned if there is none */
155 u->tcache.cached_override = GetWagonOverrideSpriteSet(u->engine_type, u->cargo_type, u->gcache.first_engine);
156
157 /* Reset colour map */
158 u->colourmap = PAL_NONE;
159
160 /* Update powered-wagon-status and visual effect */
161 u->UpdateVisualEffect(true);
162
163 if (rvi_v->pow_wag_power != 0 && rvi_u->railveh_type == RAILVEH_WAGON &&
164 UsesWagonOverride(u) && !HasBit(u->vcache.cached_vis_effect, VE_DISABLE_WAGON_POWER)) {
165 /* wagon is powered */
166 u->flags.Set(VehicleRailFlag::PoweredWagon); // cache 'powered' status
167 } else {
168 u->flags.Reset(VehicleRailFlag::PoweredWagon);
169 }
170
171 if (!u->IsArticulatedPart()) {
172 /* Do not count powered wagons for the compatible railtypes, as wagons always
173 have railtype normal */
174 if (rvi_u->power > 0) {
175 this->compatible_railtypes.Set(GetRailTypeInfo(u->railtype)->powered_railtypes);
176 }
177
178 /* Some electric engines can be allowed to run on normal rail. It happens to all
179 * existing electric engines when elrails are disabled and then re-enabled */
180 if (u->flags.Test(VehicleRailFlag::AllowedOnNormalRail)) {
181 u->railtype = RAILTYPE_RAIL;
182 u->compatible_railtypes.Set(RAILTYPE_RAIL);
183 }
184
185 /* max speed is the minimum of the speed limits of all vehicles in the consist */
186 if ((rvi_u->railveh_type != RAILVEH_WAGON || _settings_game.vehicle.wagon_speed_limits) && !UsesWagonOverride(u)) {
187 uint16_t speed = GetVehicleProperty(u, PROP_TRAIN_SPEED, rvi_u->max_speed);
188 if (speed != 0) max_speed = std::min(speed, max_speed);
189 }
190 }
191
192 uint16_t new_cap = e_u->DetermineCapacity(u);
193 if (allowed_changes.Test(ConsistChangeFlag::Capacity)) {
194 /* Update vehicle capacity. */
195 if (u->cargo_cap > new_cap) u->cargo.Truncate(new_cap);
196 u->refit_cap = std::min(new_cap, u->refit_cap);
197 u->cargo_cap = new_cap;
198 } else {
199 /* Verify capacity hasn't changed. */
200 if (new_cap != u->cargo_cap) ShowNewGrfVehicleError(u->engine_type, STR_NEWGRF_BROKEN, STR_NEWGRF_BROKEN_CAPACITY, GRFBug::VehCapacity, true);
201 }
202 u->vcache.cached_cargo_age_period = GetVehicleProperty(u, PROP_TRAIN_CARGO_AGE_PERIOD, e_u->info.cargo_age_period);
203
204 /* check the vehicle length (callback) */
205 uint16_t veh_len = CALLBACK_FAILED;
206 if (e_u->GetGRF() != nullptr && e_u->GetGRF()->grf_version >= 8) {
207 /* Use callback 36 */
208 veh_len = GetVehicleProperty(u, PROP_TRAIN_SHORTEN_FACTOR, CALLBACK_FAILED);
209
210 if (veh_len != CALLBACK_FAILED && veh_len >= VEHICLE_LENGTH) {
212 }
213 } else if (e_u->info.callback_mask.Test(VehicleCallbackMask::Length)) {
214 /* Use callback 11 */
215 veh_len = GetVehicleCallback(CBID_VEHICLE_LENGTH, 0, 0, u->engine_type, u);
216 }
217 if (veh_len == CALLBACK_FAILED) veh_len = rvi_u->shorten_factor;
218 veh_len = VEHICLE_LENGTH - Clamp(veh_len, 0, VEHICLE_LENGTH - 1);
219
220 if (allowed_changes.Test(ConsistChangeFlag::Length)) {
221 /* Update vehicle length. */
222 u->gcache.cached_veh_length = veh_len;
223 } else {
224 /* Verify length hasn't changed. */
225 if (veh_len != u->gcache.cached_veh_length) VehicleLengthChanged(u);
226 }
227
228 this->gcache.cached_total_length += u->gcache.cached_veh_length;
229 this->InvalidateNewGRFCache();
230 u->InvalidateNewGRFCache();
231 }
232
233 /* store consist weight/max speed in cache */
234 this->vcache.cached_max_speed = max_speed;
235 this->tcache.cached_tilt = train_can_tilt;
236 this->tcache.cached_curve_speed_mod = min_curve_speed_mod;
237 this->tcache.cached_max_curve_speed = this->GetCurveSpeedLimit();
238
239 /* 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) */
240 this->CargoChanged();
241
242 if (this->IsFrontEngine()) {
243 this->UpdateAcceleration();
247 InvalidateNewGRFInspectWindow(GSF_TRAINS, this->index);
248 }
249}
250
261int GetTrainStopLocation(StationID station_id, TileIndex tile, const Train *v, int *station_ahead, int *station_length)
262{
263 const Station *st = Station::Get(station_id);
264 *station_ahead = st->GetPlatformLength(tile, DirToDiagDir(v->direction)) * TILE_SIZE;
265 *station_length = st->GetPlatformLength(tile) * TILE_SIZE;
266
267 /* Default to the middle of the station for stations stops that are not in
268 * the order list like intermediate stations when non-stop is disabled */
270 if (v->gcache.cached_total_length >= *station_length) {
271 /* The train is longer than the station, make it stop at the far end of the platform */
273 } else if (v->current_order.IsType(OT_GOTO_STATION) && v->current_order.GetDestination() == station_id) {
275 }
276
277 /* The stop location of the FRONT! of the train */
278 int stop;
279 switch (osl) {
280 default: NOT_REACHED();
281
283 stop = v->gcache.cached_total_length;
284 break;
285
287 stop = *station_length - (*station_length - v->gcache.cached_total_length) / 2;
288 break;
289
291 stop = *station_length;
292 break;
293 }
294
295 /* Subtract half the front vehicle length of the train so we get the real
296 * stop location of the train. */
297 return stop - (v->gcache.cached_veh_length + 1) / 2;
298}
299
300
306{
307 assert(this->First() == this);
308
309 static const int absolute_max_speed = UINT16_MAX;
310 int max_speed = absolute_max_speed;
311
312 if (_settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) return max_speed;
313
314 int curvecount[2] = {0, 0};
315
316 /* first find the curve speed limit */
317 int numcurve = 0;
318 int sum = 0;
319 int pos = 0;
320 int lastpos = -1;
321 for (const Train *u = this; u->Next() != nullptr; u = u->Next(), pos += u->gcache.cached_veh_length) {
322 Direction this_dir = u->direction;
323 Direction next_dir = u->Next()->direction;
324
325 DirDiff dirdiff = DirDifference(this_dir, next_dir);
326 if (dirdiff == DIRDIFF_SAME) continue;
327
328 if (dirdiff == DIRDIFF_45LEFT) curvecount[0]++;
329 if (dirdiff == DIRDIFF_45RIGHT) curvecount[1]++;
330 if (dirdiff == DIRDIFF_45LEFT || dirdiff == DIRDIFF_45RIGHT) {
331 if (lastpos != -1) {
332 numcurve++;
333 sum += pos - lastpos;
334 if (pos - lastpos <= static_cast<int>(VEHICLE_LENGTH) && max_speed > 88) {
335 max_speed = 88;
336 }
337 }
338 lastpos = pos;
339 }
340
341 /* if we have a 90 degree turn, fix the speed limit to 60 */
342 if (dirdiff == DIRDIFF_90LEFT || dirdiff == DIRDIFF_90RIGHT) {
343 max_speed = 61;
344 }
345 }
346
347 if (numcurve > 0 && max_speed > 88) {
348 if (curvecount[0] == 1 && curvecount[1] == 1) {
349 max_speed = absolute_max_speed;
350 } else {
351 sum = CeilDiv(sum, VEHICLE_LENGTH);
352 sum /= numcurve;
353 max_speed = 232 - (13 - Clamp(sum, 1, 12)) * (13 - Clamp(sum, 1, 12));
354 }
355 }
356
357 if (max_speed != absolute_max_speed) {
358 /* Apply the current railtype's curve speed advantage */
359 const RailTypeInfo *rti = GetRailTypeInfo(GetRailType(this->tile));
360 max_speed += (max_speed / 2) * rti->curve_speed;
361
362 if (this->tcache.cached_tilt) {
363 /* Apply max_speed bonus of 20% for a tilting train */
364 max_speed += max_speed / 5;
365 }
366
367 /* Apply max_speed modifier (cached value is fixed-point binary with 8 fractional bits)
368 * and clamp the result to an acceptable range. */
369 max_speed += (max_speed * this->tcache.cached_curve_speed_mod) / 256;
370 max_speed = Clamp(max_speed, 2, absolute_max_speed);
371 }
372
373 return static_cast<uint16_t>(max_speed);
374}
375
381{
382 int max_speed = _settings_game.vehicle.train_acceleration_model == AM_ORIGINAL ?
384 this->tcache.cached_max_curve_speed;
385
387 StationID sid = GetStationIndex(this->tile);
388 if (this->current_order.ShouldStopAtStation(this, sid)) {
389 int station_ahead;
390 int station_length;
391 int stop_at = GetTrainStopLocation(sid, this->tile, this, &station_ahead, &station_length);
392
393 /* The distance to go is whatever is still ahead of the train minus the
394 * distance from the train's stop location to the end of the platform */
395 int distance_to_go = station_ahead / TILE_SIZE - (station_length - stop_at) / TILE_SIZE;
396
397 if (distance_to_go > 0) {
398 int st_max_speed = 120;
399
400 int delta_v = this->cur_speed / (distance_to_go + 1);
401 if (max_speed > (this->cur_speed - delta_v)) {
402 st_max_speed = this->cur_speed - (delta_v / 10);
403 }
404
405 st_max_speed = std::max(st_max_speed, 25 * distance_to_go);
406 max_speed = std::min(max_speed, st_max_speed);
407 }
408 }
409 }
410
411 for (const Train *u = this; u != nullptr; u = u->Next()) {
412 if (_settings_game.vehicle.train_acceleration_model == AM_REALISTIC && u->track == TRACK_BIT_DEPOT) {
413 max_speed = std::min(max_speed, 61);
414 break;
415 }
416
417 /* Vehicle is on the middle part of a bridge. */
418 if (u->track == TRACK_BIT_WORMHOLE && !u->vehstatus.Test(VehState::Hidden)) {
419 max_speed = std::min<int>(max_speed, GetBridgeSpec(GetBridgeType(u->tile))->speed);
420 }
421 }
422
423 max_speed = std::min<int>(max_speed, this->current_order.GetMaxSpeed());
424 return std::min<int>(max_speed, this->gcache.cached_max_track_speed);
425}
426
429{
430 assert(this->IsFrontEngine() || this->IsFreeWagon());
431
432 uint power = this->gcache.cached_power;
433 uint weight = this->gcache.cached_weight;
434 assert(weight != 0);
435 this->acceleration = Clamp(power / weight * 4, 1, 255);
436}
437
438int Train::GetCursorImageOffset() const
439{
440 if (this->gcache.cached_veh_length != 8 && this->flags.Test(VehicleRailFlag::Flipped) && !EngInfo(this->engine_type)->misc_flags.Test(EngineMiscFlag::RailFlips)) {
441 int reference_width = TRAININFO_DEFAULT_VEHICLE_WIDTH;
442
443 const Engine *e = this->GetEngine();
444 if (e->GetGRF() != nullptr && IsCustomVehicleSpriteNum(e->u.rail.image_index)) {
445 reference_width = e->GetGRF()->traininfo_vehicle_width;
446 }
447
448 return ScaleSpriteTrad((this->gcache.cached_veh_length - (int)VEHICLE_LENGTH) * reference_width / (int)VEHICLE_LENGTH);
449 }
450 return 0;
451}
452
459{
460 int reference_width = TRAININFO_DEFAULT_VEHICLE_WIDTH;
461 int vehicle_pitch = 0;
462
463 const Engine *e = this->GetEngine();
464 if (e->GetGRF() != nullptr && IsCustomVehicleSpriteNum(e->u.rail.image_index)) {
465 reference_width = e->GetGRF()->traininfo_vehicle_width;
466 vehicle_pitch = e->GetGRF()->traininfo_vehicle_pitch;
467 }
468
469 if (offset != nullptr) {
470 if (this->flags.Test(VehicleRailFlag::Flipped) && !EngInfo(this->engine_type)->misc_flags.Test(EngineMiscFlag::RailFlips)) {
471 offset->x = ScaleSpriteTrad(((int)this->gcache.cached_veh_length - (int)VEHICLE_LENGTH / 2) * reference_width / (int)VEHICLE_LENGTH);
472 } else {
473 offset->x = ScaleSpriteTrad(reference_width) / 2;
474 }
475 offset->y = ScaleSpriteTrad(vehicle_pitch);
476 }
477 return ScaleSpriteTrad(this->gcache.cached_veh_length * reference_width / VEHICLE_LENGTH);
478}
479
480static SpriteID GetDefaultTrainSprite(uint8_t spritenum, Direction direction)
481{
482 assert(IsValidImageIndex<VEH_TRAIN>(spritenum));
483 return ((direction + _engine_sprite_add[spritenum]) & _engine_sprite_and[spritenum]) + _engine_sprite_base[spritenum];
484}
485
492void Train::GetImage(Direction direction, EngineImageType image_type, VehicleSpriteSeq *result) const
493{
494 uint8_t spritenum = this->spritenum;
495
497
498 if (IsCustomVehicleSpriteNum(spritenum)) {
500 GetCustomVehicleSprite(this, direction, image_type, result);
501 if (result->IsValid()) return;
502
504 }
505
506 assert(IsValidImageIndex<VEH_TRAIN>(spritenum));
507 SpriteID sprite = GetDefaultTrainSprite(spritenum, direction);
508
509 if (this->cargo.StoredCount() >= this->cargo_cap / 2U) sprite += _wagon_full_adder[spritenum];
510
511 result->Set(sprite);
512}
513
514static void GetRailIcon(EngineID engine, bool rear_head, int &y, EngineImageType image_type, VehicleSpriteSeq *result)
515{
516 const Engine *e = Engine::Get(engine);
517 Direction dir = rear_head ? DIR_E : DIR_W;
518 uint8_t spritenum = e->u.rail.image_index;
519
520 if (IsCustomVehicleSpriteNum(spritenum)) {
521 GetCustomVehicleIcon(engine, dir, image_type, result);
522 if (result->IsValid()) {
523 if (e->GetGRF() != nullptr) {
525 }
526 return;
527 }
528
529 spritenum = Engine::Get(engine)->original_image_index;
530 }
531
532 if (rear_head) spritenum++;
533
534 result->Set(GetDefaultTrainSprite(spritenum, DIR_W));
535}
536
537void DrawTrainEngine(int left, int right, int preferred_x, int y, EngineID engine, PaletteID pal, EngineImageType image_type)
538{
539 if (RailVehInfo(engine)->railveh_type == RAILVEH_MULTIHEAD) {
540 int yf = y;
541 int yr = y;
542
543 VehicleSpriteSeq seqf, seqr;
544 GetRailIcon(engine, false, yf, image_type, &seqf);
545 GetRailIcon(engine, true, yr, image_type, &seqr);
546
547 Rect rectf, rectr;
548 seqf.GetBounds(&rectf);
549 seqr.GetBounds(&rectr);
550
551 preferred_x = Clamp(preferred_x,
552 left - UnScaleGUI(rectf.left) + ScaleSpriteTrad(14),
553 right - UnScaleGUI(rectr.right) - ScaleSpriteTrad(15));
554
555 seqf.Draw(preferred_x - ScaleSpriteTrad(14), yf, pal, pal == PALETTE_CRASH);
556 seqr.Draw(preferred_x + ScaleSpriteTrad(15), yr, pal, pal == PALETTE_CRASH);
557 } else {
559 GetRailIcon(engine, false, y, image_type, &seq);
560
561 Rect rect;
562 seq.GetBounds(&rect);
563 preferred_x = Clamp(preferred_x,
564 left - UnScaleGUI(rect.left),
565 right - UnScaleGUI(rect.right));
566
567 seq.Draw(preferred_x, y, pal, pal == PALETTE_CRASH);
568 }
569}
570
580void GetTrainSpriteSize(EngineID engine, uint &width, uint &height, int &xoffs, int &yoffs, EngineImageType image_type)
581{
582 int y = 0;
583
585 GetRailIcon(engine, false, y, image_type, &seq);
586
587 Rect rect;
588 seq.GetBounds(&rect);
589
590 width = UnScaleGUI(rect.Width());
591 height = UnScaleGUI(rect.Height());
592 xoffs = UnScaleGUI(rect.left);
593 yoffs = UnScaleGUI(rect.top);
594
595 if (RailVehInfo(engine)->railveh_type == RAILVEH_MULTIHEAD) {
596 GetRailIcon(engine, true, y, image_type, &seq);
597 seq.GetBounds(&rect);
598
599 /* Calculate values relative to an imaginary center between the two sprites. */
600 width = ScaleSpriteTrad(TRAININFO_DEFAULT_VEHICLE_WIDTH) + UnScaleGUI(rect.right) - xoffs;
601 height = std::max<uint>(height, UnScaleGUI(rect.Height()));
602 xoffs = xoffs - ScaleSpriteTrad(TRAININFO_DEFAULT_VEHICLE_WIDTH) / 2;
603 yoffs = std::min(yoffs, UnScaleGUI(rect.top));
604 }
605}
606
616{
617 const RailVehicleInfo *rvi = &e->u.rail;
618
619 /* Check that the wagon can drive on the track in question */
620 if (!IsCompatibleRail(rvi->railtype, GetRailType(tile))) return CMD_ERROR;
621
622 if (flags.Test(DoCommandFlag::Execute)) {
623 Train *v = new Train();
624 *ret = v;
625 v->spritenum = rvi->image_index;
626
627 v->engine_type = e->index;
628 v->gcache.first_engine = EngineID::Invalid(); // needs to be set before first callback
629
631
632 v->direction = DiagDirToDir(dir);
633 v->tile = tile;
634
635 int x = TileX(tile) * TILE_SIZE | _vehicle_initial_x_fract[dir];
636 int y = TileY(tile) * TILE_SIZE | _vehicle_initial_y_fract[dir];
637
638 v->x_pos = x;
639 v->y_pos = y;
640 v->z_pos = GetSlopePixelZ(x, y, true);
642 v->track = TRACK_BIT_DEPOT;
644
645 v->SetWagon();
646
647 v->SetFreeWagon();
649
651 assert(IsValidCargoType(v->cargo_type));
652 v->cargo_cap = rvi->capacity;
653 v->refit_cap = 0;
654
655 v->railtype = rvi->railtype;
656
660 v->sprite_cache.sprite_seq.Set(SPR_IMG_QUERY);
661 v->random_bits = Random();
662
664
665 auto prob = TestVehicleBuildProbability(v, v->engine_type, BuildProbabilityType::Reversed);
666 if (prob.has_value()) v->flags.Set(VehicleRailFlag::Flipped, prob.value());
668
669 v->UpdatePosition();
670 v->First()->ConsistChanged(CCF_ARRANGE);
672
674
675 /* Try to connect the vehicle to one of free chains of wagons. */
676 for (Train *w : Train::Iterate()) {
677 if (w->tile == tile &&
678 w->IsFreeWagon() &&
679 w->engine_type == e->index &&
680 w->First() != v &&
682 if (Command<CMD_MOVE_RAIL_VEHICLE>::Do(DoCommandFlag::Execute, v->index, w->Last()->index, true).Succeeded()) {
683 break;
684 }
685 }
686 }
687 }
688
689 return CommandCost();
690}
691
694{
695 assert(u->IsEngine());
696 for (const Train *v : Train::Iterate()) {
697 if (v->IsFreeWagon() && v->tile == u->tile &&
698 v->track == TRACK_BIT_DEPOT) {
699 if (Command<CMD_MOVE_RAIL_VEHICLE>::Do(DoCommandFlag::Execute, v->index, u->index, true).Failed()) {
700 break;
701 }
702 }
703 }
704}
705
706static void AddRearEngineToMultiheadedTrain(Train *v)
707{
708 Train *u = new Train();
709 v->value >>= 1;
710 u->value = v->value;
711 u->direction = v->direction;
712 u->owner = v->owner;
713 u->tile = v->tile;
714 u->x_pos = v->x_pos;
715 u->y_pos = v->y_pos;
716 u->z_pos = v->z_pos;
717 u->track = TRACK_BIT_DEPOT;
718 u->vehstatus = v->vehstatus;
720 u->spritenum = v->spritenum + 1;
721 u->cargo_type = v->cargo_type;
723 u->cargo_cap = v->cargo_cap;
724 u->refit_cap = v->refit_cap;
725 u->railtype = v->railtype;
726 u->engine_type = v->engine_type;
729 u->build_year = v->build_year;
730 u->sprite_cache.sprite_seq.Set(SPR_IMG_QUERY);
731 u->random_bits = Random();
732 v->SetMultiheaded();
733 u->SetMultiheaded();
734 v->SetNext(u);
735 auto prob = TestVehicleBuildProbability(u, u->engine_type, BuildProbabilityType::Reversed);
736 if (prob.has_value()) u->flags.Set(VehicleRailFlag::Flipped, prob.value());
737 u->UpdatePosition();
738
739 /* Now we need to link the front and rear engines together */
740 v->other_multiheaded_part = u;
741 u->other_multiheaded_part = v;
742}
743
753{
754 const RailVehicleInfo *rvi = &e->u.rail;
755
756 if (rvi->railveh_type == RAILVEH_WAGON) return CmdBuildRailWagon(flags, tile, e, ret);
757
758 /* Check if depot and new engine uses the same kind of tracks *
759 * We need to see if the engine got power on the tile to avoid electric engines in non-electric depots */
760 if (!HasPowerOnRail(rvi->railtype, GetRailType(tile))) return CMD_ERROR;
761
762 if (flags.Test(DoCommandFlag::Execute)) {
764 int x = TileX(tile) * TILE_SIZE + _vehicle_initial_x_fract[dir];
765 int y = TileY(tile) * TILE_SIZE + _vehicle_initial_y_fract[dir];
766
767 Train *v = new Train();
768 *ret = v;
769 v->direction = DiagDirToDir(dir);
770 v->tile = tile;
772 v->x_pos = x;
773 v->y_pos = y;
774 v->z_pos = GetSlopePixelZ(x, y, true);
775 v->track = TRACK_BIT_DEPOT;
777 v->spritenum = rvi->image_index;
779 assert(IsValidCargoType(v->cargo_type));
780 v->cargo_cap = rvi->capacity;
781 v->refit_cap = 0;
782 v->last_station_visited = StationID::Invalid();
783 v->last_loading_station = StationID::Invalid();
784
785 v->engine_type = e->index;
786 v->gcache.first_engine = EngineID::Invalid(); // needs to be set before first callback
787
788 v->reliability = e->reliability;
791
792 v->railtype = rvi->railtype;
793
794 v->SetServiceInterval(Company::Get(_current_company)->settings.vehicle.servint_trains);
798 v->sprite_cache.sprite_seq.Set(SPR_IMG_QUERY);
799 v->random_bits = Random();
800
802 v->SetServiceIntervalIsPercent(Company::Get(_current_company)->settings.vehicle.servint_ispercent);
803
805
806 v->SetFrontEngine();
807 v->SetEngine();
808
809 auto prob = TestVehicleBuildProbability(v, v->engine_type, BuildProbabilityType::Reversed);
810 if (prob.has_value()) v->flags.Set(VehicleRailFlag::Flipped, prob.value());
811 v->UpdatePosition();
812
813 if (rvi->railveh_type == RAILVEH_MULTIHEAD) {
814 AddRearEngineToMultiheadedTrain(v);
815 } else {
817 }
818
821
823 }
824
825 return CommandCost();
826}
827
828static Train *FindGoodVehiclePos(const Train *src)
829{
830 EngineID eng = src->engine_type;
831 TileIndex tile = src->tile;
832
833 for (Train *dst : Train::Iterate()) {
834 if (dst->IsFreeWagon() && dst->tile == tile && !dst->vehstatus.Test(VehState::Crashed)) {
835 /* check so all vehicles in the line have the same engine. */
836 Train *t = dst;
837 while (t->engine_type == eng) {
838 t = t->Next();
839 if (t == nullptr) return dst;
840 }
841 }
842 }
843
844 return nullptr;
845}
846
848typedef std::vector<Train *> TrainList;
849
855static void MakeTrainBackup(TrainList &list, Train *t)
856{
857 for (; t != nullptr; t = t->Next()) list.push_back(t);
858}
859
865{
866 /* No train, nothing to do. */
867 if (list.empty()) return;
868
869 Train *prev = nullptr;
870 /* Iterate over the list and rebuild it. */
871 for (Train *t : list) {
872 if (prev != nullptr) {
873 prev->SetNext(t);
874 } else if (t->Previous() != nullptr) {
875 /* Make sure the head of the train is always the first in the chain. */
876 t->Previous()->SetNext(nullptr);
877 }
878 prev = t;
879 }
880}
881
887static void RemoveFromConsist(Train *part, bool chain = false)
888{
889 Train *tail = chain ? part->Last() : part->GetLastEnginePart();
890
891 /* Unlink at the front, but make it point to the next
892 * vehicle after the to be remove part. */
893 if (part->Previous() != nullptr) part->Previous()->SetNext(tail->Next());
894
895 /* Unlink at the back */
896 tail->SetNext(nullptr);
897}
898
904static void InsertInConsist(Train *dst, Train *chain)
905{
906 /* We do not want to add something in the middle of an articulated part. */
907 assert(dst != nullptr && (dst->Next() == nullptr || !dst->Next()->IsArticulatedPart()));
908
909 chain->Last()->SetNext(dst->Next());
910 dst->SetNext(chain);
911}
912
919{
920 for (; t != nullptr; t = t->GetNextVehicle()) {
921 if (!t->IsMultiheaded() || !t->IsEngine()) continue;
922
923 /* Make sure that there are no free cars before next engine */
924 Train *u;
925 for (u = t; u->Next() != nullptr && !u->Next()->IsEngine(); u = u->Next()) {}
926
927 if (u == t->other_multiheaded_part) continue;
928
929 /* Remove the part from the 'wrong' train */
930 RemoveFromConsist(t->other_multiheaded_part);
931 /* And add it to the 'right' train */
932 InsertInConsist(u, t->other_multiheaded_part);
933 }
934}
935
940static void NormaliseSubtypes(Train *chain)
941{
942 /* Nothing to do */
943 if (chain == nullptr) return;
944
945 /* We must be the first in the chain. */
946 assert(chain->Previous() == nullptr);
947
948 /* Set the appropriate bits for the first in the chain. */
949 if (chain->IsWagon()) {
950 chain->SetFreeWagon();
951 } else {
952 assert(chain->IsEngine());
953 chain->SetFrontEngine();
954 }
955
956 /* Now clear the bits for the rest of the chain */
957 for (Train *t = chain->Next(); t != nullptr; t = t->Next()) {
958 t->ClearFreeWagon();
959 t->ClearFrontEngine();
960 }
961}
962
972static CommandCost CheckNewTrain(Train *original_dst, Train *dst, Train *original_src, Train *src)
973{
974 /* Just add 'new' engines and subtract the original ones.
975 * If that's less than or equal to 0 we can be sure we did
976 * not add any engines (read: trains) along the way. */
977 if ((src != nullptr && src->IsEngine() ? 1 : 0) +
978 (dst != nullptr && dst->IsEngine() ? 1 : 0) -
979 (original_src != nullptr && original_src->IsEngine() ? 1 : 0) -
980 (original_dst != nullptr && original_dst->IsEngine() ? 1 : 0) <= 0) {
981 return CommandCost();
982 }
983
984 /* Get a free unit number and check whether it's within the bounds.
985 * There will always be a maximum of one new train. */
987
988 return CommandCost(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
989}
990
997{
998 /* No multi-part train, no need to check. */
999 if (t == nullptr || t->Next() == nullptr) return CommandCost();
1000
1001 /* The maximum length for a train. For each part we decrease this by one
1002 * and if the result is negative the train is simply too long. */
1004
1005 /* For free-wagon chains, check if they are within the max_train_length limit. */
1006 if (!t->IsEngine()) {
1007 t = t->Next();
1008 while (t != nullptr) {
1009 allowed_len -= t->gcache.cached_veh_length;
1010
1011 t = t->Next();
1012 }
1013
1014 if (allowed_len < 0) return CommandCost(STR_ERROR_TRAIN_TOO_LONG);
1015 return CommandCost();
1016 }
1017
1018 Train *head = t;
1019 Train *prev = t;
1020
1021 /* Break the prev -> t link so it always holds within the loop. */
1022 t = t->Next();
1023 prev->SetNext(nullptr);
1024
1025 /* Make sure the cache is cleared. */
1026 head->InvalidateNewGRFCache();
1027
1028 while (t != nullptr) {
1029 allowed_len -= t->gcache.cached_veh_length;
1030
1031 Train *next = t->Next();
1032
1033 /* Unlink the to-be-added piece; it is already unlinked from the previous
1034 * part due to the fact that the prev -> t link is broken. */
1035 t->SetNext(nullptr);
1036
1037 /* Don't check callback for articulated or rear dual headed parts */
1038 if (!t->IsArticulatedPart() && !t->IsRearDualheaded()) {
1039 /* Back up and clear the first_engine data to avoid using wagon override group */
1040 EngineID first_engine = t->gcache.first_engine;
1041 t->gcache.first_engine = EngineID::Invalid();
1042
1043 /* We don't want the cache to interfere. head's cache is cleared before
1044 * the loop and after each callback does not need to be cleared here. */
1046
1047 std::array<int32_t, 1> regs100;
1048 uint16_t callback = GetVehicleCallbackParent(CBID_TRAIN_ALLOW_WAGON_ATTACH, 0, 0, head->engine_type, t, head, regs100);
1049
1050 /* Restore original first_engine data */
1051 t->gcache.first_engine = first_engine;
1052
1053 /* We do not want to remember any cached variables from the test run */
1055 head->InvalidateNewGRFCache();
1056
1057 if (callback != CALLBACK_FAILED) {
1058 /* A failing callback means everything is okay */
1059 StringID error = STR_NULL;
1060
1061 if (head->GetGRF()->grf_version < 8) {
1062 if (callback == 0xFD) error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
1063 if (callback < 0xFD) error = GetGRFStringID(head->GetGRFID(), GRFSTR_MISC_GRF_TEXT + callback);
1064 if (callback >= 0x100) ErrorUnknownCallbackResult(head->GetGRFID(), CBID_TRAIN_ALLOW_WAGON_ATTACH, callback);
1065 } else {
1066 if (callback < 0x400) {
1067 error = GetGRFStringID(head->GetGRFID(), GRFSTR_MISC_GRF_TEXT + callback);
1068 } else {
1069 switch (callback) {
1070 case 0x400: // allow if railtypes match (always the case for OpenTTD)
1071 case 0x401: // allow
1072 break;
1073
1074 case 0x40F:
1075 error = GetGRFStringID(head->GetGRFID(), static_cast<GRFStringID>(regs100[0]));
1076 break;
1077
1078 default: // unknown reason -> disallow
1079 case 0x402: // disallow attaching
1080 error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
1081 break;
1082 }
1083 }
1084 }
1085
1086 if (error != STR_NULL) return CommandCost(error);
1087 }
1088 }
1089
1090 /* And link it to the new part. */
1091 prev->SetNext(t);
1092 prev = t;
1093 t = next;
1094 }
1095
1096 if (allowed_len < 0) return CommandCost(STR_ERROR_TRAIN_TOO_LONG);
1097 return CommandCost();
1098}
1099
1110static CommandCost ValidateTrains(Train *original_dst, Train *dst, Train *original_src, Train *src, bool check_limit)
1111{
1112 /* Check whether we may actually construct the trains. */
1114 if (ret.Failed()) return ret;
1115 ret = CheckTrainAttachment(dst);
1116 if (ret.Failed()) return ret;
1117
1118 /* Check whether we need to build a new train. */
1119 return check_limit ? CheckNewTrain(original_dst, dst, original_src, src) : CommandCost();
1120}
1121
1130static void ArrangeTrains(Train **dst_head, Train *dst, Train **src_head, Train *src, bool move_chain)
1131{
1132 /* First determine the front of the two resulting trains */
1133 if (*src_head == *dst_head) {
1134 /* If we aren't moving part(s) to a new train, we are just moving the
1135 * front back and there is not destination head. */
1136 *dst_head = nullptr;
1137 } else if (*dst_head == nullptr) {
1138 /* If we are moving to a new train the head of the move train would become
1139 * the head of the new vehicle. */
1140 *dst_head = src;
1141 }
1142
1143 if (src == *src_head) {
1144 /* If we are moving the front of a train then we are, in effect, creating
1145 * a new head for the train. Point to that. Unless we are moving the whole
1146 * train in which case there is not 'source' train anymore.
1147 * In case we are a multiheaded part we want the complete thing to come
1148 * with us, so src->GetNextUnit(), however... when we are e.g. a wagon
1149 * that is followed by a rear multihead we do not want to include that. */
1150 *src_head = move_chain ? nullptr :
1151 (src->IsMultiheaded() ? src->GetNextUnit() : src->GetNextVehicle());
1152 }
1153
1154 /* Now it's just simply removing the part that we are going to move from the
1155 * source train and *if* the destination is a not a new train add the chain
1156 * at the destination location. */
1157 RemoveFromConsist(src, move_chain);
1158 if (*dst_head != src) InsertInConsist(dst, src);
1159
1160 /* Now normalise the dual heads, that is move the dual heads around in such
1161 * a way that the head and rear of a dual head are in the same train */
1162 NormaliseDualHeads(*src_head);
1163 NormaliseDualHeads(*dst_head);
1164}
1165
1171static void NormaliseTrainHead(Train *head)
1172{
1173 /* Not much to do! */
1174 if (head == nullptr) return;
1175
1176 /* Tell the 'world' the train changed. */
1178 UpdateTrainGroupID(head);
1179
1180 /* Not a front engine, i.e. a free wagon chain. No need to do more. */
1181 if (!head->IsFrontEngine()) return;
1182
1183 /* Update the refit button and window */
1186
1187 /* If we don't have a unit number yet, set one. */
1188 if (head->unitnumber != 0) return;
1189 head->unitnumber = Company::Get(head->owner)->freeunits[head->type].UseID(GetFreeUnitNumber(VEH_TRAIN));
1190}
1191
1201CommandCost CmdMoveRailVehicle(DoCommandFlags flags, VehicleID src_veh, VehicleID dest_veh, bool move_chain)
1202{
1203 Train *src = Train::GetIfValid(src_veh);
1204 if (src == nullptr) return CMD_ERROR;
1205
1206 CommandCost ret = CheckOwnership(src->owner);
1207 if (ret.Failed()) return ret;
1208
1209 /* Do not allow moving crashed vehicles inside the depot, it is likely to cause asserts later */
1210 if (src->vehstatus.Test(VehState::Crashed)) return CMD_ERROR;
1211
1212 /* if nothing is selected as destination, try and find a matching vehicle to drag to. */
1213 Train *dst;
1214 if (dest_veh == VehicleID::Invalid()) {
1215 dst = (src->IsEngine() || flags.Test(DoCommandFlag::AutoReplace)) ? nullptr : FindGoodVehiclePos(src);
1216 } else {
1217 dst = Train::GetIfValid(dest_veh);
1218 if (dst == nullptr) return CMD_ERROR;
1219
1220 ret = CheckOwnership(dst->owner);
1221 if (ret.Failed()) return ret;
1222
1223 /* Do not allow appending to crashed vehicles, too */
1224 if (dst->vehstatus.Test(VehState::Crashed)) return CMD_ERROR;
1225 }
1226
1227 /* if an articulated part is being handled, deal with its parent vehicle */
1228 src = src->GetFirstEnginePart();
1229 if (dst != nullptr) {
1230 dst = dst->GetFirstEnginePart();
1231 }
1232
1233 /* don't move the same vehicle.. */
1234 if (src == dst) return CommandCost();
1235
1236 /* locate the head of the two chains */
1237 Train *src_head = src->First();
1238 Train *dst_head;
1239 if (dst != nullptr) {
1240 dst_head = dst->First();
1241 if (dst_head->tile != src_head->tile) return CMD_ERROR;
1242 /* Now deal with articulated part of destination wagon */
1243 dst = dst->GetLastEnginePart();
1244 } else {
1245 dst_head = nullptr;
1246 }
1247
1248 if (src->IsRearDualheaded()) return CommandCost(STR_ERROR_REAR_ENGINE_FOLLOW_FRONT);
1249
1250 /* When moving all wagons, we can't have the same src_head and dst_head */
1251 if (move_chain && src_head == dst_head) return CommandCost();
1252
1253 /* When moving a multiheaded part to be place after itself, bail out. */
1254 if (!move_chain && dst != nullptr && dst->IsRearDualheaded() && src == dst->other_multiheaded_part) return CommandCost();
1255
1256 /* Check if all vehicles in the source train are stopped inside a depot. */
1257 if (!src_head->IsStoppedInDepot()) return CommandCost(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
1258
1259 /* Check if all vehicles in the destination train are stopped inside a depot. */
1260 if (dst_head != nullptr && !dst_head->IsStoppedInDepot()) return CommandCost(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
1261
1262 /* First make a backup of the order of the trains. That way we can do
1263 * whatever we want with the order and later on easily revert. */
1264 TrainList original_src;
1265 TrainList original_dst;
1266
1267 MakeTrainBackup(original_src, src_head);
1268 MakeTrainBackup(original_dst, dst_head);
1269
1270 /* Also make backup of the original heads as ArrangeTrains can change them.
1271 * For the destination head we do not care if it is the same as the source
1272 * head because in that case it's just a copy. */
1273 Train *original_src_head = src_head;
1274 Train *original_dst_head = (dst_head == src_head ? nullptr : dst_head);
1275
1276 /* We want this information from before the rearrangement, but execute this after the validation.
1277 * original_src_head can't be nullptr; src is by definition != nullptr, so src_head can't be nullptr as
1278 * src->GetFirst() always yields non-nullptr, so eventually original_src_head != nullptr as well. */
1279 bool original_src_head_front_engine = original_src_head->IsFrontEngine();
1280 bool original_dst_head_front_engine = original_dst_head != nullptr && original_dst_head->IsFrontEngine();
1281
1282 /* (Re)arrange the trains in the wanted arrangement. */
1283 ArrangeTrains(&dst_head, dst, &src_head, src, move_chain);
1284
1285 if (!flags.Test(DoCommandFlag::AutoReplace)) {
1286 /* If the autoreplace flag is set we do not need to test for the validity
1287 * because we are going to revert the train to its original state. As we
1288 * assume the original state was correct autoreplace can skip this. */
1289 ret = ValidateTrains(original_dst_head, dst_head, original_src_head, src_head, true);
1290 if (ret.Failed()) {
1291 /* Restore the train we had. */
1292 RestoreTrainBackup(original_src);
1293 RestoreTrainBackup(original_dst);
1294 return ret;
1295 }
1296 }
1297
1298 /* do it? */
1299 if (flags.Test(DoCommandFlag::Execute)) {
1300 /* Remove old heads from the statistics */
1301 if (original_src_head_front_engine) GroupStatistics::CountVehicle(original_src_head, -1);
1302 if (original_dst_head_front_engine) GroupStatistics::CountVehicle(original_dst_head, -1);
1303
1304 /* First normalise the sub types of the chains. */
1305 NormaliseSubtypes(src_head);
1306 NormaliseSubtypes(dst_head);
1307
1308 /* There are 14 different cases:
1309 * 1) front engine gets moved to a new train, it stays a front engine.
1310 * a) the 'next' part is a wagon that becomes a free wagon chain.
1311 * b) the 'next' part is an engine that becomes a front engine.
1312 * c) there is no 'next' part, nothing else happens
1313 * 2) front engine gets moved to another train, it is not a front engine anymore
1314 * a) the 'next' part is a wagon that becomes a free wagon chain.
1315 * b) the 'next' part is an engine that becomes a front engine.
1316 * c) there is no 'next' part, nothing else happens
1317 * 3) front engine gets moved to later in the current train, it is not a front engine anymore.
1318 * a) the 'next' part is a wagon that becomes a free wagon chain.
1319 * b) the 'next' part is an engine that becomes a front engine.
1320 * 4) free wagon gets moved
1321 * a) the 'next' part is a wagon that becomes a free wagon chain.
1322 * b) the 'next' part is an engine that becomes a front engine.
1323 * c) there is no 'next' part, nothing else happens
1324 * 5) non front engine gets moved and becomes a new train, nothing else happens
1325 * 6) non front engine gets moved within a train / to another train, nothing happens
1326 * 7) wagon gets moved, nothing happens
1327 */
1328 if (src == original_src_head && src->IsEngine() && !src->IsFrontEngine()) {
1329 /* Cases #2 and #3: the front engine gets trashed. */
1335 DeleteNewGRFInspectWindow(GSF_TRAINS, src->index);
1337
1338 if (src_head != nullptr && src_head->IsFrontEngine()) {
1339 /* Cases #?b: Transfer order, unit number and other stuff
1340 * to the new front engine. */
1341 src_head->orders = src->orders;
1342 if (src_head->orders != nullptr) src_head->AddToShared(src);
1343 src_head->CopyVehicleConfigAndStatistics(src);
1344 }
1345 /* Remove stuff not valid anymore for non-front engines. */
1347 src->ReleaseUnitNumber();
1348 src->name.clear();
1349 }
1350
1351 /* We weren't a front engine but are becoming one. So
1352 * we should be put in the default group. */
1353 if (original_src_head != src && dst_head == src) {
1356 }
1357
1358 /* Handle 'new engine' part of cases #1b, #2b, #3b, #4b and #5 in NormaliseTrainHead. */
1359 NormaliseTrainHead(src_head);
1360 NormaliseTrainHead(dst_head);
1361
1362 /* Add new heads to statistics.
1363 * This should be done after NormaliseTrainHead due to engine total limit checks in GetFreeUnitNumber. */
1364 if (src_head != nullptr && src_head->IsFrontEngine()) GroupStatistics::CountVehicle(src_head, 1);
1365 if (dst_head != nullptr && dst_head->IsFrontEngine()) GroupStatistics::CountVehicle(dst_head, 1);
1366
1368 CheckCargoCapacity(src_head);
1369 CheckCargoCapacity(dst_head);
1370 }
1371
1372 if (src_head != nullptr) src_head->First()->MarkDirty();
1373 if (dst_head != nullptr) dst_head->First()->MarkDirty();
1374
1375 /* We are undoubtedly changing something in the depot and train list. */
1378 } else {
1379 /* We don't want to execute what we're just tried. */
1380 RestoreTrainBackup(original_src);
1381 RestoreTrainBackup(original_dst);
1382 }
1383
1384 return CommandCost();
1385}
1386
1399CommandCost CmdSellRailWagon(DoCommandFlags flags, Vehicle *t, bool sell_chain, bool backup_order, ClientID user)
1400{
1402 Train *first = v->First();
1403
1404 if (v->IsRearDualheaded()) return CommandCost(STR_ERROR_REAR_ENGINE_FOLLOW_FRONT);
1405
1406 /* First make a backup of the order of the train. That way we can do
1407 * whatever we want with the order and later on easily revert. */
1408 TrainList original;
1409 MakeTrainBackup(original, first);
1410
1411 /* We need to keep track of the new head and the head of what we're going to sell. */
1412 Train *new_head = first;
1413 Train *sell_head = nullptr;
1414
1415 /* Split the train in the wanted way. */
1416 ArrangeTrains(&sell_head, nullptr, &new_head, v, sell_chain);
1417
1418 /* We don't need to validate the second train; it's going to be sold. */
1419 CommandCost ret = ValidateTrains(nullptr, nullptr, first, new_head, !flags.Test(DoCommandFlag::AutoReplace));
1420 if (ret.Failed()) {
1421 /* Restore the train we had. */
1422 RestoreTrainBackup(original);
1423 return ret;
1424 }
1425
1426 if (first->orders == nullptr && !OrderList::CanAllocateItem()) {
1427 /* Restore the train we had. */
1428 RestoreTrainBackup(original);
1429 return CommandCost(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
1430 }
1431
1433 for (Train *part = sell_head; part != nullptr; part = part->Next()) cost.AddCost(-part->value);
1434
1435 /* do it? */
1436 if (flags.Test(DoCommandFlag::Execute)) {
1437 /* First normalise the sub types of the chain. */
1438 NormaliseSubtypes(new_head);
1439
1440 if (v == first && !sell_chain && new_head != nullptr && new_head->IsFrontEngine()) {
1441 if (v->IsEngine()) {
1442 /* We are selling the front engine. In this case we want to
1443 * 'give' the order, unit number and such to the new head. */
1444 new_head->orders = first->orders;
1445 new_head->AddToShared(first);
1446 DeleteVehicleOrders(first);
1447
1448 /* Copy other important data from the front engine */
1449 new_head->CopyVehicleConfigAndStatistics(first);
1450 }
1451 GroupStatistics::CountVehicle(new_head, 1); // after copying over the profit, if required
1452 } else if (v->IsPrimaryVehicle() && backup_order) {
1453 OrderBackup::Backup(v, user);
1454 }
1455
1456 /* We need to update the information about the train. */
1457 NormaliseTrainHead(new_head);
1458
1459 /* We are undoubtedly changing something in the depot and train list. */
1462
1463 /* Actually delete the sold 'goods' */
1464 delete sell_head;
1465 } else {
1466 /* We don't want to execute what we're just tried. */
1467 RestoreTrainBackup(original);
1468 }
1469
1470 return cost;
1471}
1472
1474{
1475 /* Set common defaults. */
1476 this->x_offs = -1;
1477 this->y_offs = -1;
1478 this->x_extent = 3;
1479 this->y_extent = 3;
1480 this->z_extent = 6;
1481 this->x_bb_offs = 0;
1482 this->y_bb_offs = 0;
1483
1484 /* Set if flipped and engine is NOT flagged with custom flip handling. */
1485 int flipped = this->flags.Test(VehicleRailFlag::Flipped) && !EngInfo(this->engine_type)->misc_flags.Test(EngineMiscFlag::RailFlips);
1486 /* If flipped and vehicle length is odd, we need to adjust the bounding box offset slightly. */
1487 int flip_offs = flipped && (this->gcache.cached_veh_length & 1);
1488
1489 Direction dir = this->direction;
1490 if (flipped) dir = ReverseDir(dir);
1491
1492 if (!IsDiagonalDirection(dir)) {
1493 static const int _sign_table[] =
1494 {
1495 /* x, y */
1496 -1, -1, // DIR_N
1497 -1, 1, // DIR_E
1498 1, 1, // DIR_S
1499 1, -1, // DIR_W
1500 };
1501
1502 int half_shorten = (VEHICLE_LENGTH - this->gcache.cached_veh_length + flipped) / 2;
1503
1504 /* For all straight directions, move the bound box to the centre of the vehicle, but keep the size. */
1505 this->x_offs -= half_shorten * _sign_table[dir];
1506 this->y_offs -= half_shorten * _sign_table[dir + 1];
1507 this->x_extent += this->x_bb_offs = half_shorten * _sign_table[dir];
1508 this->y_extent += this->y_bb_offs = half_shorten * _sign_table[dir + 1];
1509 } else {
1510 switch (dir) {
1511 /* Shorten southern corner of the bounding box according the vehicle length
1512 * and center the bounding box on the vehicle. */
1513 case DIR_NE:
1514 this->x_offs = 1 - (this->gcache.cached_veh_length + 1) / 2 + flip_offs;
1515 this->x_extent = this->gcache.cached_veh_length - 1;
1516 this->x_bb_offs = -1;
1517 break;
1518
1519 case DIR_NW:
1520 this->y_offs = 1 - (this->gcache.cached_veh_length + 1) / 2 + flip_offs;
1521 this->y_extent = this->gcache.cached_veh_length - 1;
1522 this->y_bb_offs = -1;
1523 break;
1524
1525 /* Move northern corner of the bounding box down according to vehicle length
1526 * and center the bounding box on the vehicle. */
1527 case DIR_SW:
1528 this->x_offs = 1 + (this->gcache.cached_veh_length + 1) / 2 - VEHICLE_LENGTH - flip_offs;
1529 this->x_extent = VEHICLE_LENGTH - 1;
1531 break;
1532
1533 case DIR_SE:
1534 this->y_offs = 1 + (this->gcache.cached_veh_length + 1) / 2 - VEHICLE_LENGTH - flip_offs;
1535 this->y_extent = VEHICLE_LENGTH - 1;
1537 break;
1538
1539 default:
1540 NOT_REACHED();
1541 }
1542 }
1543}
1544
1550{
1551 if (!v->flags.Test(VehicleRailFlag::Stuck)) {
1552 /* It is the first time the problem occurred, set the "train stuck" flag. */
1553 v->flags.Set(VehicleRailFlag::Stuck);
1554
1555 v->wait_counter = 0;
1556
1557 /* Stop train */
1558 v->cur_speed = 0;
1559 v->subspeed = 0;
1560 v->SetLastSpeed();
1561
1563 }
1564}
1565
1573static void SwapTrainFlags(uint16_t *swap_flag1, uint16_t *swap_flag2)
1574{
1575 uint16_t flag1 = *swap_flag1;
1576 uint16_t flag2 = *swap_flag2;
1577
1578 /* Clear the flags */
1579 ClrBit(*swap_flag1, GVF_GOINGUP_BIT);
1580 ClrBit(*swap_flag1, GVF_GOINGDOWN_BIT);
1581 ClrBit(*swap_flag2, GVF_GOINGUP_BIT);
1582 ClrBit(*swap_flag2, GVF_GOINGDOWN_BIT);
1583
1584 /* Reverse the rail-flags (if needed) */
1585 if (HasBit(flag1, GVF_GOINGUP_BIT)) {
1586 SetBit(*swap_flag2, GVF_GOINGDOWN_BIT);
1587 } else if (HasBit(flag1, GVF_GOINGDOWN_BIT)) {
1588 SetBit(*swap_flag2, GVF_GOINGUP_BIT);
1589 }
1590 if (HasBit(flag2, GVF_GOINGUP_BIT)) {
1591 SetBit(*swap_flag1, GVF_GOINGDOWN_BIT);
1592 } else if (HasBit(flag2, GVF_GOINGDOWN_BIT)) {
1593 SetBit(*swap_flag1, GVF_GOINGUP_BIT);
1594 }
1595}
1596
1602{
1603 /* Reverse the direction. */
1604 if (v->track != TRACK_BIT_DEPOT) v->direction = ReverseDir(v->direction);
1605
1606 /* Call the proper EnterTile function unless we are in a wormhole. */
1607 if (v->track != TRACK_BIT_WORMHOLE) {
1608 VehicleEnterTile(v, v->tile, v->x_pos, v->y_pos);
1609 } else {
1610 /* VehicleEnter_TunnelBridge() sets TRACK_BIT_WORMHOLE when the vehicle
1611 * is on the last bit of the bridge head (frame == TILE_SIZE - 1).
1612 * If we were swapped with such a vehicle, we have set TRACK_BIT_WORMHOLE,
1613 * when we shouldn't have. Check if this is the case. */
1614 TileIndex vt = TileVirtXY(v->x_pos, v->y_pos);
1615 if (IsTileType(vt, MP_TUNNELBRIDGE)) {
1616 VehicleEnterTile(v, vt, v->x_pos, v->y_pos);
1617 if (v->track != TRACK_BIT_WORMHOLE && IsBridgeTile(v->tile)) {
1618 /* We have just left the wormhole, possibly set the
1619 * "goingdown" bit. UpdateInclination() can be used
1620 * because we are at the border of the tile. */
1621 v->UpdatePosition();
1622 v->UpdateInclination(true, true);
1623 return;
1624 }
1625 }
1626 }
1627
1628 v->UpdatePosition();
1629 v->UpdateViewport(true, true);
1630}
1631
1638void ReverseTrainSwapVeh(Train *v, int l, int r)
1639{
1640 Train *a, *b;
1641
1642 /* locate vehicles to swap */
1643 for (a = v; l != 0; l--) a = a->Next();
1644 for (b = v; r != 0; r--) b = b->Next();
1645
1646 if (a != b) {
1647 /* swap the hidden bits */
1648 {
1649 bool a_hidden = a->vehstatus.Test(VehState::Hidden);
1650 bool b_hidden = b->vehstatus.Test(VehState::Hidden);
1651 b->vehstatus.Set(VehState::Hidden, a_hidden);
1652 a->vehstatus.Set(VehState::Hidden, b_hidden);
1653 }
1654
1655 std::swap(a->track, b->track);
1656 std::swap(a->direction, b->direction);
1657 std::swap(a->x_pos, b->x_pos);
1658 std::swap(a->y_pos, b->y_pos);
1659 std::swap(a->tile, b->tile);
1660 std::swap(a->z_pos, b->z_pos);
1661
1663
1666 } else {
1667 /* Swap GVF_GOINGUP_BIT/GVF_GOINGDOWN_BIT.
1668 * This is a little bit redundant way, a->gv_flags will
1669 * be (re)set twice, but it reduces code duplication */
1672 }
1673}
1674
1680static bool IsTrain(const Vehicle *v)
1681{
1682 return v->type == VEH_TRAIN;
1683}
1684
1692{
1693 assert(IsLevelCrossingTile(tile));
1694
1695 return HasVehicleOnTile(tile, IsTrain);
1696}
1697
1705{
1706 if (v->type != VEH_TRAIN || v->vehstatus.Test(VehState::Crashed)) return false;
1707
1708 const Train *t = Train::From(v);
1709 if (!t->IsFrontEngine()) return false;
1710
1711 return TrainApproachingCrossingTile(t) == tile;
1712}
1713
1714
1722{
1723 assert(IsLevelCrossingTile(tile));
1724
1726 TileIndex tile_from = tile + TileOffsByDiagDir(dir);
1727
1728 if (HasVehicleOnTile(tile_from, [&](const Vehicle *v) {
1729 return TrainApproachingCrossingEnum(v, tile);
1730 })) return true;
1731
1732 dir = ReverseDiagDir(dir);
1733 tile_from = tile + TileOffsByDiagDir(dir);
1734
1735 return HasVehicleOnTile(tile_from, [&](const Vehicle *v) {
1736 return TrainApproachingCrossingEnum(v, tile);
1737 });
1738}
1739
1745static inline bool CheckLevelCrossing(TileIndex tile)
1746{
1747 /* reserved || train on crossing || train approaching crossing */
1749}
1750
1758static void UpdateLevelCrossingTile(TileIndex tile, bool sound, bool force_barred)
1759{
1760 assert(IsLevelCrossingTile(tile));
1761 bool set_barred;
1762
1763 /* We force the crossing to be barred when an adjacent crossing is barred, otherwise let it decide for itself. */
1764 set_barred = force_barred || CheckLevelCrossing(tile);
1765
1766 /* The state has changed */
1767 if (set_barred != IsCrossingBarred(tile)) {
1768 if (set_barred && sound && _settings_client.sound.ambient) SndPlayTileFx(SND_0E_LEVEL_CROSSING, tile);
1769 SetCrossingBarred(tile, set_barred);
1770 MarkTileDirtyByTile(tile);
1771 }
1772}
1773
1780void UpdateLevelCrossing(TileIndex tile, bool sound, bool force_bar)
1781{
1782 if (!IsLevelCrossingTile(tile)) return;
1783
1784 bool forced_state = force_bar;
1785
1786 const Axis axis = GetCrossingRoadAxis(tile);
1787 const DiagDirection dir1 = AxisToDiagDir(axis);
1788 const DiagDirection dir2 = ReverseDiagDir(dir1);
1789
1790 /* Check if an adjacent crossing is barred. */
1791 for (DiagDirection dir : { dir1, dir2 }) {
1792 for (TileIndex t = tile; !forced_state && t < Map::Size() && IsLevelCrossingTile(t) && GetCrossingRoadAxis(t) == axis; t = TileAddByDiagDir(t, dir)) {
1793 forced_state |= CheckLevelCrossing(t);
1794 }
1795 }
1796
1797 /* Now that we know whether all tiles in this crossing should be barred or open,
1798 * we need to update those tiles. We start with the tile itself, then look along the road axis. */
1799 UpdateLevelCrossingTile(tile, sound, forced_state);
1800 for (DiagDirection dir : { dir1, dir2 }) {
1801 for (TileIndex t = TileAddByDiagDir(tile, dir); t < Map::Size() && IsLevelCrossingTile(t) && GetCrossingRoadAxis(t) == axis; t = TileAddByDiagDir(t, dir)) {
1802 UpdateLevelCrossingTile(t, sound, forced_state);
1803 }
1804 }
1805}
1806
1813{
1814 const DiagDirection dir1 = AxisToDiagDir(road_axis);
1815 const DiagDirection dir2 = ReverseDiagDir(dir1);
1816 for (DiagDirection dir : { dir1, dir2 }) {
1817 const TileIndex t = TileAddByDiagDir(tile, dir);
1818 if (t < Map::Size() && IsLevelCrossingTile(t) && GetCrossingRoadAxis(t) == road_axis) {
1820 }
1821 }
1822}
1823
1830{
1831 const DiagDirection dir1 = AxisToDiagDir(road_axis);
1832 const DiagDirection dir2 = ReverseDiagDir(dir1);
1833 for (DiagDirection dir : { dir1, dir2 }) {
1834 const TileIndexDiff diff = TileOffsByDiagDir(dir);
1835 bool occupied = false;
1836 for (TileIndex t = tile + diff; t < Map::Size() && IsLevelCrossingTile(t) && GetCrossingRoadAxis(t) == road_axis; t += diff) {
1837 occupied |= CheckLevelCrossing(t);
1838 }
1839 if (occupied) {
1840 /* Mark the immediately adjacent tile dirty */
1841 const TileIndex t = tile + diff;
1842 if (t < Map::Size() && IsLevelCrossingTile(t) && GetCrossingRoadAxis(t) == road_axis) {
1844 }
1845 } else {
1846 /* Unbar the crossing tiles in this direction as necessary */
1847 for (TileIndex t = tile + diff; t < Map::Size() && IsLevelCrossingTile(t) && GetCrossingRoadAxis(t) == road_axis; t += diff) {
1848 if (IsCrossingBarred(t)) {
1849 /* The crossing tile is barred, unbar it and continue to check the next tile */
1850 SetCrossingBarred(t, false);
1852 } else {
1853 /* The crossing tile is already unbarred, mark the tile dirty and stop checking */
1855 break;
1856 }
1857 }
1858 }
1859 }
1860}
1861
1867static inline void MaybeBarCrossingWithSound(TileIndex tile)
1868{
1869 if (!IsCrossingBarred(tile)) {
1870 SetCrossingReservation(tile, true);
1871 UpdateLevelCrossing(tile, true);
1872 }
1873}
1874
1875
1882{
1883 Train *base = v;
1884 Train *first = base; // first vehicle to move
1885 Train *last = v->Last(); // last vehicle to move
1886 uint length = CountVehiclesInChain(v);
1887
1888 while (length > 2) {
1889 last = last->Previous();
1890 first = first->Next();
1891
1892 int differential = base->CalcNextVehicleOffset() - last->CalcNextVehicleOffset();
1893
1894 /* do not update images now
1895 * negative differential will be handled in AdvanceWagonsAfterSwap() */
1896 for (int i = 0; i < differential; i++) TrainController(first, last->Next());
1897
1898 base = first; // == base->Next()
1899 length -= 2;
1900 }
1901}
1902
1903
1910{
1911 /* first of all, fix the situation when the train was entering a depot */
1912 Train *dep = v; // last vehicle in front of just left depot
1913 while (dep->Next() != nullptr && (dep->track == TRACK_BIT_DEPOT || dep->Next()->track != TRACK_BIT_DEPOT)) {
1914 dep = dep->Next(); // find first vehicle outside of a depot, with next vehicle inside a depot
1915 }
1916
1917 Train *leave = dep->Next(); // first vehicle in a depot we are leaving now
1918
1919 if (leave != nullptr) {
1920 /* 'pull' next wagon out of the depot, so we won't miss it (it could stay in depot forever) */
1921 int d = TicksToLeaveDepot(dep);
1922
1923 if (d <= 0) {
1924 leave->vehstatus.Reset(VehState::Hidden); // move it out of the depot
1925 leave->track = TrackToTrackBits(GetRailDepotTrack(leave->tile));
1926 for (int i = 0; i >= d; i--) TrainController(leave, nullptr); // maybe move it, and maybe let another wagon leave
1927 }
1928 } else {
1929 dep = nullptr; // no vehicle in a depot, so no vehicle leaving a depot
1930 }
1931
1932 Train *base = v;
1933 Train *first = base; // first vehicle to move
1934 Train *last = v->Last(); // last vehicle to move
1935 uint length = CountVehiclesInChain(v);
1936
1937 /* We have to make sure all wagons that leave a depot because of train reversing are moved correctly
1938 * they have already correct spacing, so we have to make sure they are moved how they should */
1939 bool nomove = (dep == nullptr); // If there is no vehicle leaving a depot, limit the number of wagons moved immediately.
1940
1941 while (length > 2) {
1942 /* we reached vehicle (originally) in front of a depot, stop now
1943 * (we would move wagons that are already moved with new wagon length). */
1944 if (base == dep) break;
1945
1946 /* the last wagon was that one leaving a depot, so do not move it anymore */
1947 if (last == dep) nomove = true;
1948
1949 last = last->Previous();
1950 first = first->Next();
1951
1952 int differential = last->CalcNextVehicleOffset() - base->CalcNextVehicleOffset();
1953
1954 /* do not update images now */
1955 for (int i = 0; i < differential; i++) TrainController(first, (nomove ? last->Next() : nullptr));
1956
1957 base = first; // == base->Next()
1958 length -= 2;
1959 }
1960}
1961
1962static bool IsWholeTrainInsideDepot(const Train *v)
1963{
1964 for (const Train *u = v; u != nullptr; u = u->Next()) {
1965 if (u->track != TRACK_BIT_DEPOT || u->tile != v->tile) return false;
1966 }
1967 return true;
1968}
1969
1975{
1976 if (IsRailDepotTile(v->tile)) {
1977 if (IsWholeTrainInsideDepot(v)) return;
1979 }
1980
1981 /* Clear path reservation in front if train is not stuck. */
1983
1984 /* Check if we were approaching a rail/road-crossing */
1986
1987 /* count number of vehicles */
1988 int r = CountVehiclesInChain(v) - 1; // number of vehicles - 1
1989
1991
1992 /* swap start<>end, start+1<>end-1, ... */
1993 int l = 0;
1994 do {
1995 ReverseTrainSwapVeh(v, l++, r--);
1996 } while (l <= r);
1997
1999
2000 if (IsRailDepotTile(v->tile)) {
2002 }
2003
2006
2007 /* recalculate cached data */
2009
2010 /* update all images */
2011 for (Train *u = v; u != nullptr; u = u->Next()) u->UpdateViewport(false, false);
2012
2013 /* update crossing we were approaching */
2014 if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
2015
2016 /* maybe we are approaching crossing now, after reversal */
2017 crossing = TrainApproachingCrossingTile(v);
2018 if (crossing != INVALID_TILE) MaybeBarCrossingWithSound(crossing);
2019
2020 /* If we are inside a depot after reversing, don't bother with path reserving. */
2021 if (v->track == TRACK_BIT_DEPOT) {
2022 /* Can't be stuck here as inside a depot is always a safe tile. */
2024 v->flags.Reset(VehicleRailFlag::Stuck);
2025 return;
2026 }
2027
2028 /* VehicleExitDir does not always produce the desired dir for depots and
2029 * tunnels/bridges that is needed for UpdateSignalsOnSegment. */
2030 DiagDirection dir = VehicleExitDir(v->direction, v->track);
2032
2034 /* If we are currently on a tile with conventional signals, we can't treat the
2035 * current tile as a safe tile or we would enter a PBS block without a reservation. */
2036 bool first_tile_okay = !(IsTileType(v->tile, MP_RAILWAY) &&
2038 !IsPbsSignal(GetSignalType(v->tile, FindFirstTrack(v->track))));
2039
2040 /* If we are on a depot tile facing outwards, do not treat the current tile as safe. */
2041 if (IsRailDepotTile(v->tile) && TrackdirToExitdir(v->GetVehicleTrackdir()) == GetRailDepotDirection(v->tile)) first_tile_okay = false;
2042
2044 if (TryPathReserve(v, false, first_tile_okay)) {
2045 /* Do a look-ahead now in case our current tile was already a safe tile. */
2047 } else if (v->current_order.GetType() != OT_LOADING) {
2048 /* Do not wait for a way out when we're still loading */
2050 }
2051 } else if (v->flags.Test(VehicleRailFlag::Stuck)) {
2052 /* A train not inside a PBS block can't be stuck. */
2053 v->flags.Reset(VehicleRailFlag::Stuck);
2054 v->wait_counter = 0;
2055 }
2056}
2057
2065CommandCost CmdReverseTrainDirection(DoCommandFlags flags, VehicleID veh_id, bool reverse_single_veh)
2066{
2067 Train *v = Train::GetIfValid(veh_id);
2068 if (v == nullptr) return CMD_ERROR;
2069
2071 if (ret.Failed()) return ret;
2072
2073 if (reverse_single_veh) {
2074 /* turn a single unit around */
2075
2077 return CommandCost(STR_ERROR_CAN_T_REVERSE_DIRECTION_RAIL_VEHICLE_MULTIPLE_UNITS);
2078 }
2079
2080 Train *front = v->First();
2081 /* make sure the vehicle is stopped in the depot */
2082 if (!front->IsStoppedInDepot()) {
2083 return CommandCost(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
2084 }
2085
2086 if (flags.Test(DoCommandFlag::Execute)) {
2088
2094 }
2095 } else {
2096 /* turn the whole train around */
2097 if (!v->IsPrimaryVehicle()) return CMD_ERROR;
2098 if (v->vehstatus.Test(VehState::Crashed) || v->breakdown_ctr != 0) return CMD_ERROR;
2099
2100 if (flags.Test(DoCommandFlag::Execute)) {
2101 /* Properly leave the station if we are loading and won't be loading anymore */
2102 if (v->current_order.IsType(OT_LOADING)) {
2103 const Vehicle *last = v;
2104 while (last->Next() != nullptr) last = last->Next();
2105
2106 /* not a station || different station --> leave the station */
2107 if (!IsTileType(last->tile, MP_STATION) || GetStationIndex(last->tile) != GetStationIndex(v->tile)) {
2108 v->LeaveStation();
2109 }
2110 }
2111
2112 /* We cancel any 'skip signal at dangers' here */
2113 v->force_proceed = TFP_NONE;
2115
2116 if (_settings_game.vehicle.train_acceleration_model != AM_ORIGINAL && v->cur_speed != 0) {
2118 } else {
2119 v->cur_speed = 0;
2120 v->SetLastSpeed();
2123 }
2124
2125 /* Unbunching data is no longer valid. */
2127 }
2128 }
2129 return CommandCost();
2130}
2131
2139{
2140 Train *t = Train::GetIfValid(veh_id);
2141 if (t == nullptr) return CMD_ERROR;
2142
2143 if (!t->IsPrimaryVehicle()) return CMD_ERROR;
2144
2146 if (ret.Failed()) return ret;
2147
2148
2149 if (flags.Test(DoCommandFlag::Execute)) {
2150 /* If we are forced to proceed, cancel that order.
2151 * If we are marked stuck we would want to force the train
2152 * to proceed to the next signal. In the other cases we
2153 * would like to pass the signal at danger and run till the
2154 * next signal we encounter. */
2155 t->force_proceed = t->force_proceed == TFP_SIGNAL ? TFP_NONE : t->flags.Test(VehicleRailFlag::Stuck) || t->IsChainInDepot() ? TFP_STUCK : TFP_SIGNAL;
2157
2158 /* Unbunching data is no longer valid. */
2160 }
2161
2162 return CommandCost();
2163}
2164
2172static FindDepotData FindClosestTrainDepot(Train *v, int max_distance)
2173{
2174 assert(!v->vehstatus.Test(VehState::Crashed));
2175
2176 return YapfTrainFindNearestDepot(v, max_distance);
2177}
2178
2180{
2181 FindDepotData tfdd = FindClosestTrainDepot(this, 0);
2182 if (tfdd.best_length == UINT_MAX) return ClosestDepot();
2183
2184 return ClosestDepot(tfdd.tile, GetDepotIndex(tfdd.tile), tfdd.reverse);
2185}
2186
2188void Train::PlayLeaveStationSound(bool force) const
2189{
2190 static const SoundFx sfx[] = {
2196 };
2197
2198 if (PlayVehicleSound(this, VSE_START, force)) return;
2199
2200 SndPlayVehicleFx(sfx[RailVehInfo(this->engine_type)->engclass], this);
2201}
2202
2208{
2209 /* Don't do any look-ahead if path_backoff_interval is 255. */
2210 if (_settings_game.pf.path_backoff_interval == 255) return;
2211
2212 /* Exit if we are inside a depot. */
2213 if (v->track == TRACK_BIT_DEPOT) return;
2214
2215 switch (v->current_order.GetType()) {
2216 /* Exit if we reached our destination depot. */
2217 case OT_GOTO_DEPOT:
2218 if (v->tile == v->dest_tile) return;
2219 break;
2220
2221 case OT_GOTO_WAYPOINT:
2222 /* If we reached our waypoint, make sure we see that. */
2224 break;
2225
2226 case OT_NOTHING:
2227 case OT_LEAVESTATION:
2228 case OT_LOADING:
2229 /* Exit if the current order doesn't have a destination, but the train has orders. */
2230 if (v->GetNumOrders() > 0) return;
2231 break;
2232
2233 default:
2234 break;
2235 }
2236 /* Exit if we are on a station tile and are going to stop. */
2238
2239 Trackdir td = v->GetVehicleTrackdir();
2240
2241 /* On a tile with a red non-pbs signal, don't look ahead. */
2242 if (IsTileType(v->tile, MP_RAILWAY) && HasSignalOnTrackdir(v->tile, td) &&
2243 !IsPbsSignal(GetSignalType(v->tile, TrackdirToTrack(td))) &&
2245
2246 CFollowTrackRail ft(v);
2247 if (!ft.Follow(v->tile, td)) return;
2248
2250 /* Next tile is not reserved. */
2253 /* If the next tile is a PBS signal, try to make a reservation. */
2256 tracks &= ~TrackCrossesTracks(TrackdirToTrack(ft.old_td));
2257 }
2258 ChooseTrainTrack(v, ft.new_tile, ft.exitdir, tracks, false, nullptr, false);
2259 }
2260 }
2261 }
2262}
2263
2270{
2271 /* bail out if not all wagons are in the same depot or not in a depot at all */
2272 for (const Train *u = v; u != nullptr; u = u->Next()) {
2273 if (u->track != TRACK_BIT_DEPOT || u->tile != v->tile) return false;
2274 }
2275
2276 /* if the train got no power, then keep it in the depot */
2277 if (v->gcache.cached_power == 0) {
2280 return true;
2281 }
2282
2283 /* Check if we should wait here for unbunching. */
2284 if (v->IsWaitingForUnbunching()) return true;
2285
2286 SigSegState seg_state;
2287
2288 if (v->force_proceed == TFP_NONE) {
2289 /* force proceed was not pressed */
2290 if (++v->wait_counter < 37) {
2292 return true;
2293 }
2294
2295 v->wait_counter = 0;
2296
2298 if (seg_state == SIGSEG_FULL || HasDepotReservation(v->tile)) {
2299 /* Full and no PBS signal in block or depot reserved, can't exit. */
2301 return true;
2302 }
2303 } else {
2305 }
2306
2307 /* We are leaving a depot, but have to go to the exact same one; re-enter. */
2308 if (v->current_order.IsType(OT_GOTO_DEPOT) && v->tile == v->dest_tile) {
2309 /* Service when depot has no reservation. */
2311 return true;
2312 }
2313
2314 /* Only leave when we can reserve a path to our destination. */
2315 if (seg_state == SIGSEG_PBS && !TryPathReserve(v) && v->force_proceed == TFP_NONE) {
2316 /* No path and no force proceed. */
2319 return true;
2320 }
2321
2322 SetDepotReservation(v->tile, true);
2324
2329
2330 v->track = TRACK_BIT_X;
2331 if (v->direction & 2) v->track = TRACK_BIT_Y;
2332
2334 v->cur_speed = 0;
2335
2336 v->UpdateViewport(true, true);
2337 v->UpdatePosition();
2339 v->UpdateAcceleration();
2341
2342 return false;
2343}
2344
2351static void ClearPathReservation(const Train *v, TileIndex tile, Trackdir track_dir)
2352{
2353 DiagDirection dir = TrackdirToExitdir(track_dir);
2354
2355 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
2356 /* Are we just leaving a tunnel/bridge? */
2357 if (GetTunnelBridgeDirection(tile) == ReverseDiagDir(dir)) {
2359
2360 if (TunnelBridgeIsFree(tile, end, v).Succeeded()) {
2361 /* Free the reservation only if no other train is on the tiles. */
2362 SetTunnelBridgeReservation(tile, false);
2363 SetTunnelBridgeReservation(end, false);
2364
2366 if (IsBridge(tile)) {
2367 MarkBridgeDirty(tile);
2368 } else {
2369 MarkTileDirtyByTile(tile);
2371 }
2372 }
2373 }
2374 }
2375 } else if (IsRailStationTile(tile)) {
2376 TileIndex new_tile = TileAddByDiagDir(tile, dir);
2377 /* If the new tile is not a further tile of the same station, we
2378 * clear the reservation for the whole platform. */
2379 if (!IsCompatibleTrainStationTile(new_tile, tile)) {
2381 }
2382 } else {
2383 /* Any other tile */
2384 UnreserveRailTrack(tile, TrackdirToTrack(track_dir));
2385 }
2386}
2387
2393{
2394 assert(v->IsFrontEngine());
2395
2396 TileIndex tile = v->tile;
2397 Trackdir td = v->GetVehicleTrackdir();
2398 bool free_tile = !(IsRailStationTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE));
2399 StationID station_id = IsRailStationTile(v->tile) ? GetStationIndex(v->tile) : StationID::Invalid();
2400
2401 /* Can't be holding a reservation if we enter a depot. */
2402 if (IsRailDepotTile(tile) && TrackdirToExitdir(td) != GetRailDepotDirection(tile)) return;
2403 if (v->track == TRACK_BIT_DEPOT) {
2404 /* Front engine is in a depot. We enter if some part is not in the depot. */
2405 for (const Train *u = v; u != nullptr; u = u->Next()) {
2406 if (u->track != TRACK_BIT_DEPOT || u->tile != v->tile) return;
2407 }
2408 }
2409 /* Don't free reservation if it's not ours. */
2411
2413 while (ft.Follow(tile, td)) {
2414 tile = ft.new_tile;
2416 td = RemoveFirstTrackdir(&bits);
2417 assert(bits == TRACKDIR_BIT_NONE);
2418
2419 if (!IsValidTrackdir(td)) break;
2420
2421 if (IsTileType(tile, MP_RAILWAY)) {
2422 if (HasSignalOnTrackdir(tile, td) && !IsPbsSignal(GetSignalType(tile, TrackdirToTrack(td)))) {
2423 /* Conventional signal along trackdir: remove reservation and stop. */
2425 break;
2426 }
2427 if (HasPbsSignalOnTrackdir(tile, td)) {
2428 if (GetSignalStateByTrackdir(tile, td) == SIGNAL_STATE_RED) {
2429 /* Red PBS signal? Can't be our reservation, would be green then. */
2430 break;
2431 } else {
2432 /* Turn the signal back to red. */
2434 MarkTileDirtyByTile(tile);
2435 }
2436 } else if (HasPbsSignalOnTrackdir(tile, ReverseTrackdir(td))) {
2437 /* Reservation passes an opposing path signal. Mark signal for update to re-establish the proper default state. */
2439 } else if (HasSignalOnTrackdir(tile, ReverseTrackdir(td)) && IsOnewaySignal(tile, TrackdirToTrack(td))) {
2440 break;
2441 }
2442 }
2443
2444 /* Don't free first station/bridge/tunnel if we are on it. */
2445 if (free_tile || (!(ft.is_station && GetStationIndex(ft.new_tile) == station_id) && !ft.is_tunnel && !ft.is_bridge)) ClearPathReservation(v, tile, td);
2446
2447 free_tile = true;
2448 }
2449
2451}
2452
2453static const uint8_t _initial_tile_subcoord[6][4][3] = {
2454{{ 15, 8, 1 }, { 0, 0, 0 }, { 0, 8, 5 }, { 0, 0, 0 }},
2455{{ 0, 0, 0 }, { 8, 0, 3 }, { 0, 0, 0 }, { 8, 15, 7 }},
2456{{ 0, 0, 0 }, { 7, 0, 2 }, { 0, 7, 6 }, { 0, 0, 0 }},
2457{{ 15, 8, 2 }, { 0, 0, 0 }, { 0, 0, 0 }, { 8, 15, 6 }},
2458{{ 15, 7, 0 }, { 8, 0, 4 }, { 0, 0, 0 }, { 0, 0, 0 }},
2459{{ 0, 0, 0 }, { 0, 0, 0 }, { 0, 8, 4 }, { 7, 15, 0 }},
2460};
2461
2475static Track DoTrainPathfind(const Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool &path_found, bool do_track_reservation, PBSTileInfo *dest, TileIndex *final_dest)
2476{
2477 if (final_dest != nullptr) *final_dest = INVALID_TILE;
2478 return YapfTrainChooseTrack(v, tile, enterdir, tracks, path_found, do_track_reservation, dest, final_dest);
2479}
2480
2486static PBSTileInfo ExtendTrainReservation(const Train *v, TrackBits *new_tracks, DiagDirection *enterdir)
2487{
2489
2490 CFollowTrackRail ft(v);
2491
2492 std::vector<std::pair<TileIndex, Trackdir>> signals_set_to_red;
2493
2494 TileIndex tile = origin.tile;
2495 Trackdir cur_td = origin.trackdir;
2496 while (ft.Follow(tile, cur_td)) {
2498 /* Possible signal tile. */
2500 }
2501
2503 ft.new_td_bits &= ~TrackdirCrossesTrackdirs(ft.old_td);
2504 if (ft.new_td_bits == TRACKDIR_BIT_NONE) break;
2505 }
2506
2507 /* Station, depot or waypoint are a possible target. */
2508 bool target_seen = ft.is_station || (IsTileType(ft.new_tile, MP_RAILWAY) && !IsPlainRail(ft.new_tile));
2509 if (target_seen || KillFirstBit(ft.new_td_bits) != TRACKDIR_BIT_NONE) {
2510 /* Choice found or possible target encountered.
2511 * On finding a possible target, we need to stop and let the pathfinder handle the
2512 * remaining path. This is because we don't know if this target is in one of our
2513 * orders, so we might cause pathfinding to fail later on if we find a choice.
2514 * This failure would cause a bogous call to TryReserveSafePath which might reserve
2515 * a wrong path not leading to our next destination. */
2517
2518 /* If we did skip some tiles, backtrack to the first skipped tile so the pathfinder
2519 * actually starts its search at the first unreserved tile. */
2520 if (ft.tiles_skipped != 0) ft.new_tile -= TileOffsByDiagDir(ft.exitdir) * ft.tiles_skipped;
2521
2522 /* Choice found, path valid but not okay. Save info about the choice tile as well. */
2523 if (new_tracks != nullptr) *new_tracks = TrackdirBitsToTrackBits(ft.new_td_bits);
2524 if (enterdir != nullptr) *enterdir = ft.exitdir;
2525 return PBSTileInfo(ft.new_tile, ft.old_td, false);
2526 }
2527
2528 tile = ft.new_tile;
2529 cur_td = FindFirstTrackdir(ft.new_td_bits);
2530
2531 Trackdir rev_td = ReverseTrackdir(cur_td);
2532 if (IsSafeWaitingPosition(v, tile, cur_td, true, _settings_game.pf.forbid_90_deg)) {
2533 bool wp_free = IsWaitingPositionFree(v, tile, cur_td, _settings_game.pf.forbid_90_deg);
2534 if (!(wp_free && TryReserveRailTrack(tile, TrackdirToTrack(cur_td)))) break;
2535 /* Green path signal opposing the path? Turn to red. */
2536 if (HasPbsSignalOnTrackdir(tile, rev_td) && GetSignalStateByTrackdir(tile, rev_td) == SIGNAL_STATE_GREEN) {
2537 signals_set_to_red.emplace_back(tile, rev_td);
2539 MarkTileDirtyByTile(tile);
2540 }
2541 /* Safe position is all good, path valid and okay. */
2542 return PBSTileInfo(tile, cur_td, true);
2543 }
2544
2545 if (!TryReserveRailTrack(tile, TrackdirToTrack(cur_td))) break;
2546
2547 /* Green path signal opposing the path? Turn to red. */
2548 if (HasPbsSignalOnTrackdir(tile, rev_td) && GetSignalStateByTrackdir(tile, rev_td) == SIGNAL_STATE_GREEN) {
2549 signals_set_to_red.emplace_back(tile, rev_td);
2551 MarkTileDirtyByTile(tile);
2552 }
2553 }
2554
2555 if (ft.err == CFollowTrackRail::EC_OWNER || ft.err == CFollowTrackRail::EC_NO_WAY) {
2556 /* End of line, path valid and okay. */
2557 return PBSTileInfo(ft.old_tile, ft.old_td, true);
2558 }
2559
2560 /* Sorry, can't reserve path, back out. */
2561 tile = origin.tile;
2562 cur_td = origin.trackdir;
2563 TileIndex stopped = ft.old_tile;
2564 Trackdir stopped_td = ft.old_td;
2565 while (tile != stopped || cur_td != stopped_td) {
2566 if (!ft.Follow(tile, cur_td)) break;
2567
2569 ft.new_td_bits &= ~TrackdirCrossesTrackdirs(ft.old_td);
2570 assert(ft.new_td_bits != TRACKDIR_BIT_NONE);
2571 }
2573
2574 tile = ft.new_tile;
2575 cur_td = FindFirstTrackdir(ft.new_td_bits);
2576
2577 UnreserveRailTrack(tile, TrackdirToTrack(cur_td));
2578 }
2579
2580 /* Re-instate green signals we turned to red. */
2581 for (auto [sig_tile, td] : signals_set_to_red) {
2583 }
2584
2585 /* Path invalid. */
2586 return PBSTileInfo();
2587}
2588
2599static bool TryReserveSafeTrack(const Train *v, TileIndex tile, Trackdir td, bool override_railtype)
2600{
2601 return YapfTrainFindNearestSafeTile(v, tile, td, override_railtype);
2602}
2603
2606private:
2607 Train *v;
2608 Order old_order;
2609 TileIndex old_dest_tile;
2610 StationID old_last_station_visited;
2611 VehicleOrderID index;
2612 bool suppress_implicit_orders;
2613 bool restored;
2614
2615public:
2617 v(_v),
2618 old_order(_v->current_order),
2619 old_dest_tile(_v->dest_tile),
2620 old_last_station_visited(_v->last_station_visited),
2621 index(_v->cur_real_order_index),
2622 suppress_implicit_orders(HasBit(_v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS)),
2623 restored(false)
2624 {
2625 }
2626
2630 void Restore()
2631 {
2632 this->v->current_order = this->old_order;
2633 this->v->dest_tile = this->old_dest_tile;
2634 this->v->last_station_visited = this->old_last_station_visited;
2635 AssignBit(this->v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS, suppress_implicit_orders);
2636 this->restored = true;
2637 }
2638
2643 {
2644 if (!this->restored) this->Restore();
2645 }
2646
2652 bool SwitchToNextOrder(bool skip_first)
2653 {
2654 if (this->v->GetNumOrders() == 0) return false;
2655
2656 if (skip_first) ++this->index;
2657
2658 int depth = 0;
2659
2660 do {
2661 /* Wrap around. */
2662 if (this->index >= this->v->GetNumOrders()) this->index = 0;
2663
2664 Order *order = this->v->GetOrder(this->index);
2665 assert(order != nullptr);
2666
2667 switch (order->GetType()) {
2668 case OT_GOTO_DEPOT:
2669 /* Skip service in depot orders when the train doesn't need service. */
2670 if ((order->GetDepotOrderType() & ODTFB_SERVICE) && !this->v->NeedsServicing()) break;
2671 [[fallthrough]];
2672 case OT_GOTO_STATION:
2673 case OT_GOTO_WAYPOINT:
2674 this->v->current_order = *order;
2675 return UpdateOrderDest(this->v, order, 0, true);
2676 case OT_CONDITIONAL: {
2677 VehicleOrderID next = ProcessConditionalOrder(order, this->v);
2678 if (next != INVALID_VEH_ORDER_ID) {
2679 depth++;
2680 this->index = next;
2681 /* Don't increment next, so no break here. */
2682 continue;
2683 }
2684 break;
2685 }
2686 default:
2687 break;
2688 }
2689 /* Don't increment inside the while because otherwise conditional
2690 * orders can lead to an infinite loop. */
2691 ++this->index;
2692 depth++;
2693 } while (this->index != this->v->cur_real_order_index && depth < this->v->GetNumOrders());
2694
2695 return false;
2696 }
2697};
2698
2699/* choose a track */
2700static Track ChooseTrainTrack(Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool force_res, bool *got_reservation, bool mark_stuck)
2701{
2702 Track best_track = INVALID_TRACK;
2703 bool do_track_reservation = _settings_game.pf.reserve_paths || force_res;
2704 bool changed_signal = false;
2705 TileIndex final_dest = INVALID_TILE;
2706
2707 assert((tracks & ~TRACK_BIT_MASK) == 0);
2708
2709 if (got_reservation != nullptr) *got_reservation = false;
2710
2711 /* Don't use tracks here as the setting to forbid 90 deg turns might have been switched between reservation and now. */
2712 TrackBits res_tracks = (TrackBits)(GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir));
2713 /* Do we have a suitable reserved track? */
2714 if (res_tracks != TRACK_BIT_NONE) return FindFirstTrack(res_tracks);
2715
2716 /* Quick return in case only one possible track is available */
2717 if (KillFirstBit(tracks) == TRACK_BIT_NONE) {
2718 Track track = FindFirstTrack(tracks);
2719 /* We need to check for signals only here, as a junction tile can't have signals. */
2720 if (track != INVALID_TRACK && HasPbsSignalOnTrackdir(tile, TrackEnterdirToTrackdir(track, enterdir))) {
2721 do_track_reservation = true;
2722 changed_signal = true;
2724 } else if (!do_track_reservation) {
2725 return track;
2726 }
2727 best_track = track;
2728 }
2729
2730 PBSTileInfo res_dest(tile, INVALID_TRACKDIR, false);
2731 DiagDirection dest_enterdir = enterdir;
2732 if (do_track_reservation) {
2733 res_dest = ExtendTrainReservation(v, &tracks, &dest_enterdir);
2734 if (res_dest.tile == INVALID_TILE) {
2735 /* Reservation failed? */
2736 if (mark_stuck) MarkTrainAsStuck(v);
2737 if (changed_signal) SetSignalStateByTrackdir(tile, TrackEnterdirToTrackdir(best_track, enterdir), SIGNAL_STATE_RED);
2738 return FindFirstTrack(tracks);
2739 }
2740 if (res_dest.okay) {
2741 /* Got a valid reservation that ends at a safe target, quick exit. */
2742 if (got_reservation != nullptr) *got_reservation = true;
2743 if (changed_signal) MarkTileDirtyByTile(tile);
2745 return best_track;
2746 }
2747
2748 /* Check if the train needs service here, so it has a chance to always find a depot.
2749 * Also check if the current order is a service order so we don't reserve a path to
2750 * the destination but instead to the next one if service isn't needed. */
2752 if (v->current_order.IsType(OT_DUMMY) || v->current_order.IsType(OT_CONDITIONAL) || v->current_order.IsType(OT_GOTO_DEPOT)) ProcessOrders(v);
2753 }
2754
2755 /* Save the current train order. The destructor will restore the old order on function exit. */
2756 VehicleOrderSaver orders(v);
2757
2758 /* If the current tile is the destination of the current order and
2759 * a reservation was requested, advance to the next order.
2760 * Don't advance on a depot order as depots are always safe end points
2761 * for a path and no look-ahead is necessary. This also avoids a
2762 * problem with depot orders not part of the order list when the
2763 * order list itself is empty. */
2764 if (v->current_order.IsType(OT_LEAVESTATION)) {
2765 orders.SwitchToNextOrder(false);
2766 } else if (v->current_order.IsType(OT_LOADING) || (!v->current_order.IsType(OT_GOTO_DEPOT) && (
2767 v->current_order.IsType(OT_GOTO_STATION) ?
2769 v->tile == v->dest_tile))) {
2770 orders.SwitchToNextOrder(true);
2771 }
2772
2773 if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
2774 /* Pathfinders are able to tell that route was only 'guessed'. */
2775 bool path_found = true;
2776 TileIndex new_tile = res_dest.tile;
2777
2778 Track next_track = DoTrainPathfind(v, new_tile, dest_enterdir, tracks, path_found, do_track_reservation, &res_dest, &final_dest);
2779 if (new_tile == tile) best_track = next_track;
2780 v->HandlePathfindingResult(path_found);
2781 }
2782
2783 /* No track reservation requested -> finished. */
2784 if (!do_track_reservation) return best_track;
2785
2786 /* A path was found, but could not be reserved. */
2787 if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
2788 if (mark_stuck) MarkTrainAsStuck(v);
2790 return best_track;
2791 }
2792
2793 /* No possible reservation target found, we are probably lost. */
2794 if (res_dest.tile == INVALID_TILE) {
2795 /* Try to find any safe destination. */
2797 if (TryReserveSafeTrack(v, origin.tile, origin.trackdir, false)) {
2798 TrackBits res = GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir);
2799 best_track = FindFirstTrack(res);
2801 if (got_reservation != nullptr) *got_reservation = true;
2802 if (changed_signal) MarkTileDirtyByTile(tile);
2803 } else {
2805 if (mark_stuck) MarkTrainAsStuck(v);
2806 }
2807 return best_track;
2808 }
2809
2810 if (got_reservation != nullptr) *got_reservation = true;
2811
2812 /* Reservation target found and free, check if it is safe. */
2813 while (!IsSafeWaitingPosition(v, res_dest.tile, res_dest.trackdir, true, _settings_game.pf.forbid_90_deg)) {
2814 /* Extend reservation until we have found a safe position. */
2815 DiagDirection exitdir = TrackdirToExitdir(res_dest.trackdir);
2816 TileIndex next_tile = TileAddByDiagDir(res_dest.tile, exitdir);
2818 if (Rail90DegTurnDisallowed(GetTileRailType(res_dest.tile), GetTileRailType(next_tile))) {
2819 reachable &= ~TrackCrossesTracks(TrackdirToTrack(res_dest.trackdir));
2820 }
2821
2822 /* Get next order with destination. */
2823 if (orders.SwitchToNextOrder(true)) {
2824 PBSTileInfo cur_dest;
2825 bool path_found;
2826 DoTrainPathfind(v, next_tile, exitdir, reachable, path_found, true, &cur_dest, nullptr);
2827 if (cur_dest.tile != INVALID_TILE) {
2828 res_dest = cur_dest;
2829 if (res_dest.okay) continue;
2830 /* Path found, but could not be reserved. */
2832 if (mark_stuck) MarkTrainAsStuck(v);
2833 if (got_reservation != nullptr) *got_reservation = false;
2834 changed_signal = false;
2835 break;
2836 }
2837 }
2838 /* No order or no safe position found, try any position. */
2839 if (!TryReserveSafeTrack(v, res_dest.tile, res_dest.trackdir, true)) {
2841 if (mark_stuck) MarkTrainAsStuck(v);
2842 if (got_reservation != nullptr) *got_reservation = false;
2843 changed_signal = false;
2844 }
2845 break;
2846 }
2847
2849
2850 if (changed_signal) MarkTileDirtyByTile(tile);
2851
2852 orders.Restore();
2853 if (v->current_order.IsType(OT_GOTO_DEPOT) &&
2855 final_dest != INVALID_TILE && IsRailDepotTile(final_dest)) {
2857 v->dest_tile = final_dest;
2859 }
2860
2861 return best_track;
2862}
2863
2872bool TryPathReserve(Train *v, bool mark_as_stuck, bool first_tile_okay)
2873{
2874 assert(v->IsFrontEngine());
2875
2876 /* We have to handle depots specially as the track follower won't look
2877 * at the depot tile itself but starts from the next tile. If we are still
2878 * inside the depot, a depot reservation can never be ours. */
2879 if (v->track == TRACK_BIT_DEPOT) {
2880 if (HasDepotReservation(v->tile)) {
2881 if (mark_as_stuck) MarkTrainAsStuck(v);
2882 return false;
2883 } else {
2884 /* Depot not reserved, but the next tile might be. */
2886 if (HasReservedTracks(next_tile, DiagdirReachesTracks(GetRailDepotDirection(v->tile)))) return false;
2887 }
2888 }
2889
2890 Vehicle *other_train = nullptr;
2891 PBSTileInfo origin = FollowTrainReservation(v, &other_train);
2892 /* The path we are driving on is already blocked by some other train.
2893 * This can only happen in certain situations when mixing path and
2894 * block signals or when changing tracks and/or signals.
2895 * Exit here as doing any further reservations will probably just
2896 * make matters worse. */
2897 if (other_train != nullptr && other_train->index != v->index) {
2898 if (mark_as_stuck) MarkTrainAsStuck(v);
2899 return false;
2900 }
2901 /* If we have a reserved path and the path ends at a safe tile, we are finished already. */
2902 if (origin.okay && (v->tile != origin.tile || first_tile_okay)) {
2903 /* Can't be stuck then. */
2905 v->flags.Reset(VehicleRailFlag::Stuck);
2906 return true;
2907 }
2908
2909 /* If we are in a depot, tentatively reserve the depot. */
2910 if (v->track == TRACK_BIT_DEPOT) {
2911 SetDepotReservation(v->tile, true);
2913 }
2914
2915 DiagDirection exitdir = TrackdirToExitdir(origin.trackdir);
2916 TileIndex new_tile = TileAddByDiagDir(origin.tile, exitdir);
2918
2919 if (Rail90DegTurnDisallowed(GetTileRailType(origin.tile), GetTileRailType(new_tile))) reachable &= ~TrackCrossesTracks(TrackdirToTrack(origin.trackdir));
2920
2921 bool res_made = false;
2922 ChooseTrainTrack(v, new_tile, exitdir, reachable, true, &res_made, mark_as_stuck);
2923
2924 if (!res_made) {
2925 /* Free the depot reservation as well. */
2926 if (v->track == TRACK_BIT_DEPOT) SetDepotReservation(v->tile, false);
2927 return false;
2928 }
2929
2930 if (v->flags.Test(VehicleRailFlag::Stuck)) {
2931 v->wait_counter = 0;
2933 }
2934 v->flags.Reset(VehicleRailFlag::Stuck);
2935 return true;
2936}
2937
2938
2939static bool CheckReverseTrain(const Train *v)
2940{
2942 v->track == TRACK_BIT_DEPOT || v->track == TRACK_BIT_WORMHOLE ||
2943 !(v->direction & 1)) {
2944 return false;
2945 }
2946
2947 assert(v->track != TRACK_BIT_NONE);
2948
2949 return YapfTrainCheckReverse(v);
2950}
2951
2958{
2959 if (station == this->last_station_visited) this->last_station_visited = StationID::Invalid();
2960
2961 const Station *st = Station::Get(station);
2963 /* The destination station has no trainstation tiles. */
2965 return TileIndex{};
2966 }
2967
2968 return st->xy;
2969}
2970
2973{
2974 Train *v = this;
2975 do {
2976 v->colourmap = PAL_NONE;
2977 v->UpdateViewport(true, false);
2978 } while ((v = v->Next()) != nullptr);
2979
2980 /* need to update acceleration and cached values since the goods on the train changed. */
2981 this->CargoChanged();
2982 this->UpdateAcceleration();
2983}
2984
2993{
2995 default: NOT_REACHED();
2996 case AM_ORIGINAL:
2997 return this->DoUpdateSpeed(this->acceleration * (this->GetAccelerationStatus() == AS_BRAKE ? -4 : 2), 0, this->GetCurrentMaxSpeed());
2998
2999 case AM_REALISTIC:
3000 return this->DoUpdateSpeed(this->GetAcceleration(), this->GetAccelerationStatus() == AS_BRAKE ? 0 : 2, this->GetCurrentMaxSpeed());
3001 }
3002}
3003
3009static void TrainEnterStation(Train *v, StationID station)
3010{
3011 v->last_station_visited = station;
3012
3013 /* check if a train ever visited this station before */
3014 Station *st = Station::Get(station);
3015 if (!(st->had_vehicle_of_type & HVOT_TRAIN)) {
3016 st->had_vehicle_of_type |= HVOT_TRAIN;
3018 GetEncodedString(STR_NEWS_FIRST_TRAIN_ARRIVAL, st->index),
3020 v->index,
3021 st->index
3022 );
3023 AI::NewEvent(v->owner, new ScriptEventStationFirstVehicle(st->index, v->index));
3024 Game::NewEvent(new ScriptEventStationFirstVehicle(st->index, v->index));
3025 }
3026
3027 v->force_proceed = TFP_NONE;
3029
3030 v->BeginLoading();
3031
3033 TriggerStationAnimation(st, v->tile, StationAnimationTrigger::VehicleArrives);
3034}
3035
3036/* Check if the vehicle is compatible with the specified tile */
3037static inline bool CheckCompatibleRail(const Train *v, TileIndex tile)
3038{
3039 return IsTileOwner(tile, v->owner) &&
3040 (!v->IsFrontEngine() || v->compatible_railtypes.Test(GetRailType(tile)));
3041}
3042
3045 uint8_t small_turn;
3046 uint8_t large_turn;
3047 uint8_t z_up;
3048 uint8_t z_down;
3049};
3050
3053 /* normal accel */
3054 {256 / 4, 256 / 2, 256 / 4, 2},
3055 {256 / 4, 256 / 2, 256 / 4, 2},
3056 {0, 256 / 2, 256 / 4, 2},
3057};
3058
3064static inline void AffectSpeedByZChange(Train *v, int old_z)
3065{
3066 if (old_z == v->z_pos || _settings_game.vehicle.train_acceleration_model != AM_ORIGINAL) return;
3067
3069
3070 if (old_z < v->z_pos) {
3071 v->cur_speed -= (v->cur_speed * asp->z_up >> 8);
3072 } else {
3073 uint16_t spd = v->cur_speed + asp->z_down;
3074 if (spd <= v->gcache.cached_max_track_speed) v->cur_speed = spd;
3075 }
3076}
3077
3078static bool TrainMovedChangeSignals(TileIndex tile, DiagDirection dir)
3079{
3080 if (IsTileType(tile, MP_RAILWAY) &&
3083 Trackdir trackdir = FindFirstTrackdir(tracks);
3084 if (UpdateSignalsOnSegment(tile, TrackdirToExitdir(trackdir), GetTileOwner(tile)) == SIGSEG_PBS && HasSignalOnTrackdir(tile, trackdir)) {
3085 /* A PBS block with a non-PBS signal facing us? */
3086 if (!IsPbsSignal(GetSignalType(tile, TrackdirToTrack(trackdir)))) return true;
3087 }
3088 }
3089 return false;
3090}
3091
3094{
3095 for (const Train *u = this; u != nullptr; u = u->Next()) {
3096 switch (u->track) {
3097 case TRACK_BIT_WORMHOLE:
3099 break;
3100 case TRACK_BIT_DEPOT:
3101 break;
3102 default:
3104 break;
3105 }
3106 }
3107}
3108
3115uint Train::Crash(bool flooded)
3116{
3117 uint victims = 0;
3118 if (this->IsFrontEngine()) {
3119 victims += 2; // driver
3120
3121 /* Remove the reserved path in front of the train if it is not stuck.
3122 * Also clear all reserved tracks the train is currently on. */
3123 if (!this->flags.Test(VehicleRailFlag::Stuck)) FreeTrainTrackReservation(this);
3124 for (const Train *v = this; v != nullptr; v = v->Next()) {
3126 if (IsTileType(v->tile, MP_TUNNELBRIDGE)) {
3127 /* ClearPathReservation will not free the wormhole exit
3128 * if the train has just entered the wormhole. */
3130 }
3131 }
3132
3133 /* we may need to update crossing we were approaching,
3134 * but must be updated after the train has been marked crashed */
3135 TileIndex crossing = TrainApproachingCrossingTile(this);
3136 if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
3137
3138 /* Remove the loading indicators (if any) */
3140 }
3141
3142 victims += this->GroundVehicleBase::Crash(flooded);
3143
3144 this->crash_anim_pos = flooded ? 4000 : 1; // max 4440, disappear pretty fast when flooded
3145 return victims;
3146}
3147
3154static uint TrainCrashed(Train *v)
3155{
3156 uint victims = 0;
3157
3158 /* do not crash train twice */
3159 if (!v->vehstatus.Test(VehState::Crashed)) {
3160 victims = v->Crash();
3161 AI::NewEvent(v->owner, new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_TRAIN, victims, v->owner));
3162 Game::NewEvent(new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_TRAIN, victims, v->owner));
3163 }
3164
3165 /* Try to re-reserve track under already crashed train too.
3166 * Crash() clears the reservation! */
3168
3169 return victims;
3170}
3171
3179{
3180 /* not a train or in depot */
3181 if (v->type != VEH_TRAIN || Train::From(v)->track == TRACK_BIT_DEPOT) return 0;
3182
3183 /* do not crash into trains of another company. */
3184 if (v->owner != t->owner) return 0;
3185
3186 /* get first vehicle now to make most usual checks faster */
3187 Train *coll = Train::From(v)->First();
3188
3189 /* can't collide with own wagons */
3190 if (coll == t) return 0;
3191
3192 int x_diff = v->x_pos - t->x_pos;
3193 int y_diff = v->y_pos - t->y_pos;
3194
3195 /* Do fast calculation to check whether trains are not in close vicinity
3196 * and quickly reject trains distant enough for any collision.
3197 * Differences are shifted by 7, mapping range [-7 .. 8] into [0 .. 15]
3198 * Differences are then ORed and then we check for any higher bits */
3199 uint hash = (y_diff + 7) | (x_diff + 7);
3200 if (hash & ~15) return 0;
3201
3202 /* Slower check using multiplication */
3203 int min_diff = (Train::From(v)->gcache.cached_veh_length + 1) / 2 + (t->gcache.cached_veh_length + 1) / 2 - 1;
3204 if (x_diff * x_diff + y_diff * y_diff > min_diff * min_diff) return 0;
3205
3206 /* Happens when there is a train under bridge next to bridge head */
3207 if (abs(v->z_pos - t->z_pos) > 5) return 0;
3208
3209 /* crash both trains */
3210 return TrainCrashed(t) + TrainCrashed(coll);
3211}
3212
3221{
3222 /* can't collide in depot */
3223 if (v->track == TRACK_BIT_DEPOT) return false;
3224
3225 assert(v->track == TRACK_BIT_WORMHOLE || TileVirtXY(v->x_pos, v->y_pos) == v->tile);
3226
3227 uint num_victims = 0;
3228
3229 /* find colliding vehicles */
3230 if (v->track == TRACK_BIT_WORMHOLE) {
3231 for (Vehicle *u : VehiclesOnTile(v->tile)) {
3232 num_victims += CheckTrainCollision(u, v);
3233 }
3235 num_victims += CheckTrainCollision(u, v);
3236 }
3237 } else {
3238 for (Vehicle *u : VehiclesNearTileXY(v->x_pos, v->y_pos, 7)) {
3239 num_victims += CheckTrainCollision(u, v);
3240 }
3241 }
3242
3243 /* any dead -> no crash */
3244 if (num_victims == 0) return false;
3245
3246 AddTileNewsItem(GetEncodedString(STR_NEWS_TRAIN_CRASH, num_victims), NewsType::Accident, v->tile);
3247
3248 ModifyStationRatingAround(v->tile, v->owner, -160, 30);
3249 if (_settings_client.sound.disaster) SndPlayVehicleFx(SND_13_TRAIN_COLLISION, v);
3250 return true;
3251}
3252
3260bool TrainController(Train *v, Vehicle *nomove, bool reverse)
3261{
3262 Train *first = v->First();
3263 Train *prev;
3264 bool direction_changed = false; // has direction of any part changed?
3265
3266 /* For every vehicle after and including the given vehicle */
3267 for (prev = v->Previous(); v != nomove; prev = v, v = v->Next()) {
3268 DiagDirection enterdir = DIAGDIR_BEGIN;
3269 bool update_signals_crossing = false; // will we update signals or crossing state?
3270
3272 if (v->track != TRACK_BIT_WORMHOLE) {
3273 /* Not inside tunnel */
3274 if (gp.old_tile == gp.new_tile) {
3275 /* Staying in the old tile */
3276 if (v->track == TRACK_BIT_DEPOT) {
3277 /* Inside depot */
3278 gp.x = v->x_pos;
3279 gp.y = v->y_pos;
3280 } else {
3281 /* Not inside depot */
3282
3283 /* Reverse when we are at the end of the track already, do not move to the new position */
3284 if (v->IsFrontEngine() && !TrainCheckIfLineEnds(v, reverse)) return false;
3285
3286 auto vets = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
3287 if (vets.Test(VehicleEnterTileState::CannotEnter)) {
3288 goto invalid_rail;
3289 }
3291 /* The new position is the end of the platform */
3293 }
3294 }
3295 } else {
3296 /* A new tile is about to be entered. */
3297
3298 /* Determine what direction we're entering the new tile from */
3299 enterdir = DiagdirBetweenTiles(gp.old_tile, gp.new_tile);
3300 assert(IsValidDiagDirection(enterdir));
3301
3302 /* Get the status of the tracks in the new tile and mask
3303 * away the bits that aren't reachable. */
3304 TrackStatus ts = GetTileTrackStatus(gp.new_tile, TRANSPORT_RAIL, 0, ReverseDiagDir(enterdir));
3305 TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(enterdir);
3306
3307 TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
3308 TrackBits red_signals = TrackdirBitsToTrackBits(TrackStatusToRedSignals(ts) & reachable_trackdirs);
3309
3310 TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
3311 if (Rail90DegTurnDisallowed(GetTileRailType(gp.old_tile), GetTileRailType(gp.new_tile)) && prev == nullptr) {
3312 /* We allow wagons to make 90 deg turns, because forbid_90_deg
3313 * can be switched on halfway a turn */
3314 bits &= ~TrackCrossesTracks(FindFirstTrack(v->track));
3315 }
3316
3317 if (bits == TRACK_BIT_NONE) goto invalid_rail;
3318
3319 /* Check if the new tile constrains tracks that are compatible
3320 * with the current train, if not, bail out. */
3321 if (!CheckCompatibleRail(v, gp.new_tile)) goto invalid_rail;
3322
3323 TrackBits chosen_track;
3324 if (prev == nullptr) {
3325 /* Currently the locomotive is active. Determine which one of the
3326 * available tracks to choose */
3327 chosen_track = TrackToTrackBits(ChooseTrainTrack(v, gp.new_tile, enterdir, bits, false, nullptr, true));
3328 assert(chosen_track & (bits | GetReservedTrackbits(gp.new_tile)));
3329
3330 if (v->force_proceed != TFP_NONE && IsPlainRailTile(gp.new_tile) && HasSignals(gp.new_tile)) {
3331 /* For each signal we find decrease the counter by one.
3332 * We start at two, so the first signal we pass decreases
3333 * this to one, then if we reach the next signal it is
3334 * decreased to zero and we won't pass that new signal. */
3335 Trackdir dir = FindFirstTrackdir(trackdirbits);
3336 if (HasSignalOnTrackdir(gp.new_tile, dir) ||
3338 GetSignalType(gp.new_tile, TrackdirToTrack(dir)) != SIGTYPE_PBS)) {
3339 /* However, we do not want to be stopped by PBS signals
3340 * entered via the back. */
3341 v->force_proceed = (v->force_proceed == TFP_SIGNAL) ? TFP_STUCK : TFP_NONE;
3343 }
3344 }
3345
3346 /* Check if it's a red signal and that force proceed is not clicked. */
3347 if ((red_signals & chosen_track) && v->force_proceed == TFP_NONE) {
3348 /* In front of a red signal */
3349 Trackdir i = FindFirstTrackdir(trackdirbits);
3350
3351 /* Don't handle stuck trains here. */
3352 if (v->flags.Test(VehicleRailFlag::Stuck)) return false;
3353
3355 v->cur_speed = 0;
3356 v->subspeed = 0;
3357 v->progress = 255; // make sure that every bit of acceleration will hit the signal again, so speed stays 0.
3359 } else if (HasSignalOnTrackdir(gp.new_tile, i)) {
3360 v->cur_speed = 0;
3361 v->subspeed = 0;
3362 v->progress = 255; // make sure that every bit of acceleration will hit the signal again, so speed stays 0.
3364 DiagDirection exitdir = TrackdirToExitdir(i);
3365 TileIndex o_tile = TileAddByDiagDir(gp.new_tile, exitdir);
3366
3367 exitdir = ReverseDiagDir(exitdir);
3368
3369 /* check if a train is waiting on the other side */
3370 if (!HasVehicleOnTile(o_tile, [&exitdir](const Vehicle *u) {
3371 if (u->type != VEH_TRAIN || u->vehstatus.Test(VehState::Crashed)) return false;
3372 const Train *t = Train::From(u);
3373
3374 /* not front engine of a train, inside wormhole or depot, crashed */
3375 if (!t->IsFrontEngine() || !(t->track & TRACK_BIT_MASK)) return false;
3376
3377 if (t->cur_speed > 5 || VehicleExitDir(t->direction, t->track) != exitdir) return false;
3378
3379 return true;
3380 })) return false;
3381 }
3382 }
3383
3384 /* If we would reverse but are currently in a PBS block and
3385 * reversing of stuck trains is disabled, don't reverse.
3386 * This does not apply if the reason for reversing is a one-way
3387 * signal blocking us, because a train would then be stuck forever. */
3389 UpdateSignalsOnSegment(v->tile, enterdir, v->owner) == SIGSEG_PBS) {
3390 v->wait_counter = 0;
3391 return false;
3392 }
3393 goto reverse_train_direction;
3394 } else {
3395 TryReserveRailTrack(gp.new_tile, TrackBitsToTrack(chosen_track), false);
3396 }
3397 } else {
3398 /* The wagon is active, simply follow the prev vehicle. */
3399 if (prev->tile == gp.new_tile) {
3400 /* Choose the same track as prev */
3401 if (prev->track == TRACK_BIT_WORMHOLE) {
3402 /* Vehicles entering tunnels enter the wormhole earlier than for bridges.
3403 * However, just choose the track into the wormhole. */
3404 assert(IsTunnel(prev->tile));
3405 chosen_track = bits;
3406 } else {
3407 chosen_track = prev->track;
3408 }
3409 } else {
3410 /* Choose the track that leads to the tile where prev is.
3411 * This case is active if 'prev' is already on the second next tile, when 'v' just enters the next tile.
3412 * I.e. when the tile between them has only space for a single vehicle like
3413 * 1) horizontal/vertical track tiles and
3414 * 2) some orientations of tunnel entries, where the vehicle is already inside the wormhole at 8/16 from the tile edge.
3415 * Is also the train just reversing, the wagon inside the tunnel is 'on' the tile of the opposite tunnel entry.
3416 */
3417 static const TrackBits _connecting_track[DIAGDIR_END][DIAGDIR_END] = {
3422 };
3423 DiagDirection exitdir = DiagdirBetweenTiles(gp.new_tile, prev->tile);
3424 assert(IsValidDiagDirection(exitdir));
3425 chosen_track = _connecting_track[enterdir][exitdir];
3426 }
3427 chosen_track &= bits;
3428 }
3429
3430 /* Make sure chosen track is a valid track */
3431 assert(
3432 chosen_track == TRACK_BIT_X || chosen_track == TRACK_BIT_Y ||
3433 chosen_track == TRACK_BIT_UPPER || chosen_track == TRACK_BIT_LOWER ||
3434 chosen_track == TRACK_BIT_LEFT || chosen_track == TRACK_BIT_RIGHT);
3435
3436 /* Update XY to reflect the entrance to the new tile, and select the direction to use */
3437 const uint8_t *b = _initial_tile_subcoord[FindFirstBit(chosen_track)][enterdir];
3438 gp.x = (gp.x & ~0xF) | b[0];
3439 gp.y = (gp.y & ~0xF) | b[1];
3440 Direction chosen_dir = (Direction)b[2];
3441
3442 /* Call the landscape function and tell it that the vehicle entered the tile */
3443 auto vets = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
3444 if (vets.Test(VehicleEnterTileState::CannotEnter)) {
3445 goto invalid_rail;
3446 }
3447
3449 Track track = FindFirstTrack(chosen_track);
3450 Trackdir tdir = TrackDirectionToTrackdir(track, chosen_dir);
3451 if (v->IsFrontEngine() && HasPbsSignalOnTrackdir(gp.new_tile, tdir)) {
3454 }
3455
3456 /* Clear any track reservation when the last vehicle leaves the tile */
3457 if (v->Next() == nullptr) ClearPathReservation(v, v->tile, v->GetVehicleTrackdir());
3458
3459 v->tile = gp.new_tile;
3460
3462 v->First()->ConsistChanged(CCF_TRACK);
3463 }
3464
3465 v->track = chosen_track;
3466 assert(v->track);
3467 }
3468
3469 /* We need to update signal status, but after the vehicle position hash
3470 * has been updated by UpdateInclination() */
3471 update_signals_crossing = true;
3472
3473 if (chosen_dir != v->direction) {
3474 if (prev == nullptr && _settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) {
3476 DirDiff diff = DirDifference(v->direction, chosen_dir);
3477 v->cur_speed -= (diff == DIRDIFF_45RIGHT || diff == DIRDIFF_45LEFT ? asp->small_turn : asp->large_turn) * v->cur_speed >> 8;
3478 }
3479 direction_changed = true;
3480 v->direction = chosen_dir;
3481 }
3482
3483 if (v->IsFrontEngine()) {
3484 v->wait_counter = 0;
3485
3486 /* If we are approaching a crossing that is reserved, play the sound now. */
3488 if (crossing != INVALID_TILE && HasCrossingReservation(crossing) && _settings_client.sound.ambient) SndPlayTileFx(SND_0E_LEVEL_CROSSING, crossing);
3489
3490 /* Always try to extend the reservation when entering a tile. */
3492 }
3493
3495 /* The new position is the location where we want to stop */
3497 }
3498 }
3499 } else {
3501 /* Perform look-ahead on tunnel exit. */
3502 if (v->IsFrontEngine()) {
3505 }
3506 /* Prevent v->UpdateInclination() being called with wrong parameters.
3507 * This could happen if the train was reversed inside the tunnel/bridge. */
3508 if (gp.old_tile == gp.new_tile) {
3510 }
3511 } else {
3512 v->x_pos = gp.x;
3513 v->y_pos = gp.y;
3514 v->UpdatePosition();
3515 if (!v->vehstatus.Test(VehState::Hidden)) v->Vehicle::UpdateViewport(true);
3516 continue;
3517 }
3518 }
3519
3520 /* update image of train, as well as delta XY */
3521 v->UpdateDeltaXY();
3522
3523 v->x_pos = gp.x;
3524 v->y_pos = gp.y;
3525 v->UpdatePosition();
3526
3527 /* update the Z position of the vehicle */
3528 int old_z = v->UpdateInclination(gp.new_tile != gp.old_tile, false);
3529
3530 if (prev == nullptr) {
3531 /* This is the first vehicle in the train */
3532 AffectSpeedByZChange(v, old_z);
3533 }
3534
3535 if (update_signals_crossing) {
3536 if (v->IsFrontEngine()) {
3537 if (TrainMovedChangeSignals(gp.new_tile, enterdir)) {
3538 /* We are entering a block with PBS signals right now, but
3539 * not through a PBS signal. This means we don't have a
3540 * reservation right now. As a conventional signal will only
3541 * ever be green if no other train is in the block, getting
3542 * a path should always be possible. If the player built
3543 * such a strange network that it is not possible, the train
3544 * will be marked as stuck and the player has to deal with
3545 * the problem. */
3546 if ((!HasReservedTracks(gp.new_tile, v->track) &&
3547 !TryReserveRailTrack(gp.new_tile, FindFirstTrack(v->track))) ||
3548 !TryPathReserve(v)) {
3550 }
3551 }
3552 }
3553
3554 /* Signals can only change when the first
3555 * (above) or the last vehicle moves. */
3556 if (v->Next() == nullptr) {
3557 TrainMovedChangeSignals(gp.old_tile, ReverseDiagDir(enterdir));
3559 }
3560 }
3561
3562 /* Do not check on every tick to save some computing time. */
3564 }
3565
3566 if (direction_changed) first->tcache.cached_max_curve_speed = first->GetCurveSpeedLimit();
3567
3568 return true;
3569
3570invalid_rail:
3571 /* We've reached end of line?? */
3572 if (prev != nullptr) FatalError("Disconnecting train");
3573
3574reverse_train_direction:
3575 if (reverse) {
3576 v->wait_counter = 0;
3577 v->cur_speed = 0;
3578 v->subspeed = 0;
3580 }
3581
3582 return false;
3583}
3584
3585static bool IsRailStationPlatformOccupied(TileIndex tile)
3586{
3588
3589 for (TileIndex t = tile; IsCompatibleTrainStationTile(t, tile); t -= delta) {
3590 if (HasVehicleOnTile(t, IsTrain)) return true;
3591 }
3592 for (TileIndex t = tile + delta; IsCompatibleTrainStationTile(t, tile); t += delta) {
3593 if (HasVehicleOnTile(t, IsTrain)) return true;
3594 }
3595
3596 return false;
3597}
3598
3606static void DeleteLastWagon(Train *v)
3607{
3608 Train *first = v->First();
3609
3610 /* Go to the last wagon and delete the link pointing there
3611 * new_last is then the one-before-last wagon, and v the last
3612 * one which will physically be removed */
3613 Train *new_last = v;
3614 for (; v->Next() != nullptr; v = v->Next()) new_last = v;
3615 new_last->SetNext(nullptr);
3616
3617 if (first != v) {
3618 /* Recalculate cached train properties */
3620 /* Update the depot window if the first vehicle is in depot -
3621 * if v == first, then it is updated in PreDestructor() */
3622 if (first->track == TRACK_BIT_DEPOT) {
3624 }
3625 v->last_station_visited = first->last_station_visited; // for PreDestructor
3626 }
3627
3628 /* 'v' shouldn't be accessed after it has been deleted */
3629 TrackBits trackbits = v->track;
3630 TileIndex tile = v->tile;
3631 Owner owner = v->owner;
3632
3633 delete v;
3634 v = nullptr; // make sure nobody will try to read 'v' anymore
3635
3636 if (trackbits == TRACK_BIT_WORMHOLE) {
3637 /* Vehicle is inside a wormhole, v->track contains no useful value then. */
3639 }
3640
3641 Track track = TrackBitsToTrack(trackbits);
3642 if (HasReservedTracks(tile, trackbits)) {
3643 UnreserveRailTrack(tile, track);
3644
3645 /* If there are still crashed vehicles on the tile, give the track reservation to them */
3646 TrackBits remaining_trackbits = TRACK_BIT_NONE;
3647 for (const Vehicle *u : VehiclesOnTile(tile)) {
3648 if (u->type != VEH_TRAIN || !u->vehstatus.Test(VehState::Crashed)) continue;
3649 TrackBits train_tbits = Train::From(u)->track;
3650 if (train_tbits == TRACK_BIT_WORMHOLE) {
3651 /* Vehicle is inside a wormhole, u->track contains no useful value then. */
3652 remaining_trackbits |= DiagDirToDiagTrackBits(GetTunnelBridgeDirection(u->tile));
3653 } else if (train_tbits != TRACK_BIT_DEPOT) {
3654 remaining_trackbits |= train_tbits;
3655 }
3656 }
3657
3658 /* It is important that these two are the first in the loop, as reservation cannot deal with every trackbit combination */
3659 assert(TRACK_BEGIN == TRACK_X && TRACK_Y == TRACK_BEGIN + 1);
3660 for (Track t : SetTrackBitIterator(remaining_trackbits)) TryReserveRailTrack(tile, t);
3661 }
3662
3663 /* check if the wagon was on a road/rail-crossing */
3665
3666 if (IsRailStationTile(tile)) {
3667 bool occupied = IsRailStationPlatformOccupied(tile);
3669 SetRailStationPlatformReservation(tile, dir, occupied);
3671 }
3672
3673 /* Update signals */
3674 if (IsTileType(tile, MP_TUNNELBRIDGE) || IsRailDepotTile(tile)) {
3676 } else {
3677 SetSignalsOnBothDir(tile, track, owner);
3678 }
3679}
3680
3686{
3687 static const DirDiff delta[] = {
3689 };
3690
3691 do {
3692 /* We don't need to twist around vehicles if they're not visible */
3693 if (!v->vehstatus.Test(VehState::Hidden)) {
3694 v->direction = ChangeDir(v->direction, delta[GB(Random(), 0, 2)]);
3695 /* Refrain from updating the z position of the vehicle when on
3696 * a bridge, because UpdateInclination() will put the vehicle under
3697 * the bridge in that case */
3698 if (v->track != TRACK_BIT_WORMHOLE) {
3699 v->UpdatePosition();
3700 v->UpdateInclination(false, true);
3701 } else {
3702 v->UpdateViewport(false, true);
3703 }
3704 }
3705 } while ((v = v->Next()) != nullptr);
3706}
3707
3714{
3715 int state = ++v->crash_anim_pos;
3716
3717 if (state == 4 && !v->vehstatus.Test(VehState::Hidden)) {
3719 }
3720
3721 uint32_t r;
3722 if (state <= 200 && Chance16R(1, 7, r)) {
3723 int index = (r * 10 >> 16);
3724
3725 Vehicle *u = v;
3726 do {
3727 if (--index < 0) {
3728 r = Random();
3729
3731 GB(r, 8, 3) + 2,
3732 GB(r, 16, 3) + 2,
3733 GB(r, 0, 3) + 5,
3735 break;
3736 }
3737 } while ((u = u->Next()) != nullptr);
3738 }
3739
3740 if (state <= 240 && !(v->tick_counter & 3)) ChangeTrainDirRandomly(v);
3741
3742 if (state >= 4440 && !(v->tick_counter & 0x1F)) {
3743 bool ret = v->Next() != nullptr;
3744 DeleteLastWagon(v);
3745 return ret;
3746 }
3747
3748 return true;
3749}
3750
3752static const uint16_t _breakdown_speeds[16] = {
3753 225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, 15
3754};
3755
3756
3765static bool TrainApproachingLineEnd(Train *v, bool signal, bool reverse)
3766{
3767 /* Calc position within the current tile */
3768 uint x = v->x_pos & 0xF;
3769 uint y = v->y_pos & 0xF;
3770
3771 /* for diagonal directions, 'x' will be 0..15 -
3772 * for other directions, it will be 1, 3, 5, ..., 15 */
3773 switch (v->direction) {
3774 case DIR_N : x = ~x + ~y + 25; break;
3775 case DIR_NW: x = y; [[fallthrough]];
3776 case DIR_NE: x = ~x + 16; break;
3777 case DIR_E : x = ~x + y + 9; break;
3778 case DIR_SE: x = y; break;
3779 case DIR_S : x = x + y - 7; break;
3780 case DIR_W : x = ~y + x + 9; break;
3781 default: break;
3782 }
3783
3784 /* Do not reverse when approaching red signal. Make sure the vehicle's front
3785 * does not cross the tile boundary when we do reverse, but as the vehicle's
3786 * location is based on their center, use half a vehicle's length as offset.
3787 * Multiply the half-length by two for straight directions to compensate that
3788 * we only get odd x offsets there. */
3789 if (!signal && x + (v->gcache.cached_veh_length + 1) / 2 * (IsDiagonalDirection(v->direction) ? 1 : 2) >= TILE_SIZE) {
3790 /* we are too near the tile end, reverse now */
3791 v->cur_speed = 0;
3792 if (reverse) ReverseTrainDirection(v);
3793 return false;
3794 }
3795
3796 /* slow down */
3798 uint16_t break_speed = _breakdown_speeds[x & 0xF];
3799 if (break_speed < v->cur_speed) v->cur_speed = break_speed;
3800
3801 return true;
3802}
3803
3804
3810static bool TrainCanLeaveTile(const Train *v)
3811{
3812 /* Exit if inside a tunnel/bridge or a depot */
3813 if (v->track == TRACK_BIT_WORMHOLE || v->track == TRACK_BIT_DEPOT) return false;
3814
3815 TileIndex tile = v->tile;
3816
3817 /* entering a tunnel/bridge? */
3818 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
3820 if (DiagDirToDir(dir) == v->direction) return false;
3821 }
3822
3823 /* entering a depot? */
3824 if (IsRailDepotTile(tile)) {
3826 if (DiagDirToDir(dir) == v->direction) return false;
3827 }
3828
3829 return true;
3830}
3831
3832
3841{
3842 assert(v->IsFrontEngine());
3843 assert(!v->vehstatus.Test(VehState::Crashed));
3844
3845 if (!TrainCanLeaveTile(v)) return INVALID_TILE;
3846
3847 DiagDirection dir = VehicleExitDir(v->direction, v->track);
3848 TileIndex tile = v->tile + TileOffsByDiagDir(dir);
3849
3850 /* not a crossing || wrong axis || unusable rail (wrong type or owner) */
3851 if (!IsLevelCrossingTile(tile) || DiagDirToAxis(dir) == GetCrossingRoadAxis(tile) ||
3852 !CheckCompatibleRail(v, tile)) {
3853 return INVALID_TILE;
3854 }
3855
3856 return tile;
3857}
3858
3859
3867static bool TrainCheckIfLineEnds(Train *v, bool reverse)
3868{
3869 /* First, handle broken down train */
3870
3871 int t = v->breakdown_ctr;
3872 if (t > 1) {
3874
3875 uint16_t break_speed = _breakdown_speeds[GB(~t, 4, 4)];
3876 if (break_speed < v->cur_speed) v->cur_speed = break_speed;
3877 } else {
3879 }
3880
3881 if (!TrainCanLeaveTile(v)) return true;
3882
3883 /* Determine the non-diagonal direction in which we will exit this tile */
3884 DiagDirection dir = VehicleExitDir(v->direction, v->track);
3885 /* Calculate next tile */
3886 TileIndex tile = v->tile + TileOffsByDiagDir(dir);
3887
3888 /* Determine the track status on the next tile */
3889 TrackStatus ts = GetTileTrackStatus(tile, TRANSPORT_RAIL, 0, ReverseDiagDir(dir));
3890 TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(dir);
3891
3892 TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
3893 TrackdirBits red_signals = TrackStatusToRedSignals(ts) & reachable_trackdirs;
3894
3895 /* We are sure the train is not entering a depot, it is detected above */
3896
3897 /* mask unreachable track bits if we are forbidden to do 90deg turns */
3898 TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
3900 bits &= ~TrackCrossesTracks(FindFirstTrack(v->track));
3901 }
3902
3903 /* no suitable trackbits at all || unusable rail (wrong type or owner) */
3904 if (bits == TRACK_BIT_NONE || !CheckCompatibleRail(v, tile)) {
3905 return TrainApproachingLineEnd(v, false, reverse);
3906 }
3907
3908 /* approaching red signal */
3909 if ((trackdirbits & red_signals) != 0) return TrainApproachingLineEnd(v, true, reverse);
3910
3911 /* approaching a rail/road crossing? then make it red */
3913
3914 return true;
3915}
3916
3917
3918static bool TrainLocoHandler(Train *v, bool mode)
3919{
3920 /* train has crashed? */
3922 return mode ? true : HandleCrashedTrain(v); // 'this' can be deleted here
3923 }
3924
3925 if (v->force_proceed != TFP_NONE) {
3926 v->flags.Reset(VehicleRailFlag::Stuck);
3928 }
3929
3930 /* train is broken down? */
3931 if (v->HandleBreakdown()) return true;
3932
3933 if (v->flags.Test(VehicleRailFlag::Reversing) && v->cur_speed == 0) {
3935 }
3936
3937 /* exit if train is stopped */
3938 if (v->vehstatus.Test(VehState::Stopped) && v->cur_speed == 0) return true;
3939
3940 bool valid_order = !v->current_order.IsType(OT_NOTHING) && v->current_order.GetType() != OT_CONDITIONAL;
3941 if (ProcessOrders(v) && CheckReverseTrain(v)) {
3942 v->wait_counter = 0;
3943 v->cur_speed = 0;
3944 v->subspeed = 0;
3947 return true;
3948 } else if (v->flags.Test(VehicleRailFlag::LeavingStation)) {
3949 /* Try to reserve a path when leaving the station as we
3950 * might not be marked as wanting a reservation, e.g.
3951 * when an overlength train gets turned around in a station. */
3952 DiagDirection dir = VehicleExitDir(v->direction, v->track);
3954
3956 TryPathReserve(v, true, true);
3957 }
3959 }
3960
3961 v->HandleLoading(mode);
3962
3963 if (v->current_order.IsType(OT_LOADING)) return true;
3964
3965 if (CheckTrainStayInDepot(v)) return true;
3966
3967 if (!mode) v->ShowVisualEffect();
3968
3969 /* We had no order but have an order now, do look ahead. */
3970 if (!valid_order && !v->current_order.IsType(OT_NOTHING)) {
3972 }
3973
3974 /* Handle stuck trains. */
3975 if (!mode && v->flags.Test(VehicleRailFlag::Stuck)) {
3976 ++v->wait_counter;
3977
3978 /* Should we try reversing this tick if still stuck? */
3980
3981 if (!turn_around && v->wait_counter % _settings_game.pf.path_backoff_interval != 0 && v->force_proceed == TFP_NONE) return true;
3982 if (!TryPathReserve(v)) {
3983 /* Still stuck. */
3984 if (turn_around) ReverseTrainDirection(v);
3985
3987 /* Show message to player. */
3990 }
3991 v->wait_counter = 0;
3992 }
3993 /* Exit if force proceed not pressed, else reset stuck flag anyway. */
3994 if (v->force_proceed == TFP_NONE) return true;
3995 v->flags.Reset(VehicleRailFlag::Stuck);
3996 v->wait_counter = 0;
3998 }
3999 }
4000
4001 if (v->current_order.IsType(OT_LEAVESTATION)) {
4002 v->current_order.Free();
4004 return true;
4005 }
4006
4007 int j = v->UpdateSpeed();
4008
4009 /* we need to invalidate the widget if we are stopping from 'Stopping 0 km/h' to 'Stopped' */
4010 if (v->cur_speed == 0 && v->vehstatus.Test(VehState::Stopped)) {
4011 /* If we manually stopped, we're not force-proceeding anymore. */
4012 v->force_proceed = TFP_NONE;
4014 }
4015
4016 int adv_spd = v->GetAdvanceDistance();
4017 if (j < adv_spd) {
4018 /* if the vehicle has speed 0, update the last_speed field. */
4019 if (v->cur_speed == 0) v->SetLastSpeed();
4020 } else {
4022 /* Loop until the train has finished moving. */
4023 for (;;) {
4024 j -= adv_spd;
4025 TrainController(v, nullptr);
4026 /* Don't continue to move if the train crashed. */
4027 if (CheckTrainCollision(v)) break;
4028 /* Determine distance to next map position */
4029 adv_spd = v->GetAdvanceDistance();
4030
4031 /* No more moving this tick */
4032 if (j < adv_spd || v->cur_speed == 0) break;
4033
4034 OrderType order_type = v->current_order.GetType();
4035 /* Do not skip waypoints (incl. 'via' stations) when passing through at full speed. */
4036 if ((order_type == OT_GOTO_WAYPOINT || order_type == OT_GOTO_STATION) &&
4038 IsTileType(v->tile, MP_STATION) &&
4040 ProcessOrders(v);
4041 }
4042 }
4043 v->SetLastSpeed();
4044 }
4045
4046 for (Train *u = v; u != nullptr; u = u->Next()) {
4047 if (u->vehstatus.Test(VehState::Hidden)) continue;
4048
4049 u->UpdateViewport(false, false);
4050 }
4051
4052 if (v->progress == 0) v->progress = j; // Save unused spd for next time, if TrainController didn't set progress
4053
4054 return true;
4055}
4056
4062{
4063 Money cost = 0;
4064 const Train *v = this;
4065
4066 do {
4067 const Engine *e = v->GetEngine();
4068 if (e->u.rail.running_cost_class == INVALID_PRICE) continue;
4069
4070 uint cost_factor = GetVehicleProperty(v, PROP_TRAIN_RUNNING_COST_FACTOR, e->u.rail.running_cost);
4071 if (cost_factor == 0) continue;
4072
4073 /* Halve running cost for multiheaded parts */
4074 if (v->IsMultiheaded()) cost_factor /= 2;
4075
4076 cost += GetPrice(e->u.rail.running_cost_class, cost_factor, e->GetGRF());
4077 } while ((v = v->GetNextVehicle()) != nullptr);
4078
4079 return cost;
4080}
4081
4087{
4088 this->tick_counter++;
4089
4090 if (this->IsFrontEngine()) {
4092
4093 if (!this->vehstatus.Test(VehState::Stopped) || this->cur_speed > 0) this->running_ticks++;
4094
4095 this->current_order_time++;
4096
4097 if (!TrainLocoHandler(this, false)) return false;
4098
4099 return TrainLocoHandler(this, true);
4100 } else if (this->IsFreeWagon() && this->vehstatus.Test(VehState::Crashed)) {
4101 /* Delete flooded standalone wagon chain */
4102 if (++this->crash_anim_pos >= 4400) {
4103 delete this;
4104 return false;
4105 }
4106 }
4107
4108 return true;
4109}
4110
4116{
4117 if (Company::Get(v->owner)->settings.vehicle.servint_trains == 0 || !v->NeedsAutomaticServicing()) return;
4118 if (v->IsChainInDepot()) {
4120 return;
4121 }
4122
4124
4125 FindDepotData tfdd = FindClosestTrainDepot(v, max_penalty);
4126 /* Only go to the depot if it is not too far out of our way. */
4127 if (tfdd.best_length == UINT_MAX || tfdd.best_length > max_penalty) {
4128 if (v->current_order.IsType(OT_GOTO_DEPOT)) {
4129 /* If we were already heading for a depot but it has
4130 * suddenly moved farther away, we continue our normal
4131 * schedule? */
4134 }
4135 return;
4136 }
4137
4138 DepotID depot = GetDepotIndex(tfdd.tile);
4139
4140 if (v->current_order.IsType(OT_GOTO_DEPOT) &&
4141 v->current_order.GetDestination() != depot &&
4142 !Chance16(3, 16)) {
4143 return;
4144 }
4145
4148 v->dest_tile = tfdd.tile;
4150}
4151
4154{
4155 AgeVehicle(this);
4156}
4157
4160{
4161 EconomyAgeVehicle(this);
4162
4163 if ((++this->day_counter & 7) == 0) DecreaseVehicleValue(this);
4164
4165 if (this->IsFrontEngine()) {
4166 CheckVehicleBreakdown(this);
4167
4169
4170 CheckOrders(this);
4171
4172 /* update destination */
4173 if (this->current_order.IsType(OT_GOTO_STATION)) {
4175 if (tile != INVALID_TILE) this->dest_tile = tile;
4176 }
4177
4178 if (this->running_ticks != 0) {
4179 /* running costs */
4181
4182 this->profit_this_year -= cost.GetCost();
4183 this->running_ticks = 0;
4184
4186
4189 }
4190 }
4191}
4192
4198{
4200
4201 if (this->track == TRACK_BIT_DEPOT) {
4202 /* We'll assume the train is facing outwards */
4203 return DiagDirToDiagTrackdir(GetRailDepotDirection(this->tile)); // Train in depot
4204 }
4205
4206 if (this->track == TRACK_BIT_WORMHOLE) {
4207 /* train in tunnel or on bridge, so just use its direction and assume a diagonal track */
4208 return DiagDirToDiagTrackdir(DirToDiagDir(this->direction));
4209 }
4210
4211 return TrackDirectionToTrackdir(FindFirstTrack(this->track), this->direction);
4212}
4213
4214uint16_t Train::GetMaxWeight() const
4215{
4216 uint16_t weight = CargoSpec::Get(this->cargo_type)->WeightOfNUnitsInTrain(this->GetEngine()->DetermineCapacity(this));
4217
4218 /* Vehicle weight is not added for articulated parts. */
4219 if (!this->IsArticulatedPart()) {
4220 weight += GetVehicleProperty(this, PROP_TRAIN_WEIGHT, RailVehInfo(this->engine_type)->weight);
4221 }
4222
4223 /* Powered wagons have extra weight added. */
4224 if (this->flags.Test(VehicleRailFlag::PoweredWagon)) {
4225 weight += RailVehInfo(this->gcache.first_engine)->pow_wag_weight;
4226 }
4227
4228 return weight;
4229}
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).
debug_inline constexpr bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
constexpr T AssignBit(T &x, const uint8_t y, bool value)
Assigns a bit in a variable.
constexpr T SetBit(T &x, const uint8_t y)
Set a bit in a variable.
constexpr uint8_t FindFirstBit(T x)
Search the first set bit in a value.
debug_inline 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 T KillFirstBit(T value)
Clear the first bit in an integer.
constexpr T ClrBit(T &x, const uint8_t y)
Clears a bit in a variable.
const BridgeSpec * GetBridgeSpec(BridgeType i)
Get the specification of a bridge type.
Definition bridge.h:67
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
uint8_t CargoType
Cargo slots to indicate a cargo type within a game.
Definition cargo_type.h:23
bool IsValidCargoType(CargoType cargo)
Test whether cargo type is not INVALID_CARGO.
Definition cargo_type.h:106
static void NewEvent(CompanyID company, ScriptEvent *event)
Queue a new event for an AI.
Definition ai_core.cpp:235
constexpr bool Test(Tvalue_type value) const
Test if the value-th bit is set.
constexpr Timpl & Reset()
Reset all bits.
constexpr Timpl & Flip(Tvalue_type value)
Flip the value-th bit.
constexpr Timpl & Set()
Set all bits.
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?
Enum-as-bit-set wrapper.
static void NewEvent(class ScriptEvent *event)
Queue a new event for a Game Script.
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:118
RailTypes powered_railtypes
bitmask to the OTHER railtypes on which an engine of THIS railtype generates power
Definition rail.h:179
RailTypes compatible_railtypes
bitmask to the OTHER railtypes on which an engine of THIS railtype can physically travel
Definition rail.h:182
uint8_t curve_speed
Multiplier for curve maximum speed advantage.
Definition rail.h:197
uint8_t acceleration_type
Acceleration type of this rail type.
Definition rail.h:217
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 constexpr int DAYS_IN_YEAR
days per year
static Date date
Current date in days (day counter).
uint StoredCount() const
Returns sum of cargo on board the vehicle (ie not only reserved).
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,...
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:53
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.
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.
@ DIRDIFF_90LEFT
Angle of 90 degrees left.
@ DIRDIFF_45LEFT
Angle of 45 degrees left.
@ DIRDIFF_45RIGHT
Angle of 45 degrees right.
@ DIRDIFF_SAME
Both directions faces to the same direction.
@ DIRDIFF_90RIGHT
Angle of 90 degrees right.
Direction
Defines the 8 directions on the map.
@ DIR_SW
Southwest.
@ DIR_NW
Northwest.
@ DIR_N
North.
@ DIR_SE
Southeast.
@ DIR_S
South.
@ DIR_NE
Northeast.
@ DIR_W
West.
@ DIR_E
East.
Axis
Allow incrementing of DiagDirDiff variables.
DiagDirection
Enumeration for diagonal directions.
@ DIAGDIR_END
Used for iterations.
@ DIAGDIR_BEGIN
Used for iterations.
@ INVALID_DIAGDIR
Flag for an invalid DiagDirection.
Money GetPrice(Price index, uint cost_factor, const GRFFile *grf_file, int shift)
Determine a certain price.
Definition economy.cpp:952
@ EXPENSES_TRAIN_RUN
Running costs trains.
@ EXPENSES_NEW_VEHICLES
New vehicles.
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.
@ ExclusivePreview
This vehicle is in the exclusive preview stage, either being used or being offered to a company.
@ RAILVEH_WAGON
simple wagon, not motorized
Definition engine_type.h:34
@ RAILVEH_MULTIHEAD
indicates a combination of two locomotives
Definition engine_type.h:33
Functions related to errors.
@ WL_CRITICAL
Critical errors, the MessageBox is shown in all cases.
Definition error.h:27
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.
Types for recording game performance data.
@ PFE_GL_TRAINS
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.
@ GVF_SUPPRESS_IMPLICIT_ORDERS
Disable insertion and removal of automatic orders until the vehicle completes the real order.
@ GVF_GOINGDOWN_BIT
Vehicle is currently going downhill. (Cached track information for acceleration)
@ GVF_GOINGUP_BIT
Vehicle is currently going uphill. (Cached track information for acceleration)
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, uint 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.
@ Random
Randomise borders.
DiagDirection DiagdirBetweenTiles(TileIndex tile_from, TileIndex tile_to)
Determines the DiagDirection to get from one tile to another.
Definition map_func.h:622
TileIndex TileAddByDiagDir(TileIndex tile, DiagDirection dir)
Adds a DiagDir to a tile.
Definition map_func.h:610
TileIndexDiff TileOffsByAxis(Axis axis)
Convert an Axis to a TileIndexDiff.
Definition map_func.h:554
static debug_inline uint TileY(TileIndex tile)
Get the Y component of a tile.
Definition map_func.h:424
static debug_inline uint TileX(TileIndex tile)
Get the X component of a tile.
Definition map_func.h:414
TileIndexDiff TileOffsByDiagDir(DiagDirection dir)
Convert a DiagDirection to a TileIndexDiff.
Definition map_func.h:569
static debug_inline TileIndex TileVirtXY(uint x, uint y)
Get a tile from the virtual XY-coordinate.
Definition map_func.h:403
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:581
bool _networking
are we in networking mode?
Definition network.cpp:67
Basic functions/variables used all over the place.
ClientID
'Unique' identifier to be given to clients
Base for the NewGRF implementation.
@ 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(uint32_t 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.
std::optional< bool > TestVehicleBuildProbability(Vehicle *v, EngineID engine, BuildProbabilityType type)
Test for vehicle build probablity type.
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.
@ 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.
@ VSE_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(uint32_t grfid, GRFStringID stringid)
Returns the index for this stringid associated with its grfID.
Header of Action 04 "universal holder" structure and functions.
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:30
void AddVehicleAdviceNewsItem(AdviceType advice_type, EncodedString &&headline, VehicleID vehicle)
Adds a vehicle-advice news item.
Definition news_func.h:40
@ ArrivalCompany
First vehicle arrived for company.
@ ArrivalOther
First vehicle arrived for competitor.
@ Accident
An accident or disaster has occurred.
@ TrainStuck
The train got stuck and needs to be unstuck manually.
@ Error
A game paused because a (critical) error.
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
@ OSL_PLATFORM_MIDDLE
Stop at the middle of the platform.
Definition order_type.h:100
@ OSL_PLATFORM_FAR_END
Stop at the far end of the platform.
Definition order_type.h:101
@ OSL_PLATFORM_NEAR_END
Stop at the near end of the platform.
Definition order_type.h:99
@ ODTFB_SERVICE
This depot order is because of the servicing limit.
Definition order_type.h:110
uint8_t VehicleOrderID
The index of an order within its current vehicle (not pool related)
Definition order_type.h:18
@ ODATFB_NEAREST_DEPOT
Send the vehicle to the nearest depot.
Definition order_type.h:120
static const VehicleOrderID INVALID_VEH_ORDER_ID
Invalid vehicle order index (sentinel)
Definition order_type.h:39
@ ONSF_NO_STOP_AT_DESTINATION_STATION
The vehicle will stop at any station it passes except the destination.
Definition order_type.h:90
@ ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS
The vehicle will not stop at any stations it passes except the destination.
Definition order_type.h:89
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
PBSTileInfo FollowTrainReservation(const Train *v, Vehicle **train_on_res)
Follow a train reservation to the last tile.
Definition pbs.cpp:289
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:427
void UnreserveRailTrack(TileIndex tile, Track t)
Lift the reservation of a specific track on a tile.
Definition pbs.cpp:144
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:381
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:155
int TicksToLeaveDepot(const Train *v)
Compute number of ticks when next wagon will leave a depot.
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:328
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:341
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:363
const RailTypeInfo * GetRailTypeInfo(RailType railtype)
Returns a pointer to the Railtype information for a given railtype.
Definition rail.h:300
std::vector< Train * > TrainList
Helper type for lists/vectors of trains.
Definition rail_cmd.cpp:44
bool HasOnewaySignalBlockingTrackdir(Tile tile, Trackdir td)
Is a one-way signal blocking the trackdir? A one-way signal on the trackdir against will block,...
Definition rail_map.h:474
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:425
static debug_inline RailTileType GetRailTileType(Tile t)
Returns the RailTileType (normal with or without signals, waypoint or depot).
Definition rail_map.h:36
TrackBits GetTrackBits(Tile tile)
Gets the track bits of the given tile.
Definition rail_map.h:136
@ RAIL_TILE_SIGNALS
Normal rail tile with signals.
Definition rail_map.h:25
static debug_inline bool IsRailDepotTile(Tile t)
Is this tile rail tile and a rail depot?
Definition rail_map.h:105
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:448
bool HasPbsSignalOnTrackdir(Tile tile, Trackdir td)
Is a pbs signal present along the trackdir?
Definition rail_map.h:462
bool IsOnewaySignal(Tile t, Track track)
One-way signals can't be passed the 'wrong' way.
Definition rail_map.h:318
void SetDepotReservation(Tile t, bool b)
Set the reservation state of the depot.
Definition rail_map.h:269
static debug_inline bool IsPlainRail(Tile t)
Returns whether this is plain rails, with or without signals.
Definition rail_map.h:49
bool HasDepotReservation(Tile t)
Get the reservation state of the depot.
Definition rail_map.h:257
bool HasSignals(Tile t)
Checks if a rail tile has signals.
Definition rail_map.h:72
static debug_inline bool IsPlainRailTile(Tile t)
Checks whether the tile is a rail tile or rail tile with signals.
Definition rail_map.h:60
SignalState GetSignalStateByTrackdir(Tile tile, Trackdir trackdir)
Gets the state of the signal along the given trackdir.
Definition rail_map.h:437
@ RAILTYPE_RAIL
Standard non-electric rails.
Definition rail_type.h:27
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:364
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:309
void SetCrossingBarred(Tile t, bool barred)
Set the bar state of a level crossing.
Definition road_map.h:412
Axis GetCrossingRailAxis(Tile t)
Get the rail axis of a level crossing.
Definition road_map.h:321
bool IsCrossingBarred(Tile t)
Check if the level crossing is barred.
Definition road_map.h:400
void SetCrossingReservation(Tile t, bool b)
Set the reservation state of the rail crossing.
Definition road_map.h:377
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
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:645
void UpdateSignalsInBuffer()
Update signals in buffer Called from 'outside'.
Definition signal.cpp:571
void AddSideToSignalBuffer(TileIndex tile, DiagDirection side, Owner owner)
Add side of tile to signal update buffer.
Definition signal.cpp:619
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:663
SigSegState
State of the signal segment.
Definition signal_func.h:49
@ SIGSEG_PBS
Segment is a PBS segment.
Definition signal_func.h:52
@ SIGSEG_FULL
Occupied by a train.
Definition signal_func.h:51
@ SIGTYPE_PBS
normal pbs signal
Definition signal_type.h:28
@ SIGNAL_STATE_RED
The signal is red.
Definition signal_type.h:43
@ SIGNAL_STATE_GREEN
The signal is green.
Definition signal_type.h:44
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
Functions to cache sprites in memory.
static const PaletteID PALETTE_CRASH
Recolour sprite greying of crashed vehicles.
Definition sprites.h:1611
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:28
Axis GetRailStationAxis(Tile t)
Get the rail direction of a rail station.
@ HVOT_TRAIN
Station has seen a train.
@ Train
Station with train station.
@ VehicleArrives
Trigger platform when train arrives.
@ VehicleArrives
Trigger platform when train arrives.
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:271
EncodedString GetEncodedString(StringID str)
Encode a string with no parameters into an encoded string.
Definition strings.cpp:91
Functions related to OTTD's strings.
uint32_t 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:48
Track follower helper template class (can serve pathfinders and vehicle controllers).
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:137
SoundSettings sound
sound effect settings
GUISettings gui
settings related to the GUI
Structure to return information about the closest depot location, and whether it could be found.
bool line_reverse_mode
reversing at stations or not
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.
uint32_t GetGRFID() const
Retrieve the GRF ID of the NewGRF the engine is tied to.
Definition engine.cpp:157
uint16_t reliability_spd_dec
Speed of reliability decay between services (per day).
Definition engine_base.h:49
const GRFFile * GetGRF() const
Retrieve the NewGRF the engine is tied to.
uint DetermineCapacity(const Vehicle *v, uint16_t *mail_capacity=nullptr) const
Determines capacity of a given vehicle from scratch.
Definition engine.cpp:201
EngineFlags flags
Flags of the engine.
Definition engine_base.h:56
uint8_t original_image_index
Original vehicle image index, thus the image index of the overridden vehicle.
Definition engine_base.h:60
TimerGameCalendar::Date GetLifeLengthInDays() const
Returns the vehicle's (not model's!) life length in days.
Definition engine.cpp:443
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:48
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.
uint traininfo_vehicle_width
Width (in pixels) of a 8/8 train vehicle in depot GUI and vehicle details.
Definition newgrf.h:156
int traininfo_vehicle_pitch
Vertical offset for drawing train images in depot GUI and vehicle details.
Definition newgrf.h:155
bool lost_vehicle_warn
if a vehicle can't find its destination, show a warning
bool show_track_reservation
highlight reserved tracks.
PathfinderSettings pf
settings for all pathfinders
DifficultySettings difficulty
settings related to the difficulty
VehicleSettings vehicle
options for vehicles
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.
uint32_t cached_weight
Total weight of the consist (valid only for the first engine).
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...
uint16_t cached_max_track_speed
Maximum consist speed (in internal units) limited by track type (valid only for the first engine).
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.
GroundVehicleCache gcache
Cache of often calculated values.
void CargoChanged()
Recalculates the cached weight of a vehicle and its parts.
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.
uint Crash(bool flooded) override
Common code executed for crashed ground vehicles.
bool IsFreeWagon() const
Check if the vehicle is a free wagon (got no engine in front of it).
uint DoUpdateSpeed(uint accel, int min_speed, int max_speed)
Update the speed of the vehicle.
int GetAcceleration() const
Calculates the acceleration of the vehicle under its current conditions.
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 debug_inline uint Size()
Get the size of the map.
Definition map_func.h:287
VehicleSpriteSeq sprite_seq
Vehicle appearance.
static void Backup(const Vehicle *v, uint32_t user)
Create an order backup for the given vehicle.
OrderDepotTypeFlags GetDepotOrderType() const
What caused us going to the depot?
Definition order_base.h:140
uint16_t GetMaxSpeed() const
Get the maxmimum speed in km-ish/h a vehicle is allowed to reach on the way to the destination.
Definition order_base.h:197
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:138
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:142
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...
OrderNonStopFlags GetNonStopType() const
At which stations must we stop?
Definition order_base.h:136
void MakeGoToDepot(DestinationID destination, OrderDepotTypeFlags order, OrderNonStopFlags non_stop_type=ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS, OrderDepotActionFlags action=ODATF_SERVICE_ONLY, CargoType cargo=CARGO_NO_REFIT)
Makes this order a Go To Depot order.
Definition order_cmd.cpp:74
TileIndex tile
The base tile of the area.
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
uint8_t path_backoff_interval
ticks between checks for a free path.
uint8_t wait_for_pbs_path
how long to wait for a path reservation.
uint8_t wait_oneway_signal
waitingtime in days before a oneway signal
bool reserve_paths
always reserve paths regardless of signal type.
YAPFSettings yapf
pathfinder settings for the yet another pathfinder
bool reverse_at_signals
whether to reverse at signals at all
bool forbid_90_deg
forbid trains to make 90 deg turns
uint8_t wait_twoway_signal
waitingtime in days before a twoway signal
Coordinates of a point in 2D.
static Titem * Get(auto index)
Returns Titem with given index.
Tindex index
Index of this pool item.
static bool CanAllocateItem(size_t n=1)
Helper functions so we can use PoolItem::Function() instead of _poolitem_pool.Function()
Information about a rail vehicle.
Definition engine_type.h:47
uint16_t power
Power of engine (hp); For multiheaded engines the sum of both engine powers.
Definition engine_type.h:55
uint8_t user_def_data
Property 0x25: "User-defined bit mask" Used only for (very few) NewGRF vehicles.
Definition engine_type.h:67
uint8_t running_cost
Running cost of engine; For multiheaded engines the sum of both running costs.
Definition engine_type.h:57
uint8_t shorten_factor
length on main map for this type is 8 - shorten_factor
Definition engine_type.h:64
uint16_t pow_wag_power
Extra power applied to consist if wagon should be powered.
Definition engine_type.h:61
uint16_t max_speed
Maximum speed (1 unit = 1/1.6 mph = 1 km-ish/h)
Definition engine_type.h:54
uint8_t capacity
Cargo capacity of vehicle; For multiheaded engines the capacity of each single engine.
Definition engine_type.h:60
RailType railtype
Railtype, mangled if elrail is disabled.
Definition engine_type.h:51
uint8_t pow_wag_weight
Extra weight applied to consist if wagon should be powered.
Definition engine_type.h:62
Specification of a rectangle with absolute coordinates of all edges.
int Width() const
Get width of Rect.
int Height() const
Get height of Rect.
Iterable ensemble of each set bit in a value.
bool ambient
Play ambient, industry and town sounds.
bool disaster
Play disaster and accident sounds.
static Station * Get(auto index)
Gets station with given index.
T * Next() const
Get next vehicle in the chain.
static Pool::IterateWrapper< T > Iterate(size_t from=0)
Returns an iterable ensemble of all valid vehicles of type T.
T * Previous() const
Get previous vehicle in the chain.
static T * From(Vehicle *v)
Converts a Vehicle to SpecializedVehicle with type checking.
static T * GetIfValid(auto index)
Returns vehicle if the index is a valid index for this vehicle type.
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 * 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.
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:289
uint16_t cached_max_curve_speed
max consist speed limited by curves
Definition train.h:83
int16_t cached_curve_speed_mod
curve speed modifier of the entire train
Definition train.h:82
bool cached_tilt
train can tilt; feature provides a bonus in curves
Definition train.h:79
'Train' is either a loco or a wagon.
Definition train.h:91
void PlayLeaveStationSound(bool force=false) const override
Play a sound for a train 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:150
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.
uint16_t crash_anim_pos
Crash animation counter.
Definition train.h:93
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.
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...
void UpdateDeltaXY() override
Updates the x and y offsets and the size of the sprite used for this vehicle.
int CalcNextVehicleOffset() const
Calculate the offset from this vehicle's center to the following center taking the vehicle lengths in...
Definition train.h:174
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:118
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! Update its status and other parts around it.
AccelStatus GetAccelerationStatus() const
Checks the current acceleration status of this vehicle.
Definition train.h:275
void OnNewEconomyDay() override
Economy day handler.
void ConsistChanged(ConsistChangeFlags allowed_changes)
Recalculates the cached stuff of a train.
Money GetRunningCost() const override
Get running cost for the train consist.
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:94
int GetCurrentMaxSpeed() const override
Calculates the maximum speed of the vehicle under its current conditions.
uint16_t cached_max_speed
Maximum speed of the consist (minimum of the max speed of all vehicles in the consist).
UnitID max_trains
max trains in game per company
uint8_t train_acceleration_model
realistic acceleration for trains
bool wagon_speed_limits
enable wagon speed limits
uint8_t freight_trains
value to multiply the weight of cargo by
uint8_t max_train_length
maximum length for trains
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:114
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:142
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:718
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.
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:2316
void AddToShared(Vehicle *shared_chain)
Adds this vehicle to a shared vehicle chain.
Definition vehicle.cpp:2929
VehicleCargoList cargo
The cargo this vehicle is carrying.
uint8_t x_extent
x-extent of vehicle bounding box
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.
uint16_t random_bits
Bits used for randomized variational spritegroups.
void ReleaseUnitNumber()
Release the vehicle's unit number.
Definition vehicle.cpp:2385
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:2396
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.
uint8_t z_extent
z-extent of vehicle bounding box
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:2475
int8_t y_offs
y offset for vehicle sprite
CargoType cargo_type
type of cargo this vehicle is carrying
debug_inline bool IsFrontEngine() const
Check if the vehicle is a front engine.
uint8_t acceleration
used by train & aircraft
int8_t x_bb_offs
x offset of vehicle bounding box
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:762
Vehicle * Next() const
Get the next vehicle of this vehicle.
int8_t x_offs
x offset for vehicle sprite
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:728
OrderList * orders
Pointer to the order list for this vehicle.
uint8_t y_extent
y-extent of vehicle bounding box
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.
uint32_t GetGRFID() const
Retrieve the GRF ID of the NewGRF the vehicle is tied to.
Definition vehicle.cpp:738
int8_t y_bb_offs
y offset of vehicle bounding box
void BeginLoading()
Prepare everything to begin the loading when arriving at a station.
Definition vehicle.cpp:2172
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 IsWaitingForUnbunching() const
Check whether a vehicle inside a depot is waiting for unbunching.
Definition vehicle.cpp:2522
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:2900
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:1333
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:1663
StationID last_station_visited
The last station we stopped at.
void ShowVisualEffect() const
Draw visual effects (smoke and/or sparks) for a vehicle chain.
Definition vehicle.cpp:2750
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:283
uint8_t running_ticks
Number of ticks this vehicle was not stopped this day.
uint32_t maximum_go_to_depot_penalty
What is the maximum penalty that may be endured for going to a depot.
@ EnteredStation
The vehicle entered a station.
@ CannotEnter
The vehicle cannot enter the tile.
@ EnteredWormhole
The vehicle either entered a bridge, tunnel or depot tile (this includes the last tile of the bridge/...
VehicleEnterTileStates VehicleEnterTile(Vehicle *v, TileIndex tile, int x, int y)
Call the tile callback function for a vehicle entering a tile.
Definition vehicle.cpp:1808
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
static debug_inline bool IsTileType(Tile tile, TileType type)
Checks if a tile is a given tiletype.
Definition tile_map.h:150
static const uint TILE_SIZE
Tile size in world coordinates.
Definition tile_type.h:15
constexpr TileIndex INVALID_TILE
The very nice invalid tile marker.
Definition tile_type.h:95
@ MP_STATION
A tile of a station.
Definition tile_type.h:53
@ MP_TUNNELBRIDGE
Tunnel entry/exit and bridge heads.
Definition tile_type.h:57
@ MP_RAILWAY
A railway.
Definition tile_type.h:49
Definition of the game-calendar-timer.
Definition of the game-economy-timer.
Trackdir RemoveFirstTrackdir(TrackdirBits *trackdirs)
Removes first Trackdir from TrackdirBits and returns it.
Definition track_func.h:156
Track TrackdirToTrack(Trackdir trackdir)
Returns the Track that a given Trackdir represents.
Definition track_func.h:262
TrackBits TrackToTrackBits(Track track)
Maps a Track to the corresponding TrackBits value.
Definition track_func.h:77
TrackdirBits TrackBitsToTrackdirBits(TrackBits bits)
Converts TrackBits to TrackdirBits while allowing both directions.
Definition track_func.h:319
DiagDirection VehicleExitDir(Direction direction, TrackBits track)
Determine the side in which the vehicle will leave the tile.
Definition track_func.h:714
TrackdirBits TrackStatusToTrackdirBits(TrackStatus ts)
Returns the present-trackdir-information of a TrackStatus.
Definition track_func.h:352
Track TrackBitsToTrack(TrackBits tracks)
Converts TrackBits to Track.
Definition track_func.h:193
Trackdir ReverseTrackdir(Trackdir trackdir)
Maps a trackdir to the reverse trackdir.
Definition track_func.h:247
bool TracksOverlap(TrackBits bits)
Checks if the given tracks overlap, ie form a crossing.
Definition track_func.h:645
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:498
bool IsValidTrackdir(Trackdir trackdir)
Checks if a Trackdir is valid for non-road vehicles.
Definition track_func.h:52
Trackdir FindFirstTrackdir(TrackdirBits trackdirs)
Returns first Trackdir from TrackdirBits or INVALID_TRACKDIR.
Definition track_func.h:211
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:584
TrackdirBits DiagdirReachesTrackdirs(DiagDirection diagdir)
Returns all trackdirs that can be reached when entering a tile from a given (diagonal) direction.
Definition track_func.h:555
Track FindFirstTrack(TrackBits tracks)
Returns first Track from TrackBits or INVALID_TRACK.
Definition track_func.h:177
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:486
TrackBits DiagdirReachesTracks(DiagDirection diagdir)
Returns all tracks that can be reached when entering a tile from a given (diagonal) direction.
Definition track_func.h:573
TrackBits DiagDirToDiagTrackBits(DiagDirection diagdir)
Maps a (4-way) direction to the diagonal track bits incidating with that diagdir.
Definition track_func.h:524
Trackdir DiagDirToDiagTrackdir(DiagDirection diagdir)
Maps a (4-way) direction to the diagonal trackdir that runs in that direction.
Definition track_func.h:537
TrackdirBits TrackStatusToRedSignals(TrackStatus ts)
Returns the red-signal-information of a TrackStatus.
Definition track_func.h:376
DiagDirection TrackdirToExitdir(Trackdir trackdir)
Maps a trackdir to the (4-way) direction the tile is exited when following that trackdir.
Definition track_func.h:439
Track DiagDirToDiagTrack(DiagDirection diagdir)
Maps a (4-way) direction to the diagonal track incidating with that diagdir.
Definition track_func.h:512
TrackBits TrackdirBitsToTrackBits(TrackdirBits bits)
Discards all directional information from a TrackdirBits value.
Definition track_func.h:308
TrackBits
Allow incrementing of Track variables.
Definition track_type.h:35
@ TRACK_BIT_WORMHOLE
Bitflag for a wormhole (used for tunnels)
Definition track_type.h:52
@ TRACK_BIT_UPPER
Upper track.
Definition track_type.h:39
@ TRACK_BIT_DEPOT
Bitflag for a depot.
Definition track_type.h:53
@ TRACK_BIT_LEFT
Left track.
Definition track_type.h:41
@ TRACK_BIT_Y
Y-axis track.
Definition track_type.h:38
@ TRACK_BIT_NONE
No track.
Definition track_type.h:36
@ TRACK_BIT_X
X-axis track.
Definition track_type.h:37
@ TRACK_BIT_MASK
Bitmask for the first 6 bits.
Definition track_type.h:51
@ TRACK_BIT_LOWER
Lower track.
Definition track_type.h:40
@ TRACK_BIT_RIGHT
Right track.
Definition track_type.h:42
Trackdir
Enumeration for tracks and directions.
Definition track_type.h:66
@ INVALID_TRACKDIR
Flag for an invalid trackdir.
Definition track_type.h:85
TrackdirBits
Allow incrementing of Trackdir variables.
Definition track_type.h:97
@ TRACKDIR_BIT_NONE
No track build.
Definition track_type.h:98
Track
These are used to specify a single track.
Definition track_type.h:19
@ INVALID_TRACK
Flag for an invalid track.
Definition track_type.h:28
@ TRACK_Y
Track along the y-axis (north-west to south-east)
Definition track_type.h:22
@ TRACK_BEGIN
Used for iterations.
Definition track_type.h:20
@ TRACK_X
Track along the x-axis (north-east to south-west)
Definition track_type.h:21
@ Capacity
Allow vehicles to change capacity.
@ Length
Allow vehicles to change length.
static constexpr ConsistChangeFlags CCF_TRACK
Valid changes while vehicle is driving, and possibly changing tracks.
Definition train.h:52
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
@ AllowedOnNormalRail
Electric train engine is allowed to run on normal rail. *‍/.
Definition train.h:30
@ Stuck
Train can't get a path reservation.
Definition train.h:32
@ Flipped
Reverse the visible direction of the vehicle.
Definition train.h:28
@ PoweredWagon
Wagon is powered.
Definition train.h:27
@ LeavingStation
Train is just leaving a station.
Definition train.h:33
@ Reversing
Train is slowing down to reverse.
Definition train.h:26
int GetTrainStopLocation(StationID station_id, TileIndex tile, const Train *v, 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.
@ TFP_SIGNAL
Ignore next signal, after the signal ignore being stuck.
Definition train.h:41
@ TFP_NONE
Normal operation.
Definition train.h:39
@ TFP_STUCK
Proceed till next signal, but ignore being stuck till then. This includes force leaving depots.
Definition train.h:40
static constexpr ConsistChangeFlags CCF_ARRANGE
Valid changes for arranging the consist in a depot.
Definition train.h:56
static void AffectSpeedByZChange(Train *v, int old_z)
Modify the speed of the vehicle due to a change in altitude.
static CommandCost CmdBuildRailWagon(DoCommandFlags flags, TileIndex tile, const Engine *e, Vehicle **ret)
Build a railroad wagon.
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).
static uint CheckTrainCollision(Vehicle *v, Train *t)
Collision test function.
static void MakeTrainBackup(TrainList &list, Train *t)
Make a backup of a train into a train list.
static void CheckNextTrainTile(Train *v)
Check if the train is on the last reserved tile and try to extend the path then.
static void ArrangeTrains(Train **dst_head, Train *dst, Train **src_head, Train *src, bool move_chain)
Arrange the trains in the wanted way.
bool TryPathReserve(Train *v, bool mark_as_stuck, bool first_tile_okay)
Try to reserve a path to a safe position.
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 bool TrainApproachingLineEnd(Train *v, bool signal, bool reverse)
Train is approaching line end, slow down and possibly reverse.
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 void SwapTrainFlags(uint16_t *swap_flag1, uint16_t *swap_flag2)
Swap the two up/down flags in two ways:
static void UpdateLevelCrossingTile(TileIndex tile, bool sound, bool force_barred)
Sets a level crossing tile to the correct state.
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.
static void AdvanceWagonsBeforeSwap(Train *v)
Advances wagons for train reversing, needed for variable length wagons.
CommandCost CmdBuildRailVehicle(DoCommandFlags flags, TileIndex tile, const Engine *e, Vehicle **ret)
Build a railroad vehicle.
static void AdvanceWagonsAfterSwap(Train *v)
Advances wagons for train reversing, needed for variable length wagons.
uint8_t FreightWagonMult(CargoType cargo)
Return the cargo weight multiplier to use for a rail vehicle.
Definition train_cmd.cpp:69
static bool TrainCheckIfLineEnds(Train *v, bool reverse=true)
Checks for line end.
void ReverseTrainDirection(Train *v)
Turn a train around.
void FreeTrainTrackReservation(const Train *v)
Free the reserved path in front of a vehicle.
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.
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 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 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:76
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.
static TileIndex TrainApproachingCrossingTile(const Train *v)
Determines whether train is approaching a rail-road crossing (thus making it barred)
static void RemoveFromConsist(Train *part, bool chain=false)
Remove the given wagon from its consist.
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 TrainCanLeaveTile(const Train *v)
Determines whether train would like to leave the tile.
int GetTrainStopLocation(StationID station_id, TileIndex tile, const Train *v, 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 void TrainEnterStation(Train *v, StationID station)
Trains enters a station, send out a news item if it is the first train, and start loading.
static void MarkTrainAsStuck(Train *v)
Mark a train as stuck and stop it if it isn't stopped right now.
static bool TrainApproachingCrossing(TileIndex tile)
Finds a vehicle approaching rail-road crossing.
void ReverseTrainSwapVeh(Train *v, int l, int r)
Swap vehicles l and r in consist v, and reverse their direction.
static PBSTileInfo ExtendTrainReservation(const Train *v, TrackBits *new_tracks, DiagDirection *enterdir)
Extend a train path as far as possible.
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.
std::vector< Train * > TrainList
Helper type for lists/vectors of trains.
static bool TrainApproachingCrossingEnum(const Vehicle *v, TileIndex tile)
Checks if a train is approaching a rail-road crossing.
static void UpdateStatusAfterSwap(Train *v)
Updates some variables after swapping the vehicle.
Command definitions related to trains.
Sprites to use for trains.
@ TRANSPORT_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.
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:328
void VehicleEnterDepot(Vehicle *v)
Vehicle entirely entered the depot, update its status, orders, vehicle windows, service it,...
Definition vehicle.cpp:1521
UnitID GetFreeUnitNumber(VehicleType type)
Get an unused unit number for a vehicle (if allowed).
Definition vehicle.cpp:1865
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:354
void VehicleServiceInDepot(Vehicle *v)
Service a vehicle and all subsequent vehicles in the consist.
Definition vehicle.cpp:178
GetNewVehiclePosResult GetNewVehiclePos(const Vehicle *v)
Get position information of a vehicle when moving one pixel in the direction it is facing.
Definition vehicle.cpp:1754
void DecreaseVehicleValue(Vehicle *v)
Decrease the value of a vehicle.
Definition vehicle.cpp:1271
void EconomyAgeVehicle(Vehicle *v)
Update economy age of a vehicle.
Definition vehicle.cpp:1399
CommandCost TunnelBridgeIsFree(TileIndex tile, TileIndex endtile, const Vehicle *ignore)
Finds vehicle in tunnel / bridge.
Definition vehicle.cpp:551
void AgeVehicle(Vehicle *v)
Update age of a vehicle.
Definition vehicle.cpp:1411
@ VE_DISABLE_WAGON_POWER
Flag to disable wagon power.
@ 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.
@ 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.
@ VIWD_CONSIST_CHANGED
Vehicle composition was changed.
Definition vehicle_gui.h:37
EngineImageType
Visualisation contexts of vehicles and engines.
@ VEH_TRAIN
Train vehicle type.
static const uint VEHICLE_LENGTH
The length of a vehicle in tile units.
@ 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:1182
void SetWindowClassesDirty(WindowClass cls)
Mark all windows of a particular class as dirty (in need of repainting)
Definition window.cpp:3173
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:3265
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:3160
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
Definition window.cpp:3147
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:3282
@ WC_VEHICLE_ORDERS
Vehicle orders; Window numbers:
@ WC_VEHICLE_DEPOT
Depot view; Window numbers:
@ WC_TRAINS_LIST
Trains list; Window numbers:
@ WC_VEHICLE_REFIT
Vehicle refit; Window numbers:
@ WC_VEHICLE_DETAILS
Vehicle details; Window numbers:
@ WC_COMPANY
Company view; Window numbers:
@ WC_VEHICLE_VIEW
Vehicle view; Window numbers:
@ WC_VEHICLE_TIMETABLE
Vehicle timetable; Window numbers:
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.
Base includes/functions for 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