Culling and the frame
Text from a bitmap font
An engine often needs to show a few lines of text before it has any UI: frame times, counters, a warning. The smallest way to do it needs no font file, no texture and no text layout library: a tiny font stored as bits inside the shader, a buffer of character codes, and one rectangle whose pixels look up their own bit. This page explains how that works, and what the bigger alternatives do. The last part shows how RASM does it.
In short
- A bitmap font stores each character (a glyph) as a small grid of on/off pixels. An 8×8 glyph is 64 bits: one byte per row.
- Two 32-bit integers hold one glyph. The 94 printable ASCII characters fit in 752 bytes, small enough to live as a constant array in the shader.
- The CPU writes the text as a grid of character codes, row by row, into a small buffer, 4 characters per integer.
- One quad covers the text area. For each pixel, the fragment shader finds the cell (which character), the glyph pixel inside it, and the bit: on gives the text color, off the background.
- An integer scale keeps the pixels sharp on big screens.
- Font atlases and SDF fonts give nicer, proportional, scalable text, at the price of textures, per-glyph quads and a layout step.
1The problem
Normal text rendering is a large system. It is the right tool for game UI:
- Font fileload TrueType or OpenType
- Rasterizeturn the outlines of each glyph into pixels
- Atlaspack the glyphs into a texture
- Layoutplace the string with the right spacing and kerning
- Drawone textured quad per character
That is too much for a debug overlay that must work on the first day of a new engine, with nothing else in place. The minimal version gives up a lot on purpose:
A full text renderer
A font file, a texture, a layout step, and a quad for every character, each with its own width.
The minimal version
One fixed size, one fixed width per character, plain ASCII, no smoothing. In return it needs a short shader, a little C++, no assets, and one draw call.
2A font as bits
A bitmap font stores each glyph as a grid of pixels that are either on or off. Old computers worked this way: the IBM PC's VGA text mode drew every character from an 8×8 or 8×16 grid stored in ROM. An 8×8 grid has 8 rows of 8 pixels. One row is 8 bits, exactly one byte.
Here bit 0 is the leftmost pixel. The other order (bit 7 on the left) is just as common.
A font only needs the characters it will show:
3Packing glyphs into integers
Shaders work best with 32-bit integers. Four rows fit in one, so a glyph is two integers: rows 0 to 3 in the first, rows 4 to 7 in the second. The first row goes in the lowest byte:
word 0 = row0 | row1 << 8 | row2 << 16 | row3 << 24
word 1 = row4 | row5 << 8 | row6 << 16 | row7 << 24
'A': word 0 = 0x33 << 24 | 0x33 << 16 | 0x1E << 8 | 0x0C = 0x33331E0C
word 1 = 0x00 << 24 | 0x33 << 16 | 0x33 << 8 | 0x3F = 0x0033333F
Draw a glyph and watch the two words change. The grid starts with the 'A' from the picture.
To read pixel (x, y) of the glyph for character c, go from the word to the byte to the bit:
- wordthe integer: rows 0–3 or rows 4–7
- rowthe byte inside the word
- litthe bit inside the byte: the pixel
word = font[(c − 33) · 2 + y / 4] the integer: rows 0–3 or 4–7
row = (word >> ((y % 4) · 8)) & 0xFF the byte: the row
lit = (row >> x) & 1 the bit: the pixel
A 64-bit integer would hold a whole glyph, but 64-bit integers in shaders are optional on some hardware. Two 32-bit words work everywhere.
4The text as a grid
With every glyph the same width, text layout is trivial: character i of line j goes in column i, row j of a grid. The CPU builds the grid as one string, row by row. Each line is padded with spaces to the width of the longest one, so every row has the same length, and the position of a cell is simple arithmetic:
Shaders often cannot read single bytes from a buffer, so the grid is read as 32-bit words and the byte is picked out: word i / 4, then shift by (i % 4) · 8 and mask with 0xFF. A space, or any code outside the font's range, is drawn as background.
5One quad, and a lookup per pixel
The draw itself is the simplest possible: one rectangle over the area where the text goes. All the work happens in the fragment shader, once per pixel of the rectangle.
- CPUtext grid, grid size, scale
- Text buffercharacter codes
- Vertex shader × 6corner → pixel → clip space
- Rasterizerone fragment per covered pixel
- Fragment shaderper pixel: cell, character, glyph pixel, bit
From a pixel to its bit
Let the text start at pixel o (the panel's corner plus a margin), each font pixel be s × s screen pixels, and glyphs be 8 × 8. For a fragment at pixel p:
t = p − o pixel, from the text's corner
if t.x < 0 or t.y < 0: background (the padding)
f = t / s font pixel (integer division)
cell = f / 8 character cell (column, row)
if cell.x ≥ columns or cell.y ≥ rows: background
g = f % 8 pixel inside the glyph
code = byte number (cell.y · columns + cell.x) of the text
if code is outside the font: background
lit = bit g.x of row g.y of the glyph of code
Every step is integer math. Division drops the remainder, and % keeps it. Because the scale is a whole number, each font pixel covers exactly s × s screen pixels, and the edges stay sharp.
6Worked example
The two lines from section 4 (14 columns, 2 rows) on a 3840 × 2160 screen, with scale s = 2 and the text starting at o = (16, 16). Which color does the fragment at pixel (34, 42) get?
1. The panel
Drawn at 1 SVG unit per screen pixel. The panel is the text grid plus padding on all four sides, times the scale.
2. Pixel → font pixel → cell
The pixel is in cell (1, 1), at column 1, row 5 of that cell's glyph.
3. Cell → character
Rows are not aligned to words: a word can hold the end of one row and the start of the next. The index arithmetic does not care.
4. Character → bit
One array read, two shifts and two masks. The pixel is part of the stem of the P.
Now move the pixel yourself. The panel below is drawn by running this lookup for every screen pixel. It starts at pixel (34, 42).
7Placing, scaling, readability
Scale
A whole number, picked from the screen size, for example screen height / 1080. 8×8 glyphs are tiny on a 4K screen. A whole-number scale keeps every font pixel the same size.
Fractional: some font pixels are one screen pixel wider than others
Position
In screen pixels, from a corner. The vertex shader turns pixels into clip space: xclip = x / width · 2 − 1, and y flipped if the API's clip space points up.
Background
An opaque box, a translucent box, an outline, a drop shadow, or nothing. An opaque box is always readable and needs no blending. A translucent one needs alpha blending.
No box: needs an outline or a shadow to stay readable over a bright scene
Depth
The overlay must win over the scene. Either draw it last with the depth test off, or put the quad at the depth value that means "nearest".
Update rate
Every frame, or a few times per second. Numbers that change every frame cannot be read. See GPU timing.
8Alternatives, and what they cost
The per-pixel bitmap font is the simplest end of a range. Each step up the range solves a limit of the one before:
Bitmap font, per-pixel lookup
This page. One quad over the text area; the fragment shader finds the bit.
Good: no assets, no textures, one draw, a few lines of code.
Limits: one size, fixed width, ASCII only, no smoothing; every pixel of the box runs the shader, blank or not
Font atlas
Glyphs rasterized from a TrueType font (for example with stb_truetype or FreeType) into one texture; one textured quad per character.
Good: any font, proportional widths, kerning, anti-aliased edges, many languages.
Limits: a texture per size; a layout step on the CPU; blurry when scaled up
Signed distance field (SDF) atlas
The atlas stores the distance to the glyph's edge instead of coverage; the shader thresholds it (Green, 2007).
Good: one atlas for many sizes; cheap outlines, shadows and glow.
Limits: round corners at large sizes; MSDF (multi-channel) keeps corners sharp
Vector glyphs on the GPU
The shader evaluates the glyph's curves directly (Loop and Blinn, 2005; the Slug library).
Good: sharp at every size and angle, for text in the 3D world.
Limits: much more complex; heavier per pixel
A UI library
Dear ImGui and similar: an atlas, plus widgets.
Good: windows, buttons, graphs, input.
Limits: a dependency, its own render pass
The two ways to cover the text with geometry:
One big quad
6 vertices for any amount of text. Cost: the fragment shader runs on every pixel of the box, including empty space and padding. For a small box that is a few hundred thousand pixels at most: tiny for a GPU.
One quad per character
6 vertices per character, built on the CPU or expanded by a shader. Only glyph areas are shaded, and each character can have its own size and position. This is how most text renderers work.
9In RASM
RASM uses exactly the method of sections 2 to 6 for its stats overlay, the panel that shows the numbers from GPU timing and frame statistics. The font, the lookup and the panel layout are in one shader, shaders/passes/statsOverlay.slang. The text is built on the CPU in src/renderer/statsOverlay.cpp. F1 turns it on and off (showStats). With the Dear ImGui UI on (EngineConfig::ui), the same numbers show in the RASM window instead, and the overlay is not drawn; see Immediate-mode UI.
The push constant
OverlayPushConstants in statsOverlay.cpp mirrors PushConstants in statsOverlay.slang. A static_assert checks it is exactly PUSH_CONSTANTS_SIZE (16 bytes).Where RASM follows the textbook, and where it differs
| Part | This page | RASM |
|---|---|---|
| Font | 8×8, 1 bit, bit 0 on the left | The same: the public-domain IBM VGA 8x8 font, ! to ~ (FIRST_CHAR 33, LAST_CHAR 126), as FONT[188] in the shader. |
| Text grid | row by row, padded, 4 codes per word | The same. buildGrid pads lines to the longest one, cut at MAX_TEXT_COLUMNS = 40 columns and MAX_TEXT_ROWS = 76 rows, room for every GPU timer. One host-visible buffer of 3040 bytes per frame slot. |
| Update rate | a few times per second | The text is rebuilt every 0.25 s of frame time (TEXT_REFRESH; gridAge adds up the engine's deltaTime, so EngineConfig::fixedDeltaTime rebuilds it on the same frames in every run); the current grid is copied into the slot's buffer every frame. |
| Geometry | one quad, no vertex buffer | The same: draw of 6 vertices; vertMain builds the corners from SV_VertexID. The triangles wind clockwise on screen, so the draw sets CullMode::NONE. |
| Placement | pixels from a corner | 8 screen pixels from the top-left corner (MARGIN), text 4 font pixels inside the panel (PADDING). Viewport and scissor are reset to the whole window first. |
| Scale | a whole number from the screen size | max(1, swapchain height / 1080): 1 at 1080p, 2 at 2160p. |
| Background | opaque, translucent, outline … | Opaque, no blending: BACKGROUND near black, FOREGROUND light grey, both linear colors. |
| Depth | depth test off, or nearest depth | Drawn last, in a pass with no depth attachment, so nothing is tested. The shader still puts the panel at depth 1, the nearest value under reversed-Z (see Projection and reversed-Z depth). |
| When drawn | last | Once per frame, after every other pass: endFrame calls drawStatsOverlay, which begins a pass of its own on the window that loads the color (so the frame's image stays) and has no depth attachment, so it costs no depth clear. The pass has no GPU timer. |
| Alternatives | atlas, SDF, UI library | A UI library: with EngineConfig::ui the stats show in a Dear ImGui window, with an atlas font, and this overlay is off (Immediate-mode UI). The overlay stays for programs without the UI, and for a rasm built without ImGui. |
Where it lives in code
| What | Where |
|---|---|
| Font, panel, per-pixel lookup | FONT, vertMain, fragMain in shaders/passes/statsOverlay.slang |
| Text and grid | buildText, buildGrid in src/renderer/statsOverlay.cpp; formatCount in src/renderer/frameStats.cpp |
| Buffers and pipeline | Renderer::createStatsOverlay; per-slot state StatsOverlaySlot in src/renderer/statsOverlay.h |
| Per-frame copy, the draw | Renderer::updateStatsOverlay, Renderer::drawStatsOverlay in src/renderer/statsOverlay.cpp |
| Where it is called | Renderer::beginFrame and Renderer::endPass in src/renderer/renderer.cpp |
F1, showStats | Renderer::pollEvents in src/renderer/renderer.cpp, the SDL events in src/platform/sdlPlatform.cpp; EngineConfig in include/rasm/types.h |
OverlayPushConstants(C++) andPushConstantsinstatsOverlay.slangchange together and stay at 16 bytes (PUSH_CONSTANTS_SIZE).- Columns and rows must fit 8 bits each, the screen size 16 bits per side. A bigger grid also needs a bigger text buffer.
- The overlay's pass and pipeline have no depth (
Format::UNKNOWN): it stays on top because it is drawn last. Give the pipeline a depth format and its draws are skipped. - A shader that fails to compile only turns the overlay off; the engine keeps running.
Further reading
- Chris Green, Improved Alpha-Tested Magnification for Vector Textures and Special Effects, SIGGRAPH 2007 course: SDF text.
- Viktor Chlumský, Shape Decomposition for Multi-channel Distance Fields, master's thesis (2015): MSDF.
- Charles Loop and Jim Blinn, Resolution Independent Curve Rendering using Programmable Graphics Hardware, SIGGRAPH 2005.
- Sean Barrett, stb_truetype.h: a single-file font rasterizer for building atlases.