/*
 *  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 "Texture.hxx"
#include <cmath>

void Texture::Bind(void)
{
	static Texture *bound = 0;
	if (bound != this)
		glBindTexture(GL_TEXTURE_2D, gl_texture);
}

void Texture::Draw(const Rect & src, const Rect & dst)
{
	float fx1 = float (src.x) / float (rect.w);
	float fy1 = float (src.y) / float (rect.h);
	float fx2 = float (src.x + src.w) / float (rect.w);
	float fy2 = float (src.y + src.h) / float (rect.h);

	Bind();

	glBegin(GL_QUADS);
	glTexCoord2f(fx1, fy1);
	glVertex3f(dst.x, dst.y, 0);
	glTexCoord2f(fx2, fy1);
	glVertex3f(dst.x + dst.w, dst.y, 0);
	glTexCoord2f(fx2, fy2);
	glVertex3f(dst.x + dst.w, dst.y + dst.h, 0);
	glTexCoord2f(fx1, fy2);
	glVertex3f(dst.x, dst.y + dst.h, 0);
	glEnd();
}

void Texture::Draw(const Rect & src, const Rect & dst,float angle)
{
	float fx1 = float (src.x) / float (rect.w);
	float fy1 = float (src.y) / float (rect.h);
	float fx2 = float (src.x + src.w) / float (rect.w);
	float fy2 = float (src.y + src.h) / float (rect.h);

	Polygon dstp(dst);
	dstp.Rotate(angle);

	Bind();

	glBegin(GL_QUADS);
	glTexCoord2f(fx1, fy1);
	glVertex3f(dstp[0].x, dstp[0].y, 0);
	glTexCoord2f(fx2, fy1);
	glVertex3f(dstp[1].x, dstp[1].y, 0);
	glTexCoord2f(fx2, fy2);
	glVertex3f(dstp[2].x, dstp[2].y, 0);
	glTexCoord2f(fx1, fy2);
	glVertex3f(dstp[3].x, dstp[3].y, 0);
	glEnd();
}

