[Fork] Getting corners of a defined shape (without CanMove)

CSharp · Console

/Program.cs

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Net;
using System.Linq;
using System.IO;
using System.Xml.Serialization;
using Newtonsoft.Json;
using Color = zenthion.Color;
using Point = zenthion.Point;

public class Program
{
	public static void Main()
	{
		string imageStr = "",
			   pointsStr = "";
		
		string url = "https://pastebin.com/raw/29MQJ7LT", // "https://pastebin.com/raw/77iz85Uq",
			   dataUrl = "https://pastebin.com/raw/XC3RrV1V";
		
		using (var webClient = new WebClient()) {
			imageStr = webClient.DownloadString(url);
			pointsStr = webClient.DownloadString(dataUrl);
		}
		
		pointsStr = pointsStr.Base64Decode().Replace(@" encoding=""utf-16""", "");
		
		// Console.WriteLine(pointsStr);
		
		Point[] points = pointsStr.Deserialize<HashSet<Point>>().ToArray();
		
		
		int width = imageStr.IndexOf(Environment.NewLine);
		
		imageStr = imageStr.Replace(Environment.NewLine, "");
		
		int height = imageStr.Length / width;
		
		//Console.WriteLine(imageStr.Length);
		//Console.WriteLine("({0}, {1})", width, height);
		
		Stopwatch sw = Stopwatch.StartNew();
		
		string source = (string)imageStr.Clone(),
			   target = (string)imageStr.Clone();
		
		IterateBuild(points, source, ref target, width);
	
		// target = target.ReplaceAt(F.P(0, 0, width, 0), 'v');
		
		Print(target.ToCharArray(), (c) => c.ToString(), width);
		
		// Console.WriteLine(imageColors[0]);
		
		sw.Stop();
		
		Console.WriteLine("Ellapsed: {0} s", (sw.ElapsedMilliseconds / 1000f).ToString("F2"));
	}

	public static void IterateBuild(Point[] points, string source, ref string target, int width, bool drawEdges = false)
	{
		
		// source.Select((x, i) => x == '2' ? new Point(i % width, i / width) : Point.zero).Where(x => x != Point.zero)
		HashSet<Point> edges = new HashSet<Point>();
		
		int k = 0;
		if(drawEdges)
			foreach(Point p in points)
			{
				target = target.ReplaceAt(F.P(p.x, p.y, width, 0), '2');

				++k;
			}
		
		//Console.WriteLine("K: "+k);

		Point[] corners = new Point[] { Point.upperLeft, Point.upperRight, Point.downLeft, Point.downRight },
			sides = new Point[] { Point.left, Point.up, Point.right, Point.down };
			
		float mean = 0;
		int meanElements = 0;
		
		Point actualCorner = points[points.Length - 1], // We get the actual corner (it be always the last point we found)
			  lastPoint = points[points.Length - 1]; // The last point will always be the previous to the actual (we will start 0)
		
		// target = target.ReplaceAt(F.P(actualCorner.x, actualCorner.y, width, 0), '☐');
		
		Dictionary<Point, float> slopes = new Dictionary<Point, float>();
		
		int j = 0;
         for (int i = 0; i < points.Length - 2; ++i)
         {
			 // This is the current point
			 Point p = points[i];
			
			 target = target.ReplaceAt(F.P(p.x, p.y, width, 0), '□');
			 
			 // If the current pixel is in the upper, left, down or right side of the last we aren't interesed on save the slope
			 if(sides.Contains(p - lastPoint))
				 continue;
			 
			 // This is the actual slope
			 float actSlope = p.GetSlope(actualCorner);
			 
			 // This will store the slopes of every point respect the lastCorner
			 slopes.Add(p, actSlope);
			 
			 mean = mean.AddToMean(actSlope, ref meanElements);
			 
			 target = target.ReplaceAt(F.P(p.x, p.y, width, 0), '■');
			 
			 if(j > 0 && j == 49) 
			 {
				 Console.WriteLine("I: {0}", i);
			 	 Console.WriteLine("Actual Slope: {0}", actSlope);
				 Console.WriteLine("Mean: {0}", mean);
				 
				 target = target.ReplaceAt(F.P(p.x, p.y, width, 0), '✖');
			 }
			 
			 // actSlope = p.GetMean(lastPoint);
			 
			 //if(i == 4) 
			 //{
				 // Console.WriteLine(actualCorner.GetMean(p));
				 
			 //}
			 
			 lastPoint = p;
			 
			 ++j;
		 }
		
		// Console.WriteLine(j);
	

	}

	private static void Print<T>(T[] objs, Func<T, string> result, int splitEvery = 10)
	{
		int i = 1;
		foreach (T item in objs)
		{
			Console.Write(result == null ? (object)item : (object)result(item));
			if (i % splitEvery == 0)
				Console.WriteLine();
			++i;
		}
	}

	private static string ColorString(Color color)
	{
		if (color == Color.black)
			return "0";
		else if (color == Color.white)
			return "1";
		else if (color == Color.blue)
			return "2";
		else if (color == Color.green)
			return "3";
		
		return "x";
	}
}

/// <summary>
/// Enum Direction
/// </summary>
public enum InnerDirection
{
	/// <summary>
	/// Up
	/// </summary>
	up,
	/// <summary>
	/// The right
	/// </summary>
	right,
	/// <summary>
	/// Down
	/// </summary>
	down,
	/// <summary>
	/// The left
	/// </summary>
	left
}

/// <summary>
/// Class Dirs.
/// </summary>
public class InnerDirs
{
	private const int dirLength = 4;
	/// <summary>
	/// Gets the perpendicular.
	/// </summary>
	/// <param name = "dir">The dir.</param>
	/// <returns>Direction.</returns>
	public static InnerDirection GetPerpendicular(InnerDirection dir, bool inverse = false)
	{
		// left ==> up
		// down ==> left ...
		return GetDir(dir, inverse ? -1 : 1);
	}

	public static InnerDirection GetInverse(InnerDirection dir, bool inverse = false)
	{
		// down ==> up
		// right ==> left
		return GetDir(dir, inverse ? -2 : 2);
	}

	private static InnerDirection GetDir(InnerDirection dir, int n)
	{
		int v = (int)dir + n;
		if (v < 0)
			v += dirLength;
		else if (v >= dirLength)
			v -= dirLength;
		return (InnerDirection)v;
	}
}

public static class F
{
	private static int BmpStride = 0;
	public static IEnumerable<Color> ToColor(this Bitmap bmp)
	{
		Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
		BitmapData bmpData = bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, bmp.PixelFormat);
		IntPtr ptr = bmpData.Scan0;
		int bytes = bmpData.Stride * bmp.Height;
		byte[] rgbValues = new byte[bytes];
		// Copy the RGB values into the array.
		Marshal.Copy(ptr, rgbValues, 0, bytes);
		BmpStride = bmpData.Stride;
		for (int column = 0; column < bmpData.Height; column++)
		{
			for (int row = 0; row < bmpData.Width; row++)
			{
				// Little endian
				byte b = (byte)(rgbValues[(column * BmpStride) + (row * 4)]);
				byte g = (byte)(rgbValues[(column * BmpStride) + (row * 4) + 1]);
				byte r = (byte)(rgbValues[(column * BmpStride) + (row * 4) + 2]);
				yield return new Color(r, g, b, 255);
			}
		}

		// Unlock the bits.
		bmp.UnlockBits(bmpData);
	}

	public static void SaveBitmap(this Color[] bmp, int width, int height, string path)
	{
		int stride = BmpStride;
		byte[] rgbValues = new byte[BmpStride * height];
		for (int column = 0; column < height; column++)
		{
			for (int row = 0; row < width; row++)
			{
				int i = Pn(row, column, width);
				// Little endian
				rgbValues[(column * BmpStride) + (row * 4)] = bmp[i].b;
				rgbValues[(column * BmpStride) + (row * 4) + 1] = bmp[i].g;
				rgbValues[(column * BmpStride) + (row * 4) + 2] = bmp[i].r;
				rgbValues[(column * BmpStride) + (row * 4) + 3] = bmp[i].a;
			}
		}

		using (Bitmap image = new Bitmap(width, height, width * 4, PixelFormat.Format32bppArgb, Marshal.UnsafeAddrOfPinnedArrayElement(rgbValues, 0)))
		{
			image.Save(path);
		}
	}

	public static int Pn(int x, int y, int w)
	{
		return x + (y * w);
	}

	public static int P(int x, int y, int w, int h)
	{
		// return x + ((h - y - 1) * w);
		return x + (y * w);
	}

    public static string ReplaceAt(this string value, int index, char newchar)
    {
        if (value.Length <= index)
            return value;
        else
            return string.Concat(value.Select((c, i) => i == index ? newchar : c));
    }
	
	public static float GetSlope(this Point p1, Point p2) 
	{
		// Console.WriteLine(p1);
		// Console.WriteLine(p2);
		
		return (float)(p2.y - p1.y) / (p2.x - p1.x);
	}
	
	        public static string Base64Encode(this string plainText)
        {
            var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
            return System.Convert.ToBase64String(plainTextBytes);
        }

        public static string Base64Decode(this string base64EncodedData)
        {
            var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
            return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
        }
	
	public static float AddToMean(this float mean, float newEl, ref int curElements) 
	{
		return (mean + newEl) / (++curElements);
	}
}

public static class Mathf
{
	public static T Clamp<T>(this T val, T min, T max)where T : IComparable<T>
	{
		if (val.CompareTo(min) < 0)
			return min;
		else if (val.CompareTo(max) > 0)
			return max;
		else
			return val;
	}

	// Interpolates between /a/ and /b/ by /t/. /t/ is clamped between 0 and 1.
	public static float Lerp(float a, float b, float t)
	{
		return a + (b - a) * Clamp01(t);
	}

	// Clamps value between 0 and 1 and returns value
	public static float Clamp01(float value)
	{
		if (value < 0F)
			return 0F;
		else if (value > 1F)
			return 1F;
		else
			return value;
	}
}

namespace zenthion
{
	/// <summary>
	/// Struct Color
	/// </summary>
	/// <seealso cref = "System.ICloneable"/>
	[Serializable]
	public struct Color : ICloneable
	{
		/// <summary>
		/// Clones this instance.
		/// </summary>
		/// <returns>System.Object.</returns>
		public object Clone()
		{
			return MemberwiseClone();
		}

		/// <summary>
		/// The r
		/// </summary>
		public byte r, g, b, a;
		/// <summary>
		/// Gets the white.
		/// </summary>
		/// <value>The white.</value>
		public static Color white
		{
			get
			{
				return new Color(255, 255, 255);
			}
		}

		/// <summary>
		/// Gets the red.
		/// </summary>
		/// <value>The red.</value>
		public static Color red
		{
			get
			{
				return new Color(255, 0, 0);
			}
		}

		/// <summary>
		/// Gets the green.
		/// </summary>
		/// <value>The green.</value>
		public static Color green
		{
			get
			{
				return new Color(0, 255, 0);
			}
		}

		/// <summary>
		/// Gets the blue.
		/// </summary>
		/// <value>The blue.</value>
		public static Color blue
		{
			get
			{
				return new Color(0, 0, 255);
			}
		}

		/// <summary>
		/// Gets the yellow.
		/// </summary>
		/// <value>The yellow.</value>
		public static Color yellow
		{
			get
			{
				return new Color(255, 255, 0);
			}
		}

		/// <summary>
		/// Gets the gray.
		/// </summary>
		/// <value>The gray.</value>
		public static Color gray
		{
			get
			{
				return new Color(128, 128, 128);
			}
		}

		/// <summary>
		/// Gets the black.
		/// </summary>
		/// <value>The black.</value>
		public static Color black
		{
			get
			{
				return new Color(0, 0, 0);
			}
		}

		/// <summary>
		/// Gets the transparent.
		/// </summary>
		/// <value>The transparent.</value>
		public static Color transparent
		{
			get
			{
				unchecked
				{
					return new Color(0, 0, 0, 0);
				}
			}
		}

		/// <summary>
		/// Initializes a new instance of the <see cref = "Color"/> struct.
		/// </summary>
		/// <param name = "r">The r.</param>
		/// <param name = "g">The g.</param>
		/// <param name = "b">The b.</param>
		public Color(byte r, byte g, byte b)
		{
			this.r = r;
			this.g = g;
			this.b = b;
			a = byte.MaxValue;
		}

		/// <summary>
		/// Initializes a new instance of the <see cref = "Color"/> struct.
		/// </summary>
		/// <param name = "r">The r.</param>
		/// <param name = "g">The g.</param>
		/// <param name = "b">The b.</param>
		/// <param name = "a">a.</param>
		public Color(byte r, byte g, byte b, byte a)
		{
			this.r = r;
			this.g = g;
			this.b = b;
			this.a = a;
		}

		/// <summary>
		/// Implements the ==.
		/// </summary>
		/// <param name = "c1">The c1.</param>
		/// <param name = "c2">The c2.</param>
		/// <returns>The result of the operator.</returns>
		public static bool operator ==(Color c1, Color c2)
		{
			return c1.r == c2.r && c1.g == c2.g && c1.b == c2.b && c1.a == c2.a;
		}

		/// <summary>
		/// Implements the !=.
		/// </summary>
		/// <param name = "c1">The c1.</param>
		/// <param name = "c2">The c2.</param>
		/// <returns>The result of the operator.</returns>
		public static bool operator !=(Color c1, Color c2)
		{
			return !(c1.r == c2.r && c1.g == c2.g && c1.b == c2.b && c1.a == c2.a);
		}

		/// <summary>
		/// Returns a hash code for this instance.
		/// </summary>
		/// <returns>A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.</returns>
		public override int GetHashCode()
		{
			return base.GetHashCode();
		}

		/// <summary>
		/// Determines whether the specified <see cref = "System.Object"/> is equal to this instance.
		/// </summary>
		/// <param name = "obj">The <see cref = "System.Object"/> to compare with this instance.</param>
		/// <returns><c>true</c> if the specified <see cref = "System.Object"/> is equal to this instance; otherwise, <c>false</c>.</returns>
		public override bool Equals(object obj)
		{
			Color c = (Color)obj;
			return r == c.r && g == c.g && b == c.b;
		}

		/// <summary>
		/// Implements the -.
		/// </summary>
		/// <param name = "c1">The c1.</param>
		/// <param name = "c2">The c2.</param>
		/// <returns>The result of the operator.</returns>
		public static Color operator -(Color c1, Color c2)
		{
			return new Color((byte)Mathf.Clamp(c1.r - c2.r, 0, 255), (byte)Mathf.Clamp(c2.g - c2.g, 0, 255), (byte)Mathf.Clamp(c2.b - c2.b, 0, 255));
		}

		/// <summary>
		/// Implements the +.
		/// </summary>
		/// <param name = "c1">The c1.</param>
		/// <param name = "c2">The c2.</param>
		/// <returns>The result of the operator.</returns>
		public static Color operator +(Color c1, Color c2)
		{
			return new Color((byte)Mathf.Clamp(c1.r + c2.r, 0, 255), (byte)Mathf.Clamp(c2.g + c2.g, 0, 255), (byte)Mathf.Clamp(c2.b + c2.b, 0, 255));
		}

		/// <summary>
		/// Lerps the specified c2.
		/// </summary>
		/// <param name = "c2">The c2.</param>
		/// <param name = "t">The t.</param>
		/// <returns>Color.</returns>
		public Color Lerp(Color c2, float t)
		{
			return new Color((byte)Mathf.Lerp(r, c2.r, t), (byte)Mathf.Lerp(g, c2.g, t), (byte)Mathf.Lerp(b, c2.b, t));
		}

		/// <summary>
		/// Inverts this instance.
		/// </summary>
		/// <returns>Color.</returns>
		public Color Invert()
		{
			return new Color((byte)Mathf.Clamp(byte.MaxValue - r, 0, 255), (byte)Mathf.Clamp(byte.MaxValue - g, 0, 255), (byte)Mathf.Clamp(byte.MaxValue - b, 0, 255));
		}

		/// <summary>
		/// Returns a <see cref = "System.String"/> that represents this instance.
		/// </summary>
		/// <returns>A <see cref = "System.String"/> that represents this instance.</returns>
		public override string ToString()
		{
			if (this == white)
				return "white";
			else if (this == transparent)
				return "transparent";
			else if (this == red)
				return "red";
			else if (this == blue)
				return "blue";
			else if (this == black)
				return "black";
			else if (this == green)
				return "green";
			else if (this == yellow)
				return "yellow";
			else
				return string.Format("({0}, {1}, {2}, {3})", r, g, b, a);
		}

		/// <summary>
		/// Fills the specified x.
		/// </summary>
		/// <param name = "x">The x.</param>
		/// <param name = "y">The y.</param>
		/// <returns>Color[].</returns>
		public static IEnumerable<Color> Fill(int x, int y)
		{
			for (int i = 0; i < x * y; ++i)
				yield return black;
		}
	}
	
	    /// <summary>
    /// Struct Point
    /// </summary>
    [Serializable]
    public struct Point : ICloneable
    {
        /// <summary>
        /// The x
        /// </summary>
        public int x, y;

        /// <summary>
        /// Gets the zero.
        /// </summary>
        /// <value>The zero.</value>
        public static Point zero
        {
            get
            {
                return new Point(0, 0);
            }
        }

        /// <summary>
        /// Gets down.
        /// </summary>
        /// <value>Down.</value>
        public static Point down
        {
            get
            {
                return new Point(0, -1);
            }
        }

        /// <summary>
        /// Gets the left.
        /// </summary>
        /// <value>The left.</value>
        public static Point left
        {
            get
            {
                return new Point(-1, 0);
            }
        }

        /// <summary>
        /// Gets the right.
        /// </summary>
        /// <value>The right.</value>
        public static Point right
        {
            get
            {
                return new Point(1, 0);
            }
        }

        /// <summary>
        /// Gets up.
        /// </summary>
        /// <value>Up.</value>
        public static Point up
        {
            get
            {
                return new Point(0, 1);
            }
        }

        /// <summary>
        /// Gets the upper left.
        /// </summary>
        /// <value>The upper left.</value>
        public static Point upperLeft
        {
            get
            {
                return new Point(-1, 1);
            }
        }

        /// <summary>
        /// Gets the upper right.
        /// </summary>
        /// <value>The upper right.</value>
        public static Point upperRight
        {
            get
            {
                return new Point(1, 1);
            }
        }

        /// <summary>
        /// Gets down left.
        /// </summary>
        /// <value>Down left.</value>
        public static Point downLeft
        {
            get
            {
                return new Point(-1, -1);
            }
        }

        /// <summary>
        /// Gets down right.
        /// </summary>
        /// <value>Down right.</value>
        public static Point downRight
        {
            get
            {
                return new Point(1, -1);
            }
        }

        /// <summary>
        /// Gets the name.
        /// </summary>
        /// <value>The name.</value>
        public string name
        {
            get
            {
                return GetName();
            }
        }

        /// <summary>
        /// Gets the SQR magnitude.
        /// </summary>
        /// <value>The SQR magnitude.</value>
        public float sqrMagnitude
        {
            get
            {
                return x * x + y * y;
            }
        }

        /// <summary>
        /// Gets the magnitude.
        /// </summary>
        /// <value>The magnitude.</value>
        public float magnitude
        {
            get
            {
                return (float)Math.Sqrt(sqrMagnitude);
            }
        }

        /// <summary>
        /// Gets the normalized.
        /// </summary>
        /// <value>The normalized.</value>
        public Point normalized
        {
            get
            {
                return new Point((int)Mathf.Clamp01(x), (int)Mathf.Clamp01(y));
            }
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="Point"/> struct.
        /// </summary>
        /// <param name="x">The x.</param>
        /// <param name="y">The y.</param>
        public Point(int x, int y)
        {
            this.x = x;
            this.y = y;
        }

        /// <summary>
        /// Implements the +.
        /// </summary>
        /// <param name="a">a.</param>
        /// <param name="b">The b.</param>
        /// <returns>The result of the operator.</returns>
        public static Point operator +(Point a, Point b)
        {
            return new Point(a.x + b.x, a.y + b.y);
        }

        /// <summary>
        /// Implements the -.
        /// </summary>
        /// <param name="a">a.</param>
        /// <param name="b">The b.</param>
        /// <returns>The result of the operator.</returns>
        public static Point operator -(Point a, Point b)
        {
            return new Point(a.x - b.x, a.y - b.y);
        }

        /// <summary>
        /// Implements the *.
        /// </summary>
        /// <param name="a">a.</param>
        /// <param name="b">The b.</param>
        /// <returns>The result of the operator.</returns>
        public static Point operator *(Point a, Point b)
        {
            return new Point(a.x * b.x, a.y * b.y);
        }

        /// <summary>
        /// Implements the /.
        /// </summary>
        /// <param name="a">a.</param>
        /// <param name="b">The b.</param>
        /// <returns>The result of the operator.</returns>
        public static Point operator /(Point a, Point b)
        {
            return new Point(a.x / b.x, a.y / b.y);
        }

        /// <summary>
        /// Implements the *.
        /// </summary>
        /// <param name="a">a.</param>
        /// <param name="b">The b.</param>
        /// <returns>The result of the operator.</returns>
        public static Point operator *(Point a, int b)
        {
            return new Point(a.x * b, a.y * b);
        }

        /// <summary>
        /// Implements the /.
        /// </summary>
        /// <param name="a">a.</param>
        /// <param name="b">The b.</param>
        /// <returns>The result of the operator.</returns>
        public static Point operator /(Point a, int b)
        {
            return new Point(a.x / b, a.y / b);
        }

        /// <summary>
        /// Returns a <see cref="System.String" /> that represents this instance.
        /// </summary>
        /// <returns>A <see cref="System.String" /> that represents this instance.</returns>
        public override string ToString()
        {
            return string.Format("({0}, {1})", x, y);
        }

        /// <summary>
        /// Implements the ==.
        /// </summary>
        /// <param name="p1">The p1.</param>
        /// <param name="p2">The p2.</param>
        /// <returns>The result of the operator.</returns>
        public static bool operator ==(Point p1, Point p2)
        {
            return p1.x == p2.x && p1.y == p2.y;
        }

        /// <summary>
        /// Implements the !=.
        /// </summary>
        /// <param name="p1">The p1.</param>
        /// <param name="p2">The p2.</param>
        /// <returns>The result of the operator.</returns>
        public static bool operator !=(Point p1, Point p2)
        {
            return p1.x != p2.x || p1.y != p2.y;
        }

        /// <summary>
        /// Determines whether the specified <see cref="System.Object" /> is equal to this instance.
        /// </summary>
        /// <param name="obj">The <see cref="System.Object" /> to compare with this instance.</param>
        /// <returns><c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; otherwise, <c>false</c>.</returns>
        public override bool Equals(object obj)
        {
            Point p = (Point)obj;
            return x == p.x && y == p.y;
        }

        /// <summary>
        /// Returns a hash code for this instance.
        /// </summary>
        /// <returns>A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.</returns>
        public override int GetHashCode()
        {
            return base.GetHashCode();
        }

        private string GetName()
        {
            if (this == upperLeft)
                return "upperLeft";
            else if (this == up)
                return "up";
            else if (this == upperRight)
                return "upperRight";
            else if (this == left)
                return "left";
            else if (this == right)
                return "right";
            else if (this == downLeft)
                return "downLeft";
            else if (this == down)
                return "down";
            else if (this == downRight)
                return "downRight";
            else if (this == zero)
                return "center";
            else
                return "none";
        }

        /// <summary>
        /// Gets the point.
        /// </summary>
        /// <param name="dir">The dir.</param>
        /// <returns>Point.</returns>
        public Point GetInnerPoint(InnerDirection dir)
        {
            switch (dir)
            {
                case InnerDirection.up:
                    return up;

                case InnerDirection.right:
                    return right;

                case InnerDirection.down:
                    return down;

                case InnerDirection.left:
                    return left;
            }

            return zero;
        }

        /// <summary>
        /// News the position.
        /// </summary>
        /// <param name="dir">The dir.</param>
        /// <returns>Point.</returns>
        public Point NewInnerPos(InnerDirection dir)
        {
            return this + GetInnerPoint(dir);
        }

        public Point NextDirection(ref InnerDirection lastDirection)
        {
            lastDirection = InnerDirs.GetPerpendicular(lastDirection);
            return GetInnerPoint(lastDirection);
        }

        public object Clone()
        {
            return MemberwiseClone();
        }
    }
}

    public static class SerializerHelper
    {
        public static string Serialize<T>(this T data, SerializeFormat format = SerializeFormat.JSON)
        {
            switch (format)
            {
                case SerializeFormat.XML:
                    return SerializeToXml(data);

                case SerializeFormat.JSON:
                    return SerializeToJson(data);

                default:
                    return string.Empty;
            }
        }

        public static T Deserialize<T>(this string data, SerializeFormat format = SerializeFormat.JSON)
        {
            switch (format)
            {
                case SerializeFormat.XML:
                    return DeserializeToXml<T>(data);

                case SerializeFormat.JSON:
                    return DeserializeFromJson<T>(data);

                default:
                    return default(T);
            }
        }

        /*public static string SerializeToXml<T>(T data)
        {
            var serializer = new DataContractSerializer(data.GetType());
            var builder = new StringBuilder();
            var writer = XmlWriter.Create(builder);
            serializer.WriteObject(writer, data);
            writer.Flush();
            return builder.ToString();
        }*/

        private static string SerializeToXml<T>(T data)
        {
            var xmlSerializer = new XmlSerializer(typeof(T));
            // xmlSerializer.WriteProcessingInstruction("xml", "version='1.0'");

            using (var stringWriter = new StringWriter())
            {
                xmlSerializer.Serialize(stringWriter, data);
                return stringWriter.ToString();
            }
        }

        /*public static T DeserializeToXml<T>(string data)
        {
            var serializer = new DataContractSerializer(data.GetType());
            var writer = XmlReader.Create(GenerateStreamFromString(data));
            var result = serializer.ReadObject(writer);
            return (T)result;
        }*/

        private static T DeserializeToXml<T>(string data)
        {
            try
            {
				XmlRootAttribute xRoot = new XmlRootAttribute();
				xRoot.ElementName = "ArrayOfPoint";
				xRoot.IsNullable = true;
				
                var xmlSerializer = new XmlSerializer(data.GetType(), xRoot);
                using (var stream = GenerateStreamFromString(data))
                {
                    var result = xmlSerializer.Deserialize(stream);
                    return (T)result;
                }
            }
            catch (Exception ex)
            {
				Console.WriteLine(ex);
                return default(T);
            }
        }

        private static Stream GenerateStreamFromString(string s)
        {
            // using
            var stream = new MemoryStream();
            var writer = new StreamWriter(stream, System.Text.Encoding.UTF8);

            writer.Write(s);
            writer.Flush();
            stream.Position = 0;

            return stream;
        }

        private static string SerializeToJson<T>(T data)
        {
            return JsonConvert.SerializeObject(data);
            // throw new NotImplementedException();
        }

        private static T DeserializeFromJson<T>(string data)
        {
            return JsonConvert.DeserializeObject<T>(data);
            // throw new NotImplementedException();
        }
    }

    public enum SerializeFormat
    {
        XML = 1,
        JSON = 2
    }
;