using System;


namespace MyGeometry
{
	// Draw a floor
	public class Volume
	{
		private int vertexNum;
		private int faceNum;
		private int planeVertexNum;
		private int[,] sideFaceIndex = null;
		private int[,] capFaceIndex;
		private float[,] faceNormal = null;
		private float[,] points = null;

		
		public int VertexNum
		{
			get { return vertexNum; }
		}

		// Suppose it is a rectangular
		public void Volume(Vector3d[,] vertices, float lift_height)
		{
			int vi = 0;
			int vj = 0;

			this.planeVertexNum = vertices.Length;

			for (vi = 0; vi < vertices.Length; vi++)
			{
				this.points[vi, 0] = vertices[vi].x;
				this.points[vi, 1] = vertices[vi].y;
				this.points[vi, 2] = vertices[vi].z;
			}

			// Normal of the plane
			Vector3d v1 = vertices[1] - vertices[0];
			Vector3d v2 = vertices[vertices.Length-1] - vertices[0];
			Vector3d normal = v1.Cross(v2).Normalize();
			
			//Move along the normal direction
			for (vj = 0; vj < vertices.Length; vj++)
			{
				Vector3d current = vertices[vj] + normal * lift_height;
				this.points[vi, 0] = current.x; 
				this.points[vi, 1] = current.y; 
				this.points[vi, 2] = current.z; 
				vi++;
			}

			this.vertexNum = vi;
			if (vi != vertices.Length * 2) return;

			// Faces vertices.Length+2
			this.capFaceIndex = new int[2,vertices.Length];
			for (vj = 0; vj < vertices.Length; vj++)
			{
				this.sideFaceIndex[vj, 0] = vj;
				this.sideFaceIndex[vj, 1] = vj + 1;
				this.sideFaceIndex[vj, 2] = vj + vertices.Length;
				this.sideFaceIndex[vj, 3] = vj + 1 + vertices.Length;
				this.capFaceIndex[1, vj] = vj;
				this.capFaceIndex[2, vj + vertices.Length] = vj + vertices.Length;
			}

			this.faceNum = vertices.Length + 2;
			this.faceNormal = new float[this.faceNum,3];
			faceNormal[this.faceNum - 2, 0] = -normal.x;
			faceNormal[this.faceNum - 2, 1] = -normal.y;
			faceNormal[this.faceNum - 2, 2] = -normal.z;
			faceNormal[this.faceNum - 1, 0] = normal.x;
			faceNormal[this.faceNum - 1, 1] = normal.y;
			faceNormal[this.faceNum - 1, 2] = normal.z;


			this.ComputeFaceNormal();
		}
		

		public void ComputeFaceNormal()
		{
			for (int i = 0; i < this.planeVertexNum; i++)
			{
				Vector3d v_1 = points[sideFaceIndex[i, 1]] - points[sideFaceIndex[i, 0]];
				Vector3d v_2 = points[sideFaceIndex[i, 3]] - points[sideFaceIndex[i, 0]];
				Vector3d f_normal = v_1.Cross(v_2).Normalize();
				faceNormal[i, 0] = f_normal.x;
				faceNormal[i, 1] = f_normal.y;
				faceNormal[i, 2] = f_normal.z;
			}

		}

		public void liftFace(int findex, float lift_height)
		{

		}

	}
}
