How to keep all of the glyphs on a single texture? (SDL_ttf)

Hello, I’m trying to render some texts on the window, and creating a surface and turning it to a texture every frame isn’t a fast and good idea, so I’ve been informed about TTF_GlyphMetrics which allows me to make a texture out of each character once and render it multiple time every frames, which does make my game so much faster, but there is a problem, each of these letters currently have their own texture, if I have 5 fonts, I use each of them in 3 sizes, and use 100 different characters, I’m going to have 1500 textures, so I’m planning to keep all of the characters which share font and font size, on a single textures, so not only I’ll have to deal with 15 textures instead 1500, but also according to this answer on stack-exchange, the rendering will be done faster

So my question is: What’s an simple solution to keep all of the glyphs which share font and font size in a single texture?

(My fonts aren’t mono-spaced)

Some kind of rectangle packing algorithm.

Look into something like stb_rect_pack. You give it a bounding rectangle (the size of your font texture) and a list of smaller rectangles to fit inside (corresponding to the size of each glyph) and it gives you back a list of where each of the smaller rectangles fit inside the bigger one. It’s then up to you to render each glyph at the corresponding position in the font texture, as well as keep track of where they are (and also the Y offset and X advance for each) so later you can use it to render text.

But if you’re going that route, maybe forget about SDL_TTF and instead use stb_truetype which handles most of that for you.

Either way (do it yourself or use stb_truetype) will work fine with variable-width fonts.

You can look for example font atlas code here: Signed Distance Field Fonts