
#include "ResourceManager.h"
#include "stb_image.h"
#include <iostream>

///////////////////////////////////////////////////////////////
//リソースマネージャ
///////////////////////////////////////////////////////////////

ResourceManager::ResourceManager() { }
ResourceManager::~ResourceManager() {
	auto it = mapTextures.begin();
	while( it != mapTextures.end() ) {
		TEXTURE &tex = it->second;
		glDeleteTextures(1, &tex.ID);
		tex.ID = 0;
		it++;
	}
}

const ResourceManager::TEXTURE &ResourceManager::GetTexture(const std::string &filename) {
	auto it = mapTextures.find(filename);
	if( it == mapTextures.end() ) {
		//初めて読み込む画像のとき
		TEXTURE tex = LoadImage(filename);
		auto it = mapTextures.insert(
			std::pair<std::string, TEXTURE>(filename, tex)
		);
		return it.first->second;
		
	} else {
		//既に読み込んだ画像のとき
		return it->second;
	}
	
}

void ResourceManager::RemoveTexture(const std::string &filename) {
	mapTextures.erase(filename);
}

ResourceManager::TEXTURE ResourceManager::LoadImage(const std::string &filename) {
	TEXTURE tex;
	
	glGenTextures(1, &tex.ID);
	glBindTexture(GL_TEXTURE_2D, tex.ID);
	
	int n;
	unsigned char *pixel =
		stbi_load(filename.c_str(), &tex.Width, &tex.Height, &n, 4);
	
	glTexImage2D(
		GL_TEXTURE_2D, 0, GL_RGBA, tex.Width, tex.Height, 0,
		GL_RGBA, GL_UNSIGNED_BYTE, pixel
	);
	
	stbi_image_free(pixel);
	
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	
	glBindTexture(GL_TEXTURE_2D, 0);
	
	return tex;
	
}


