/*
 * GLUT Shapes Demo
 *
 * Written by Nigel Stewart November 2003
 *
 * This program is test harness for the sphere, cone
 * and torus shapes in GLUT.
 *
 * Spinning wireframe and smooth shaded shapes are
 * displayed until the ESC or q key is pressed.  The
 * number of geometry stacks and slices can be adjusted
 * using the + and - keys.
 */

#ifdef __APPLE__
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
#include <stdlib.h>
#include "FreeImage.h"
#include <stdio.h>
#include <iostream>


using namespace std;

void loadTextureFromFile()
{
	//glShadeModel(GL_FLAT);
	 glEnable(GL_DEPTH_TEST);


	FIBITMAP *bitmap = FreeImage_Load(FIF_PNG, "testetransp.png", PNG_DEFAULT);

    int nWidth = FreeImage_GetWidth(bitmap);
    int nHeight = FreeImage_GetHeight(bitmap);

    BYTE *imgPtr = FreeImage_GetBits(bitmap);

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

	gluBuild2DMipmaps(GL_TEXTURE_2D, 4, nWidth, nHeight,
					 GL_RGBA, GL_UNSIGNED_BYTE, (void*)FreeImage_GetBits(bitmap) );

}

/*
 * Draw the texture in the OpenGL graphics window
 */
void drawScene(void)
{
    glClearColor (1.0, 0.0, 1.0, 1.0);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glEnable(GL_TEXTURE_2D);
 glEnable(GL_BLEND);
 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    glBegin(GL_QUADS);


       glTexCoord2f(0.0, 0.0);
   glVertex3f(-1.0, -1.0, 0.0);

       glTexCoord2f(0.0, 1.0);
   glVertex3f(-1.0, 1.0, 0.0);

    glTexCoord2f(1.0, 1.0);

   glVertex3f(1.0, 1.0, 0.0);

    glTexCoord2f(1.0, 0.0);
   glVertex3f(1.0, -1.0, 0.0);

   glEnd();

   glFlush();

   glDisable(GL_TEXTURE_2D);
}

void resizeWindow(int w, int h)
{
	float viewWidth = 1.1;
	float viewHeight = 1.1;
	glViewport(0, 0, w, h);
	h = (h==0) ? 1 : h;
	w = (w==0) ? 1 : w;
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	if ( h < w ) {
		viewWidth *= (float)w/(float)h;
	}
	else {
		viewHeight *= (float)h/(float)w;
	}
	glOrtho( -viewWidth, viewWidth, -viewHeight, viewHeight, -1.0, 1.0 );

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
}

void keyboard (unsigned char key, int x, int y)
{
	switch (key) {
		case 27:
			exit(0);
			break;
		default:
			break;
   }
}


int main(int argc, char** argv)
{
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_ALPHA | GLUT_RGBA | GLUT_DEPTH);
	glutInitWindowSize(240, 240);
	glutInitWindowPosition(100, 100);
	glutCreateWindow(argv[0]);

    loadTextureFromFile();

    glutDisplayFunc(drawScene);

	glutReshapeFunc(resizeWindow);
	glutKeyboardFunc(keyboard);
	glutMainLoop();
	return 0;
}
