playground-sdk/gfx/draw.cpp

308 lines
14 KiB
C++

#include "gfx/draw.h"
#include <SDL3_image/SDL_image.h>
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <vector>
namespace {
struct Point { float x, y; };
struct Edge { Point a, b; };
struct Glyph { uint32_t code, offset; float minY, maxY, advance; };
uint16_t u16(const playground::Bytes& b, size_t p) {
return static_cast<uint16_t>(b[p] | (b[p + 1] << 8));
}
int16_t s16(const playground::Bytes& b, size_t p) { return static_cast<int16_t>(u16(b, p)); }
uint32_t u32(const playground::Bytes& b, size_t p) {
return static_cast<uint32_t>(b[p]) | (static_cast<uint32_t>(b[p+1]) << 8) |
(static_cast<uint32_t>(b[p+2]) << 16) | (static_cast<uint32_t>(b[p+3]) << 24);
}
std::vector<uint32_t> decodeUtf8(const std::string& text) {
std::vector<uint32_t> codes;
for (size_t i = 0; i < text.size();) {
const auto c = static_cast<unsigned char>(text[i++]);
if (c < 0x80) { codes.push_back(c); continue; }
const int count = c < 0xe0 ? 1 : c < 0xf0 ? 2 : 3;
uint32_t value = c & (count == 1 ? 0x1f : count == 2 ? 0x0f : 0x07);
if (i + count > text.size()) { codes.push_back('?'); break; }
for (int j = 0; j < count; ++j) value = (value << 6) | (static_cast<unsigned char>(text[i++]) & 0x3f);
codes.push_back(value);
}
return codes;
}
bool mvecTable(const playground::Bytes& b, std::vector<Glyph>& glyphs, float& ascent, float& descent) {
if (b.size() < 12 || std::string(reinterpret_cast<const char*>(b.data()), 4) != "MVC4") return false;
const uint16_t count = u16(b, 4);
if (12 + static_cast<size_t>(count) * 18 > b.size()) return false;
ascent = 0; descent = 0;
glyphs.reserve(count);
for (size_t i = 0; i < count; ++i) {
const size_t p = 12 + i * 18;
Glyph g{u32(b,p), u32(b,p+14), s16(b,p+8)/128.0f, s16(b,p+10)/128.0f, s16(b,p+12)/128.0f};
if (g.offset >= b.size()) return false;
if (g.code == 'W') ascent = std::max(0.0f, -g.minY);
if (g.code < 128 && g.code != '_') descent = std::max(descent, g.maxY);
glyphs.push_back(g);
}
return ascent > 0;
}
void glyphEdges(const playground::Bytes& b, uint32_t offset, float penX, float scale, float baseline,
std::vector<Edge>& edges) {
Point current{};
bool active = false;
for (size_t p = offset; p < b.size();) {
const auto command = b[p++];
if (command == 8) break;
if (command == 2) { if (p >= b.size()) break; ++p; continue; }
if (command != 4 && command != 5 && command != 6) break;
const size_t need = command == 6 ? 8 : 4;
if (p + need > b.size()) break;
auto at = [&](size_t q) -> Point {
return {penX + s16(b,q)/128.0f*scale, baseline + s16(b,q+2)/128.0f*scale};
};
const Point next = at(p + (command == 6 ? 4 : 0));
if (command == 4 || !active) { current = next; active = true; }
else if (command == 5) { edges.push_back({current,next}); current = next; }
else {
const Point control = at(p);
const float length = std::hypot(next.x-current.x,next.y-current.y) +
std::hypot(control.x-current.x,control.y-current.y);
const int steps = std::clamp(static_cast<int>(std::ceil(length/3.0f)), 4, 32);
Point from = current;
for (int i=1; i<=steps; ++i) {
const float t = static_cast<float>(i)/steps, a = 1-t;
const Point to{a*a*current.x+2*a*t*control.x+t*t*next.x,
a*a*current.y+2*a*t*control.y+t*t*next.y};
edges.push_back({from,to}); from=to;
}
current=next;
}
p += need;
}
}
SDL_Texture* rasterMvec(SDL_Renderer* renderer, const playground::Bytes& b, const std::string& text,
int lineHeight, SDL_Color ink, int outlineSize, SDL_Color outlineInk) {
std::vector<Glyph> glyphs;
float ascent=0, descent=0;
if (!mvecTable(b,glyphs,ascent,descent)) return nullptr;
const float scale = lineHeight * 0.8f / std::max(1.0f, ascent+descent);
const float baseline = lineHeight*0.15f + ascent*scale;
std::vector<Edge> edges;
float pen = static_cast<float>(outlineSize+2);
for (uint32_t code : decodeUtf8(text)) {
auto found = std::find_if(glyphs.begin(),glyphs.end(),[&](const Glyph& g){return g.code==code;});
if (found == glyphs.end()) found = std::find_if(glyphs.begin(),glyphs.end(),[](const Glyph& g){return g.code=='?';});
if (found == glyphs.end()) continue;
glyphEdges(b, found->offset, pen, scale, baseline+outlineSize, edges);
pen += found->advance*scale;
}
const int width = std::max(1, static_cast<int>(std::ceil(pen))+outlineSize+2);
const int height = std::max(1, lineHeight+outlineSize*2);
SDL_Surface* surface = SDL_CreateSurface(width,height,SDL_PIXELFORMAT_RGBA32);
if (!surface) return nullptr;
SDL_ClearSurface(surface,0,0,0,0);
// Resolve the thin MVEC strokes at subpixel precision. A binary 1x mask
// drops parts of Fertigo's smaller (16–20 px) glyphs.
constexpr int samples = 3;
const int highWidth = width * samples, highHeight = height * samples;
std::vector<uint8_t> mask(static_cast<size_t>(highWidth)*highHeight,0);
std::vector<Edge> highEdges;
highEdges.reserve(edges.size());
for (const auto& edge : edges)
highEdges.push_back({{edge.a.x*samples,edge.a.y*samples},
{edge.b.x*samples,edge.b.y*samples}});
for (int y=0; y<highHeight; ++y) {
std::vector<float> xs;
for (const auto& e : highEdges) {
const float scan = y+0.5f;
if ((e.a.y<=scan && e.b.y>scan) || (e.b.y<=scan && e.a.y>scan))
xs.push_back(e.a.x+(scan-e.a.y)*(e.b.x-e.a.x)/(e.b.y-e.a.y));
}
std::sort(xs.begin(),xs.end());
for (size_t i=0; i+1<xs.size(); i+=2) {
const int from=std::max(0,static_cast<int>(std::ceil(xs[i]-0.5f)));
const int to=std::min(highWidth,static_cast<int>(std::ceil(xs[i+1]-0.5f)));
for (int x=from;x<to;++x) mask[static_cast<size_t>(y)*highWidth+x]=1;
}
}
std::vector<uint8_t> borderMask;
if (outlineSize) {
borderMask.resize(mask.size(),0);
const int radius = outlineSize * samples;
for (int y=0; y<highHeight; ++y) for (int x=0; x<highWidth; ++x) {
if (mask[static_cast<size_t>(y)*highWidth+x]) continue;
bool border = false;
for (int dy=-radius;dy<=radius && !border;++dy)
for (int dx=-radius;dx<=radius;++dx) {
const int nx=x+dx,ny=y+dy;
if (dx*dx+dy*dy<=radius*radius && nx>=0 && nx<highWidth && ny>=0 && ny<highHeight &&
mask[static_cast<size_t>(ny)*highWidth+nx]) {border=true;break;}
}
borderMask[static_cast<size_t>(y)*highWidth+x]=border;
}
}
SDL_LockSurface(surface);
for (int y=0; y<height; ++y) {
auto* row = reinterpret_cast<uint32_t*>(static_cast<uint8_t*>(surface->pixels)+y*surface->pitch);
for (int x=0; x<width; ++x) {
int fillCount=0, borderCount=0;
for (int sy=0;sy<samples;++sy) for (int sx=0;sx<samples;++sx) {
const size_t at=static_cast<size_t>(y*samples+sy)*highWidth+x*samples+sx;
fillCount += mask[at] != 0;
if (outlineSize) borderCount += borderMask[at] != 0;
}
const int fillAlpha=fillCount*ink.a, borderAlpha=borderCount*outlineInk.a;
const int totalAlpha=fillAlpha+borderAlpha;
if (totalAlpha) {
row[x]=SDL_MapSurfaceRGBA(surface,
static_cast<uint8_t>((fillAlpha*ink.r+borderAlpha*outlineInk.r)/totalAlpha),
static_cast<uint8_t>((fillAlpha*ink.g+borderAlpha*outlineInk.g)/totalAlpha),
static_cast<uint8_t>((fillAlpha*ink.b+borderAlpha*outlineInk.b)/totalAlpha),
static_cast<uint8_t>(totalAlpha/(samples*samples)));
}
}
}
SDL_UnlockSurface(surface);
SDL_Texture* texture=SDL_CreateTextureFromSurface(renderer,surface);
SDL_DestroySurface(surface);
return texture;
}
} // namespace
namespace playground {
Draw::Draw(SDL_Renderer* renderer, const Vfs& assets) : renderer_(renderer), assets_(assets) {
ttfReady_ = TTF_Init();
}
Draw::~Draw() {
clear();
for (auto& [_, font] : sizedFonts_) if (font) TTF_CloseFont(font);
if (ttfReady_) TTF_Quit();
}
void Draw::clear() {
for (auto& [_, texture] : textures_) SDL_DestroyTexture(texture);
textures_.clear();
for (auto& [_, texture] : textTextures_) SDL_DestroyTexture(texture);
textTextures_.clear();
}
SDL_Texture* Draw::load(const std::string& path) {
const auto found = textures_.find(path);
if (found != textures_.end()) return found->second;
Bytes bytes;
if (!assets_.read(path, bytes) || bytes.empty()) return nullptr;
SDL_IOStream* stream = SDL_IOFromConstMem(bytes.data(), bytes.size());
if (!stream) return nullptr;
SDL_Surface* surface = IMG_Load_IO(stream, true);
if (!surface) return nullptr;
SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer_, surface);
SDL_DestroySurface(surface);
if (!texture) return nullptr;
SDL_SetTextureScaleMode(texture, SDL_SCALEMODE_LINEAR);
textures_.emplace(path, texture);
return texture;
}
bool Draw::image(const std::string& path, const SDL_FRect& destination) {
return image(path, nullptr, destination);
}
bool Draw::image(const std::string& path, const SDL_FRect* source, const SDL_FRect& destination) {
SDL_Texture* texture = load(path);
return texture && SDL_RenderTexture(renderer_, texture, source, &destination);
}
bool Draw::text(const std::string& utf8, float x, float y, SDL_Color color,
int pointSize, float alignWidth, bool center,
const std::string& fontName, int outlineSize, SDL_Color outlineColor) {
if (utf8.empty()) return true;
if (pointSize < 1) pointSize = 1;
if (outlineSize < 0) outlineSize = 0;
if (fontName.ends_with(".mvec")) {
auto it = vectorFonts_.find(fontName);
if (it == vectorFonts_.end()) {
Bytes bytes;
assets_.read(fontName, bytes);
it = vectorFonts_.emplace(fontName, std::move(bytes)).first;
}
if (!it->second.empty()) {
std::string key = "mvec:" + fontName + ":" + std::to_string(pointSize) + ":" + utf8;
key.append({static_cast<char>(color.r),static_cast<char>(color.g),
static_cast<char>(color.b),static_cast<char>(color.a),
static_cast<char>(outlineSize),static_cast<char>(outlineColor.r),
static_cast<char>(outlineColor.g),static_cast<char>(outlineColor.b),
static_cast<char>(outlineColor.a)});
SDL_Texture* texture = nullptr;
if (auto cached = textTextures_.find(key); cached != textTextures_.end()) texture=cached->second;
else {
texture=rasterMvec(renderer_,it->second,utf8,pointSize,color,outlineSize,outlineColor);
if (texture) textTextures_.emplace(key,texture);
}
if (texture) {
const float left=x+(center?(alignWidth-static_cast<float>(texture->w))/2:0);
const SDL_FRect destination{left,y,static_cast<float>(texture->w),static_cast<float>(texture->h)};
return SDL_RenderTexture(renderer_,texture,nullptr,&destination);
}
}
if (warnedVectorFonts_.insert(fontName).second)
SDL_LogWarn(SDL_LOG_CATEGORY_RENDER,"MVC4 font %s failed; using default fallback",fontName.c_str());
}
// Applications may provide their own optional TrueType fallback.
const std::string face = "fonts/default.ttf";
const std::string fontKey = face + ":" + std::to_string(pointSize);
TTF_Font* selected = nullptr;
if (ttfReady_) {
auto it = sizedFonts_.find(fontKey);
if (it == sizedFonts_.end()) {
const std::string path = std::string(SDL_GetBasePath()) + face;
selected = TTF_OpenFont(path.c_str(), static_cast<float>(pointSize));
sizedFonts_.emplace(fontKey, selected);
} else selected = it->second;
}
if (selected) {
std::string key = fontName + ":" + fontKey + ":" + utf8;
key.push_back('\0');
key.append({static_cast<char>(color.r), static_cast<char>(color.g),
static_cast<char>(color.b), static_cast<char>(color.a)});
const auto cachedText = [&](const std::string& cacheKey, SDL_Color ink, int outline) -> SDL_Texture* {
if (const auto found = textTextures_.find(cacheKey); found != textTextures_.end()) return found->second;
TTF_SetFontOutline(selected, outline);
SDL_Surface* surface = TTF_RenderText_Blended(selected, utf8.c_str(), utf8.size(), ink);
TTF_SetFontOutline(selected, 0);
if (!surface) return nullptr;
SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer_, surface);
SDL_DestroySurface(surface);
if (texture) textTextures_.emplace(cacheKey, texture);
return texture;
};
SDL_Texture* fill = cachedText(key, color, 0);
if (!fill) return false;
const float left = x + (center ? (alignWidth-static_cast<float>(fill->w))/2 : 0);
if (outlineSize > 0) {
std::string outlineKey = key + ":outline:" + std::to_string(outlineSize);
outlineKey.append({static_cast<char>(outlineColor.r), static_cast<char>(outlineColor.g),
static_cast<char>(outlineColor.b), static_cast<char>(outlineColor.a)});
SDL_Texture* outline = cachedText(outlineKey, outlineColor, outlineSize);
if (outline) {
const SDL_FRect border{left-static_cast<float>(outlineSize), y-static_cast<float>(outlineSize),
static_cast<float>(outline->w), static_cast<float>(outline->h)};
SDL_RenderTexture(renderer_, outline, nullptr, &border);
}
}
const SDL_FRect destination{left, y, static_cast<float>(fill->w), static_cast<float>(fill->h)};
return SDL_RenderTexture(renderer_, fill, nullptr, &destination);
}
// Visible fallback when the application has no TrueType font.
SDL_SetRenderDrawColor(renderer_, color.r, color.g, color.b, color.a);
return SDL_RenderDebugText(renderer_, x, y, utf8.c_str());
}
} // namespace playground