/*
	AramakiOnline
	Copyright (C) 2008 superbacker

	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 3 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, see <http://www.gnu.org/licenses/>.
 */

#include "TextPolygon.h"
#include <wx/glcanvas.h>
#include "Utility.h"
#include "MainFrame.h"

TextPolygon::~TextPolygon() {
	if (texture) delete texture;
}

void TextPolygon::draw() const {
	//描画
	if (texture) {
		glEnable(GL_TEXTURE_2D);
		texture->bind();

		glNormal3d(0,1,0);
		glBegin(GL_QUADS);
		glTexCoord2d(textureRight,0); glVertex3d(position.x+width,position.y+height,position.z);
		glTexCoord2d(0,0); glVertex3d(position.x,position.y+height,position.z);
		glTexCoord2d(0,textureBottom); glVertex3d(position.x,position.y,position.z);
		glTexCoord2d(textureRight,textureBottom); glVertex3d(position.x+width,position.y,position.z);
		glEnd();
	}
}

void TextPolygon::generateTextTexture() {
	wxBitmap bmp;
	wxMemoryDC dc;
	wxSize size,textureSize;
	wxImage img;

	dc.SetFont(font);

	//文字列のサイズを取得
	size=dc.GetMultiLineTextExtent(text);
	size.SetWidth(size.GetWidth()+3);
	size.SetHeight(size.GetHeight()+3);

	//テクスチャのサイズは2の冪乗でなければならない
	textureSize.SetWidth(toPow2(size.GetWidth()));
	textureSize.SetHeight(toPow2(size.GetHeight()));

	//ビットマップに文字を描画
	bmp.Create(textureSize.GetWidth(),textureSize.GetHeight());
	dc.SelectObject(bmp);
	dc.SetBackground(wxBrush(backgroundColor));
	dc.SetTextBackground(backgroundColor);
	dc.SetTextForeground(textColor);
	dc.Clear();
	dc.DrawLabel(text,wxRect(1,1,0,0));
	dc.SelectObject(wxNullBitmap);

	//イメージに変換
	img=bmp.ConvertToImage();
	if (transparent) {
		//透過
		img.SetMaskColour(backgroundColor.Red(),backgroundColor.Green(),backgroundColor.Blue());
	}

	//テクスチャに変換
	if (!texture) delete texture;
	texture=new Texture(img);

	textureRight=(double)size.GetWidth()/textureSize.GetWidth();
	textureBottom=(double)size.GetHeight()/textureSize.GetHeight();
	width=(double)size.GetWidth()*0.017;
	height=(double)size.GetHeight()*0.017;
}
