#include "gfx/draw.h" #include #include #include #include #include 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(b[p] | (b[p + 1] << 8)); } int16_t s16(const playground::Bytes& b, size_t p) { return static_cast(u16(b, p)); } uint32_t u32(const playground::Bytes& b, size_t p) { return static_cast(b[p]) | (static_cast(b[p+1]) << 8) | (static_cast(b[p+2]) << 16) | (static_cast(b[p+3]) << 24); } std::vector decodeUtf8(const std::string& text) { std::vector codes; for (size_t i = 0; i < text.size();) { const auto c = static_cast(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(text[i++]) & 0x3f); codes.push_back(value); } return codes; } bool mvecTable(const playground::Bytes& b, std::vector& glyphs, float& ascent, float& descent) { if (b.size() < 12 || std::string(reinterpret_cast(b.data()), 4) != "MVC4") return false; const uint16_t count = u16(b, 4); if (12 + static_cast(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& 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(std::ceil(length/3.0f)), 4, 32); Point from = current; for (int i=1; i<=steps; ++i) { const float t = static_cast(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 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 edges; float pen = static_cast(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(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 mask(static_cast(highWidth)*highHeight,0); std::vector 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 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(std::ceil(xs[i]-0.5f))); const int to=std::min(highWidth,static_cast(std::ceil(xs[i+1]-0.5f))); for (int x=from;x(y)*highWidth+x]=1; } } std::vector borderMask; if (outlineSize) { borderMask.resize(mask.size(),0); const int radius = outlineSize * samples; for (int y=0; y(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=0 && ny(ny)*highWidth+nx]) {border=true;break;} } borderMask[static_cast(y)*highWidth+x]=border; } } SDL_LockSurface(surface); for (int y=0; y(static_cast(surface->pixels)+y*surface->pitch); for (int x=0; x(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((fillAlpha*ink.r+borderAlpha*outlineInk.r)/totalAlpha), static_cast((fillAlpha*ink.g+borderAlpha*outlineInk.g)/totalAlpha), static_cast((fillAlpha*ink.b+borderAlpha*outlineInk.b)/totalAlpha), static_cast(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(color.r),static_cast(color.g), static_cast(color.b),static_cast(color.a), static_cast(outlineSize),static_cast(outlineColor.r), static_cast(outlineColor.g),static_cast(outlineColor.b), static_cast(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(texture->w))/2:0); const SDL_FRect destination{left,y,static_cast(texture->w),static_cast(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(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(color.r), static_cast(color.g), static_cast(color.b), static_cast(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(fill->w))/2 : 0); if (outlineSize > 0) { std::string outlineKey = key + ":outline:" + std::to_string(outlineSize); outlineKey.append({static_cast(outlineColor.r), static_cast(outlineColor.g), static_cast(outlineColor.b), static_cast(outlineColor.a)}); SDL_Texture* outline = cachedText(outlineKey, outlineColor, outlineSize); if (outline) { const SDL_FRect border{left-static_cast(outlineSize), y-static_cast(outlineSize), static_cast(outline->w), static_cast(outline->h)}; SDL_RenderTexture(renderer_, outline, nullptr, &border); } } const SDL_FRect destination{left, y, static_cast(fill->w), static_cast(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