engine/src/resources/font.cpp

77 lines
1.6 KiB
C++
Raw Normal View History

2022-09-02 11:06:59 +00:00
#include "resources/font.hpp"
2022-11-23 16:20:08 +00:00
#define STB_TRUETYPE_IMPLEMENTATION
#include <stb_truetype.h>
#include "util/files.hpp"
#include "gfx_device.hpp"
2022-09-02 11:06:59 +00:00
2022-11-23 18:09:49 +00:00
#include "log.hpp"
2022-10-06 10:30:44 +00:00
namespace engine::resources {
2022-09-02 11:06:59 +00:00
Font::Font(const std::filesystem::path& resPath) : Resource(resPath, "font")
{
2022-11-23 16:20:08 +00:00
// TODO: load font
auto fontBuffer = util::readBinaryFile(resPath);
2022-09-02 11:06:59 +00:00
2022-11-23 16:20:08 +00:00
stbtt_fontinfo info{};
int res = stbtt_InitFont(&info, fontBuffer->data(), 0);
2022-11-23 18:09:49 +00:00
if (!res) {
2022-11-23 16:20:08 +00:00
throw std::runtime_error("Failed to read font file: " + resPath.string());
2022-09-02 11:06:59 +00:00
}
2022-11-23 16:20:08 +00:00
float scale = stbtt_ScaleForPixelHeight(&info, 64);
2022-09-02 11:06:59 +00:00
2022-11-23 16:20:08 +00:00
for (unsigned char c = 0; c < 128; c++) {
2022-09-02 11:06:59 +00:00
2022-11-23 16:20:08 +00:00
// TODO: get character bitmap buffer, size, offsets, advance
int32_t advance = 0, xoff = 0;
stbtt_GetCodepointHMetrics(&info, c, &advance, &xoff);
2022-09-02 11:06:59 +00:00
2022-11-23 16:20:08 +00:00
int32_t w, h, yoff;
const uint8_t* bitmap = stbtt_GetCodepointBitmap(&info, scale, scale, c, &w, &h, &xoff, &yoff);
2022-09-02 11:06:59 +00:00
2022-11-23 18:09:49 +00:00
DEBUG("char width: {} char height: {}", w, h);
2022-11-23 16:20:08 +00:00
auto colorBuffer = std::make_unique<std::vector<uint32_t>>(w * h);
int i = 0;
for (uint32_t& col : *colorBuffer) {
2022-11-23 18:09:49 +00:00
if (bitmap[i] == 0) {
col = 0;
} else {
col = 0xFFFFFFFF;
}
2022-11-23 16:20:08 +00:00
i++;
2022-09-02 11:06:59 +00:00
}
// generate texture
2022-11-23 16:20:08 +00:00
gfx::Texture* texture = gfxdev->createTexture(colorBuffer->data(), w, h, gfx::TextureFilter::LINEAR, gfx::TextureFilter::LINEAR);
2022-09-02 11:06:59 +00:00
Character character = {
texture,
2022-11-23 16:20:08 +00:00
glm::ivec2{w, h}, // Size of Glyph
glm::ivec2{xoff, yoff}, // Offset from baseline (bottom-left) to top-left of glyph
advance
2022-09-02 11:06:59 +00:00
};
m_characters.insert(std::make_pair(c, character));
}
2022-11-23 16:20:08 +00:00
// TODO clean up resources
2022-09-02 11:06:59 +00:00
}
Font::~Font()
{
}
Font::Character Font::getChar(char c)
{
return m_characters.at(c);
}
}