/*
	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/>.
 */

#ifndef TEXTURE_H_
#define TEXTURE_H_

#include <wx/wx.h>
#include <wx/glcanvas.h>

//2次元テクスチャのラッパ
class Texture {
	//テクスチャ名
	GLuint name;

	Texture(const Texture &);
	void operator=(const Texture &);
public:
	inline Texture(const wxString &fileName) {
		//テクスチャを作成し画像をロード
		wxImage image(fileName.mb_str());
		char *pixels=new char[image.GetWidth()*image.GetHeight()*4];

		if (!image.Ok()) wxLogFatalError(fileName+wxT("の読み込み失敗"));

		//画像がアルファ値を持っていなければ準備
		if (!image.HasAlpha()) image.InitAlpha();

		//RGBA形式に変換
		for (int y=0;y<image.GetHeight();++y) {
			for (int x=0;x<image.GetWidth();++x) {
				pixels[(y*image.GetWidth()+x)*4]=image.GetRed(x,y);
				pixels[(y*image.GetWidth()+x)*4+1]=image.GetGreen(x,y);
				pixels[(y*image.GetWidth()+x)*4+2]=image.GetBlue(x,y);
				pixels[(y*image.GetWidth()+x)*4+3]=image.GetAlpha(x,y);
			}
		}

		glGenTextures(1,&name);
		bind();
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
		glTexImage2D(GL_TEXTURE_2D,0,4,image.GetWidth(),image.GetHeight(),0,GL_RGBA,GL_UNSIGNED_BYTE,pixels);

		delete[] pixels;
	}

	inline Texture(const wxImage &textureImage) {
		//画像からテクスチャを作成
		wxImage image(textureImage);
		char *pixels=new char[image.GetWidth()*image.GetHeight()*4];

		//画像がアルファ値を持っていなければ準備
		if (!image.HasAlpha()) image.InitAlpha();

		//RGBA形式に変換
		for (int y=0;y<image.GetHeight();++y) {
			for (int x=0;x<image.GetWidth();++x) {
				pixels[(y*image.GetWidth()+x)*4]=image.GetRed(x,y);
				pixels[(y*image.GetWidth()+x)*4+1]=image.GetGreen(x,y);
				pixels[(y*image.GetWidth()+x)*4+2]=image.GetBlue(x,y);
				pixels[(y*image.GetWidth()+x)*4+3]=image.GetAlpha(x,y);
			}
		}

		glGenTextures(1,&name);
		bind();
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
		glTexImage2D(GL_TEXTURE_2D,0,4,image.GetWidth(),image.GetHeight(),0,GL_RGBA,GL_UNSIGNED_BYTE,pixels);

		delete[] pixels;
	}

	inline void bind() const {
		//テクスチャをバインド
		glBindTexture(GL_TEXTURE_2D,name);
	}

	inline ~Texture() {
		//テクスチャを削除
		glDeleteTextures(1,&name);
	}
};

#endif /* TEXTURE_H_ */
