// // texture.cpp // graphics // // Created by Sam Jaffe on 7/5/16. // #include "game/graphics/texture.hpp" #include #include "scope_guard/scope_guard.hpp" #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wcomma" #define STB_IMAGE_IMPLEMENTATION #include "stb/stb_image.h" #pragma clang diagnostic pop #include "game/util/hash.hpp" #include "helper.hpp" unsigned char * stbi_load(char const *, int *, int *, int *, int); void stbi_image_free(void *); using namespace graphics; namespace { std::unordered_map> g_textures; } static textures::format format(int comps) { switch (comps) { case 3: return textures::format::RGB; case 4: return textures::format::RGBA; default: throw; } } flyweight texture::create(std::string const & imagefile) { auto found = g_textures.find(imagefile); if (found != g_textures.end()) { return found->second; } int components = 0; math::vec2i size; unsigned char * data = stbi_load(imagefile.c_str(), &size.x(), &size.y(), &components, 0); scope(exit) { stbi_image_free(data); }; auto id = textures::init(format(components), size, data); flyweight fly{id, {id, size}}; return g_textures.emplace(imagefile, fly).first->second; } texture texture::create(char const * data, math::vec2i size) { return {textures::init(format(4), size, data), size}; } texture::texture(unsigned int id, math::vec2i sz) : identity(id), size(sz) {} texture const texture::WHITE = texture::create("\xFF\xFF\xFF\xFF", {{1, 1}}); texture const texture::DARK_YELLOW = texture::create("\x80\x80\x00\xFF", {{1, 1}}); texture const texture::LIGHT_BLUE = texture::create("\x80\x80\xFF\xFF", {{1, 1}});