/*
 *  Copyright (C) 2005-2008  Maarten de Boer <maarten@resorama.com>
 * 
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU General Public License
 *  as published by the Free Software Foundation; either version 2
 *  of the License, or (at your option) any later version.
 * 
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 * 
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 *  02110-1301, USA.
 * 
 */

#include "Screen.hxx"

#include <SDL.h>

#include <GL/gl.h>
#include <cstdlib>

Screen::Screen(int w, int h, int glw, int glh)
:w(w), h(h), glw(glw), glh(glh)
{
	flags = 0;
	bpp = 0;
	sdl_surface = 0;
}

void Screen::FullScreen(bool b)
{
	if (b)
		flags |= SDL_FULLSCREEN;
	else
		flags &= (~SDL_FULLSCREEN);
}

void Screen::DoubleBuffer(bool b)
{
	if (b)
		flags |= SDL_DOUBLEBUF;
	else
		flags &= (~SDL_DOUBLEBUF);
}

void Screen::Init(void)
{
	SDL_Init(SDL_INIT_VIDEO);
	atexit(SDL_Quit);

	GLint gl_doublebuf;
	GLint maxtexsize;

	flags |= SDL_OPENGL;

	gl_doublebuf = flags & SDL_DOUBLEBUF;
	if (bpp == 15) {
		SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
		SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5);
		SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
	}
	if (bpp == 16) {
		SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
		SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 6);
		SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
	} else if (bpp >= 24) {
		SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
		SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
		SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
	}
	if (bpp)
		SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, bpp);

	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, gl_doublebuf);

	sdl_surface = SDL_SetVideoMode(w, h, bpp, flags);
	if (!sdl_surface) {
		fprintf(stderr, "Failed to open screen %d %d %d %d!\n", w, h, bpp,
				  flags);
		exit(-1);
	}

	/*
		SDL_Delay(1000);
	 */
	glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxtexsize);
	if (maxtexsize < 1024) {
		fprintf(stderr, "Need at least 1024x1024 textures!\n");
		exit(-1);
	}

	/*
	 * Set up OpenGL for 2D rendering.
	 */
	glDisable(GL_DEPTH_TEST);
	glDisable(GL_CULL_FACE);

	glViewport(0, 0, w, h);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrtho(0, glw, glh, 0, -1.0, 1.0);

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	glTranslatef(0.0f, 0.0f, 0.0f);
}

void Screen::Exit(void)
{
	SDL_Quit();
}

void Screen::Flip(void)
{
	SDL_GL_SwapBuffers();
}


