/*
 * This file is part of OpenTTD.
 * 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.
 * 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.
 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
 */

/** @file rail_map.h Hides the direct accesses to the map array with map accessors. */

#ifndef RAIL_MAP_H
#define RAIL_MAP_H

#include "rail_type.h"
#include "depot_type.h"
#include "signal_func.h"
#include "track_func.h"
#include "tile_map.h"
#include "water_map.h"
#include "signal_type.h"


/** Different types of Rail-related tiles */
enum class RailTileType : uint8_t {
	Normal = 0, ///< Normal rail tile without signals
	Signals = 1, ///< Normal rail tile with signals
	Depot = 3, ///< Depot (one entrance)
};

/**
 * Returns the RailTileType (normal with or without signals,
 * waypoint or depot).
 * @param t the tile to get the information from
 * @pre IsTileType(t, TileType::Railway)
 * @return the RailTileType
 */
[[debug_inline]] inline static RailTileType GetRailTileType(Tile t)
{
	assert(IsTileType(t, TileType::Railway));
	return static_cast<RailTileType>(GB(t.m5(), 6, 2));
}

/**
 * Returns whether this is plain rails, with or without signals. Iow, if this
 * tiles RailTileType is RailTileType::Normal or RailTileType::Signals.
 * @param t the tile to get the information from
 * @pre IsTileType(t, TileType::Railway)
 * @return true if and only if the tile is normal rail (with or without signals)
 */
[[debug_inline]] inline static bool IsPlainRail(Tile t)
{
	RailTileType rtt = GetRailTileType(t);
	return rtt == RailTileType::Normal || rtt == RailTileType::Signals;
}

/**
 * Checks whether the tile is a rail tile or rail tile with signals.
 * @param t the tile to get the information from
 * @return true if and only if the tile is normal rail (with or without signals)
 */
[[debug_inline]] inline static bool IsPlainRailTile(Tile t)
{
	return IsTileType(t, TileType::Railway) && IsPlainRail(t);
}


/**
 * Checks if a rail tile has signals.
 * @param t the tile to get the information from
 * @pre IsTileType(t, TileType::Railway)
 * @return true if and only if the tile has signals
 */
inline bool HasSignals(Tile t)
{
	return GetRailTileType(t) == RailTileType::Signals;
}

/**
 * Add/remove the 'has signal' bit from the RailTileType
 * @param tile the tile to add/remove the signals to/from
 * @param signals whether the rail tile should have signals or not
 * @pre IsPlainRailTile(tile)
 */
inline void SetHasSignals(Tile tile, bool signals)
{
	assert(IsPlainRailTile(tile));
	SB(tile.m5(), 6, 2, to_underlying(signals ? RailTileType::Signals : RailTileType::Normal));
}

/**
 * Is this rail tile a rail depot?
 * @param t the tile to get the information from
 * @pre IsTileType(t, TileType::Railway)
 * @return true if and only if the tile is a rail depot
 */
[[debug_inline]] inline static bool IsRailDepot(Tile t)
{
	return GetRailTileType(t) == RailTileType::Depot;
}

/**
 * Is this tile rail tile and a rail depot?
 * @param t the tile to get the information from
 * @return true if and only if the tile is a rail depot
 */
[[debug_inline]] inline static bool IsRailDepotTile(Tile t)
{
	return IsTileType(t, TileType::Railway) && IsRailDepot(t);
}

/**
 * Gets the rail type of the given tile
 * @param t the tile to get the rail type from
 * @return the rail type of the tile
 */
inline RailType GetRailType(Tile t)
{
	return (RailType)GB(t.m8(), 0, 6);
}

/**
 * Sets the rail type of the given tile
 * @param t the tile to set the rail type of
 * @param r the new rail type for the tile
 */
inline void SetRailType(Tile t, RailType r)
{
	SB(t.m8(), 0, 6, r);
}


/**
 * Gets the track bits of the given tile
 * @param tile the tile to get the track bits from
 * @return the track bits of the tile
 */
inline TrackBits GetTrackBits(Tile tile)
{
	assert(IsPlainRailTile(tile));
	return static_cast<TrackBits>(GB(tile.m5(), 0, 6));
}

/**
 * Sets the track bits of the given tile
 * @param t the tile to set the track bits of
 * @param b the new track bits for the tile
 */
inline void SetTrackBits(Tile t, TrackBits b)
{
	assert(IsPlainRailTile(t));
	SB(t.m5(), 0, 6, b.base());
}

/**
 * Returns whether the given track is present on the given tile.
 * @param tile  the tile to check the track presence of
 * @param track the track to search for on the tile
 * @pre IsPlainRailTile(tile)
 * @return true if and only if the given track exists on the tile
 */
inline bool HasTrack(Tile tile, Track track)
{
	return GetTrackBits(tile).Test(track);
}

/**
 * Returns the direction the depot is facing to
 * @param t the tile to get the depot facing from
 * @pre IsRailDepotTile(t)
 * @return the direction the depot is facing
 */
inline DiagDirection GetRailDepotDirection(Tile t)
{
	return (DiagDirection)GB(t.m5(), 0, 2);
}

/**
 * Returns the track of a depot, ignoring direction
 * @pre IsRailDepotTile(t)
 * @param t the tile to get the depot track from
 * @return the track of the depot
 */
inline Track GetRailDepotTrack(Tile t)
{
	return DiagDirToDiagTrack(GetRailDepotDirection(t));
}


/**
 * Returns the reserved track bits of the tile
 * @pre IsPlainRailTile(t)
 * @param t the tile to query
 * @return the track bits
 */
inline TrackBits GetRailReservationTrackBits(Tile t)
{
	assert(IsPlainRailTile(t));
	uint8_t track_b = GB(t.m2(), 8, 3);
	if (track_b == 0) return {};
	Track track = static_cast<Track>(track_b - 1); // map array saves Track+1
	return (HasBit(t.m2(), 11) ? TrackToOppositeTrack(track) : TrackBits{}) | track;
}

/**
 * Sets the reserved track bits of the tile
 * @pre IsPlainRailTile(t) && !TracksOverlap(b)
 * @param t the tile to change
 * @param b the track bits
 */
inline void SetTrackReservation(Tile t, TrackBits b)
{
	assert(IsPlainRailTile(t));
	assert(!TracksOverlap(b));
	Track track = RemoveFirstTrack(b);
	SB(t.m2(), 8, 3, IsValidTrack(track) ? to_underlying(track) + 1 : 0);
	AssignBit(t.m2(), 11, b.Any());
}

/**
 * Try to reserve a specific track on a tile
 * @pre IsPlainRailTile(tile) && HasTrack(tile, t)
 * @param tile the tile
 * @param t the track to reserve
 * @return true if successful
 */
inline bool TryReserveTrack(Tile tile, Track t)
{
	assert(HasTrack(tile, t));
	TrackBits res = GetRailReservationTrackBits(tile);
	if (res.Test(t)) return false;  // already reserved
	res.Set(t);
	if (TracksOverlap(res)) return false;  // crossing reservation present
	SetTrackReservation(tile, res);
	return true;
}

/**
 * Lift the reservation of a specific track on a tile
 * @pre IsPlainRailTile(tile) && HasTrack(tile, t)
 * @param tile the tile
 * @param t the track to free
 */
inline void UnreserveTrack(Tile tile, Track t)
{
	assert(HasTrack(tile, t));
	TrackBits res = GetRailReservationTrackBits(tile);
	res.Reset(t);
	SetTrackReservation(tile, res);
}

/**
 * Get the reservation state of the depot
 * @pre IsRailDepot(t)
 * @param t the depot tile
 * @return reservation state
 */
inline bool HasDepotReservation(Tile t)
{
	assert(IsRailDepot(t));
	return HasBit(t.m5(), 4);
}

/**
 * Set the reservation state of the depot
 * @pre IsRailDepot(t)
 * @param t the depot tile
 * @param b the reservation state
 */
inline void SetDepotReservation(Tile t, bool b)
{
	assert(IsRailDepot(t));
	AssignBit(t.m5(), 4, b);
}

/**
 * Get the reserved track bits for a depot
 * @pre IsRailDepot(t)
 * @param t the tile
 * @return reserved track bits
 */
inline TrackBits GetDepotReservationTrackBits(Tile t)
{
	return HasDepotReservation(t) ? GetRailDepotTrack(t) : TrackBits{};
}


/**
 * Checks whether the given signal is a path based signal.
 * @param s The signal to check.
 * @return \c true when it is a path based signal.
 */
inline bool IsPbsSignal(SignalType s)
{
	return s == SignalType::Path || s == SignalType::PathOneWay;
}

/**
 * Get the signal type for a track on a tile.
 * In horizontal and vertical orientation there may be two tracks on a tile with a signal.
 * @param t The tile to query.
 * @param track The track to query for.
 * @return The signal type.
 */
inline SignalType GetSignalType(Tile t, Track track)
{
	assert(GetRailTileType(t) == RailTileType::Signals);
	uint8_t pos = (track == Track::Lower || track == Track::Right) ? 4 : 0;
	return static_cast<SignalType>(GB(t.m2(), pos, 3));
}

/**
 * Set the signal type for a track on a tile.
 * In horizontal and vertical orientation there may be two tracks on a tile with a signal.
 * @param t The tile to update.
 * @param track The track to update for.
 * @param s The new signal type.
 */
inline void SetSignalType(Tile t, Track track, SignalType s)
{
	assert(GetRailTileType(t) == RailTileType::Signals);
	uint8_t pos = (track == Track::Lower || track == Track::Right) ? 4 : 0;
	SB(t.m2(), pos, 3, to_underlying(s));
	if (!IsValidTrack(track)) SB(t.m2(), 4, 3, to_underlying(s));
}

/**
 * Is the signal at the given track on a tile a presignal entry signal?
 * In horizontal and vertical orientation there may be two tracks on a tile with a signal.
 * @param t The tile to query.
 * @param track The track to query for.
 * @return \c true iff it is a presignal entry signal.
 */
inline bool IsPresignalEntry(Tile t, Track track)
{
	return GetSignalType(t, track) == SignalType::Entry || GetSignalType(t, track) == SignalType::Combo;
}

/**
 * Is the signal at the given track on a tile a presignal exit signal?
 * In horizontal and vertical orientation there may be two tracks on a tile with a signal.
 * @param t The tile to query.
 * @param track The track to query for.
 * @return \c true iff it is a presignal exit signal.
 */
inline bool IsPresignalExit(Tile t, Track track)
{
	return GetSignalType(t, track) == SignalType::Exit || GetSignalType(t, track) == SignalType::Combo;
}

/**
 * Is the signal at the given track on a tile a one way signal?
 * One-way signals can't be passed the 'wrong' way.
 * In horizontal and vertical orientation there may be two tracks on a tile with a signal.
 * @param t The tile to query.
 * @param track The track to query for.
 * @return \c true iff it is an one way signal.
 */
inline bool IsOnewaySignal(Tile t, Track track)
{
	return GetSignalType(t, track) != SignalType::Path;
}

/**
 * Cycle to the next signal side at the given track on a tile.
 * For path based signals there are two options, for other signals there is a third option with both sides.
 * @param t The tile to update.
 * @param track The track to update for.
 */
inline void CycleSignalSide(Tile t, Track track)
{
	uint8_t sig;
	uint8_t pos = (track == Track::Lower || track == Track::Right) ? 4 : 6;

	sig = GB(t.m3(), pos, 2);
	if (--sig == 0) sig = IsPbsSignal(GetSignalType(t, track)) ? 2 : 3;
	SB(t.m3(), pos, 2, sig);
}

/**
 * Get the signal variant for a track on a tile.
 * In horizontal and vertical orientation there may be two tracks on a tile with a signal.
 * @param t The tile to query.
 * @param track The track to query for.
 * @return The signal variant.
 */
inline SignalVariant GetSignalVariant(Tile t, Track track)
{
	uint8_t pos = (track == Track::Lower || track == Track::Right) ? 7 : 3;
	return static_cast<SignalVariant>(GB(t.m2(), pos, 1));
}

/**
 * Set the signal variant for a track on a tile.
 * In horizontal and vertical orientation there may be two tracks on a tile with a signal.
 * @param t The tile to update.
 * @param track The track to update for.
 * @param v The new signal variant.
 */
inline void SetSignalVariant(Tile t, Track track, SignalVariant v)
{
	uint8_t pos = (track == Track::Lower || track == Track::Right) ? 7 : 3;
	SB(t.m2(), pos, 1, to_underlying(v));
	if (!IsValidTrack(track)) SB(t.m2(), 7, 1, to_underlying(v));
}

/**
 * Set the states of the signals (Along/AgainstTrackDir)
 * @param tile  the tile to set the states for
 * @param state the new state
 */
inline void SetSignalStates(Tile tile, uint state)
{
	SB(tile.m4(), 4, 4, state);
}

/**
 * Set the states of the signals (Along/AgainstTrackDir)
 * @param tile  the tile to set the states for
 * @return the state of the signals
 */
inline uint GetSignalStates(Tile tile)
{
	return GB(tile.m4(), 4, 4);
}

/**
 * Get the state of a single signal
 * @param t         the tile to get the signal state for
 * @param signalbit the signal
 * @return the state of the signal
 */
inline SignalState GetSingleSignalState(Tile t, uint8_t signalbit)
{
	return static_cast<SignalState>(HasBit(GetSignalStates(t), signalbit));
}

/**
 * Set whether the given signals are present (Along/AgainstTrackDir)
 * @param tile    the tile to set the present signals for
 * @param signals the signals that have to be present
 */
inline void SetPresentSignals(Tile tile, uint signals)
{
	SB(tile.m3(), 4, 4, signals);
}

/**
 * Get whether the given signals are present (Along/AgainstTrackDir)
 * @param tile the tile to get the present signals for
 * @return the signals that are present
 */
inline uint GetPresentSignals(Tile tile)
{
	return GB(tile.m3(), 4, 4);
}

/**
 * Checks whether the given signals is present
 * @param t         the tile to check on
 * @param signalbit the signal
 * @return true if and only if the signal is present
 */
inline bool IsSignalPresent(Tile t, uint8_t signalbit)
{
	return HasBit(GetPresentSignals(t), signalbit);
}

/**
 * Checks for the presence of signals (either way) on the given track on the
 * given rail tile.
 * @param tile The tile to query.
 * @param track The track to query for.
 * @return \c true iff there is a signal in any direction.
 */
inline bool HasSignalOnTrack(Tile tile, Track track)
{
	assert(IsValidTrack(track));
	return GetRailTileType(tile) == RailTileType::Signals && (GetPresentSignals(tile) & SignalOnTrack(track)) != 0;
}

/**
 * Checks for the presence of signals along the given trackdir on the given
 * rail tile.
 *
 * Along meaning if you are currently driving on the given trackdir, this is
 * the signal that is facing us (for which we stop when it's red).
 * @param tile The tile to query.
 * @param trackdir The trackdir to query for.
 * @return \c true iff there is a signal in the given direction.
 */
inline bool HasSignalOnTrackdir(Tile tile, Trackdir trackdir)
{
	assert (IsValidTrackdir(trackdir));
	return GetRailTileType(tile) == RailTileType::Signals && GetPresentSignals(tile) & SignalAlongTrackdir(trackdir);
}

/**
 * Gets the state of the signal along the given trackdir.
 *
 * Along meaning if you are currently driving on the given trackdir, this is
 * the signal that is facing us (for which we stop when it's red).
 * @param tile The tile to query.
 * @param trackdir The trackdir to query for.
 * @return The signal state for the given trackdir.
 */
inline SignalState GetSignalStateByTrackdir(Tile tile, Trackdir trackdir)
{
	assert(IsValidTrackdir(trackdir));
	assert(HasSignalOnTrack(tile, TrackdirToTrack(trackdir)));
	return GetSignalStates(tile) & SignalAlongTrackdir(trackdir) ?
		SignalState::Green : SignalState::Red;
}

/**
 * Sets the state of the signal along the given trackdir.
 * @param tile The tile to update.
 * @param trackdir The trackdir to update for.
 * @param state The new signal state.
 */
inline void SetSignalStateByTrackdir(Tile tile, Trackdir trackdir, SignalState state)
{
	if (state == SignalState::Green) { // set 1
		SetSignalStates(tile, GetSignalStates(tile) | SignalAlongTrackdir(trackdir));
	} else {
		SetSignalStates(tile, GetSignalStates(tile) & ~SignalAlongTrackdir(trackdir));
	}
}

/**
 * Is a pbs signal present along the trackdir?
 * @param tile the tile to check
 * @param td the trackdir to check
 * @return \c true iff there is a path based signal on the trackdir.
 */
inline bool HasPbsSignalOnTrackdir(Tile tile, Trackdir td)
{
	return IsTileType(tile, TileType::Railway) && HasSignalOnTrackdir(tile, td) &&
			IsPbsSignal(GetSignalType(tile, TrackdirToTrack(td)));
}

/**
 * Is a one-way signal blocking the trackdir? A one-way signal on the
 * trackdir against will block, but signals on both trackdirs won't.
 * @param tile the tile to check
 * @param td the trackdir to check
 * @return \c true iff a one way signals blocks the trackdir.
 */
inline bool HasOnewaySignalBlockingTrackdir(Tile tile, Trackdir td)
{
	return IsTileType(tile, TileType::Railway) && HasSignalOnTrackdir(tile, ReverseTrackdir(td)) &&
			!HasSignalOnTrackdir(tile, td) && IsOnewaySignal(tile, TrackdirToTrack(td));
}

/**
 * Check whether a block signal is present along the trackdir.
 * @param tile The tile to check.
 * @param td The trackdir to check.
 * @return \c true iff a block signal present along the trackdir.
 */
inline bool HasBlockSignalOnTrackdir(Tile tile, Trackdir td)
{
	return IsTileType(tile, TileType::Railway) && HasSignalOnTrackdir(tile, td) &&
		!IsPbsSignal(GetSignalType(tile, TrackdirToTrack(td)));
}

RailType GetTileRailType(Tile tile);

/** The ground 'under' the rail */
enum class RailGroundType : uint8_t {
	Barren = 0, ///< Nothing (dirt)
	Grass = 1, ///< Grassy
	FenceNW = 2, ///< Grass with a fence at the NW edge
	FenceSE = 3, ///< Grass with a fence at the SE edge
	FenceSENW = 4, ///< Grass with a fence at the NW and SE edges
	FenceNE = 5, ///< Grass with a fence at the NE edge
	FenceSW = 6, ///< Grass with a fence at the SW edge
	FenceNESW = 7, ///< Grass with a fence at the NE and SW edges
	FenceVert1 = 8, ///< Grass with a fence at the eastern side
	FenceVert2 = 9, ///< Grass with a fence at the western side
	FenceHoriz1 = 10, ///< Grass with a fence at the southern side
	FenceHoriz2 = 11, ///< Grass with a fence at the northern side
	SnowOrDesert = 12, ///< Icy or sandy
	HalfTileWater = 13, ///< Grass with a fence and shore or water on the free halftile
	HalfTileSnow = 14, ///< Snow only on higher part of slope (steep or one corner raised)
};

/**
 * Set the ground type for rail tiles.
 * @param t The tile to update.
 * @param rgt The new ground type.
 */
inline void SetRailGroundType(Tile t, RailGroundType rgt)
{
	SB(t.m4(), 0, 4, to_underlying(rgt));
}

/**
 * Get the ground type for rail tiles.
 * @param t The tile to query.
 * @return The ground type.
 */
inline RailGroundType GetRailGroundType(Tile t)
{
	return static_cast<RailGroundType>(GB(t.m4(), 0, 4));
}

/**
 * Is the given rail tile snowy or deserty.
 * @param t The tile to query.
 * @return \c true iff the tile is snowy or deserty.
 */
inline bool IsSnowOrDesertRailGround(Tile t)
{
	return GetRailGroundType(t) == RailGroundType::SnowOrDesert;
}


/**
 * Make the given tile a normal rail.
 * @param t The tile to convert.
 * @param o The new owner.
 * @param b The bits/tracks to set.
 * @param r The new rail type.
 */
inline void MakeRailNormal(Tile t, Owner o, TrackBits b, RailType r)
{
	SetTileType(t, TileType::Railway);
	SetTileOwner(t, o);
	SetDockingTile(t, false);
	t.m2() = 0;
	t.m3() = 0;
	t.m4() = 0;
	t.m5() = to_underlying(RailTileType::Normal) << 6 | b.base();
	SB(t.m6(), 2, 6, 0);
	t.m7() = 0;
	t.m8() = r;
}

/**
 * Sets the exit direction of a rail depot.
 * @param tile Tile of the depot.
 * @param dir  Direction of the depot exit.
 */
inline void SetRailDepotExitDirection(Tile tile, DiagDirection dir)
{
	assert(IsRailDepotTile(tile));
	SB(tile.m5(), 0, 2, to_underlying(dir));
}

/**
 * Make a rail depot.
 * @param tile      Tile to make a depot on.
 * @param owner     New owner of the depot.
 * @param depot_id  New depot ID.
 * @param dir       Direction of the depot exit.
 * @param rail_type Rail type of the depot.
 */
inline void MakeRailDepot(Tile tile, Owner owner, DepotID depot_id, DiagDirection dir, RailType rail_type)
{
	SetTileType(tile, TileType::Railway);
	SetTileOwner(tile, owner);
	SetDockingTile(tile, false);
	tile.m2() = depot_id.base();
	tile.m3() = 0;
	tile.m4() = 0;
	tile.m5() = to_underlying(RailTileType::Depot) << 6 | to_underlying(dir);
	SB(tile.m6(), 2, 6, 0);
	tile.m7() = 0;
	tile.m8() = rail_type;
}

#endif /* RAIL_MAP_H */
