Changeset - r14217:40beee5d2e82
[Not reviewed]
master
0 1 0
michi_cc - 15 years ago 2010-01-11 00:02:14
michi_cc@openttd.org
(svn r18778) -Fix [FS#3483]: [YAPP] Remove a special check for two-sided signals when reserving a path as this causes trains to get stuck in front of them.
1 file changed with 0 insertions and 14 deletions:
0 comments (0 inline, 0 general)
src/train_cmd.cpp
Show inline comments
 
@@ -2086,1550 +2086,1536 @@ CommandCost CmdRefitRailVehicle(TileInde
 
	}
 

	
 
	return cost;
 
}
 

	
 
/** returns the tile of a depot to goto to. The given vehicle must not be
 
 * crashed! */
 
static FindDepotData FindClosestTrainDepot(Train *v, int max_distance)
 
{
 
	assert(!(v->vehstatus & VS_CRASHED));
 

	
 
	if (IsRailDepotTile(v->tile)) return FindDepotData(v->tile, 0);
 

	
 
	PBSTileInfo origin = FollowTrainReservation(v);
 
	if (IsRailDepotTile(origin.tile)) return FindDepotData(origin.tile, 0);
 

	
 
	switch (_settings_game.pf.pathfinder_for_trains) {
 
		case VPF_NPF: return NPFTrainFindNearestDepot(v, max_distance);
 
		case VPF_YAPF: return YapfTrainFindNearestDepot(v, max_distance);
 

	
 
		default: NOT_REACHED();
 
	}
 
}
 

	
 
bool Train::FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
 
{
 
	FindDepotData tfdd = FindClosestTrainDepot(this, 0);
 
	if (tfdd.best_length == UINT_MAX) return false;
 

	
 
	if (location    != NULL) *location    = tfdd.tile;
 
	if (destination != NULL) *destination = GetDepotIndex(tfdd.tile);
 
	if (reverse     != NULL) *reverse     = tfdd.reverse;
 

	
 
	return true;
 
}
 

	
 
/** Send a train to a depot
 
 * @param tile unused
 
 * @param flags type of operation
 
 * @param p1 train to send to the depot
 
 * @param p2 various bitmasked elements
 
 * - p2 bit 0-3 - DEPOT_ flags (see vehicle.h)
 
 * - p2 bit 8-10 - VLW flag (for mass goto depot)
 
 * @param text unused
 
 * @return the cost of this operation or an error
 
 */
 
CommandCost CmdSendTrainToDepot(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
 
{
 
	if (p2 & DEPOT_MASS_SEND) {
 
		/* Mass goto depot requested */
 
		if (!ValidVLWFlags(p2 & VLW_MASK)) return CMD_ERROR;
 
		return SendAllVehiclesToDepot(VEH_TRAIN, flags, p2 & DEPOT_SERVICE, _current_company, (p2 & VLW_MASK), p1);
 
	}
 

	
 
	Train *v = Train::GetIfValid(p1);
 
	if (v == NULL) return CMD_ERROR;
 

	
 
	return v->SendToDepot(flags, (DepotCommand)(p2 & DEPOT_COMMAND_MASK));
 
}
 

	
 
static const int8 _vehicle_smoke_pos[8] = {
 
	1, 1, 1, 0, -1, -1, -1, 0
 
};
 

	
 
static void HandleLocomotiveSmokeCloud(const Train *v)
 
{
 
	bool sound = false;
 

	
 
	if ((v->vehstatus & VS_TRAIN_SLOWING) || v->cur_speed < 2) {
 
		return;
 
	}
 

	
 
	const Train *u = v;
 

	
 
	do {
 
		const RailVehicleInfo *rvi = RailVehInfo(v->engine_type);
 
		int effect_offset = GB(v->tcache.cached_vis_effect, 0, 4) - 8;
 
		byte effect_type = GB(v->tcache.cached_vis_effect, 4, 2);
 
		bool disable_effect = HasBit(v->tcache.cached_vis_effect, 6);
 

	
 
		/* no smoke? */
 
		if ((rvi->railveh_type == RAILVEH_WAGON && effect_type == 0) ||
 
				disable_effect ||
 
				v->vehstatus & VS_HIDDEN) {
 
			continue;
 
		}
 

	
 
		/* No smoke in depots or tunnels */
 
		if (IsRailDepotTile(v->tile) || IsTunnelTile(v->tile)) continue;
 

	
 
		/* No sparks for electric vehicles on nonelectrified tracks */
 
		if (!HasPowerOnRail(v->railtype, GetTileRailType(v->tile))) continue;
 

	
 
		if (effect_type == 0) {
 
			/* Use default effect type for engine class. */
 
			effect_type = rvi->engclass;
 
		} else {
 
			effect_type--;
 
		}
 

	
 
		int x = _vehicle_smoke_pos[v->direction] * effect_offset;
 
		int y = _vehicle_smoke_pos[(v->direction + 2) % 8] * effect_offset;
 

	
 
		if (HasBit(v->flags, VRF_REVERSE_DIRECTION)) {
 
			x = -x;
 
			y = -y;
 
		}
 

	
 
		switch (effect_type) {
 
			case 0:
 
				/* steam smoke. */
 
				if (GB(v->tick_counter, 0, 4) == 0) {
 
					CreateEffectVehicleRel(v, x, y, 10, EV_STEAM_SMOKE);
 
					sound = true;
 
				}
 
				break;
 

	
 
			case 1:
 
				/* diesel smoke */
 
				if (u->cur_speed <= 40 && Chance16(15, 128)) {
 
					CreateEffectVehicleRel(v, 0, 0, 10, EV_DIESEL_SMOKE);
 
					sound = true;
 
				}
 
				break;
 

	
 
			case 2:
 
				/* blue spark */
 
				if (GB(v->tick_counter, 0, 2) == 0 && Chance16(1, 45)) {
 
					CreateEffectVehicleRel(v, 0, 0, 10, EV_ELECTRIC_SPARK);
 
					sound = true;
 
				}
 
				break;
 

	
 
			default:
 
				break;
 
		}
 
	} while ((v = v->Next()) != NULL);
 

	
 
	if (sound) PlayVehicleSound(u, VSE_TRAIN_EFFECT);
 
}
 

	
 
void Train::PlayLeaveStationSound() const
 
{
 
	static const SoundFx sfx[] = {
 
		SND_04_TRAIN,
 
		SND_0A_TRAIN_HORN,
 
		SND_0A_TRAIN_HORN,
 
		SND_47_MAGLEV_2,
 
		SND_41_MAGLEV
 
	};
 

	
 
	if (PlayVehicleSound(this, VSE_START)) return;
 

	
 
	EngineID engtype = this->engine_type;
 
	SndPlayVehicleFx(sfx[RailVehInfo(engtype)->engclass], this);
 
}
 

	
 
/** Check if the train is on the last reserved tile and try to extend the path then. */
 
static void CheckNextTrainTile(Train *v)
 
{
 
	/* Don't do any look-ahead if path_backoff_interval is 255. */
 
	if (_settings_game.pf.path_backoff_interval == 255) return;
 

	
 
	/* Exit if we reached our destination depot or are inside a depot. */
 
	if ((v->tile == v->dest_tile && v->current_order.IsType(OT_GOTO_DEPOT)) || v->track == TRACK_BIT_DEPOT) return;
 
	/* Exit if we are on a station tile and are going to stop. */
 
	if (IsRailStationTile(v->tile) && v->current_order.ShouldStopAtStation(v, GetStationIndex(v->tile))) return;
 
	/* Exit if the current order doesn't have a destination, but the train has orders. */
 
	if ((v->current_order.IsType(OT_NOTHING) || v->current_order.IsType(OT_LEAVESTATION) || v->current_order.IsType(OT_LOADING)) && v->GetNumOrders() > 0) return;
 

	
 
	Trackdir td = v->GetVehicleTrackdir();
 

	
 
	/* On a tile with a red non-pbs signal, don't look ahead. */
 
	if (IsTileType(v->tile, MP_RAILWAY) && HasSignalOnTrackdir(v->tile, td) &&
 
			!IsPbsSignal(GetSignalType(v->tile, TrackdirToTrack(td))) &&
 
			GetSignalStateByTrackdir(v->tile, td) == SIGNAL_STATE_RED) return;
 

	
 
	CFollowTrackRail ft(v);
 
	if (!ft.Follow(v->tile, td)) return;
 

	
 
	if (!HasReservedTracks(ft.m_new_tile, TrackdirBitsToTrackBits(ft.m_new_td_bits))) {
 
		/* Next tile is not reserved. */
 
		if (KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE) {
 
			if (HasPbsSignalOnTrackdir(ft.m_new_tile, FindFirstTrackdir(ft.m_new_td_bits))) {
 
				/* If the next tile is a PBS signal, try to make a reservation. */
 
				TrackBits tracks = TrackdirBitsToTrackBits(ft.m_new_td_bits);
 
				if (_settings_game.pf.forbid_90_deg) {
 
					tracks &= ~TrackCrossesTracks(TrackdirToTrack(ft.m_old_td));
 
				}
 
				ChooseTrainTrack(v, ft.m_new_tile, ft.m_exitdir, tracks, false, NULL, false);
 
			}
 
		}
 
	}
 
}
 

	
 
static bool CheckTrainStayInDepot(Train *v)
 
{
 
	/* bail out if not all wagons are in the same depot or not in a depot at all */
 
	for (const Train *u = v; u != NULL; u = u->Next()) {
 
		if (u->track != TRACK_BIT_DEPOT || u->tile != v->tile) return false;
 
	}
 

	
 
	/* if the train got no power, then keep it in the depot */
 
	if (v->tcache.cached_power == 0) {
 
		v->vehstatus |= VS_STOPPED;
 
		SetWindowDirty(WC_VEHICLE_DEPOT, v->tile);
 
		return true;
 
	}
 

	
 
	SigSegState seg_state;
 

	
 
	if (v->force_proceed == 0) {
 
		/* force proceed was not pressed */
 
		if (++v->wait_counter < 37) {
 
			SetWindowClassesDirty(WC_TRAINS_LIST);
 
			return true;
 
		}
 

	
 
		v->wait_counter = 0;
 

	
 
		seg_state = _settings_game.pf.reserve_paths ? SIGSEG_PBS : UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
 
		if (seg_state == SIGSEG_FULL || HasDepotReservation(v->tile)) {
 
			/* Full and no PBS signal in block or depot reserved, can't exit. */
 
			SetWindowClassesDirty(WC_TRAINS_LIST);
 
			return true;
 
		}
 
	} else {
 
		seg_state = _settings_game.pf.reserve_paths ? SIGSEG_PBS : UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
 
	}
 

	
 
	/* We are leaving a depot, but have to go to the exact same one; re-enter */
 
	if (v->current_order.IsType(OT_GOTO_DEPOT) && v->tile == v->dest_tile) {
 
		/* We need to have a reservation for this to work. */
 
		if (HasDepotReservation(v->tile)) return true;
 
		SetDepotReservation(v->tile, true);
 
		VehicleEnterDepot(v);
 
		return true;
 
	}
 

	
 
	/* Only leave when we can reserve a path to our destination. */
 
	if (seg_state == SIGSEG_PBS && !TryPathReserve(v) && v->force_proceed == 0) {
 
		/* No path and no force proceed. */
 
		SetWindowClassesDirty(WC_TRAINS_LIST);
 
		MarkTrainAsStuck(v);
 
		return true;
 
	}
 

	
 
	SetDepotReservation(v->tile, true);
 
	if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(v->tile);
 

	
 
	VehicleServiceInDepot(v);
 
	SetWindowClassesDirty(WC_TRAINS_LIST);
 
	v->PlayLeaveStationSound();
 

	
 
	v->track = TRACK_BIT_X;
 
	if (v->direction & 2) v->track = TRACK_BIT_Y;
 

	
 
	v->vehstatus &= ~VS_HIDDEN;
 
	v->cur_speed = 0;
 

	
 
	v->UpdateDeltaXY(v->direction);
 
	v->cur_image = v->GetImage(v->direction);
 
	VehicleMove(v, false);
 
	UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
 
	UpdateTrainAcceleration(v);
 
	InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
 

	
 
	return false;
 
}
 

	
 
/** Clear the reservation of a tile that was just left by a wagon on track_dir. */
 
static void ClearPathReservation(const Train *v, TileIndex tile, Trackdir track_dir)
 
{
 
	DiagDirection dir = TrackdirToExitdir(track_dir);
 

	
 
	if (IsTileType(tile, MP_TUNNELBRIDGE)) {
 
		/* Are we just leaving a tunnel/bridge? */
 
		if (GetTunnelBridgeDirection(tile) == ReverseDiagDir(dir)) {
 
			TileIndex end = GetOtherTunnelBridgeEnd(tile);
 

	
 
			if (!HasVehicleOnTunnelBridge(tile, end, v)) {
 
				/* Free the reservation only if no other train is on the tiles. */
 
				SetTunnelBridgeReservation(tile, false);
 
				SetTunnelBridgeReservation(end, false);
 

	
 
				if (_settings_client.gui.show_track_reservation) {
 
					MarkTileDirtyByTile(tile);
 
					MarkTileDirtyByTile(end);
 
				}
 
			}
 
		}
 
	} else if (IsRailStationTile(tile)) {
 
		TileIndex new_tile = TileAddByDiagDir(tile, dir);
 
		/* If the new tile is not a further tile of the same station, we
 
		 * clear the reservation for the whole platform. */
 
		if (!IsCompatibleTrainStationTile(new_tile, tile)) {
 
			SetRailStationPlatformReservation(tile, ReverseDiagDir(dir), false);
 
		}
 
	} else {
 
		/* Any other tile */
 
		UnreserveRailTrack(tile, TrackdirToTrack(track_dir));
 
	}
 
}
 

	
 
/** Free the reserved path in front of a vehicle. */
 
void FreeTrainTrackReservation(const Train *v, TileIndex origin, Trackdir orig_td)
 
{
 
	assert(v->IsFrontEngine());
 

	
 
	TileIndex tile = origin != INVALID_TILE ? origin : v->tile;
 
	Trackdir  td = orig_td != INVALID_TRACKDIR ? orig_td : v->GetVehicleTrackdir();
 
	bool      free_tile = tile != v->tile || !(IsRailStationTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE));
 
	StationID station_id = IsRailStationTile(v->tile) ? GetStationIndex(v->tile) : INVALID_STATION;
 

	
 
	/* Don't free reservation if it's not ours. */
 
	if (TracksOverlap(GetReservedTrackbits(tile) | TrackToTrackBits(TrackdirToTrack(td)))) return;
 

	
 
	CFollowTrackRail ft(v, GetRailTypeInfo(v->railtype)->compatible_railtypes);
 
	while (ft.Follow(tile, td)) {
 
		tile = ft.m_new_tile;
 
		TrackdirBits bits = ft.m_new_td_bits & TrackBitsToTrackdirBits(GetReservedTrackbits(tile));
 
		td = RemoveFirstTrackdir(&bits);
 
		assert(bits == TRACKDIR_BIT_NONE);
 

	
 
		if (!IsValidTrackdir(td)) break;
 

	
 
		if (IsTileType(tile, MP_RAILWAY)) {
 
			if (HasSignalOnTrackdir(tile, td) && !IsPbsSignal(GetSignalType(tile, TrackdirToTrack(td)))) {
 
				/* Conventional signal along trackdir: remove reservation and stop. */
 
				UnreserveRailTrack(tile, TrackdirToTrack(td));
 
				break;
 
			}
 
			if (HasPbsSignalOnTrackdir(tile, td)) {
 
				if (GetSignalStateByTrackdir(tile, td) == SIGNAL_STATE_RED) {
 
					/* Red PBS signal? Can't be our reservation, would be green then. */
 
					break;
 
				} else {
 
					/* Turn the signal back to red. */
 
					SetSignalStateByTrackdir(tile, td, SIGNAL_STATE_RED);
 
					MarkTileDirtyByTile(tile);
 
				}
 
			} else if (HasSignalOnTrackdir(tile, ReverseTrackdir(td)) && IsOnewaySignal(tile, TrackdirToTrack(td))) {
 
				break;
 
			}
 
		}
 

	
 
		/* Don't free first station/bridge/tunnel if we are on it. */
 
		if (free_tile || (!(ft.m_is_station && GetStationIndex(ft.m_new_tile) == station_id) && !ft.m_is_tunnel && !ft.m_is_bridge)) ClearPathReservation(v, tile, td);
 

	
 
		free_tile = true;
 
	}
 
}
 

	
 
static const byte _initial_tile_subcoord[6][4][3] = {
 
{{ 15, 8, 1 }, { 0, 0, 0 }, { 0, 8, 5 }, { 0,  0, 0 }},
 
{{  0, 0, 0 }, { 8, 0, 3 }, { 0, 0, 0 }, { 8, 15, 7 }},
 
{{  0, 0, 0 }, { 7, 0, 2 }, { 0, 7, 6 }, { 0,  0, 0 }},
 
{{ 15, 8, 2 }, { 0, 0, 0 }, { 0, 0, 0 }, { 8, 15, 6 }},
 
{{ 15, 7, 0 }, { 8, 0, 4 }, { 0, 0, 0 }, { 0,  0, 0 }},
 
{{  0, 0, 0 }, { 0, 0, 0 }, { 0, 8, 4 }, { 7, 15, 0 }},
 
};
 

	
 
/**
 
 * Perform pathfinding for a train.
 
 *
 
 * @param v The train
 
 * @param tile The tile the train is about to enter
 
 * @param enterdir Diagonal direction the train is coming from
 
 * @param tracks Usable tracks on the new tile
 
 * @param path_not_found [out] Set to false if the pathfinder couldn't find a way to the destination
 
 * @param do_track_reservation Path reservation is requested
 
 * @param dest [out] State and destination of the requested path
 
 * @return The best track the train should follow
 
 */
 
static Track DoTrainPathfind(const Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool *path_not_found, bool do_track_reservation, PBSTileInfo *dest)
 
{
 
	switch (_settings_game.pf.pathfinder_for_trains) {
 
		case VPF_NPF: return NPFTrainChooseTrack(v, tile, enterdir, tracks, path_not_found, do_track_reservation, dest);
 
		case VPF_YAPF: return YapfTrainChooseTrack(v, tile, enterdir, tracks, path_not_found, do_track_reservation, dest);
 

	
 
		default: NOT_REACHED();
 
	}
 
}
 

	
 
/**
 
 * Extend a train path as far as possible. Stops on encountering a safe tile,
 
 * another reservation or a track choice.
 
 * @return INVALID_TILE indicates that the reservation failed.
 
 */
 
static PBSTileInfo ExtendTrainReservation(const Train *v, TrackBits *new_tracks, DiagDirection *enterdir)
 
{
 
	PBSTileInfo origin = FollowTrainReservation(v);
 

	
 
	CFollowTrackRail ft(v);
 

	
 
	TileIndex tile = origin.tile;
 
	Trackdir  cur_td = origin.trackdir;
 
	while (ft.Follow(tile, cur_td)) {
 
		if (KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE) {
 
			/* Possible signal tile. */
 
			if (HasOnewaySignalBlockingTrackdir(ft.m_new_tile, FindFirstTrackdir(ft.m_new_td_bits))) break;
 
		}
 

	
 
		if (_settings_game.pf.forbid_90_deg) {
 
			ft.m_new_td_bits &= ~TrackdirCrossesTrackdirs(ft.m_old_td);
 
			if (ft.m_new_td_bits == TRACKDIR_BIT_NONE) break;
 
		}
 

	
 
		/* Station, depot or waypoint are a possible target. */
 
		bool target_seen = ft.m_is_station || (IsTileType(ft.m_new_tile, MP_RAILWAY) && !IsPlainRail(ft.m_new_tile));
 
		if (target_seen || KillFirstBit(ft.m_new_td_bits) != TRACKDIR_BIT_NONE) {
 
			/* Choice found or possible target encountered.
 
			 * On finding a possible target, we need to stop and let the pathfinder handle the
 
			 * remaining path. This is because we don't know if this target is in one of our
 
			 * orders, so we might cause pathfinding to fail later on if we find a choice.
 
			 * This failure would cause a bogous call to TryReserveSafePath which might reserve
 
			 * a wrong path not leading to our next destination. */
 
			if (HasReservedTracks(ft.m_new_tile, TrackdirBitsToTrackBits(TrackdirReachesTrackdirs(ft.m_old_td)))) break;
 

	
 
			/* If we did skip some tiles, backtrack to the first skipped tile so the pathfinder
 
			 * actually starts its search at the first unreserved tile. */
 
			if (ft.m_tiles_skipped != 0) ft.m_new_tile -= TileOffsByDiagDir(ft.m_exitdir) * ft.m_tiles_skipped;
 

	
 
			/* Choice found, path valid but not okay. Save info about the choice tile as well. */
 
			if (new_tracks) *new_tracks = TrackdirBitsToTrackBits(ft.m_new_td_bits);
 
			if (enterdir) *enterdir = ft.m_exitdir;
 
			return PBSTileInfo(ft.m_new_tile, ft.m_old_td, false);
 
		}
 

	
 
		tile = ft.m_new_tile;
 
		cur_td = FindFirstTrackdir(ft.m_new_td_bits);
 

	
 
		if (IsSafeWaitingPosition(v, tile, cur_td, true, _settings_game.pf.forbid_90_deg)) {
 
			bool wp_free = IsWaitingPositionFree(v, tile, cur_td, _settings_game.pf.forbid_90_deg);
 
			if (!(wp_free && TryReserveRailTrack(tile, TrackdirToTrack(cur_td)))) break;
 
			/* Safe position is all good, path valid and okay. */
 
			return PBSTileInfo(tile, cur_td, true);
 
		}
 

	
 
		if (!TryReserveRailTrack(tile, TrackdirToTrack(cur_td))) break;
 
	}
 

	
 
	if (ft.m_err == CFollowTrackRail::EC_OWNER || ft.m_err == CFollowTrackRail::EC_NO_WAY) {
 
		/* End of line, path valid and okay. */
 
		return PBSTileInfo(ft.m_old_tile, ft.m_old_td, true);
 
	}
 

	
 
	/* Sorry, can't reserve path, back out. */
 
	tile = origin.tile;
 
	cur_td = origin.trackdir;
 
	TileIndex stopped = ft.m_old_tile;
 
	Trackdir  stopped_td = ft.m_old_td;
 
	while (tile != stopped || cur_td != stopped_td) {
 
		if (!ft.Follow(tile, cur_td)) break;
 

	
 
		if (_settings_game.pf.forbid_90_deg) {
 
			ft.m_new_td_bits &= ~TrackdirCrossesTrackdirs(ft.m_old_td);
 
			assert(ft.m_new_td_bits != TRACKDIR_BIT_NONE);
 
		}
 
		assert(KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE);
 

	
 
		tile = ft.m_new_tile;
 
		cur_td = FindFirstTrackdir(ft.m_new_td_bits);
 

	
 
		UnreserveRailTrack(tile, TrackdirToTrack(cur_td));
 
	}
 

	
 
	/* Path invalid. */
 
	return PBSTileInfo();
 
}
 

	
 
/**
 
 * Try to reserve any path to a safe tile, ignoring the vehicle's destination.
 
 * Safe tiles are tiles in front of a signal, depots and station tiles at end of line.
 
 *
 
 * @param v The vehicle.
 
 * @param tile The tile the search should start from.
 
 * @param td The trackdir the search should start from.
 
 * @param override_railtype Whether all physically compatible railtypes should be followed.
 
 * @return True if a path to a safe stopping tile could be reserved.
 
 */
 
static bool TryReserveSafeTrack(const Train *v, TileIndex tile, Trackdir td, bool override_tailtype)
 
{
 
	switch (_settings_game.pf.pathfinder_for_trains) {
 
		case VPF_NPF: return NPFTrainFindNearestSafeTile(v, tile, td, override_tailtype);
 
		case VPF_YAPF: return YapfTrainFindNearestSafeTile(v, tile, td, override_tailtype);
 

	
 
		default: NOT_REACHED();
 
	}
 
}
 

	
 
/** This class will save the current order of a vehicle and restore it on destruction. */
 
class VehicleOrderSaver
 
{
 
private:
 
	Vehicle        *v;
 
	Order          old_order;
 
	TileIndex      old_dest_tile;
 
	StationID      old_last_station_visited;
 
	VehicleOrderID index;
 

	
 
public:
 
	VehicleOrderSaver(Vehicle *_v) :
 
		v(_v),
 
		old_order(_v->current_order),
 
		old_dest_tile(_v->dest_tile),
 
		old_last_station_visited(_v->last_station_visited),
 
		index(_v->cur_order_index)
 
	{
 
	}
 

	
 
	~VehicleOrderSaver()
 
	{
 
		this->v->current_order = this->old_order;
 
		this->v->dest_tile = this->old_dest_tile;
 
		this->v->last_station_visited = this->old_last_station_visited;
 
	}
 

	
 
	/**
 
	 * Set the current vehicle order to the next order in the order list.
 
	 * @param skip_first Shall the first (i.e. active) order be skipped?
 
	 * @return True if a suitable next order could be found.
 
	 */
 
	bool SwitchToNextOrder(bool skip_first)
 
	{
 
		if (this->v->GetNumOrders() == 0) return false;
 

	
 
		if (skip_first) ++this->index;
 

	
 
		int conditional_depth = 0;
 

	
 
		do {
 
			/* Wrap around. */
 
			if (this->index >= this->v->GetNumOrders()) this->index = 0;
 

	
 
			Order *order = this->v->GetOrder(this->index);
 
			assert(order != NULL);
 

	
 
			switch (order->GetType()) {
 
				case OT_GOTO_DEPOT:
 
					/* Skip service in depot orders when the train doesn't need service. */
 
					if ((order->GetDepotOrderType() & ODTFB_SERVICE) && !this->v->NeedsServicing()) break;
 
				case OT_GOTO_STATION:
 
				case OT_GOTO_WAYPOINT:
 
					this->v->current_order = *order;
 
					UpdateOrderDest(this->v, order);
 
					return true;
 
				case OT_CONDITIONAL: {
 
					if (conditional_depth > this->v->GetNumOrders()) return false;
 
					VehicleOrderID next = ProcessConditionalOrder(order, this->v);
 
					if (next != INVALID_VEH_ORDER_ID) {
 
						conditional_depth++;
 
						this->index = next;
 
						/* Don't increment next, so no break here. */
 
						continue;
 
					}
 
					break;
 
				}
 
				default:
 
					break;
 
			}
 
			/* Don't increment inside the while because otherwise conditional
 
			 * orders can lead to an infinite loop. */
 
			++this->index;
 
		} while (this->index != this->v->cur_order_index);
 

	
 
		return false;
 
	}
 
};
 

	
 
/* choose a track */
 
static Track ChooseTrainTrack(Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool force_res, bool *got_reservation, bool mark_stuck)
 
{
 
	Track best_track = INVALID_TRACK;
 
	bool do_track_reservation = _settings_game.pf.reserve_paths || force_res;
 
	bool changed_signal = false;
 

	
 
	assert((tracks & ~TRACK_BIT_MASK) == 0);
 

	
 
	if (got_reservation != NULL) *got_reservation = false;
 

	
 
	/* Don't use tracks here as the setting to forbid 90 deg turns might have been switched between reservation and now. */
 
	TrackBits res_tracks = (TrackBits)(GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir));
 
	/* Do we have a suitable reserved track? */
 
	if (res_tracks != TRACK_BIT_NONE) return FindFirstTrack(res_tracks);
 

	
 
	/* Quick return in case only one possible track is available */
 
	if (KillFirstBit(tracks) == TRACK_BIT_NONE) {
 
		Track track = FindFirstTrack(tracks);
 
		/* We need to check for signals only here, as a junction tile can't have signals. */
 
		if (track != INVALID_TRACK && HasPbsSignalOnTrackdir(tile, TrackEnterdirToTrackdir(track, enterdir))) {
 
			do_track_reservation = true;
 
			changed_signal = true;
 
			SetSignalStateByTrackdir(tile, TrackEnterdirToTrackdir(track, enterdir), SIGNAL_STATE_GREEN);
 
		} else if (!do_track_reservation) {
 
			return track;
 
		}
 
		best_track = track;
 
	}
 

	
 
	PBSTileInfo   res_dest(tile, INVALID_TRACKDIR, false);
 
	DiagDirection dest_enterdir = enterdir;
 
	if (do_track_reservation) {
 
		/* Check if the train needs service here, so it has a chance to always find a depot.
 
		 * Also check if the current order is a service order so we don't reserve a path to
 
		 * the destination but instead to the next one if service isn't needed. */
 
		CheckIfTrainNeedsService(v);
 
		if (v->current_order.IsType(OT_DUMMY) || v->current_order.IsType(OT_CONDITIONAL) || v->current_order.IsType(OT_GOTO_DEPOT)) ProcessOrders(v);
 

	
 
		res_dest = ExtendTrainReservation(v, &tracks, &dest_enterdir);
 
		if (res_dest.tile == INVALID_TILE) {
 
			/* Reservation failed? */
 
			if (mark_stuck) MarkTrainAsStuck(v);
 
			if (changed_signal) SetSignalStateByTrackdir(tile, TrackEnterdirToTrackdir(best_track, enterdir), SIGNAL_STATE_RED);
 
			return FindFirstTrack(tracks);
 
		}
 
	}
 

	
 
	/* Save the current train order. The destructor will restore the old order on function exit. */
 
	VehicleOrderSaver orders(v);
 

	
 
	/* If the current tile is the destination of the current order and
 
	 * a reservation was requested, advance to the next order.
 
	 * Don't advance on a depot order as depots are always safe end points
 
	 * for a path and no look-ahead is necessary. This also avoids a
 
	 * problem with depot orders not part of the order list when the
 
	 * order list itself is empty. */
 
	if (v->current_order.IsType(OT_LEAVESTATION)) {
 
		orders.SwitchToNextOrder(false);
 
	} else if (v->current_order.IsType(OT_LOADING) || (!v->current_order.IsType(OT_GOTO_DEPOT) && (
 
			v->current_order.IsType(OT_GOTO_STATION) ?
 
			IsRailStationTile(v->tile) && v->current_order.GetDestination() == GetStationIndex(v->tile) :
 
			v->tile == v->dest_tile))) {
 
		orders.SwitchToNextOrder(true);
 
	}
 

	
 
	if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
 
		/* Pathfinders are able to tell that route was only 'guessed'. */
 
		bool      path_not_found = false;
 
		TileIndex new_tile = res_dest.tile;
 

	
 
		Track next_track = DoTrainPathfind(v, new_tile, dest_enterdir, tracks, &path_not_found, do_track_reservation, &res_dest);
 
		if (new_tile == tile) best_track = next_track;
 

	
 
		/* handle "path not found" state */
 
		if (path_not_found) {
 
			/* PF didn't find the route */
 
			if (!HasBit(v->flags, VRF_NO_PATH_TO_DESTINATION)) {
 
				/* it is first time the problem occurred, set the "path not found" flag */
 
				SetBit(v->flags, VRF_NO_PATH_TO_DESTINATION);
 
				/* and notify user about the event */
 
				AI::NewEvent(v->owner, new AIEventVehicleLost(v->index));
 
				if (_settings_client.gui.lost_train_warn && v->owner == _local_company) {
 
					SetDParam(0, v->index);
 
					AddVehicleNewsItem(
 
						STR_NEWS_TRAIN_IS_LOST,
 
						NS_ADVICE,
 
						v->index
 
					);
 
				}
 
			}
 
		} else {
 
			/* route found, is the train marked with "path not found" flag? */
 
			if (HasBit(v->flags, VRF_NO_PATH_TO_DESTINATION)) {
 
				/* clear the flag as the PF's problem was solved */
 
				ClrBit(v->flags, VRF_NO_PATH_TO_DESTINATION);
 
				/* can we also delete the "News" item somehow? */
 
			}
 
		}
 
	}
 

	
 
	/* No track reservation requested -> finished. */
 
	if (!do_track_reservation) return best_track;
 

	
 
	/* A path was found, but could not be reserved. */
 
	if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
 
		if (mark_stuck) MarkTrainAsStuck(v);
 
		FreeTrainTrackReservation(v);
 
		return best_track;
 
	}
 

	
 
	/* No possible reservation target found, we are probably lost. */
 
	if (res_dest.tile == INVALID_TILE) {
 
		/* Try to find any safe destination. */
 
		PBSTileInfo origin = FollowTrainReservation(v);
 
		if (TryReserveSafeTrack(v, origin.tile, origin.trackdir, false)) {
 
			TrackBits res = GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir);
 
			best_track = FindFirstTrack(res);
 
			TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
 
			if (got_reservation != NULL) *got_reservation = true;
 
			if (changed_signal) MarkTileDirtyByTile(tile);
 
		} else {
 
			FreeTrainTrackReservation(v);
 
			if (mark_stuck) MarkTrainAsStuck(v);
 
		}
 
		return best_track;
 
	}
 

	
 
	if (got_reservation != NULL) *got_reservation = true;
 

	
 
	/* Reservation target found and free, check if it is safe. */
 
	while (!IsSafeWaitingPosition(v, res_dest.tile, res_dest.trackdir, true, _settings_game.pf.forbid_90_deg)) {
 
		/* Extend reservation until we have found a safe position. */
 
		DiagDirection exitdir = TrackdirToExitdir(res_dest.trackdir);
 
		TileIndex     next_tile = TileAddByDiagDir(res_dest.tile, exitdir);
 
		TrackBits     reachable = TrackdirBitsToTrackBits((TrackdirBits)(GetTileTrackStatus(next_tile, TRANSPORT_RAIL, 0))) & DiagdirReachesTracks(exitdir);
 
		if (_settings_game.pf.forbid_90_deg) {
 
			reachable &= ~TrackCrossesTracks(TrackdirToTrack(res_dest.trackdir));
 
		}
 

	
 
		/* Get next order with destination. */
 
		if (orders.SwitchToNextOrder(true)) {
 
			PBSTileInfo cur_dest;
 
			DoTrainPathfind(v, next_tile, exitdir, reachable, NULL, true, &cur_dest);
 
			if (cur_dest.tile != INVALID_TILE) {
 
				res_dest = cur_dest;
 
				if (res_dest.okay) continue;
 
				/* Path found, but could not be reserved. */
 
				FreeTrainTrackReservation(v);
 
				if (mark_stuck) MarkTrainAsStuck(v);
 
				if (got_reservation != NULL) *got_reservation = false;
 
				changed_signal = false;
 
				break;
 
			}
 
		}
 
		/* No order or no safe position found, try any position. */
 
		if (!TryReserveSafeTrack(v, res_dest.tile, res_dest.trackdir, true)) {
 
			FreeTrainTrackReservation(v);
 
			if (mark_stuck) MarkTrainAsStuck(v);
 
			if (got_reservation != NULL) *got_reservation = false;
 
			changed_signal = false;
 
		}
 
		break;
 
	}
 

	
 
	TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
 

	
 
	if (changed_signal) MarkTileDirtyByTile(tile);
 

	
 
	return best_track;
 
}
 

	
 
/**
 
 * Try to reserve a path to a safe position.
 
 *
 
 * @param v The vehicle
 
 * @param mark_as_stuck Should the train be marked as stuck on a failed reservation?
 
 * @param first_tile_okay True if no path should be reserved if the current tile is a safe position.
 
 * @return True if a path could be reserved.
 
 */
 
bool TryPathReserve(Train *v, bool mark_as_stuck, bool first_tile_okay)
 
{
 
	assert(v->IsFrontEngine());
 

	
 
	/* We have to handle depots specially as the track follower won't look
 
	 * at the depot tile itself but starts from the next tile. If we are still
 
	 * inside the depot, a depot reservation can never be ours. */
 
	if (v->track == TRACK_BIT_DEPOT) {
 
		if (HasDepotReservation(v->tile)) {
 
			if (mark_as_stuck) MarkTrainAsStuck(v);
 
			return false;
 
		} else {
 
			/* Depot not reserved, but the next tile might be. */
 
			TileIndex next_tile = TileAddByDiagDir(v->tile, GetRailDepotDirection(v->tile));
 
			if (HasReservedTracks(next_tile, DiagdirReachesTracks(GetRailDepotDirection(v->tile)))) return false;
 
		}
 
	}
 

	
 
	/* Special check if we are in front of a two-sided conventional signal. */
 
	DiagDirection dir = TrainExitDir(v->direction, v->track);
 
	TileIndex next_tile = TileAddByDiagDir(v->tile, dir);
 
	if (IsTileType(next_tile, MP_RAILWAY) && HasReservedTracks(next_tile, DiagdirReachesTracks(dir))) {
 
		/* Can have only one reserved trackdir. */
 
		Trackdir td = FindFirstTrackdir(TrackBitsToTrackdirBits(GetReservedTrackbits(next_tile)) & DiagdirReachesTrackdirs(dir));
 
		if (HasSignalOnTrackdir(next_tile, td) && HasSignalOnTrackdir(next_tile, ReverseTrackdir(td)) &&
 
				!IsPbsSignal(GetSignalType(next_tile, TrackdirToTrack(td)))) {
 
			/* Signal already reserved, is not ours. */
 
			if (mark_as_stuck) MarkTrainAsStuck(v);
 
			return false;
 
		}
 
	}
 

	
 
	Vehicle *other_train = NULL;
 
	PBSTileInfo origin = FollowTrainReservation(v, &other_train);
 
	/* The path we are driving on is alread blocked by some other train.
 
	 * This can only happen in certain situations when mixing path and
 
	 * block signals or when changing tracks and/or signals.
 
	 * Exit here as doing any further reservations will probably just
 
	 * make matters worse. */
 
	if (other_train != NULL && other_train->index != v->index) {
 
		if (mark_as_stuck) MarkTrainAsStuck(v);
 
		return false;
 
	}
 
	/* If we have a reserved path and the path ends at a safe tile, we are finished already. */
 
	if (origin.okay && (v->tile != origin.tile || first_tile_okay)) {
 
		/* Can't be stuck then. */
 
		if (HasBit(v->flags, VRF_TRAIN_STUCK)) SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
 
		ClrBit(v->flags, VRF_TRAIN_STUCK);
 
		return true;
 
	}
 

	
 
	/* If we are in a depot, tentativly reserve the depot. */
 
	if (v->track == TRACK_BIT_DEPOT) {
 
		SetDepotReservation(v->tile, true);
 
		if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(v->tile);
 
	}
 

	
 
	DiagDirection exitdir = TrackdirToExitdir(origin.trackdir);
 
	TileIndex     new_tile = TileAddByDiagDir(origin.tile, exitdir);
 
	TrackBits     reachable = TrackdirBitsToTrackBits(TrackStatusToTrackdirBits(GetTileTrackStatus(new_tile, TRANSPORT_RAIL, 0)) & DiagdirReachesTrackdirs(exitdir));
 

	
 
	if (_settings_game.pf.forbid_90_deg) reachable &= ~TrackCrossesTracks(TrackdirToTrack(origin.trackdir));
 

	
 
	bool res_made = false;
 
	ChooseTrainTrack(v, new_tile, exitdir, reachable, true, &res_made, mark_as_stuck);
 

	
 
	if (!res_made) {
 
		/* Free the depot reservation as well. */
 
		if (v->track == TRACK_BIT_DEPOT) SetDepotReservation(v->tile, false);
 
		return false;
 
	}
 

	
 
	if (HasBit(v->flags, VRF_TRAIN_STUCK)) {
 
		v->wait_counter = 0;
 
		SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
 
	}
 
	ClrBit(v->flags, VRF_TRAIN_STUCK);
 
	return true;
 
}
 

	
 

	
 
static bool CheckReverseTrain(const Train *v)
 
{
 
	if (_settings_game.difficulty.line_reverse_mode != 0 ||
 
			v->track == TRACK_BIT_DEPOT || v->track == TRACK_BIT_WORMHOLE ||
 
			!(v->direction & 1)) {
 
		return false;
 
	}
 

	
 
	assert(v->track != TRACK_BIT_NONE);
 

	
 
	switch (_settings_game.pf.pathfinder_for_trains) {
 
		case VPF_NPF: return NPFTrainCheckReverse(v);
 
		case VPF_YAPF: return YapfTrainCheckReverse(v);
 

	
 
		default: NOT_REACHED();
 
	}
 
}
 

	
 
TileIndex Train::GetOrderStationLocation(StationID station)
 
{
 
	if (station == this->last_station_visited) this->last_station_visited = INVALID_STATION;
 

	
 
	const Station *st = Station::Get(station);
 
	if (!(st->facilities & FACIL_TRAIN)) {
 
		/* The destination station has no trainstation tiles. */
 
		this->IncrementOrderIndex();
 
		return 0;
 
	}
 

	
 
	return st->xy;
 
}
 

	
 
void Train::MarkDirty()
 
{
 
	Vehicle *v = this;
 
	do {
 
		v->UpdateViewport(false, false);
 
	} while ((v = v->Next()) != NULL);
 

	
 
	/* need to update acceleration and cached values since the goods on the train changed. */
 
	TrainCargoChanged(this);
 
	UpdateTrainAcceleration(this);
 
}
 

	
 
/**
 
 * This function looks at the vehicle and updates it's speed (cur_speed
 
 * and subspeed) variables. Furthermore, it returns the distance that
 
 * the train can drive this tick. This distance is expressed as 256 * n,
 
 * where n is the number of straight (long) tracks the train can
 
 * traverse. This means that moving along a straight track costs 256
 
 * "speed" and a diagonal track costs 192 "speed".
 
 * @param v The vehicle to update the speed of.
 
 * @return distance to drive.
 
 */
 
static int UpdateTrainSpeed(Train *v)
 
{
 
	uint accel;
 

	
 
	if ((v->vehstatus & VS_STOPPED) || HasBit(v->flags, VRF_REVERSING) || HasBit(v->flags, VRF_TRAIN_STUCK)) {
 
		switch (_settings_game.vehicle.train_acceleration_model) {
 
			default: NOT_REACHED();
 
			case TAM_ORIGINAL:  accel = v->acceleration * -4; break;
 
			case TAM_REALISTIC: accel = GetTrainAcceleration(v, AM_BRAKE); break;
 
		}
 
	} else {
 
		switch (_settings_game.vehicle.train_acceleration_model) {
 
			default: NOT_REACHED();
 
			case TAM_ORIGINAL:  accel = v->acceleration * 2; break;
 
			case TAM_REALISTIC: accel = GetTrainAcceleration(v, AM_ACCEL); break;
 
		}
 
	}
 

	
 
	uint spd = v->subspeed + accel;
 
	v->subspeed = (byte)spd;
 
	{
 
		int tempmax = v->max_speed;
 
		if (v->cur_speed > v->max_speed)
 
			tempmax = v->cur_speed - (v->cur_speed / 10) - 1;
 
		v->cur_speed = spd = Clamp(v->cur_speed + ((int)spd >> 8), 0, tempmax);
 
	}
 

	
 
	/* Scale speed by 3/4. Previously this was only done when the train was
 
	 * facing diagonally and would apply to however many moves the train made
 
	 * regardless the of direction actually moved in. Now it is always scaled,
 
	 * 256 spd is used to go straight and 192 is used to go diagonally
 
	 * (3/4 of 256). This results in the same effect, but without the error the
 
	 * previous method caused.
 
	 *
 
	 * The scaling is done in this direction and not by multiplying the amount
 
	 * to be subtracted by 4/3 so that the leftover speed can be saved in a
 
	 * byte in v->progress.
 
	 */
 
	int scaled_spd = spd * 3 >> 2;
 

	
 
	scaled_spd += v->progress;
 
	v->progress = 0; // set later in TrainLocoHandler or TrainController
 
	return scaled_spd;
 
}
 

	
 
static void TrainEnterStation(Train *v, StationID station)
 
{
 
	v->last_station_visited = station;
 

	
 
	/* check if a train ever visited this station before */
 
	Station *st = Station::Get(station);
 
	if (!(st->had_vehicle_of_type & HVOT_TRAIN)) {
 
		st->had_vehicle_of_type |= HVOT_TRAIN;
 
		SetDParam(0, st->index);
 
		AddVehicleNewsItem(
 
			STR_NEWS_FIRST_TRAIN_ARRIVAL,
 
			v->owner == _local_company ? NS_ARRIVAL_COMPANY : NS_ARRIVAL_OTHER,
 
			v->index,
 
			st->index
 
		);
 
		AI::NewEvent(v->owner, new AIEventStationFirstVehicle(st->index, v->index));
 
	}
 

	
 
	v->BeginLoading();
 

	
 
	StationAnimationTrigger(st, v->tile, STAT_ANIM_TRAIN_ARRIVES);
 
}
 

	
 
static byte AfterSetTrainPos(Train *v, bool new_tile)
 
{
 
	byte old_z = v->z_pos;
 
	v->z_pos = GetSlopeZ(v->x_pos, v->y_pos);
 

	
 
	if (new_tile) {
 
		ClrBit(v->flags, VRF_GOINGUP);
 
		ClrBit(v->flags, VRF_GOINGDOWN);
 

	
 
		if (v->track == TRACK_BIT_X || v->track == TRACK_BIT_Y) {
 
			/* Any track that isn't TRACK_BIT_X or TRACK_BIT_Y cannot be sloped.
 
			 * To check whether the current tile is sloped, and in which
 
			 * direction it is sloped, we get the 'z' at the center of
 
			 * the tile (middle_z) and the edge of the tile (old_z),
 
			 * which we then can compare. */
 
			static const int HALF_TILE_SIZE = TILE_SIZE / 2;
 
			static const int INV_TILE_SIZE_MASK = ~(TILE_SIZE - 1);
 

	
 
			byte middle_z = GetSlopeZ((v->x_pos & INV_TILE_SIZE_MASK) | HALF_TILE_SIZE, (v->y_pos & INV_TILE_SIZE_MASK) | HALF_TILE_SIZE);
 

	
 
			if (middle_z != v->z_pos) {
 
				SetBit(v->flags, (middle_z > old_z) ? VRF_GOINGUP : VRF_GOINGDOWN);
 
			}
 
		}
 
	}
 

	
 
	VehicleMove(v, true);
 
	return old_z;
 
}
 

	
 
/* Check if the vehicle is compatible with the specified tile */
 
static inline bool CheckCompatibleRail(const Train *v, TileIndex tile)
 
{
 
	return
 
		IsTileOwner(tile, v->owner) && (
 
			!v->IsFrontEngine() ||
 
			HasBit(v->compatible_railtypes, GetRailType(tile))
 
		);
 
}
 

	
 
struct RailtypeSlowdownParams {
 
	byte small_turn, large_turn;
 
	byte z_up; // fraction to remove when moving up
 
	byte z_down; // fraction to remove when moving down
 
};
 

	
 
static const RailtypeSlowdownParams _railtype_slowdown[] = {
 
	/* normal accel */
 
	{256 / 4, 256 / 2, 256 / 4, 2}, ///< normal
 
	{256 / 4, 256 / 2, 256 / 4, 2}, ///< electrified
 
	{256 / 4, 256 / 2, 256 / 4, 2}, ///< monorail
 
	{0,       256 / 2, 256 / 4, 2}, ///< maglev
 
};
 

	
 
/** Modify the speed of the vehicle due to a change in altitude */
 
static inline void AffectSpeedByZChange(Train *v, byte old_z)
 
{
 
	if (old_z == v->z_pos || _settings_game.vehicle.train_acceleration_model != TAM_ORIGINAL) return;
 

	
 
	const RailtypeSlowdownParams *rsp = &_railtype_slowdown[v->railtype];
 

	
 
	if (old_z < v->z_pos) {
 
		v->cur_speed -= (v->cur_speed * rsp->z_up >> 8);
 
	} else {
 
		uint16 spd = v->cur_speed + rsp->z_down;
 
		if (spd <= v->max_speed) v->cur_speed = spd;
 
	}
 
}
 

	
 
static bool TrainMovedChangeSignals(TileIndex tile, DiagDirection dir)
 
{
 
	if (IsTileType(tile, MP_RAILWAY) &&
 
			GetRailTileType(tile) == RAIL_TILE_SIGNALS) {
 
		TrackdirBits tracks = TrackBitsToTrackdirBits(GetTrackBits(tile)) & DiagdirReachesTrackdirs(dir);
 
		Trackdir trackdir = FindFirstTrackdir(tracks);
 
		if (UpdateSignalsOnSegment(tile,  TrackdirToExitdir(trackdir), GetTileOwner(tile)) == SIGSEG_PBS && HasSignalOnTrackdir(tile, trackdir)) {
 
			/* A PBS block with a non-PBS signal facing us? */
 
			if (!IsPbsSignal(GetSignalType(tile, TrackdirToTrack(trackdir)))) return true;
 
		}
 
	}
 
	return false;
 
}
 

	
 
/**
 
 * Tries to reserve track under whole train consist
 
 */
 
void Train::ReserveTrackUnderConsist() const
 
{
 
	for (const Train *u = this; u != NULL; u = u->Next()) {
 
		switch (u->track) {
 
			case TRACK_BIT_WORMHOLE:
 
				TryReserveRailTrack(u->tile, DiagDirToDiagTrack(GetTunnelBridgeDirection(u->tile)));
 
				break;
 
			case TRACK_BIT_DEPOT:
 
				break;
 
			default:
 
				TryReserveRailTrack(u->tile, TrackBitsToTrack(u->track));
 
				break;
 
		}
 
	}
 
}
 

	
 
uint Train::Crash(bool flooded)
 
{
 
	uint pass = 0;
 
	if (this->IsFrontEngine()) {
 
		pass += 4; // driver
 

	
 
		/* Remove the reserved path in front of the train if it is not stuck.
 
		 * Also clear all reserved tracks the train is currently on. */
 
		if (!HasBit(this->flags, VRF_TRAIN_STUCK)) FreeTrainTrackReservation(this);
 
		for (const Train *v = this; v != NULL; v = v->Next()) {
 
			ClearPathReservation(v, v->tile, v->GetVehicleTrackdir());
 
			if (IsTileType(v->tile, MP_TUNNELBRIDGE)) {
 
				/* ClearPathReservation will not free the wormhole exit
 
				 * if the train has just entered the wormhole. */
 
				SetTunnelBridgeReservation(GetOtherTunnelBridgeEnd(v->tile), false);
 
			}
 
		}
 

	
 
		/* we may need to update crossing we were approaching,
 
		* but must be updated after the train has been marked crashed */
 
		TileIndex crossing = TrainApproachingCrossingTile(this);
 
		if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
 
	}
 

	
 
	pass += Vehicle::Crash(flooded);
 

	
 
	this->crash_anim_pos = flooded ? 4000 : 1; // max 4440, disappear pretty fast when flooded
 
	return pass;
 
}
 

	
 
/**
 
 * Marks train as crashed and creates an AI event.
 
 * Doesn't do anything if the train is crashed already.
 
 * @param v first vehicle of chain
 
 * @return number of victims (including 2 drivers; zero if train was already crashed)
 
 */
 
static uint TrainCrashed(Train *v)
 
{
 
	uint num = 0;
 

	
 
	/* do not crash train twice */
 
	if (!(v->vehstatus & VS_CRASHED)) {
 
		num = v->Crash();
 
		AI::NewEvent(v->owner, new AIEventVehicleCrashed(v->index, v->tile, AIEventVehicleCrashed::CRASH_TRAIN));
 
	}
 

	
 
	/* Try to re-reserve track under already crashed train too.
 
	 * SetVehicleCrashed() clears the reservation! */
 
	v->ReserveTrackUnderConsist();
 

	
 
	return num;
 
}
 

	
 
struct TrainCollideChecker {
 
	Train *v; ///< vehicle we are testing for collision
 
	uint num; ///< number of victims if train collided
 
};
 

	
 
static Vehicle *FindTrainCollideEnum(Vehicle *v, void *data)
 
{
 
	TrainCollideChecker *tcc = (TrainCollideChecker*)data;
 

	
 
	/* not a train or in depot */
 
	if (v->type != VEH_TRAIN || Train::From(v)->track == TRACK_BIT_DEPOT) return NULL;
 

	
 
	/* get first vehicle now to make most usual checks faster */
 
	Train *coll = Train::From(v)->First();
 

	
 
	/* can't collide with own wagons */
 
	if (coll == tcc->v) return NULL;
 

	
 
	int x_diff = v->x_pos - tcc->v->x_pos;
 
	int y_diff = v->y_pos - tcc->v->y_pos;
 

	
 
	/* Do fast calculation to check whether trains are not in close vicinity
 
	 * and quickly reject trains distant enough for any collision.
 
	 * Differences are shifted by 7, mapping range [-7 .. 8] into [0 .. 15]
 
	 * Differences are then ORed and then we check for any higher bits */
 
	uint hash = (y_diff + 7) | (x_diff + 7);
 
	if (hash & ~15) return NULL;
 

	
 
	/* Slower check using multiplication */
 
	if (x_diff * x_diff + y_diff * y_diff > 25) return NULL;
 

	
 
	/* Happens when there is a train under bridge next to bridge head */
 
	if (abs(v->z_pos - tcc->v->z_pos) > 5) return NULL;
 

	
 
	/* crash both trains */
 
	tcc->num += TrainCrashed(tcc->v);
 
	tcc->num += TrainCrashed(coll);
 

	
 
	return NULL; // continue searching
 
}
 

	
 
/**
 
 * Checks whether the specified train has a collision with another vehicle. If
 
 * so, destroys this vehicle, and the other vehicle if its subtype has TS_Front.
 
 * Reports the incident in a flashy news item, modifies station ratings and
 
 * plays a sound.
 
 */
 
static bool CheckTrainCollision(Train *v)
 
{
 
	/* can't collide in depot */
 
	if (v->track == TRACK_BIT_DEPOT) return false;
 

	
 
	assert(v->track == TRACK_BIT_WORMHOLE || TileVirtXY(v->x_pos, v->y_pos) == v->tile);
 

	
 
	TrainCollideChecker tcc;
 
	tcc.v = v;
 
	tcc.num = 0;
 

	
 
	/* find colliding vehicles */
 
	if (v->track == TRACK_BIT_WORMHOLE) {
 
		FindVehicleOnPos(v->tile, &tcc, FindTrainCollideEnum);
 
		FindVehicleOnPos(GetOtherTunnelBridgeEnd(v->tile), &tcc, FindTrainCollideEnum);
 
	} else {
 
		FindVehicleOnPosXY(v->x_pos, v->y_pos, &tcc, FindTrainCollideEnum);
 
	}
 

	
 
	/* any dead -> no crash */
 
	if (tcc.num == 0) return false;
 

	
 
	SetDParam(0, tcc.num);
 
	AddVehicleNewsItem(STR_NEWS_TRAIN_CRASH,
 
		NS_ACCIDENT,
 
		v->index
 
	);
 

	
 
	ModifyStationRatingAround(v->tile, v->owner, -160, 30);
 
	SndPlayVehicleFx(SND_13_BIG_CRASH, v);
 
	return true;
 
}
 

	
 
static Vehicle *CheckTrainAtSignal(Vehicle *v, void *data)
 
{
 
	if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) return NULL;
 

	
 
	Train *t = Train::From(v);
 
	DiagDirection exitdir = *(DiagDirection *)data;
 

	
 
	/* not front engine of a train, inside wormhole or depot, crashed */
 
	if (!t->IsFrontEngine() || !(t->track & TRACK_BIT_MASK)) return NULL;
 

	
 
	if (t->cur_speed > 5 || TrainExitDir(t->direction, t->track) != exitdir) return NULL;
 

	
 
	return t;
 
}
 

	
 
static void TrainController(Train *v, Vehicle *nomove)
 
{
 
	Train *first = v->First();
 
	Train *prev;
 
	bool direction_changed = false; // has direction of any part changed?
 

	
 
	/* For every vehicle after and including the given vehicle */
 
	for (prev = v->Previous(); v != nomove; prev = v, v = v->Next()) {
 
		DiagDirection enterdir = DIAGDIR_BEGIN;
 
		bool update_signals_crossing = false; // will we update signals or crossing state?
 

	
 
		GetNewVehiclePosResult gp = GetNewVehiclePos(v);
 
		if (v->track != TRACK_BIT_WORMHOLE) {
 
			/* Not inside tunnel */
 
			if (gp.old_tile == gp.new_tile) {
 
				/* Staying in the old tile */
 
				if (v->track == TRACK_BIT_DEPOT) {
 
					/* Inside depot */
 
					gp.x = v->x_pos;
 
					gp.y = v->y_pos;
 
				} else {
 
					/* Not inside depot */
 

	
 
					/* Reverse when we are at the end of the track already, do not move to the new position */
 
					if (v->IsFrontEngine() && !TrainCheckIfLineEnds(v)) return;
 

	
 
					uint32 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
 
					if (HasBit(r, VETS_CANNOT_ENTER)) {
 
						goto invalid_rail;
 
					}
 
					if (HasBit(r, VETS_ENTERED_STATION)) {
 
						/* The new position is the end of the platform */
 
						TrainEnterStation(v, r >> VETS_STATION_ID_OFFSET);
 
					}
 
				}
 
			} else {
 
				/* A new tile is about to be entered. */
 

	
 
				/* Determine what direction we're entering the new tile from */
 
				enterdir = DiagdirBetweenTiles(gp.old_tile, gp.new_tile);
 
				assert(IsValidDiagDirection(enterdir));
 

	
 
				/* Get the status of the tracks in the new tile and mask
 
				 * away the bits that aren't reachable. */
 
				TrackStatus ts = GetTileTrackStatus(gp.new_tile, TRANSPORT_RAIL, 0, ReverseDiagDir(enterdir));
 
				TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(enterdir);
 

	
 
				TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
 
				TrackBits red_signals = TrackdirBitsToTrackBits(TrackStatusToRedSignals(ts) & reachable_trackdirs);
 

	
 
				TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
 
				if (_settings_game.pf.forbid_90_deg && prev == NULL) {
 
					/* We allow wagons to make 90 deg turns, because forbid_90_deg
 
					 * can be switched on halfway a turn */
 
					bits &= ~TrackCrossesTracks(FindFirstTrack(v->track));
 
				}
 

	
 
				if (bits == TRACK_BIT_NONE) goto invalid_rail;
 

	
 
				/* Check if the new tile contrains tracks that are compatible
 
				 * with the current train, if not, bail out. */
 
				if (!CheckCompatibleRail(v, gp.new_tile)) goto invalid_rail;
 

	
 
				TrackBits chosen_track;
 
				if (prev == NULL) {
 
					/* Currently the locomotive is active. Determine which one of the
 
					 * available tracks to choose */
 
					chosen_track = TrackToTrackBits(ChooseTrainTrack(v, gp.new_tile, enterdir, bits, false, NULL, true));
 
					assert(chosen_track & (bits | GetReservedTrackbits(gp.new_tile)));
 

	
 
					if (v->force_proceed != 0 && IsPlainRailTile(gp.new_tile) && HasSignals(gp.new_tile)) {
 
						/* For each signal we find decrease the counter by one.
 
						 * We start at two, so the first signal we pass decreases
 
						 * this to one, then if we reach the next signal it is
 
						 * decreased to zero and we won't pass that new signal. */
 
						Trackdir dir = FindFirstTrackdir(trackdirbits);
 
						if (GetSignalType(gp.new_tile, TrackdirToTrack(dir)) != SIGTYPE_PBS ||
 
								!HasSignalOnTrackdir(gp.new_tile, ReverseTrackdir(dir))) {
 
							/* However, we do not want to be stopped by PBS signals
 
							 * entered via the back. */
 
							v->force_proceed--;
 
							SetWindowDirty(WC_VEHICLE_VIEW, v->index);
 
						}
 
					}
 

	
 
					/* Check if it's a red signal and that force proceed is not clicked. */
 
					if ((red_signals & chosen_track) && v->force_proceed == 0) {
 
						/* In front of a red signal */
 
						Trackdir i = FindFirstTrackdir(trackdirbits);
 

	
 
						/* Don't handle stuck trains here. */
 
						if (HasBit(v->flags, VRF_TRAIN_STUCK)) return;
 

	
 
						if (!HasSignalOnTrackdir(gp.new_tile, ReverseTrackdir(i))) {
 
							v->cur_speed = 0;
 
							v->subspeed = 0;
 
							v->progress = 255 - 100;
 
							if (_settings_game.pf.wait_oneway_signal == 255 || ++v->wait_counter < _settings_game.pf.wait_oneway_signal * 20) return;
 
						} else if (HasSignalOnTrackdir(gp.new_tile, i)) {
 
							v->cur_speed = 0;
 
							v->subspeed = 0;
 
							v->progress = 255 - 10;
 
							if (_settings_game.pf.wait_twoway_signal == 255 || ++v->wait_counter < _settings_game.pf.wait_twoway_signal * 73) {
 
								DiagDirection exitdir = TrackdirToExitdir(i);
 
								TileIndex o_tile = TileAddByDiagDir(gp.new_tile, exitdir);
 

	
 
								exitdir = ReverseDiagDir(exitdir);
 

	
 
								/* check if a train is waiting on the other side */
 
								if (!HasVehicleOnPos(o_tile, &exitdir, &CheckTrainAtSignal)) return;
 
							}
 
						}
 

	
 
						/* If we would reverse but are currently in a PBS block and
 
						 * reversing of stuck trains is disabled, don't reverse. */
 
						if (_settings_game.pf.wait_for_pbs_path == 255 && UpdateSignalsOnSegment(v->tile, enterdir, v->owner) == SIGSEG_PBS) {
 
							v->wait_counter = 0;
 
							return;
 
						}
 
						goto reverse_train_direction;
 
					} else {
 
						TryReserveRailTrack(gp.new_tile, TrackBitsToTrack(chosen_track));
 
					}
 
				} else {
 
					/* The wagon is active, simply follow the prev vehicle. */
 
					if (prev->tile == gp.new_tile) {
 
						/* Choose the same track as prev */
 
						if (prev->track == TRACK_BIT_WORMHOLE) {
 
							/* Vehicles entering tunnels enter the wormhole earlier than for bridges.
 
							 * However, just choose the track into the wormhole. */
 
							assert(IsTunnel(prev->tile));
 
							chosen_track = bits;
 
						} else {
 
							chosen_track = prev->track;
 
						}
 
					} else {
 
						/* Choose the track that leads to the tile where prev is.
 
						 * This case is active if 'prev' is already on the second next tile, when 'v' just enters the next tile.
 
						 * I.e. when the tile between them has only space for a single vehicle like
 
						 *  1) horizontal/vertical track tiles and
 
						 *  2) some orientations of tunnelentries, where the vehicle is already inside the wormhole at 8/16 from the tileedge.
 
						 *     Is also the train just reversing, the wagon inside the tunnel is 'on' the tile of the opposite tunnelentry.
 
						 */
 
						static const TrackBits _connecting_track[DIAGDIR_END][DIAGDIR_END] = {
 
							{TRACK_BIT_X,     TRACK_BIT_LOWER, TRACK_BIT_NONE,  TRACK_BIT_LEFT },
 
							{TRACK_BIT_UPPER, TRACK_BIT_Y,     TRACK_BIT_LEFT,  TRACK_BIT_NONE },
 
							{TRACK_BIT_NONE,  TRACK_BIT_RIGHT, TRACK_BIT_X,     TRACK_BIT_UPPER},
 
							{TRACK_BIT_RIGHT, TRACK_BIT_NONE,  TRACK_BIT_LOWER, TRACK_BIT_Y    }
 
						};
 
						DiagDirection exitdir = DiagdirBetweenTiles(gp.new_tile, prev->tile);
 
						assert(IsValidDiagDirection(exitdir));
 
						chosen_track = _connecting_track[enterdir][exitdir];
 
					}
 
					chosen_track &= bits;
 
				}
 

	
 
				/* Make sure chosen track is a valid track */
 
				assert(
 
						chosen_track == TRACK_BIT_X     || chosen_track == TRACK_BIT_Y ||
 
						chosen_track == TRACK_BIT_UPPER || chosen_track == TRACK_BIT_LOWER ||
 
						chosen_track == TRACK_BIT_LEFT  || chosen_track == TRACK_BIT_RIGHT);
 

	
 
				/* Update XY to reflect the entrance to the new tile, and select the direction to use */
 
				const byte *b = _initial_tile_subcoord[FIND_FIRST_BIT(chosen_track)][enterdir];
 
				gp.x = (gp.x & ~0xF) | b[0];
 
				gp.y = (gp.y & ~0xF) | b[1];
 
				Direction chosen_dir = (Direction)b[2];
 

	
 
				/* Call the landscape function and tell it that the vehicle entered the tile */
 
				uint32 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
 
				if (HasBit(r, VETS_CANNOT_ENTER)) {
 
					goto invalid_rail;
 
				}
 

	
 
				if (!HasBit(r, VETS_ENTERED_WORMHOLE)) {
 
					Track track = FindFirstTrack(chosen_track);
 
					Trackdir tdir = TrackDirectionToTrackdir(track, chosen_dir);
 
					if (v->IsFrontEngine() && HasPbsSignalOnTrackdir(gp.new_tile, tdir)) {
 
						SetSignalStateByTrackdir(gp.new_tile, tdir, SIGNAL_STATE_RED);
 
						MarkTileDirtyByTile(gp.new_tile);
 
					}
 

	
 
					/* Clear any track reservation when the last vehicle leaves the tile */
 
					if (v->Next() == NULL) ClearPathReservation(v, v->tile, v->GetVehicleTrackdir());
 

	
 
					v->tile = gp.new_tile;
 

	
 
					if (GetTileRailType(gp.new_tile) != GetTileRailType(gp.old_tile)) {
 
						TrainPowerChanged(v->First());
 
					}
 

	
 
					v->track = chosen_track;
 
					assert(v->track);
 
				}
 

	
 
				/* We need to update signal status, but after the vehicle position hash
 
				 * has been updated by AfterSetTrainPos() */
 
				update_signals_crossing = true;
 

	
 
				if (chosen_dir != v->direction) {
 
					if (prev == NULL && _settings_game.vehicle.train_acceleration_model == TAM_ORIGINAL) {
 
						const RailtypeSlowdownParams *rsp = &_railtype_slowdown[v->railtype];
 
						DirDiff diff = DirDifference(v->direction, chosen_dir);
 
						v->cur_speed -= (diff == DIRDIFF_45RIGHT || diff == DIRDIFF_45LEFT ? rsp->small_turn : rsp->large_turn) * v->cur_speed >> 8;
 
					}
 
					direction_changed = true;
 
					v->direction = chosen_dir;
 
				}
 

	
 
				if (v->IsFrontEngine()) {
 
					v->wait_counter = 0;
 

	
 
					/* If we are approching a crossing that is reserved, play the sound now. */
 
					TileIndex crossing = TrainApproachingCrossingTile(v);
 
					if (crossing != INVALID_TILE && HasCrossingReservation(crossing)) SndPlayTileFx(SND_0E_LEVEL_CROSSING, crossing);
 

	
 
					/* Always try to extend the reservation when entering a tile. */
 
					CheckNextTrainTile(v);
 
				}
 

	
 
				if (HasBit(r, VETS_ENTERED_STATION)) {
 
					/* The new position is the location where we want to stop */
 
					TrainEnterStation(v, r >> VETS_STATION_ID_OFFSET);
 
				}
 
			}
 
		} else {
 
			/* In a tunnel or on a bridge
 
			 * - for tunnels, only the part when the vehicle is not visible (part of enter/exit tile too)
 
			 * - for bridges, only the middle part - without the bridge heads */
 
			if (!(v->vehstatus & VS_HIDDEN)) {
 
				v->cur_speed =
 
					min(v->cur_speed, GetBridgeSpec(GetBridgeType(v->tile))->speed);
 
			}
 

	
 
			if (IsTileType(gp.new_tile, MP_TUNNELBRIDGE) && HasBit(VehicleEnterTile(v, gp.new_tile, gp.x, gp.y), VETS_ENTERED_WORMHOLE)) {
 
				/* Perform look-ahead on tunnel exit. */
 
				if (v->IsFrontEngine()) {
 
					TryReserveRailTrack(gp.new_tile, DiagDirToDiagTrack(GetTunnelBridgeDirection(gp.new_tile)));
 
					CheckNextTrainTile(v);
 
				}
 
			} else {
 
				v->x_pos = gp.x;
 
				v->y_pos = gp.y;
 
				VehicleMove(v, !(v->vehstatus & VS_HIDDEN));
 
				continue;
 
			}
 
		}
 

	
 
		/* update image of train, as well as delta XY */
 
		v->UpdateDeltaXY(v->direction);
 

	
 
		v->x_pos = gp.x;
 
		v->y_pos = gp.y;
 

	
 
		/* update the Z position of the vehicle */
 
		byte old_z = AfterSetTrainPos(v, (gp.new_tile != gp.old_tile));
 

	
 
		if (prev == NULL) {
 
			/* This is the first vehicle in the train */
 
			AffectSpeedByZChange(v, old_z);
 
		}
 

	
 
		if (update_signals_crossing) {
 
			if (v->IsFrontEngine()) {
 
				if (TrainMovedChangeSignals(gp.new_tile, enterdir)) {
 
					/* We are entering a block with PBS signals right now, but
 
					 * not through a PBS signal. This means we don't have a
 
					 * reservation right now. As a conventional signal will only
 
					 * ever be green if no other train is in the block, getting
 
					 * a path should always be possible. If the player built
 
					 * such a strange network that it is not possible, the train
 
					 * will be marked as stuck and the player has to deal with
 
					 * the problem. */
 
					if ((!HasReservedTracks(gp.new_tile, v->track) &&
 
							!TryReserveRailTrack(gp.new_tile, FindFirstTrack(v->track))) ||
 
							!TryPathReserve(v)) {
 
						MarkTrainAsStuck(v);
 
					}
 
				}
 
			}
 

	
 
			/* Signals can only change when the first
 
			 * (above) or the last vehicle moves. */
 
			if (v->Next() == NULL) {
 
				TrainMovedChangeSignals(gp.old_tile, ReverseDiagDir(enterdir));
 
				if (IsLevelCrossingTile(gp.old_tile)) UpdateLevelCrossing(gp.old_tile);
 
			}
 
		}
 

	
 
		/* Do not check on every tick to save some computing time. */
 
		if (v->IsFrontEngine() && v->tick_counter % _settings_game.pf.path_backoff_interval == 0) CheckNextTrainTile(v);
 
	}
 

	
 
	if (direction_changed) first->tcache.cached_max_curve_speed = GetTrainCurveSpeedLimit(first);
 

	
 
	return;
 

	
 
invalid_rail:
 
	/* We've reached end of line?? */
 
	if (prev != NULL) error("Disconnecting train");
 

	
 
reverse_train_direction:
 
	v->wait_counter = 0;
 
	v->cur_speed = 0;
 
	v->subspeed = 0;
 
	ReverseTrainDirection(v);
 
}
 

	
 
/** Collect trackbits of all crashed train vehicles on a tile
 
 * @param v Vehicle passed from Find/HasVehicleOnPos()
 
 * @param data trackdirbits for the result
 
 * @return NULL to iterate over all vehicles on the tile.
 
 */
 
static Vehicle *CollectTrackbitsFromCrashedVehiclesEnum(Vehicle *v, void *data)
 
{
 
	TrackBits *trackbits = (TrackBits *)data;
 

	
 
	if (v->type == VEH_TRAIN && (v->vehstatus & VS_CRASHED) != 0) {
 
		if (Train::From(v)->track == TRACK_BIT_WORMHOLE) {
 
			/* Vehicle is inside a wormhole, v->track contains no useful value then. */
 
			*trackbits |= DiagDirToDiagTrackBits(GetTunnelBridgeDirection(v->tile));
 
		} else {
 
			*trackbits |= Train::From(v)->track;
 
		}
 
	}
 

	
 
	return NULL;
 
}
 

	
 
/**
 
 * Deletes/Clears the last wagon of a crashed train. It takes the engine of the
 
 * train, then goes to the last wagon and deletes that. Each call to this function
 
 * will remove the last wagon of a crashed train. If this wagon was on a crossing,
 
 * or inside a tunnel/bridge, recalculate the signals as they might need updating
 
 * @param v the Vehicle of which last wagon is to be removed
 
 */
 
static void DeleteLastWagon(Train *v)
 
{
 
	Train *first = v->First();
 

	
 
	/* Go to the last wagon and delete the link pointing there
 
	 * *u is then the one-before-last wagon, and *v the last
 
	 * one which will physicially be removed */
 
	Train *u = v;
 
	for (; v->Next() != NULL; v = v->Next()) u = v;
 
	u->SetNext(NULL);
 

	
0 comments (0 inline, 0 general)