Drawing

Text and labels

A map names its places: towns, streets, mountains. The names stand at points in the world, but they are read on the screen: they keep their size in pixels, face the viewer, stay sharp at any size, and never cover each other. This page shows how: glyphs stored as distances to their edge, a halo from the same distances, text laid out from the font's metrics, labels spread across the screen from a world anchor, a placement each frame that keeps the most important names, and what depth, MSAA and TAA need. The last part shows how RASM does it.

In short

  • A font's glyphs go into an atlas of signed distances to their edge, not of coverage. Distances blend into straight lines, so a magnified edge stays one pixel wide.
  • A fragment turns the distance into screen pixels and covers what is inside: coverage = saturate(distance + 0.5). A halo is the same test a few pixels further out.
  • Text is laid out with a pen: each glyph moves it by its advance, and kerning moves pairs such as "AV" closer.
  • A label has a world anchor; its glyph quads are spread around the anchor's point on the screen, in pixels.
  • Each frame, each view places its labels: the highest priority first, each one only where no placed box is. Equal labels keep the winner of the last frame, and labels fade in and out.
  • A label is shown or hidden whole, by whether its anchor is in front of what the scene drew there. It moves with its anchor and has no TAA jitter, so it stays sharp.

1The problem

Text on a map has three needs that ordinary textures do not meet. (The stats overlay's text is another case: fixed-size debug text from bits, see Text from a bitmap font.)

12 pxHarbour 40 px Harbour

Sharp at any size

One atlas serves 10 px and 60 px text. A scaled bitmap blurs; distances do not.

Marlow

In the world, on the screen

The name stands at a world point but faces the viewer, upright, at a size in pixels.

Old TownHarbourQuay Harbour overlapplaced by priority

Never on top of each other

A dense map has more names than room. Each frame keeps the important ones that fit.

2Glyphs as distances

An atlas texel can store how much of it the glyph covers (a bitmap), or its signed distance to the glyph's edge: positive inside, negative outside. The texture filter blends neighbour texels in a straight line. A blend of coverage is a soft ramp; a blend of distances is still a distance, so the edge, where the distance is 0, stays a sharp line between the texels.

coverage (bitmap) 000.411 0.5 magnified: a ramp many pixels wide, a blurry edge signed distance −2−10.21.22.2 0 the line crosses 0 at one point: the edge, sharp
The atlas stores 0.5 + distance / range in 8 bits: 0.5 on the edge. range is how many atlas texels the stored values span; distances farther out are clamped to 0 or 1.

The fragment shader turns the stored value back into a distance in screen pixels, then covers the part of the pixel that is inside. How many screen pixels one atlas texel spans comes from how fast the atlas coordinate moves across the screen (fwidth), so it works for any size and any tilt:

screenRange = range · (screen pixels per atlas texel)

distance = (value − 0.5) · screenRange

coverage = saturate(distance + 0.5)

value
the bilinear sample of the atlas, 0 to 1
screen pixels per atlas texel
1 / fwidth(texel coordinate): 2 when the text is drawn twice as large as the atlas
coverage
the fragment's alpha: 1 more than half a pixel inside, 0 more than half a pixel outside, a one-pixel ramp across the edge
Make the text large: the bitmap blurs, the distance field stays sharp. Then add a halo and make the text small: past the range the atlas holds, the halo is cut.

A distance atlas is small: 32 texels per em is enough for map text from 8 to 60 pixels. Very large text shows the atlas's own limits: the corners of a glyph become slightly round, because one distance per texel cannot hold a sharp corner. A multi-channel distance field (MSDF) stores three distances per texel and keeps the corners; it reads the same way, through the median of the three.

3The halo

A label over a busy map needs a halo: a band of a second color around each glyph, so the text reads over roads and water. It is the same test, further out: saturate(distance + halo + 0.5). It can reach only as far as the atlas stores distances: half the range, in screen pixels.

Halo with each glyph

glyph 2's halo is drawn over glyph 1

Close glyphs overlap: a halo drawn after a neighbour's fill covers part of it.

All halos, then all fills

halo quads first, fill quads second

Each label emits its glyph quads twice: the halo's first, in the outline color, then the fill's.

4Laying out a line of text

Text arrives as UTF-8 bytes. They are decoded into codepoints (one to four bytes each), and each codepoint picks its glyph in the atlas. A glyph knows its quad (where it sits from the pen, and its size) and its advance, how far it moves the pen. A kerning pair moves two glyphs closer or apart.

baseline ascent descent A V e pen advance of A kerning A, V quad: offset and size box: the widest line,ascent to the last line'sdescent; each new line aline height lower,centred
Metrics are in ems, the font's size: an em of 1 is the text's size in pixels. The box around the text is what placement tests for overlap.

Where the text sits around its anchor is a choice of the style:

Center

Center

A region's name over its middle.

Above

Bottom

The text's bottom over the point: a summit's name.

Beside

Left

The text's left beside the point: a shop's name by its marker.

5In the world, on the screen

Every vertex of a label holds the same world point, its anchor, and its glyph corner in ems. The vertex shader projects the anchor, then moves the vertex across the screen by the corner times the text's size in pixels. The text faces the screen and keeps its size whatever the distance. A size in metres instead divides by the size of a pixel at the anchor, so the text shrinks with distance like the ground does.

anchor (world) camera screen Marlow corner (ems) × text size (px) project
The anchor alone goes through the camera; the text is drawn in the screen's own axes. A large world needs no care beyond the anchor's: it is projected like any vertex in render space.

6Placing labels

Each frame and each view, the labels' boxes are projected to the screen and placed greedily: sort them, then walk the list and place each one whose box touches nothing placed before it. A grid of small cells makes the test cheap: a placed box marks its cells, and a later box is free when none of its cells is marked.

  1. Projecteach label's anchor, and its box in pixels from the text's size
  2. Sorthigher priority first; among equals, the ones placed last frame first
  3. Testthe box's cells: all free, or one taken by a placed box
  4. Mark and fadea placed box marks its cells; each label fades toward shown or hidden
Zoom out: the names keep their size, so they collide and the small places go first. Switch to list order and watch a city lose its name to a village.
Lindholm Ashby equal: last frame's winner stays

Stable

Equal labels keep last frame's winner, then a fixed order. A moving camera does not make them swap every frame.

placedhidden

Fade

A label fades in and out over a fraction of a second, so a change of placement never pops.

main viewmap

Per view

Each view has its own screen, so each places its labels itself, and remembers its own fades.

7Shown or hidden whole

A label must hide behind a hill or a nearer building. The first idea is the depth test: give the text the depth of its anchor and let each pixel be tested. That cuts labels apart. The text is flat on the screen, but the world behind it is not: a hill beside the anchor rises in front of part of the text, a post or a box edge crosses it, and the label is torn, a word missing its first letters. When the camera moves, the cut moves with it and the text flickers.

So a label is tested once, at its anchor, and drawn whole or not at all. After the scene's opaque draws, and before the labels, a small pass reads the depth they left around each label's anchor. The anchor is moved toward the camera by a few pixels' size first, so the ground it stands on does not hide it, and it is tested at the 3 x 3 pixels around its own: shown when it is in front of one of them, so a thin wire or the edge of a roof right at the anchor does not make it blink. The answer fades the label in or out over a moment, as placement does, and the text is then drawn over everything.

per pixel: torn anchor Mill Road post hill in front at the anchor: whole anchor in front: shown Mill Road behind a box:hidden whole
Left: each pixel of the text against the depth behind it. Right: one answer for the label, from its anchor, and the text drawn over everything.

Placement on the CPU still runs before the depth is known: a label hidden behind a building keeps its room on the screen, so it can still push a visible label out.

8Sharp under MSAA and TAA

The glyph's edge is smoothed by its own distance, so MSAA adds nothing and takes nothing away. TAA is the risk: it moves the camera by a sub-pixel jitter each frame and blends the frames, which softens edges that already are smooth. So text is drawn without the jitter, on the same pixels every frame, and the blend of identical frames is the frame itself. When the camera moves, each glyph writes the motion of its anchor, so the history follows the text instead of smearing it.

9Culling text measured in pixels

A label's draw is culled by the bounds of its anchors. Its text reaches past them, in pixels, so the cull test pads the bounds by the farthest the text may reach (a number of ems) times the text's size, at the far side of the bounds. A label whose anchor is just off screen keeps its draw while its text may still show.

10Pitfalls

Large text is blurry
The atlas holds coverage. Store distances and turn them into coverage over one screen pixel.
The halo is cut off in a box around each letter
The halo reaches past the distances the atlas stores. Use a larger range, or a thinner halo for small text.
A letter's right side is covered by its neighbour's halo
Halo and fill are drawn glyph by glyph. Draw all of a label's halo quads first, then its fills.
Labels flicker when the camera moves
Equal labels swap places frame to frame. Prefer last frame's winner among equals, fade, and sort with a fixed tie-break.
Text shimmers or looks soft with TAA
It takes the jitter and the history blends it. Draw it without the jitter, and give it its anchor's motion.
Labels are torn by hills, posts and edges
Each pixel of the text is tested against the depth behind it. Test the anchor once, and draw the label whole or not at all.
A label on a slope blinks out
Its anchor lies on the ground, at the ground's own depth. Move it toward the camera by a few pixels' size before the test, and test a few pixels around it.
Names in Arabic or Devanagari look wrong
Those scripts need shaping: glyphs that change by their neighbours, joined, reordered. A codepoint-to-glyph layout cannot do it.

11In RASM

Labels are vector features (Vector lines, polygons and points): a mesh built by addVectorLabels and drawn with a MaterialType::VECTOR material whose VectorMaterial::font names a font. Its width is the text's size, its outlineColor and outlineWidth the halo. So labels go through the GPU culling, the blend sort, MSAA and TAA like the other vectors, and are a TileStreamer tile's content like any mesh. What is new is the font atlas and the placement each view runs on the CPU.

Exports An export places its labels once, on the whole image's pixels, with the text, the halo, the depth bias and the collision cells times its pixel scale (placeLabels takes the cell size), and with no fade. A survey frame per tile tests each anchor in the one tile that keeps it, at once; the tiles then keep those fades, so a label that crosses a tile border is drawn whole in both.
any thread the renderer's thread, each frame shaders
any thread loadFont / buildFontAtlasFontAtlas: distances, metrics addVectorLabelsglyph quads (halo, fill)and a MeshLabel each buildVectorMeshlabels kept in the build renderer createFontR8_UNORM atlas, clamped an entity's labels:a range of label slots each view: project,placeLabelsfade alpha, anchor's testlabelsPtr, labelProbesPtr shaders cull: pad byVECTOR_LABEL_REACH getVectorVertexspread, no jitter, alpha 0:collapsed shadeGlyphcoverage, halo Label Depth pass:anchor vs depth, fade
The atlas and the layout touch no renderer, so a map builds its tiles' labels on its own threads; the renderer only uploads them and places them each frame.
// From examples/25_vector_map/main.cpp: the font once, a label layer, then a tile's names on a server thread.
rasm::FontAtlas fontAtlas;
if (!engine.loadFont("fonts/Roboto-Medium.ttf", fontAtlas))
    return 1;
const rasm::FontHandle font = engine.createFont(fontAtlas);
layers[PLACE_NAMES] =
    makeLayer(engine, {.color = glm::vec4(0.15f, 0.12f, 0.1f, 1.0f), .width = 13.0f, .outlineColor = glm::vec4(1.0f, 1.0f, 1.0f, 0.9f), .outlineWidth = 2.0f, .drawOrder = 40, .font = font});
// ... on a server thread:
names.push_back({.position = place, .text = features.placeNames[p].c_str(), .priority = 1.0f, .anchor = rasm::LabelAnchor::LEFT, .offset = glm::vec2(0.2f, 0.0f)});
rasm::addVectorLabels(geometry[PLACE_NAMES], origin, *features.font, names.data(), static_cast<uint32_t>(names.size()));

Where RASM follows this page, and where it differs

TopicThis pageRASM
The atlassigned distancesFontAtlas: one byte a texel holding 0.5 + distance / distanceRange, GlyphMetrics sorted by codepoint, KerningPairs, ascent, descent, lineHeight, a fallback glyph. buildFontAtlas makes one with stb_truetype's SDF (FontLoadOptions: 32 texels per em and a range of 16 by default; ASCII and Latin-1 unless the codepoints are given), packed in rows into an atlas 512 texels wide (wider when it must, up to 4096). Renderer::createFont takes any atlas with that contract, so an application can bring its own; an MSDF atlas would need only a shader change.
Coverage, halodistance and fwidthshadeGlyph: the screen range from fwidth(uv); the halo is cut at half the range less a pixel. addVectorLabels emits each label's halo quads (uv[2].y = 1), then its fill quads; the halo quads collapse when outlineWidth is 0.
Layoutpen, advance, kerningdecodeUtf8 (a malformed byte becomes U+FFFD), findGlyph, getKerning. Lines split at a line feed and are centred; other control characters are not drawn. LabelAnchor places the box around the anchor with a gap of a quarter em; LabelDesc::offset moves it in ems. No shaping (D46).
Anchorworld point, screen offsetsEvery glyph vertex: pos the anchor, uv[0] the corner in ems, uv[1] the atlas coordinate, tangent.x the label's index in the mesh. The size is VectorMaterial::width in PIXELS or METRES; text always faces the screen.
Placementgreedy, by priority, stable, fadingplaceViewLabels in prepareSceneView, for each shaded view: each label's box from its anchor in doubles (MeshLabel), then placeLabels on cells of LABEL_CELL_PIXELS (8). Order: LabelDesc::priority, then placed last frame, then slot. Fade over LABEL_FADE_SECONDS (0.25 s) of the frame's step; a view's first placement shows at once. Each entity with labels holds a range of the renderer's MAX_LABELS slots (one that finds none left draws no labels); a slot's stamp tells a view that a new label took it, which then starts hidden. The scratch vectors keep their capacity: a steady frame allocates nothing.
To the GPU—A buffer per view and frame slot of one float per slot (SceneData::labelsPtr); the instance's first slot in InstanceData::meshletVisibility, free on a mesh with no meshlets. Alpha 0 collapses the quad.
Depththe anchor, whole labelThe Label Depth pass (shaders/passes/labelDepth.slang, recordLabelDepth), after the view's last draw pass and before Transparent. placeViewLabels gives each slot its anchor's pixel and the depth it must be in front of: its own, moved toward the camera by LABEL_DEPTH_PIXELS (4) pixels' size (SceneData::labelProbesPtr). It is shown when it is in front of one of the 3 x 3 pixels around it (with MSAA, each pixel's farthest sample). The answer fades in SceneData::labelFadesPtr, a buffer per view kept across frames, by the placement's step, and multiplies the slot's alpha; a label that was hidden starts at the answer. The glyphs are then drawn at the near plane, over everything. An OVERLAY label is always shown. A label hidden by depth still takes its room in placement (D47). Bug B36: before, each glyph corner took the depth of the ground's plane under it, and hills and objects cut labels.
MSAA, TAAno jitter, the anchor's motionremoveJitter on each glyph vertex; toVectorOutput writes the anchor's motion times coverage. Image tests labels_msaa4 and labels_taa.
Cullingpad by the reachgetVectorPadding with VECTOR_TEXT: VECTOR_LABEL_REACH (= MAX_LABEL_REACH, 12 ems) times the text's size, plus the halo.

Where it lives in code

WhatWhere
FontsFontAtlas, GlyphMetrics, KerningPair, findGlyph, getKerning, decodeUtf8 in include/rasm/text.h, src/scene/text.cpp (with Renderer::createFont, Renderer::destroyFont); buildFontAtlas, FontLoadOptions, AssetLoader::loadFont in src/assets/fontLoad.cpp (rasm::rasm only)
LabelsLabelDesc, LabelAnchor, addVectorLabels in include/rasm/vector.h, src/scene/vector.cpp; MeshLabel, Mesh::labels
PlacementplaceLabels, LabelPlacement, LabelCandidate in src/renderer/labelPlacement.cpp; placeViewLabels and the label slots in src/renderer/gpuScene.cpp
DepthlabelDepthMain in shaders/passes/labelDepth.slang; recordLabelDepth and the Label Depth pass in src/renderer/gpuScene.cpp; LABEL_DEPTH_PIXELS, LABEL_PROBE_DEPTH in src/renderer/labelPlacement.h
ShadersgetVectorVertex (VECTOR_KIND_GLYPH), shadeGlyph, getVectorPadding in shaders/lib/vector.slang; rasm.slang
The C API (1.6)rasm_build_font_atlas, rasm_asset_loader_load_font, rasm_create_font, rasm_destroy_font, rasm_vector_add_labels, rasm_label_desc, rasm_material_desc's font in src/c/cText.cpp, src/c/cVector.cpp, src/c/cLoader.cpp
Teststests/textTests.cpp (UTF-8, glyphs, kerning, the layout, Roboto's atlas), tests/labelPlacementTests.cpp; image tests labels, labels_msaa4, labels_taa, far_labels, draped (names on hills, across a post, behind a box)
Exampleexamples/25_vector_map: place names beside their points and district names over the map, in both views; the font in assets/fonts (Roboto, Apache 2.0)
Keep these true
  • No glyph corner reaches past MAX_LABEL_REACH ems from its anchor, or culling may drop its draw at the screen's edge. It must equal VECTOR_LABEL_REACH.
  • A label's halo quads come before its fill quads in the index buffer.
  • A mesh with labels has no meshlets (buildVectorMesh): its instance's meshletVisibility holds its first label slot.
  • stb_truetype trusts a font's tables: load only fonts you trust.
Not done yet

Shaping for complex scripts and right-to-left text (D46). Labels hidden by depth still take their room (D47). Labels along lines (a road's name that follows its curve) and labels that rotate with the map. MSDF atlases. A font file is trusted (B34). Pipelines compiled on first use still stall the frame (P31); labels add no pipeline of their own.

Further reading