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:

  1. Font fileload TrueType or OpenType
  2. Rasterizeturn the outlines of each glyph into pixels
  3. Atlaspack the glyphs into a texture
  4. Layoutplace the string with the right spacing and kerning
  5. 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:

ABC abc 123 glyphs in a texture F r a m e … one quad per character

A full text renderer

A font file, a texture, a layout step, and a quad for every character, each with its own width.

one quad, 14 cells of the same size F r a m e 1 6 . 6 7 m s font: bits in the shader text: character codes in a buffer

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.

0123 4567 0123 4567 x: bit 0 is the leftmost pixel byte 0x0C 0x1E 0x33 0x33 0x3F 0x33 0x33 0x00 Row 2 = 0x33 0123 4567 bit 1100 1100 value Written as a binary number, the highest bit is on the left: 0011 0011 the pixels are this number read right to left
The last row and the rightmost two columns are empty. They are the space between lines and between letters, so the glyphs can be drawn edge to edge.
A font and its reader must agree on the bit order

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:

ASCII codes 0 … 127 0 … 31: control codes ! (33) … ~ (126): 94 glyphs in the font 32: the space, no glyph
The printable ASCII characters go from ! (code 33) to ~ (code 126): 94 glyphs. The space (code 32) needs no glyph: it is all background.

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:

0x0C 0x1E 0x33 0x33 0x3F 0x33 0x33 0x00 'A', one byte per row a 32-bit word, written high byte first: row 0 is in the lowest byte bits 31–2423–1615–87–0 0x33row 3 0x33row 2 0x1Erow 1 0x0Crow 0 word 0 = 0x33331E0C 0x00row 7 0x33row 6 0x33row 5 0x3Frow 4 word 1 = 0x0033333F
One glyph is 64 bits: two words of four row bytes each.
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.

Click a pixel in row 0: only the lowest byte of word 0 changes. Click one in row 7: the highest byte of word 1 changes. The small picture shows the glyph three times, edge to edge, as text draws it.
188integers in the whole font94 · 2
752 bytessmall enough to be a constant array in the shader source188 · 4
0textures, uploads and samplers

To read pixel (x, y) of the glyph for character c, go from the word to the byte to the bit:

  1. wordthe integer: rows 0–3 or rows 4–7
  2. rowthe byte inside the word
  3. 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
Why not one 64-bit integer?

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:

lines Frame 16.67 ms GPU 1.31 ms pad grid: 14 columns × 2 rows 0 1 2 3 4 5 6 7 8 9 10 11 12 13 F r a m e 1 6 . 6 7 m s G P U 1 . 3 1 m s · · · row 0: index 0 … 13 row 1: index 14 … 27 · = padding spaces index(column, row) = row · columns + column 'P' is at (1, 1) → index 1 · 14 + 1 = 15 buffer: 4 characters per 32-bit word, the first in the low byte F r a m e 1 6 . 6 7 m s G P U 1 . 3 1 m s · · · word 0 word 1 word 2 word 3 word 4 word 5 word 6 index i → word i / 4, byte i % 4. Word 3 holds the end of row 0 and the start of row 1.
The buffer only holds codes, one byte each. A 40 × 25 grid is 1000 bytes. The CPU rewrites it whenever the text changes.

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.

  1. CPUtext grid, grid size, scale
  2. Text buffercharacter codes
  3. Vertex shader × 6corner → pixel → clip space
  4. Rasterizerone fragment per covered pixel
  5. Fragment shaderper pixel: cell, character, glyph pixel, bit
1 One quad on the screen 2 triangles, 6 vertices, no vertex buffer: the corners come from the vertex index 2 Pixel → cell → code Frame1 GPU1.3 the cell says which character; its code comes from the text buffer … 'm' 's' 'G' 'P' 'U' … 3 Glyph pixel → bit on: text color · off: background
No textures and no blending. Every pixel of the rectangle gets a color, so the panel is an opaque box behind the text. The rectangle is two triangles (6 vertices) and needs no vertex buffer: the vertex shader makes the 4 corners from the vertex index and the panel's size.

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

window, top-left corner Frame 16.67 ms GPU 1.31 ms pixel (34, 42) margin: 8 pixels from the window corner padding: 4 font pixels = 8 screen pixels so the text starts at o = (16, 16) scale s = 2: a glyph is 16 × 16 screen pixels panel width = (14 · 8 + 2 · 4) · 2 = 240 panel height = (2 · 8 + 2 · 4) · 2 = 48

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

x 0 x 1 x 2 y 0 y 1 cells of the grid, one font pixel drawn 9 units wide p = (34.5, 42.5) t = (34, 42) − (16, 16) = (18, 26) f = t / 2 = (9, 13) cell = f / 8 = (1, 1) g = f % 8 = (1, 5) A fragment's position is the center of its pixel, so it is rounded down to whole pixels first.

The pixel is in cell (1, 1), at column 1, row 5 of that cell's glyph.

3. Cell → character

index = cell.y · columns + cell.x = 1 · 14 + 1 = 15 word = text[15 / 4] = text[3] byte = 15 % 4 = 3 → (word >> 24) & 0xFF word 3 'm' 0x6D byte 0 · index 12 's' 0x73 byte 1 · index 13 'G' 0x47 byte 2 · index 14 'P' 0x50 byte 3 · index 15 low byte first: the word is 0x5047736D 'm' and 's' end row 0 (indices 12, 13), 'G' starts row 1. 0x50 = 80 = 'P', inside 33 … 126, so it has a glyph.

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

0 5 0 1 x → font[(80 − 33) · 2 + 5 / 4] = font[95]                            = 0x000F0606 row = (0x000F0606 >> (5 % 4) · 8) & 0xFF      = 0x06 = 0000 0110 lit = (0x06 >> 1) & 1 = 1 → the text color Rows 4 to 7 of 'P' are in its second word: 0x06, 0x06, 0x0F, 0x00.

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).

Drag the orange point over a letter, a space, the padding and the area outside the panel. Then set the scale to 1: the same pixel now falls in another place.

7Placing, scaling, readability

scale 2: every font pixel 2 wide scale 1.5: 1 or 2 wide

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

−1 x in clip space +1

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.

opaque translucent outline nothing

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

eye overlay nearest scene farther

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".

every frame: the digits flicker a few times per second: readable 16.716.916.6

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

ABC abc 123 T e x t

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

edge: distance 0 rings: equal distance to it

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

inside control point

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

Stats Button

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:

F r a m e 1 6 . 6 7 m s the shader runs on every pixel of the box

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.

F r a m e 1 6 . 6 7 m s only the glyph areas are shaded

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.

CPU · every 0.25 s of frame time buildText FrameStats → lines buildGrid pad to columns × rows CPU · every frame updateStatsOverlay fillBuffer into the slot's buffer Stats Overlay Text s 3040 bytes, host-visible, per slot CPU · endFrame, after every other pass drawStatsOverlay: own pass, load color · viewport = window, CullMode::NONE, bind pipeline, push 16 bytes, draw 6 statsOverlay.slang: vertMain places the panel, fragMain looks up each pixel's bit FONT[188] in the shader · reads the grid through the buffer's device address
Each frame slot draws from its own text buffer, so the CPU can rewrite one while the GPU may still read the other. See Frames in flight.

The push constant

byte 0 8 12 16 text 64-bit device address of the slot's text buffer grid cols | rows<<8 | scale<<16 screen width | height<<16 29 | 11<<8 | 2<<16 = 0x00020B1D 3840 | 2160<<16 = 0x08700F00 example: a 29 × 11 grid at 3840 × 2160, scale 2
RASM's push-constant range is 16 bytes, so the grid size, the scale and the screen size are packed into two words. Columns and rows fit 8 bits each (at most 40 and 76); the screen size fits 16 bits per side. 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

PartThis pageRASM
Font8×8, 1 bit, bit 0 on the leftThe same: the public-domain IBM VGA 8x8 font, ! to ~ (FIRST_CHAR 33, LAST_CHAR 126), as FONT[188] in the shader.
Text gridrow by row, padded, 4 codes per wordThe 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 ratea few times per secondThe 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.
Geometryone quad, no vertex bufferThe same: draw of 6 vertices; vertMain builds the corners from SV_VertexID. The triangles wind clockwise on screen, so the draw sets CullMode::NONE.
Placementpixels from a corner8 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.
Scalea whole number from the screen sizemax(1, swapchain height / 1080): 1 at 1080p, 2 at 2160p.
Backgroundopaque, translucent, outline …Opaque, no blending: BACKGROUND near black, FOREGROUND light grey, both linear colors.
Depthdepth test off, or nearest depthDrawn 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 drawnlastOnce 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.
Alternativesatlas, SDF, UI libraryA 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

WhatWhere
Font, panel, per-pixel lookupFONT, vertMain, fragMain in shaders/passes/statsOverlay.slang
Text and gridbuildText, buildGrid in src/renderer/statsOverlay.cpp; formatCount in src/renderer/frameStats.cpp
Buffers and pipelineRenderer::createStatsOverlay; per-slot state StatsOverlaySlot in src/renderer/statsOverlay.h
Per-frame copy, the drawRenderer::updateStatsOverlay, Renderer::drawStatsOverlay in src/renderer/statsOverlay.cpp
Where it is calledRenderer::beginFrame and Renderer::endPass in src/renderer/renderer.cpp
F1, showStatsRenderer::pollEvents in src/renderer/renderer.cpp, the SDL events in src/platform/sdlPlatform.cpp; EngineConfig in include/rasm/types.h
Keep these true
  • OverlayPushConstants (C++) and PushConstants in statsOverlay.slang change 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