#include "Prism.h"


Prism::Prism(const Matrix4x4f& matrix, int matId, float size, float angle)
{
  float frontBound = -size;
  float backBound = size;

  float leftBound = -size/2;
  float rightBound = size/2;

  float h = rightBound/tanf(angle/2);

  // left frace
  vert[0].pos.set(leftBound,0,frontBound,1);
  vert[1].pos.set(leftBound,0,backBound,1);
  vert[2].pos.set(0,h,backBound,1);
  vert[3].pos.set(0,h,frontBound,1);

  indices[0] = 0;
  indices[1] = 1;
  indices[2] = 2;

  indices[3] = 0;
  indices[4] = 2;
  indices[5] = 3;


  // right frace
  vert[4].pos.set(rightBound,0,frontBound,1);
  vert[5].pos.set(rightBound,0,backBound,1);
  vert[6].pos.set(0,h,backBound,1);
  vert[7].pos.set(0,h,frontBound,1);

  indices[6] = 4;
  indices[7] = 5;
  indices[8] = 6;

  indices[9] = 4;
  indices[10] = 6;
  indices[11] = 7;

  // down frace
  vert[8].pos.set(leftBound,0,frontBound,1);
  vert[9].pos.set(leftBound,0,backBound,1);
  vert[10].pos.set(rightBound,0,backBound,1);
  vert[11].pos.set(rightBound,0,frontBound,1);

  indices[12] = 8;
  indices[13] = 9;
  indices[14] = 10;

  indices[15] = 8;
  indices[16] = 10;
  indices[17] = 11;


  // front frace
  vert[12].pos.set(leftBound,0,frontBound,1);
  vert[13].pos.set(rightBound,0,frontBound,1);
  vert[14].pos.set(0,h,frontBound,1);
  indices[18] = 12;
  indices[19] = 13;
  indices[20] = 14;

   // back face
  vert[15].pos.set(leftBound,0,backBound,1);
  vert[16].pos.set(rightBound,0,backBound,1);
  vert[17].pos.set(0,h,backBound,1);
  
  indices[21] = 15;
  indices[22] = 16;
  indices[23] = 17;

  for(int i=0;i<VERT_NUM;i++)
	{
		vert[i].material_id = matId;
		vert[i].texture_id[0] = 255;
	}

  CalcNormals();

  // transform geometry with matrix
	for(int i=0;i<VERT_NUM;i++)
	{
		vert[i].pos = matrix*vert[i].pos;
		vert[i].norm = matrix*vert[i].norm;
		vert[i].norm.Normalize();
	}
}


void Prism::CalcNormals()
{
	for(unsigned int i=0;i<INDEX_NUM;i+=3)
	{	
		vec4f A = vert[indices[i+0]].pos;
		vec4f B = vert[indices[i+1]].pos;
		vec4f C = vert[indices[i+2]].pos;
		vec4f norm = (A-B)->*(A-C);

		norm.Normalize();
		vert[indices[i+0]].norm = norm;
		vert[indices[i+1]].norm = norm;
		vert[indices[i+2]].norm = norm;
	}
}



void Prism::InvertNormals()
{
	for(int i=0;i<VERT_NUM;i++)
	{
		vert[i].norm *= (-1);
  }
}