﻿using UnityEngine;
using System.Collections;

public class ProceduralCirclePlane : MonoBehaviour
{
	public float radius = 5;
	public int sections = 4;
	public bool flip = false;
	private float m_LastRadius = 0;
	private int m_LastSections = -1;
	private bool m_LastFlip = false;
	public static Mesh Create(float aRadius, int aSections, bool aFlipSide)
	{
		Vector3[] vertices = new Vector3[aSections + 1];
		Color[] colors = new Color[vertices.Length];
		Vector2[] uvs = new Vector2[vertices.Length];
		int[] indices = new int[aSections*3];
		vertices[0] = Vector3.zero;
		colors[0] = new Color(1,1,1,1);
		uvs[0] = Vector2.one * 0.5f;
		for(int i = 0; i < aSections; i++)
		{
			float angle = ((float)i / aSections) * Mathf.PI*2;
			Vector2 v = new Vector2(Mathf.Cos(angle),Mathf.Sin(angle));
			vertices[i+1] = v*aRadius;
			uvs[i+1] = (v+Vector2.one)*0.5f;
			colors[i+1] = new Color(1,1,1,0);
			indices[i*3 + 0] = 0;
			if (aFlipSide)
			{
				indices[i*3 + 1] = (i+1) % aSections +1;
				indices[i*3 + 2] = (i  )             +1;
			}
			else
			{
				indices[i*3 + 1] = (i  )             +1;
				indices[i*3 + 2] = (i+1) % aSections +1;
			}

		}
		var m = new Mesh();
		m.vertices = vertices;
		m.colors = colors;
		m.uv = uvs;
		m.triangles = indices;
		m.RecalculateNormals();
		m.RecalculateBounds();
		return m;
	}

	void UpdateMesh()
	{
		var mesh = Create(radius, sections,flip);
		m_LastRadius = radius;
		m_LastSections = sections;
		m_LastFlip = flip;
		var mf = GetComponent<MeshFilter>();
		if (mf != null)
			mf.sharedMesh = mesh;
	}

	void Start ()
	{
		UpdateMesh ();
	}
	
	void Update ()
	{
		if (radius != m_LastRadius || sections != m_LastSections || flip != m_LastFlip)
			UpdateMesh();
	}
}
