#include <gl/glut.h>
#include "output/gloutput.h"

void GLOutput::display(){
//void display(){
	glClear(GL_COLOR_BUFFER_BIT);
	glPushMatrix();
	glRotatef(spin, 0.0 , 0.0 ,1.0);
	glColor3f(0.0,1.0,1.0);
	gluLookAt(0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
//	glutWireCube(1.0);
	
	vertices[13]=1.0+height; 
	vertices[28]=-1.0-height;
	vertices[42]=1.0+height;
	vertices[57]=-1.0-height;
//	vertices[74]=1.0+height;
//	vertices[89]=-1.0-height;
	
	glVertexPointer(3,GL_FLOAT,0,vertices);
	glColor3f(0.0,0.0,1.0);
//	glutWireCube(2.0);
	glDrawElements(GL_LINE_LOOP,12,GL_UNSIGNED_BYTE, indices_sides_1);
	glDrawElements(GL_LINE_LOOP,12,GL_UNSIGNED_BYTE, indices_sides_2);
	glColor3f(1.0,0.0,0.0);
	glDrawElements(GL_LINE_LOOP,12,GL_UNSIGNED_BYTE, indices_sides_3);
	glDrawElements(GL_LINE_LOOP,12,GL_UNSIGNED_BYTE, indices_sides_4);
//	glColor3f(0.0,1.0,0.0);
//	glDrawElements(GL_LINE_LOOP,12,GL_UNSIGNED_BYTE, indices_sides_5);
//	glDrawElements(GL_LINE_LOOP,12,GL_UNSIGNED_BYTE, indices_sides_6);
	
	glPopMatrix();
	glutSwapBuffers();
//	AmigaMesaSwapBuffers(con);
	glFlush();
}

void GLOutput::DrawNextFrame(UINT trackNo){

	height=((float)o_GetCurrentValue(trackNo)/255.0)*3.0;
	cout << "Value: " << height << endl;
	spin+=2.0;
	if (spin>360.0)
		spin-=360;
//	if (direction)
//		height+=0.5;
	else
//		height-=0.5;
//	if (height>3 || height <0.5)
//		direction=!direction;
	
//	display();
	glutPostRedisplay();		
}

void GLOutput::reshape(int w, int h){
	glViewport(0,0,(GLsizei)w,(GLsizei)h);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glFrustum(-1.0,1.0,-1.0,1.0,1.5,20.0);
	glMatrixMode(GL_MODELVIEW);
}


void GLOutput::OnInit(){
	// Create a context etc
	TagItem contextTags[]={
		{AMA_Screen,	(ULONG)o_mainScr},
		{AMA_RastPort, (ULONG)&(o_mainScr->sc_RastPort)},
		{AMA_DoubleBuf, TRUE},
		{AMA_RGBMode, TRUE},
		{AMA_Left, 0},
		{AMA_Bottom, 0},
		{AMA_Height,o_mainScr->Height},
		{AMA_Width, o_mainScr->Width},
		{AMA_Fullscreen, TRUE},
		{TAG_DONE, NULL}
	};
										
	
//	con=AmigaMesaCreateContext(&contextTags[0]);
//	if (con){
//		AmigaMesaMakeCurrent(con,con->buffer);
	
		glClearColor(0.0,0.0,0.0,0.0);
		glShadeModel(GL_FLAT);
		glEnableClientState(GL_VERTEX_ARRAY);
//	}
//	else
//		Error("Unable to create GL Context",NULL);
}
	
BOOL GLOutput::Initialise(){	
	glutDisplayFunc(display);
	glutIdleFunc(display);
	AddTrackName("Spikes");
	return OmegaOutput::Initialise()
}

GLOutput::GLOutput(){
	oa_SetName("OpenGL Output");
	oa_Author="T.Miles";
	oa_Version="1.0";
	op_Type=0x474C;
	spin=0.0;
	height=0.0;
	direction=TRUE;
	con=NULL;
}

void GLOutput::OnExit(){
//	if (con)
//		AmigaMesaDestroyContext(con);  // This freezes - why?
}

GLOutput::~GLOutput(){

}