add: Basic Font Rendering

This commit is contained in:
Simon Hardt
2022-03-05 02:37:08 +01:00
parent df1ce5583b
commit 0553927dad
15 changed files with 386 additions and 9 deletions

114
fontConverter/src/main.cpp Normal file
View File

@@ -0,0 +1,114 @@
#include <fmt/format.h>
#include <fstream>
#include <nlohmann/json.hpp>
#include <sfml/Graphics.hpp>
using json = nlohmann::json;
void PrintGlyph(sf::Font const& font, sf::Glyph const& g, unsigned int size);
int main()
{
sf::Font font;
auto ok =
font.loadFromFile(R"(C:\Users\s-har\Downloads\FiraCode-Regular.ttf)");
fmt::print("Loaded {}\n", ok);
std::vector<char> chars = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
fmt::print("{}\n", font.getInfo().family);
fmt::print("Line Spacing: {}\n", font.getLineSpacing(14));
std::map<char, sf::Glyph> glyphs;
for(auto el : chars)
{
auto a = font.getGlyph(el, 14, false);
fmt::print("{}: w {} h {}\n",
el,
a.textureRect.width,
a.textureRect.height);
fmt::print("- t: {} l: {} w: {} h: {}\n",
a.bounds.top,
a.bounds.left,
a.bounds.width,
a.bounds.height);
fmt::print("offset: {}\n\n", a.advance);
glyphs[el] = a;
}
auto font_image = font.getTexture(14).copyToImage();
auto size = font_image.getSize();
json export_font;
export_font["name"] = font.getInfo().family;
export_font["sizes"] = json::object();
auto& size_14 = export_font["sizes"]["14"];
size_14["LineSpacing"] = font.getLineSpacing(14);
auto& Glyphs = size_14["Glyphs"];
for(auto&& [c, g] : glyphs)
{
auto& current = Glyphs[std::string{c}];
current["advance"] = g.advance;
current["x_offset"] = g.bounds.left;
current["y_offset"] = g.bounds.top;
current["width"] = g.bounds.width;
current["height"] = g.bounds.height;
std::vector<uint8_t> data;
for(int y = 0; y < (int)g.bounds.height; ++y)
{
for(int x = 0; x < (int)g.bounds.width; ++x)
{
auto c = font_image.getPixel(g.textureRect.left + x,
g.textureRect.top + y);
data.push_back(c.a > 100 ? 1 : 0);
}
}
current["data"] = data;
}
std::fstream out(fmt::format("{}.json", font.getInfo().family),
std::ios::out);
out << export_font.dump();
fmt::print("Size x: {} y: {}\n", size.x, size.y);
font_image.saveToFile("Test.png");
}
void PrintGlyph(sf::Font const& font, sf::Glyph const& g, unsigned int size)
{
auto font_image = font.getTexture(size).copyToImage();
for(int y = 0; y < (int)g.bounds.height; ++y)
{
for(int x = 0; x < (int)g.bounds.width; ++x)
{
auto c = font_image.getPixel(g.textureRect.left + x,
g.textureRect.top + y);
if(c.a > 100)
{
fmt::print("X");
} else
{
fmt::print(" ");
}
}
fmt::print("\n");
}
}