city-generation/Game/Assets/Scripts/Model/Road/RoadSegment.cs
2015-06-17 14:06:54 +03:00

128 lines
3.4 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using TransportGame.Primitives;
namespace TransportGame.Model.Road
{
/// <summary>
/// Represents a road segment
/// </summary>
[XmlRoot("segment")]
public class RoadSegment
{
/// <summary>
/// Gets or sets the id
/// </summary>
[XmlAttribute("id")]
public int Id { get; set; }
/// <summary>
/// Gets or sets the parent network
/// </summary>
[XmlIgnore]
public RoadNetwork ParentNetwork { get; set; }
/// <summary>
/// Gets or sets the id of the first terminal
/// </summary>
[XmlAttribute("term1")]
public int Terminal1Id { get; set; }
/// <summary>
/// Gets or sets the id of the second terminal
/// </summary>
[XmlAttribute("term2")]
public int Terminal2Id { get; set; }
/// <summary>
/// Gets or sets the first terminal
/// </summary>
[XmlIgnore]
public RoadNode Terminal1
{
get
{
return (Terminal1Id == -1) ? null : ParentNetwork.Nodes[Terminal1Id];
}
set
{
Terminal1Id = (value == null) ? -1 : value.Id;
}
}
/// <summary>
/// Gets or sets the second terminal
/// </summary>
[XmlIgnore]
public RoadNode Terminal2
{
get
{
return (Terminal2Id == -1) ? null : ParentNetwork.Nodes[Terminal2Id];
}
set
{
Terminal2Id = (value == null) ? -1 : value.Id;
}
}
/// <summary>
/// Gets or sets the number of lanes going from terminal 1 to terminal 2
/// </summary>
[XmlAttribute("lanesTo2")]
public int LanesTo2 { get; set; }
/// <summary>
/// Gets or sets the number of lanes going form terminal 2 to terminal 1
/// </summary>
[XmlAttribute("lanesTo1")]
public int LanesTo1 { get; set; }
/// <summary>
/// Gets the direction vector of this road segment
/// </summary>
[XmlIgnore]
public Vector2 Direction
{
get
{
if (Terminal1Id == -1 || Terminal2Id == -1 || ParentNetwork == null)
return Vector2.Zero;
return (Terminal2.Position - Terminal1.Position).Normalized;
}
}
/// <summary>
/// Gets the road segment as a line segment
/// </summary>
/// <returns></returns>
public LineSegment AsLineSegment()
{
if (Terminal1Id == -1 || Terminal2Id == -1 || ParentNetwork == null)
throw new InvalidOperationException("Terminals are not initialized.");
return new LineSegment(Terminal1.Position, Terminal2.Position);
}
/// <summary>
/// Initializes road segment
/// </summary>
public RoadSegment()
{
LanesTo1 = 1;
LanesTo2 = 1;
Terminal1Id = -1;
Terminal2Id = -1;
}
public override string ToString()
{
return string.Format("(segment id={0}, {1}->{2})", Id, Terminal1, Terminal2);
}
}
}