zztaeha

Rust, C ABIMIT

Text and shaping engine. Rust, no_std, zero dependencies.

daegun turns a font file and a string into positioned glyphs, and those into pixels or the outlines to draw them with. It parses TrueType and OpenType, shapes complex scripts, breaks and lays out lines, hints, and subsets a font down to the glyphs a page's text can reach. The pixels are daegun's rasterizer's, or yours: whatever you draw with instead, on the CPU or the GPU, daegun hands it what it needs. A C ABI sits alongside the Rust API rather than behind it, so that holds from C too.

There are no dependencies at all, so the supply chain is the Rust compiler and nothing else. The parsers, the shaper and the rasterizer forbid unsafe code outright, enforced by the compiler rather than by discipline: a font file is data from strangers, and daegun treats it that way.


Start here

  1. Install it, for Rust or for C.
  2. Open a font, shape a string and draw what comes back, in Rust or in C.
  3. Look something up among the 1383 documented names, every function and type with an example.

The source is at github.com/zztaeha/daegun.

What holds it up

  • No dependencies, and no unsafe code in the engine. Only the C layer opts back in, in one place.
  • Every Rust call is reachable from C, bar a handful that would be pointless there.
  • 2,000 mutated fonts go through it on every run of its release gate, and 500 more on a 32-bit build, each one reproducible from its seed.
  • It never unwinds into a C caller: a panic aborts, and the library calls neither unwrap nor expect, which the gate enforces.

What it supports

OutlinesTrueType glyf, CFF, CFF2, and variable fonts on any number of axes.
ColorCOLR v0 and v1 paint graphs, CPAL palettes, and sbix, CBDT and EBDT bitmap strikes.
ShapingGSUB and GPOS in full, Apple morx and kerx, and shapers for Arabic, Hebrew, Thai, Hangul, Khmer, Myanmar, nine Indic scripts and 91 more through the Universal Shaping Engine.
TextBidi, line breaking greedy or optimal, with Thai, Lao, Khmer and Myanmar broken between words, justification, vertical writing, math.
RasterizingGlyphs and paths to coverage, exact where contours overlap and the same bytes on every CPU. A display's stripes, darkened stems and sRGB alpha. COLR glyphs composited in linear light. SDF and MSDF fields. A cache of what's drawn.
For your rasterizerOutlines in pixels with hinting, transforms, stroking and synthetic bold and oblique. Quadratic curves for GPU shaders. Flattened polygons with overlaps resolved. Color glyphs as scenes, with gradient sampling and compositing. Subpixel filters.
AndSubsetting to the glyphs a text can reach, TrueType and CFF hinting, an autohinter, and collections.
File formatsTrueType and OpenType fonts and collections. Decompress WOFF and WOFF2 first. Formats that predate OpenType, such as Type 1, BDF and PCF, are refused.

Installing

daegun needs Rust 1.99 or newer, also to build the C library. It has no dependencies, so there is nothing else to fetch.

  • Rust, one line in Cargo.toml.
  • C, one command with cargo-c, or a build of your own and a link line.

Installing for Rust

[dependencies]
daegun = "2.0.0"

That is a caret requirement, so it accepts every later 2.x release. The minimum Rust is 1.99, and it moves only in a minor release, which says so.

Features

FeatureDefaultWhat it does
stdyesTakes the standard library's float math and keeps scratch lists per thread. Without it the crate is no_std, needing only alloc and a target with atomic compare-and-swap at pointer width, as Arc does: an Armv7-M microcontroller has it, an Armv6-M one doesn't.
threadingnoMakes a Font Send + Sync, so one font serves every thread through an Arc. Implies std.
capinoBuilds the C ABI. Implies threading.
dictionariesnoBuilds in word lists for breaking Thai, Lao, Khmer and Myanmar lines between words, about 1 MB.

Breaking lines in Thai, Lao, Khmer and Myanmar

These scripts are written without spaces between words, so a line can break between words only where a word list finds them. The dictionaries feature builds in lists for all four. Without it, pass your own segmenter in LayoutOptions::segmenter, or such text breaks only at spaces, and between graphemes where a word won't fit the line.

The lists come under their own licenses, whose notices are in the engine's src/daecore/src/daeshaper/generated/word_lists.rs. A program built with them has to carry those notices, which the engine's CREDITS.txt holds too.

Speed

daegun's own numbers are measured with link-time optimization and one codegen unit, which a dependency can't set for you. Where shaping or drawing is your hot path, put them in your own profile:

[profile.release]
lto = true
codegen-units = 1

Installing for C

The C ABI is the same crate, built with its capi feature, which implies threading. The quickest way to the library, its headers and a daegun.pc is cargo-c.

With cargo-c

Install cargo-c once with cargo install --locked cargo-c. On Linux that needs git, curl, pkg-config and OpenSSL's headers (libssl-dev on Debian), or --features vendored-openssl in place of the last. Then install as yourself into a folder and copy it into place as root, since sudo cargo wouldn't find a rustup of your own:

cargo cinstall --release --prefix /usr/local --destdir stage
sudo cp -R stage/usr/local/. /usr/local/

On Linux, run sudo ldconfig afterward so the loader finds the shared library. Fedora and its relatives look in neither /usr/local/lib for libraries nor /usr/local/lib/pkgconfig for .pc files: name the first in a file under /etc/ld.so.conf.d before running ldconfig, and the second in PKG_CONFIG_PATH.

Add --features dictionaries to build in the word lists for Thai, Lao, Khmer and Myanmar.

Finding it from a build system

A build system finds daegun through pkg-config. The .pc carries the C ABI's version, so >=2.0 and <3 take this ABI or a later minor, never a major whose calls differ.

find_package(PkgConfig REQUIRED)
pkg_check_modules(DAEGUN REQUIRED IMPORTED_TARGET "daegun>=2.0" "daegun<3")
target_link_libraries(app PRIVATE PkgConfig::DAEGUN)
executable('app', 'app.c', dependencies: dependency('daegun', version: ['>=2.0', '<3']))

The first is CMake, the second Meson. With neither: cc app.c $(pkg-config --cflags --libs daegun).

Building it yourself

Or build the library in the shape you want:

cargo rustc --release --features capi --crate-type staticlib  # libdaegun.a, daegun.lib
# Windows: daegun.dll with the VC runtime linked in, so it needs only the UCRT, part of Windows since 10
cargo rustc --release --features capi --crate-type cdylib -- -C target-feature=+crt-static \
  -C link-arg=/NODEFAULTLIB:libucrt.lib -C link-arg=/DEFAULTLIB:ucrt.lib

A shared library on macOS or Linux carries the ABI's major in the name a program loads it by, 2 for this release, so a program never loads one whose calls differ from those it was built against. Install it under that name:

# macOS: libdaegun.dylib, installed as libdaegun.2.dylib on the program's rpath
cargo rustc --release --features capi --crate-type cdylib -- \
  -C link-arg=-Wl,-install_name,@rpath/libdaegun.2.dylib \
  -C link-arg=-Wl,-current_version,2.0.0 -C link-arg=-Wl,-compatibility_version,2 \
  -C link-arg=-Wl,-headerpad_max_install_names
# Linux: libdaegun.so, installed as libdaegun.so.2, with libdaegun.so a link to it for the linker
cargo rustc --release --features capi --crate-type cdylib -- -C link-arg=-Wl,-soname,libdaegun.so.2

Then compile with -I src/api/c/include and include daegun.h, which includes a header for each area.

Linking

A static library needs the system libraries Rust's standard library links against. A shared one carries its own.

PlatformLink line
macOS, iOScc app.c libdaegun.a
Linuxcc app.c libdaegun.a -lgcc_s -lutil -lrt -lpthread -lm -ldl
Linux, muslcc app.c libdaegun.a
Androidcc app.c libdaegun.a -llog -lm
Windowscl /std:c11 /MD app.c daegun.lib kernel32.lib ntdll.lib userenv.lib ws2_32.lib dbghelp.lib
MinGWgcc app.c libdaegun.a -lkernel32 -lntdll -luserenv -lws2_32 -ldbghelp

A program that calls part of the API drops the rest of a static library at the link, with -Wl,-dead_strip on macOS and iOS or -Wl,--gc-sections on Linux: one calling 29 of the 349 functions comes out at under half the size.

On Windows an application built /MT needs the library built with -C target-feature=+crt-static, as every object in one link takes one C runtime.

The DLL on Windows

The DLL carries the same major in its name, daegun-2.dll. A program that links it defines DAEGUN_DLL before including the header, so each call goes straight to the DLL, and links its import library: cl /std:c11 /MD /DDAEGUN_DLL app.c daegun-2.dll.lib. MinGW links the same DLL the same way, gcc -DDAEGUN_DLL app.c daegun-2.dll.lib, or a static library built with --target x86_64-pc-windows-gnu.

If you build the DLL yourself, rename daegun.dll to daegun-2.dll and make the import library, as cargo's names the old name: write a daegun-2.def holding LIBRARY daegun-2.dll, EXPORTS and each name dumpbin /exports lists, then run lib /def:daegun-2.def /machine:x64 /out:daegun-2.dll.lib.

Beside another Rust library

Every Rust static library carries its own copy of Rust's standard library, so a program linking daegun's beside another stops at the link on the symbols both define, rust_eh_personality among them. Link one of them shared, or merge daegun's archive into one object that exports its calls alone:

# macOS
cc -r -nostdlib -o daegun.o -Wl,-all_load libdaegun.a -Wl,-exported_symbol,'_daegun_*'
# Linux
ld -r --whole-archive libdaegun.a -o daegun.o && objcopy --wildcard --keep-global-symbol='daegun_*' daegun.o
# either: the object alone as the archive
rm libdaegun.a && ar rcs libdaegun.a daegun.o

On Windows, link daegun-2.dll: neither Microsoft's tools nor LLVM's hide a symbol in an MSVC object.

Inside a shared library of yours

A shared library that links libdaegun.a exports daegun's calls as its own unless it hides them. On Linux, two such libraries in one process, built against different releases, would then call each other's daegun. Hide them with -Wl,--exclude-libs,libdaegun.a on Linux, Android and MinGW, or -Wl,-hidden-ldaegun on macOS in place of -ldaegun.

Check the library at startup

The header and the library each know the ABI they are. Refuse a library whose major differs from the header's, or whose minor is lower, since a lower minor lacks calls you may use. DAEGUN_ABI_COMPATIBLE does both checks:

if (!DAEGUN_ABI_COMPATIBLE(daegun_abi_version())) return 1;

daegun_str release = daegun_version(); /* "2.0.0", for a log or a bug report */

The ABI's version is its own, not the crate's. Its minor moves when calls or constants are added or an options struct grows at its end, and its major whenever an existing call, constant or any other struct changes.

From C++

C++ includes daegun.h as it is and links the same way, with c++ in place of cc. No call throws, as GCC, clang and MSVC's C++ are told, so C++ around one needs no cleanup. A callback you hand daegun must not throw either, so declare it noexcept.

A handle fits a std::unique_ptr whose deleter calls its _free, and a stateless deleter keeps the owner a pointer wide. C++23's std::out_ptr hands such an owner to a call that writes the handle. The engine's src/api/c/tests/handles.cpp shows both, with a small stand-in for std::out_ptr that works from C++17.

Under a sanitizer

A freed handle is kept for the thread's next one of its kind, so a loop that makes and frees one allocates nothing. It also means a sanitizer can't see a handle used after its free. When you check a program under ASan or Valgrind, build daegun with RUSTFLAGS="--cfg daegun_no_spares", which frees each handle at once.

MemorySanitizer reads every value written by a library it didn't instrument as uninitialized, so on Linux build daegun instrumented, and Rust's standard library with it, which takes nightly:

RUSTFLAGS=-Zsanitizer=memory cargo +nightly rustc -Zbuild-std --features capi --crate-type staticlib \
  --target x86_64-unknown-linux-gnu

Then link with clang's -fsanitize=memory. On Arm, put $(clang -print-libgcc-file-name) before the library: MSan starts by calling an atomic that Rust's instrumented copy would answer before MSan's memory is mapped. In a container, MSan runs a program again without address randomization, which under Docker takes --security-opt seccomp=unconfined.

The Rust API

Open a font, shape a string, and draw each glyph. That is the whole loop.

use daegun::outline::{OutlineOptions, Path};
use daegun::shape::ShapeOptions;
use daegun::{Font, Location};

let bytes = std::fs::read("Inter.ttf")?;
let font = Font::from_bytes(&bytes)?;

let run = font.shape("Wave", &Location::default(), &ShapeOptions::DEFAULT);
// glyphs [459, 507, 980, 614], advances [1914.0, 1120.0, 1111.0, 1194.0]

let mut outline = Path::default();
font.prepared_outline(run.glyphs[0], &Location::default(), 32.0, &OutlineOptions::default(), &mut outline)?;
// one contour, 15 lines and 16 quadratics, about 30 by 23 pixels, y up from the baseline

Font::shape turns the string into glyphs with their advances, and Font::prepared_outline draws a glyph's outline in pixels onto any OutlinePen. A rasterizer of your own implements that trait and takes the calls directly, or reads them back out of a Path as here. To get pixels from daegun itself, hand the glyph to its rasterizer instead.

Everything is in font units

Every number is in the font's own units, y up and unrounded: advances, metrics, boxes and outlines alike. They come as f64, and an outline's points as f32. Font::units_per_em says how many make an em, so a pen position in pixels is advance * px / f64::from(font.units_per_em()). Only the calls that take a pixel size, Font::prepared_outline, Font::hinted_outline, Font::bitmap and the rasterizer's, answer in pixels.

Positions in text are byte offsets

Every position in text is a UTF-8 byte offset on a character boundary: a run's clusters, a feature's range, line breaks, boundaries, bidi runs and carets alike. So &text[range] slices exactly what a result names.

A location picks a variable font's instance

A variable font's axes are resolved once into a Location, which every call that depends on one takes by reference. Location::default() is the default instance, of any font.

use daegun::shape::ShapeOptions;
use daegun::Tag;

let bold = font.location(&[(Tag::new(b"wght"), 700.0), (Tag::new(b"opsz"), 28.0)]);
let run = font.shape("Wave", &bold, &ShapeOptions::DEFAULT);

Fonts and locations covers opening fonts, collections and the caches.

What can fail, and what can be missing

A font is checked as it opens, so its metrics are plain numbers afterward. An Option means the font has none of something, never a 0 or a -1 standing in for none. A call that can fail for a reason worth acting on returns daegun::Result: its Error has a kind() to match on and a message() naming the table or the step.

use daegun::{ErrorKind, Font};

match Font::from_bytes(b"not a font") {
    Ok(font) => { /* use it */ }
    Err(e) if e.kind() == ErrorKind::Malformed => eprintln!("not a font file: {}", e.message()),
    Err(e) => eprintln!("{e}"),
}

Threads

With the threading feature a Font is Send + Sync: one font serves every thread through an Arc, and each thread keeps its own shaping buffer, hinters, locations and recent runs. Without the feature a font stays on the thread that opened it. Results cross threads in every build.

A thread keeps what it last hinted with and the locations it last read at, so a dropped font's bytes may stay until that thread hints or reads other fonts, ends, or calls daegun::release_thread. A pool's worker calls it as it goes idle.

Types that may grow

What a minor release may add to is #[non_exhaustive]: every struct a call returns, every type of options and every enum that may gain a variant. Build options with their constructors, their with_ methods or Default, and match such an enum with a _ arm. Plain values whose fields are all they are, such as GlyphId, Bounds or shape::Feature, stay open to build by literal.

Where to go next

  • Fonts and locations: opening, collections, variable fonts, caches.
  • Shaping: options, features, mixed directions, carets.
  • Layout: paragraphs, line breaking, alignment, vertical text.
  • Outlines: hinting, transforms, strokes, bold and oblique.
  • Curves and polygons: what a GPU rasterizer takes.
  • Rasterizing: glyphs to pixels with daegun's own rasterizer.
  • Color: color glyphs as scenes, gradients and compositing.
  • Subsetting: a font cut down to the text it sets.

The reference has every method, type and constant, each with what it returns and what it does when it cannot, and an example for every method and type.

Fonts and locations

A Font is one face of a font file, read lazily, with the caches that make calls on it again cheap. Opening checks the table directory, the units per em and the glyph count, so a font's metrics are plain numbers. The rest is read as calls need it, so a later call can still find a table malformed, and says so with an error.

Opening

There are three ways in, which differ in who keeps the bytes:

use daegun::Font;

let bytes = std::fs::read("Inter.ttf")?;

// Copies the file, so `bytes` can go.
let copied = Font::from_bytes(&bytes)?;

// Keeps the Vec as it is given. The index picks a face of a collection, 0 for a font file.
let kept = Font::from_vec(bytes.clone(), 0)?;

// Reads bytes that live as long as the program where they lie, copying nothing.
let leaked: &'static [u8] = Box::leak(bytes.into_boxed_slice());
let in_place = Font::from_static(leaked, 0)?;

Opening fails with ErrorKind::Malformed for bytes that aren't a font file or whose table directory runs past their end, and with ErrorKind::Missing for a font without its units per em or glyph count. WOFF and WOFF2 are compressed wrappers: decompress them first.

Collections

A .ttc or .otc file holds several faces. Font::face_count says how many, and each opens by its index:

use daegun::{Font, Location};

let bytes = std::fs::read("Fonts.ttc")?;
for index in 0..Font::face_count(&bytes) {
    let face = Font::from_collection(&bytes, index)?;
    println!("{index}: {:?}", face.family_name(&Location::default()));
}

A font file counts as 1 face, and bytes that are neither count as 0. An index past the faces is an ErrorKind::InvalidArgument error.

Variable fonts

Font::axes lists a variable font's axes, each with its tag and its range. Font::location turns the values you want into a Location, once, and every call that depends on the instance takes it by reference.

use daegun::shape::ShapeOptions;
use daegun::{Location, Tag};

for axis in font.axes() {
    println!("{}: {} to {}, default {}", axis.tag, axis.min, axis.max, axis.default);
}

let bold = font.location(&[(Tag::new(b"wght"), 700.0)]);
let regular = Location::default();
let wider = font.shape("Wave", &bold, &ShapeOptions::DEFAULT).width();

// A value past an axis's range is clamped to it, and a tag the font lacks is ignored.
let heavy = font.location(&[(Tag::new(b"wght"), 5000.0), (Tag::new(b"slnt"), -10.0)]);
assert_eq!(heavy.coords(), [(Tag::new(b"wght"), 900.0)]);

Location::default() is the default instance of any font, so it is what you pass for a static font too. A location remembers the values it was asked for, so handing it to another font resolves it again for that font. Font::named_instances lists the instances the font names, such as Bold or Light, each with its coordinates ready to pass to Font::location.

Font::instance goes the other way: it writes the font out as a static font file at a location, to save or to open again.

What the font says about itself

use daegun::{Location, NameId, Tag};

let here = Location::default();
let family = font.family_name(&here);
let style = font.style(&here);
let version = font.name(NameId::VERSION_STRING, &here);

// A table's bytes as stored, for a reader of your own.
if let Some(os2) = font.table(Tag::new(b"OS/2")) {
    println!("OS/2 is {} bytes", os2.len());
}

Names are read at a location, since a variable font's instance carries its own. An Option means the font has no such name.

Caches

A font keeps four caches, each with a budget of its own in bytes. A budget is a ceiling the cache grows into, never memory reserved.

CacheKeeps
Cache::ShapeShaped runs, for text shaped again.
Cache::InstanceEach location's tables and what is built there.
Cache::OutlineOutlines that Font::prewarm drew ahead, replayed in place of being decoded.
Cache::RasterImages a Rasterizer drew of the font's glyphs. Off, at a budget of 0, until you set one.
use daegun::shape::ShapeOptions;
use daegun::{Cache, Location};

font.set_cache_budget(Cache::Shape, 256 * 1024);
let _ = font.shape("Wave", &Location::default(), &ShapeOptions::DEFAULT);

let stats = font.cache_stats(Cache::Shape);
println!("{} runs, {} bytes", stats.entries, stats.bytes);

font.clear_cache(Cache::Shape);

Lowering a budget applies at once and keeps what was used last. A CachePool is one budget that the caches of several fonts share, each joining it with Font::set_cache_pool: past it, the entry least recently used across all of them goes first, whichever font's.

Shaping

Shaping turns a string into the glyphs that draw it, each with where it goes. Font::shape does it for one run of text in one direction, and returns a ShapedRun.

use daegun::shape::ShapeOptions;
use daegun::Location;

let run = font.shape("Wave", &Location::default(), &ShapeOptions::DEFAULT);
let scale = 16.0 / f64::from(font.units_per_em());

let mut pen = 0.0;
for i in 0..run.glyphs.len() {
    let x = (pen + run.offsets[i].x) * scale;
    let y = run.offsets[i].y * scale;
    // Draw run.glyphs[i] at (x, y) pixels from the start of the baseline.
    pen += run.advances[i];
}

The glyphs come in the order they are drawn. Each advance moves the pen, and each offset moves one glyph from the pen, which is how a mark lands on its base. Everything is in font units.

Glyphs are not characters

A ligature makes one glyph from several characters, and some scripts make several glyphs from one, or draw them in another order than the text has them. ShapedRun::clusters maps each glyph back to the byte of the text its piece starts at, which is what selection and hit testing need.

use daegun::shape::ShapeOptions;
use daegun::Location;

// EB Garamond draws the "ffi" of "office" as one ligature glyph.
let run = font.shape("office", &Location::default(), &ShapeOptions::DEFAULT);
assert_eq!(run.glyphs.len(), 4);
assert_eq!(run.clusters, [0, 1, 4, 5]);

Options

ShapeOptions carries everything else: direction, script, language, OpenType features, and the text around the run. Start from ShapeOptions::DEFAULT and name only what you change.

use daegun::shape::{Feature, ShapeOptions};
use daegun::{Location, Tag};

// Tabular figures, so a column of numbers lines up, with kerning off.
let features = [Feature::new(Tag::new(b"tnum"), 1), Feature::new(Tag::new(b"kern"), 0)];
let options = ShapeOptions::DEFAULT.with_features(&features);
let run = font.shape("1,204.50", &Location::default(), &options);

// A feature can also come from text, as CSS and shaping tools write one.
let small_caps: Feature = "+smcp".parse()?;

When you shape a piece of a longer text, pass what surrounds it with ShapeOptions::with_context. An Arabic letter takes a different form depending on its neighbors, and a piece shaped alone gets the wrong form at its edges. Only joining reads that context: a kerning pair or a ligature across the edge needs both characters inside the run.

Mixed directions

Text that mixes Arabic or Hebrew with Latin has to be split into runs of one direction, and those runs put in the order they are drawn. Font::shape_bidi does both, and cuts each run again where the script changes:

use daegun::shape::ShapeOptions;
use daegun::unicode::BaseDirection;
use daegun::Location;

let text = "Read مرحبا aloud";
let runs = font.shape_bidi(text, &Location::default(), BaseDirection::Auto, &ShapeOptions::DEFAULT);

let mut pen = 0.0;
for bidi in &runs {
    // Draw bidi.run at `pen`. It shows &text[bidi.bytes], right to left if bidi.level is odd.
    pen += bidi.run.width();
}

It expects one paragraph. A line feed, a carriage return or a paragraph separator such as U+2029 starts a new one, which is ordered on its own, so split the text there first. For a paragraph that wraps, layout does all of this line by line.

Carets

Font::caret_positions gives where the cursor sits before each byte of a string, indexed by byte offset, with the trailing edge last. A caret never lands between a letter and its marks, and inside a ligature it moves through the glyph. The call takes no options: it shapes horizontal text as Font::shape_bidi does with the default options and the direction taken from the text, and vertical text as one run from top to bottom.

use daegun::{Location, Orientation};

let text = "Wave";
let carets = font.caret_positions(text, &Location::default(), Orientation::Horizontal);
assert_eq!(carets.len(), text.len() + 1);
// carets[2] sits between "Wa" and "ve", in font units from the left edge.

The shape cache

A run comes back in an Arc. One shaped with plain options comes from the font's shape cache, so shaping the same text again is as a rule a lookup that hands back the same run. A very long run is not kept, past roughly 30,000 glyphs at the default budget or 1,900 with threading. Options that set features, a script, a cluster level or the other less common fields are shaped afresh each call, and Font::shape_into shapes into a run you own, reusing its memory.

Layout

Font::layout wraps a paragraph into lines, breaks them, aligns them and places every run, in one call. It works in font units like everything else, so convert a pixel width to font units on the way in, and positions back to pixels on the way out.

use daegun::layout::{Align, BreakStrategy, LayoutOptions};
use daegun::Location;

let text = "Type is the voice of the page. Set it well and the words carry further.";
let scale = 16.0 / f64::from(font.units_per_em());
let options = LayoutOptions::default()
    .with_max_inline_size(240.0 / scale)
    .with_line_height(20.0 / scale)
    .with_strategy(BreakStrategy::Optimal)
    .with_align(Align::Start);
let layout = font.layout(text, &Location::default(), &options);

for line in &layout.lines {
    let baseline = line.baseline * scale; // pixels down from the top of the block
    for run in &line.runs {
        let x = run.offset.x * scale; // pixels from the left edge of the measure
        // Draw run.run along the baseline from x, as any shaped run is drawn.
    }
}
// Three lines at 16 px, none wider than 240 pixels.

What comes back

A TextLayout holds the lines in order, the widest line's extent in inline_size and the height of all of them in block_size. Each LayoutLine has:

  • baseline, where its baseline lies from the block's top edge.
  • runs, in the order they are drawn, each a PositionedRun with its shaped run and the offset it starts at from the left edge of the measure, alignment included, or from the top in a vertical line.
  • bytes, the range of the text it covers, so &text[line.bytes.clone()] is the line's text.
  • ascent and descent, and hard_break, whether a hard break or the end of the text closes it.

A run's clusters count from the start of that run's own text, run.bytes.start, since the run was shaped from there.

Breaking lines

BreakStrategy::Greedy fills each line as far as it goes before starting the next. BreakStrategy::Optimal chooses a paragraph's breaks together for even lines, which is Knuth and Plass's total fit. Without a max_inline_size lines end only at hard breaks.

use daegun::layout::LayoutOptions;
use daegun::Location;

let text = "One paragraph.
And a second, which is longer than the first one.";
let options = LayoutOptions::default().with_max_inline_size(30_000.0).with_max_lines(2);
let layout = font.layout(text, &Location::default(), &options);

assert_eq!(layout.lines.len(), 2);
// The first line ends at the line feed, and the text past the second line was left out.
assert!(layout.lines[0].hard_break);
if let Some(rest) = layout.truncated {
    println!("not laid out: {:?}", &text[rest..]);
}

Thai, Lao, Khmer and Myanmar are written without spaces between words. Lines break between their words with the dictionaries feature, or with a segmenter of your own in LayoutOptions::segmenter. Without either, such text breaks only at spaces, and between graphemes where a word won't fit the line.

Alignment

Align::Start puts lines at the start edge, which is the left in a left-to-right paragraph and the right in a right-to-left one. Align::End and Align::Center do what they say, and Align::Justify spreads each line to fill the measure, except one that ends at a hard break, as a paragraph's last line does.

use daegun::layout::{Align, LayoutOptions};
use daegun::Location;

let options = LayoutOptions::default().with_max_inline_size(20_000.0).with_align(Align::Center);
let layout = font.layout("Centered", &Location::default(), &options);

let line = &layout.lines[0];
// The run starts half the leftover space in from the line's start.
assert_eq!(line.runs[0].offset.x, (20_000.0 - line.inline_size) / 2.0);

Mixed directions

Each line's runs are already in visual order, with the bidi level each reads at, so Arabic or Hebrew inside Latin text needs nothing more from you. LayoutOptions::with_base_direction sets the direction of the paragraphs where the text shouldn't decide it.

Vertical text

WritingMode::VerticalRl runs lines downward and stacks them leftward, as Japanese is set, and WritingMode::VerticalLr stacks them rightward, as Mongolian is. A line's baseline is then measured from the block's left edge, and a run's offset.y and its advances count down the column from the top. TextOrientation says how characters stand in those lines: upright where Unicode says so, all upright, or all sideways. In an upright run a glyph's own offset stays y up, so add its x to the baseline and subtract its y from the pen. A run on its side, as Latin is by default, has upright false: it is shaped as horizontal text, for you to draw turned a quarter turn clockwise.

use daegun::layout::{LayoutOptions, WritingMode};
use daegun::Location;

let options = LayoutOptions::default()
    .with_writing_mode(WritingMode::VerticalRl)
    .with_max_inline_size(3_000.0);
let layout = font.layout("日本語の組版", &Location::default(), &options);
// Six characters, three to a column in this font: two columns.
assert_eq!(layout.lines.len(), 2);

Justifying one line

Some fonts carry a JSTF table that says how to make a line wider or narrower in their script's own way, as Arabic stretches its letters. Font::justify shapes one line to a width with it, and Font::justification_priorities lists the levels it tries.

Outlines

There are two ways to get a glyph's shape. Font::outline draws it as the font stores it, in font units. Font::prepared_outline draws it ready for a rasterizer: scaled to a pixel size, and hinted, leaned, transformed, stroked or emboldened as you ask. Both draw onto a pen.

A pen

OutlinePen is a trait with five calls: move to, line to, quadratic curve to, cubic curve to and close. A Path is the pen that records them, to read back or replay later. A rasterizer of your own implements the trait and takes the calls directly:

use daegun::outline::{OutlineOptions, OutlinePen};
use daegun::Location;

struct Counter {
    contours: usize,
    curves: usize,
}

impl OutlinePen for Counter {
    fn move_to(&mut self, _x: f32, _y: f32) { self.contours += 1; }
    fn line_to(&mut self, _x: f32, _y: f32) {}
    fn quad_to(&mut self, _cx: f32, _cy: f32, _x: f32, _y: f32) { self.curves += 1; }
    fn curve_to(&mut self, _c1x: f32, _c1y: f32, _c2x: f32, _c2y: f32, _x: f32, _y: f32) {
        self.curves += 1;
    }
    fn close(&mut self) {}
}

let w = font.glyph_id('W').expect("Inter has a W");
let mut pen = Counter { contours: 0, curves: 0 };
font.prepared_outline(w, &Location::default(), 32.0, &OutlineOptions::DEFAULT, &mut pen)?;
// One contour with 16 curves, in pixels at 32 px to the em, y up from the glyph's origin.
assert_eq!((pen.contours, pen.curves), (1, 16));

TrueType outlines arrive as quadratic curves and CFF outlines as cubic ones, so a pen sees whichever the font has. Curves and polygons has the calls that give one kind only.

Options

OutlineOptions is a builder, so you name only what you change. What it holds is applied in this order: hinting, then the oblique and the transform, then a stroke or an embolden.

use daegun::outline::{HintMode, OutlineOptions, Path};
use daegun::Location;

let w = font.glyph_id('W').expect("Inter has a W");
let options = OutlineOptions::default().with_hinting(HintMode::Auto).with_embolden(40.0);

let mut outline = Path::default();
let glyph = font.prepared_outline(w, &Location::default(), 32.0, &options, &mut outline)?;
// glyph.advance_width is in pixels and includes the embolden, and glyph.hinted says a hinter ran.
assert!(glyph.hinted);
OptionWhat it does
with_hintingFits the outline to the pixel grid, with the font's own hints or daegun's autohinter. See below.
with_obliqueLeans the glyph. The value is the tangent of the lean from upright, positive to the right, applied before the transform so the glyph leans in its own frame.
with_transformA 2×3 matrix [a, b, c, d, dx, dy], its offsets in font units, applied after hinting. It scales neither a stroke, an embolden nor the advances.
with_strokeDraws the outline's stroke in place of its fill, a StrokeStyle with a width in font units, a join and a cap.
with_emboldenAdds stem width in font units, and widens the advances by as much. Ignored with a stroke, and at zero or below.

An embolden overlaps itself, and so does a stroke wherever a corner is too tight for its width or two parts lie closer than it is wide. A non-zero fill hides that, and a rasterizer that sums coverage does not: it needs the overlaps resolved first. daegun's own rasterizer does that itself.

Hinting

HintMode picks the hinter:

  • HintMode::None: no hinting. The default.
  • HintMode::Font: the font's own hints, which are its TrueType bytecode or its CFF or CFF2 hints. Bytecode fits y to the grid, and x only in a font that declares native ClearType.
  • HintMode::Auto: chosen once for the whole font. daegun's autohinter takes a font with TrueType outlines and no hinting program of its own to speak of, and the font's own hints take any other. A glyph those don't hint is left unhinted.
  • HintMode::AutoForce: the autohinter for every glyph.

Font::hinted_outline gives the hinted points themselves, in pixels. It returns None where no hinter takes the glyph, and you draw it unhinted then, as Font::prepared_outline does on its own.

When it fails

Font::prepared_outline returns an ErrorKind::InvalidArgument error unless the pixel size is finite and above zero and the options are finite, and an ErrorKind::Overflow error for anything past f32 once scaled. A glyph the font can't decode gives the decoder's error. A call that fails draws nothing onto the pen.

use daegun::outline::{OutlineOptions, Path};
use daegun::{ErrorKind, GlyphId, Location};

let mut outline = Path::default();
let here = Location::default();
let bad_size = font.prepared_outline(GlyphId(5), &here, 0.0, &OutlineOptions::DEFAULT, &mut outline);
assert_eq!(bad_size.unwrap_err().kind(), ErrorKind::InvalidArgument);

Drawing the same glyphs again

Font::prewarm draws glyphs into the font's outline cache ahead of time, so Font::outline replays them in place of decoding them. It takes a run's glyphs as they are: font.prewarm(&run.glyphs, &location).

Curves and polygons

A font's outlines mix lines, quadratic curves and cubic curves. A GPU rasterizer that evaluates curves in a shader wants quadratics only, and one that walks straight edges wants polygons. daegun gives either.

Quadratic curves

Font::quads returns a glyph's outline as quadratic curves alone, in font units. A line becomes a curve with its control at the midpoint, and a cubic is split until each piece is within 1/4096 of an em of it.

use daegun::outline::Quad;
use daegun::Location;

let w = font.glyph_id('W').expect("Inter has a W");
let curves: Vec<Quad> = font.quads(w, &Location::default())?;
// 32 curves, each a Quad { start, control, end } in font units.
assert_eq!(curves.len(), 32);

The curves come wound clockwise, TrueType's convention, by outline::normalize_winding, so a shader can tell inside from outside. A glyph that draws nothing, such as a space, is an ErrorKind::NoOutline error. Font::quads_into fills a list you keep between glyphs, so a loop allocates only to grow it.

Polygons

Path::flatten turns an outline into closed polygons, one list of points per contour. Its argument bounds how far the straight edges may stray from a curve, as an area, and outline::max_area_for gives the value for a path in font units drawn at a pixel size:

use daegun::outline::{max_area_for, Path};
use daegun::Location;

let w = font.glyph_id('W').expect("Inter has a W");
let mut units = Path::default();
font.outline(w, &Location::default(), &mut units)?;

let tolerance = max_area_for(32.0, f32::from(font.units_per_em()));
let polygons = units.flatten(tolerance)?;
// One contour of 34 points, in font units, fine enough for 32 px.

Flattening fails with an ErrorKind::LimitExceeded error past outline::MAX_FLATTEN_POINTS points, which no real glyph reaches, and with an ErrorKind::InvalidArgument error for a path holding a point that isn't finite.

Overlaps

Contours may cross themselves or each other: a variable font's strokes often do, and so do an emboldened outline and a stroke where a corner is too tight for its width. A non-zero fill doesn't mind. A rasterizer that sums the coverage of each edge counts the overlap twice, and needs it removed first. outline::resolve_overlaps replaces contours that cross with boundaries that don't, each wound with the filled side on its left:

use daegun::outline::{max_area_for, resolve_overlaps, Path};
use daegun::Location;

let w = font.glyph_id('W').expect("Inter has a W");
let mut units = Path::default();
font.outline(w, &Location::default(), &mut units)?;
let polygons = units.flatten(max_area_for(32.0, f32::from(font.units_per_em())))?;

match resolve_overlaps(&polygons) {
    // The W's one contour crosses itself where its strokes meet, so it comes back as one
    // counterclockwise boundary.
    Some(merged) => { /* draw `merged` */ }
    // Keep `polygons` as they are: they don't overlap, as an H's don't, or meet too closely to call.
    None => {}
}

Font::has_overlap_flag says whether a TrueType font flags a glyph as one whose contours may overlap. It is only a cue: a glyph without the flag may overlap all the same, and CFF fonts carry no such flag.

Rasterizing

A Rasterizer turns a glyph into pixels. It lends an image placed by its left and top from the glyph's origin on the baseline, and it keeps its buffers between calls, so once warm it allocates nothing. Coverage is the share of each pixel the outline covers, an area worked out with its curves followed to within a 32nd of a pixel, and a place where contours overlap counts once. Every CPU gets the same bytes.

A run, set into a canvas of one byte a pixel:

use daegun::raster::{RasterOptions, Rasterizer};
use daegun::shape::ShapeOptions;
use daegun::Location;

let (px, baseline) = (32.0, 30);
let scale = f64::from(px) / f64::from(font.units_per_em());
let run = font.shape("Wave", &Location::default(), &ShapeOptions::DEFAULT);
let (width, height) = (96, 40);
let mut canvas = vec![0u8; width * height];

let mut rasterizer = Rasterizer::new();
let mut pen = 2.0;
for ((&gid, advance), offset) in run.glyphs.iter().zip(&run.advances).zip(&run.offsets) {
    // whole pixels place the image, and the fraction moves the glyph within it
    let (x, y) = (pen + offset.x * scale, offset.y * scale);
    let options = RasterOptions::DEFAULT.with_offset(x.fract() as f32, y.fract() as f32);
    let image = rasterizer.glyph(&font, gid, &Location::default(), px, &options)?;
    let (left, top) = (x as i32 + image.left, baseline - y as i32 - image.top);
    for row in 0..image.height {
        let start = (top + row as i32) as usize * width + left as usize;
        for (dst, &src) in canvas[start..].iter_mut().zip(image.row(row)) {
            *dst = dst.saturating_add(src);
        }
    }
    pen += advance * scale;
}
// "Wave" inked across 82 by 25 pixels, each byte the share of its pixel the glyphs cover

The image

An Image borrows the rasterizer's pixels, so it is valid until the rasterizer's next call. Its rows run top to bottom, stride bytes apart, and Image::row gives one row. left is how far its left edge sits right of the glyph's origin, and top how far its top sits above the baseline. Image::to_bitmap copies it into a Bitmap you own.

channels says what a pixel holds: 1 byte of coverage or of distance, 3 for a display's stripes or a multi-channel distance field, or 4 for a color glyph's premultiplied RGBA.

Options

RasterOptions is a builder, as OutlineOptions is, and carries one:

use daegun::color::Rgba;
use daegun::outline::{HintMode, OutlineOptions};
use daegun::raster::{Gamma, RasterOptions, Rasterizer, StripeOrder, SubpixelLayout};
use daegun::Location;

let stripes = SubpixelLayout::horizontal(StripeOrder::Rgb);
let options = RasterOptions::DEFAULT
    .with_outline(OutlineOptions::DEFAULT.with_hinting(HintMode::Auto))
    .with_layout(&stripes)
    .with_darken(true)
    .with_gamma(Gamma::Srgb { text: Rgba::opaque(0, 0, 0), contrast: 0.5 });

let mut rasterizer = Rasterizer::new();
let a = font.glyph_id('a').expect("Inter has an a");
let image = rasterizer.glyph(&font, a, &Location::default(), 14.0, &options)?;
// Three bytes a pixel now: one for each of the display's stripes.
assert_eq!(image.channels, 3);
OptionWhat it does
with_outlineHinting, a transform, a stroke, an embolden or a lean, as Font::prepared_outline takes them.
with_offsetMoves the glyph right and up by a fraction of a pixel before it's drawn, so text set between pixels keeps its spacing.
with_layoutA SubpixelLayout: plain coverage by default, or a display's stripes, three bytes a pixel.
with_darkenWidens thin stems, since text drawn small otherwise reads too light.
with_gammaGamma::Linear, the default, gives coverage as it is, for a compositor that blends in linear light. Gamma::Srgb gives the alpha a compositor that blends sRGB values needs, for text of a given color.

Color glyphs, distance fields and paths

use daegun::color::SceneOptions;
use daegun::outline::{FillRule, Path};
use daegun::raster::{Field, RasterOptions, Rasterizer};
use daegun::Location;

let here = Location::default();
let (plain, palette) = (RasterOptions::DEFAULT, SceneOptions::DEFAULT);
let a = font.glyph_id('A').expect("the font has an A");
let mut rasterizer = Rasterizer::new();

// A COLR color glyph, as premultiplied RGBA. None for a glyph with no color description.
if let Some(image) = rasterizer.color_glyph(&font, a, &here, 64.0, &plain, &palette)? {
    assert_eq!(image.channels, 4);
}

// A signed distance field, for text a shader scales. Msdf keeps corners sharp, in three channels.
let field = rasterizer.distance_field(&font, a, &here, 32.0, Field::Sdf { spread: 4.0 })?;
assert_eq!(field.channels, 1);

// Any path of your own, filled.
let mut path = Path::default();
font.outline(a, &here, &mut path)?;
let image = rasterizer.path(&path, FillRule::NonZero, None)?;

Rasterizer::path takes the path's units as pixels, and an optional 2×3 transform to scale and place it first.

Drawing into your own pixels

The calls above lend an image of at most raster::MAX_SIDE pixels a side and raster::MAX_DRAW_BYTES bytes of drawing. To draw straight into pixels of your own, at any size, hand a Target to Rasterizer::glyph_into, Rasterizer::color_glyph_into or Rasterizer::path_into:

use daegun::raster::{RasterOptions, Rasterizer, Target};
use daegun::Location;

let (width, height) = (64u32, 64u32);
let mut pixels = vec![0u8; (width * height) as usize];
// The target's top left corner sits 0 pixels right of the glyph's origin and 48 above it.
let target = Target::new(0, 48, width, height, width as usize, &mut pixels);

let a = font.glyph_id('a').expect("Inter has an a");
let mut rasterizer = Rasterizer::new();
rasterizer.glyph_into(&font, a, &Location::default(), 48.0, &RasterOptions::DEFAULT, target)?;

Keeping what was drawn

Give Cache::Raster a budget and a font keeps the images drawn of its glyphs, lent again in place of being drawn. It is off until you do.

use daegun::raster::{RasterOptions, Rasterizer};
use daegun::{Cache, Location};

font.set_cache_budget(Cache::Raster, 1 << 20);

let a = font.glyph_id('a').expect("Inter has an a");
let mut rasterizer = Rasterizer::new();
for _ in 0..3 {
    let _ = rasterizer.glyph(&font, a, &Location::default(), 16.0, &RasterOptions::DEFAULT)?;
}
// Drawn once and kept: the second and third calls were lent the same image.
assert_eq!(font.cache_stats(Cache::Raster).entries, 1);

For a GPU, raster::ShelfPacker finds room for each image in an atlas texture: ShelfPacker::insert takes a width and a height and answers the rectangle to copy it to.

Color

A color glyph has more than one color in it, so it comes back as a scene rather than one outline. Font::color_scene reads the font's COLR table, version 1's paint graph or version 0's layers, and hands you a DisplayList: fills, clips and layers in the order to draw them.

use daegun::color::{Op, Paint, SceneOptions};
use daegun::Location;

let a = font.glyph_id('A').expect("the font has an A");
let scene = font.color_scene(a, &Location::default(), &SceneOptions::default())?
    .expect("is a color glyph");

for op in scene.ops() {
    match op {
        Op::Fill { path, paint, transform, .. } => {
            let outline = scene.path(*path).expect("the scene holds its paths");
            match paint {
                Paint::Solid(color) => { /* fill `outline` with `color`, placed by `transform` */ }
                Paint::Gradient(id) => { /* or with scene.gradient(*id) */ }
                _ => {}
            }
        }
        Op::PushClip { shapes } => { /* clip to scene.shapes(shapes.clone()) until the matching pop */ }
        Op::PushLayer { opacity, blend } => { /* start a layer, composited on its pop */ }
        Op::PopClip | Op::PopLayer => {}
        _ => {}
    }
}
// Bungee Tint's A is two solid fills, back to front.

Everything in the scene is in font units, y up. Each outline is held once and placed by its op's transform. None means the glyph has no color description, so draw its plain outline instead.

Or let the rasterizer draw it

If pixels are all you need, Rasterizer::color_glyph does all of the above and hands back premultiplied RGBA. See Rasterizing.

Palettes and the text's color

A font may carry several palettes, such as one for light backgrounds and one for dark. SceneOptions picks which, and sets the foreground color, which is what a layer takes where the font says "use the text's color".

use daegun::color::{Rgba, SceneOptions};
use daegun::Location;

for palette in font.palettes() {
    let (index, light, dark) = (palette.index, palette.light_safe, palette.dark_safe);
    println!("palette {index} (light {light}, dark {dark}): {:?}", font.palette_colors(index));
}

let options = SceneOptions::default().with_palette(0).with_foreground(Rgba::opaque(30, 30, 30));
let a = font.glyph_id('A').expect("the font has an A");
let scene = font.color_scene(a, &Location::default(), &options)?;

Gradients

A fill's paint may be a gradient: linear, radial or sweep, with its stops and how it extends past them. color::gradient::Ramp samples one as COLR defines it, so you don't have to implement the three kinds yourself:

use daegun::color::gradient::Ramp;
use daegun::color::{Op, Paint, SceneOptions, IDENTITY};
use daegun::{GlyphId, Location};

for glyph in 0..font.glyph_count() {
    let Some(scene) = font.color_scene(GlyphId(glyph), &Location::default(), &SceneOptions::default())? else {
        continue;
    };
    for op in scene.ops() {
        if let Op::Fill { paint: Paint::Gradient(id), .. } = op {
            let gradient = scene.gradient(*id).expect("the scene holds its gradients");
            // IDENTITY samples in the scene's own units. Pass your scale to sample in pixels.
            let ramp = Ramp::new(&gradient, &IDENTITY);
            let color = ramp.at(100.0, 100.0); // None where the gradient paints nothing
        }
    }
}

Compositing

A layer is composited over what lies below it in one of COLR's 28 modes. Blend::composite does one pixel of that: a source color and its alpha over a backdrop and its alpha, with colors straight and from 0 to 1, giving a premultiplied result.

use daegun::color::Blend;

// Half-transparent red multiplied onto opaque white.
let out = Blend::Multiply.composite([1.0, 0.0, 0.0], 0.5, [1.0, 1.0, 1.0], 1.0);

Bitmap glyphs

Emoji fonts often store pictures instead of outlines. Font::bitmap finds a glyph's image in the smallest strike at or above the size you ask for that holds the glyph, or else the largest below it that does:

use daegun::color::BitmapImage;

let smile = font.glyph_id('😀').expect("the font has the emoji");
if let Some(bitmap) = font.bitmap(smile, 64) {
    match bitmap.image {
        // Lent from the font. Decode it with a PNG library, then scale it from bitmap.ppem.
        BitmapImage::Png(png) => assert!(png.starts_with(b"\x89PNG")),
        // One byte of coverage a pixel, rows top to bottom.
        BitmapImage::Coverage { width, height, pixels } => {
            assert_eq!(pixels.len(), usize::from(width) * usize::from(height));
        }
        _ => {}
    }
}

Subsetting

A subset is a new, smaller font file that holds only the glyphs some text needs. A Japanese sentence of 37 characters can ship as about 10 KB of font in place of 8 MB.

use daegun::Location;

let subset = font.subset_text("Type is the voice of the page.", &Location::default())?;
std::fs::write("subset.ttf", &subset.font)?;
// 879,708 bytes to 9,824

Font::subset_text takes the text rather than glyph ids. It keeps every glyph those characters can reach, so ligatures, joining forms, components and color layers survive. The result carries a real cmap holding the text's characters, and the few more that shaping derives from them, so it loads straight into @font-face.

A subset is pinned to a location

The second argument is a Location. A subset of a variable font is a static font at that location: the instance you chose, and nothing of the others.

use daegun::{Font, Tag};

let bold = font.location(&[(Tag::new(b"wght"), 700.0)]);
let subset = font.subset_text("Bold headline", &bold)?;

let small = Font::from_vec(subset.font, 0)?;
assert!(!small.is_variable());

By glyph id

Font::subset takes glyph ids when you already know them, such as the glyphs of the runs you shaped. Its cmap keeps the source's characters for the glyphs it keeps. A subset of a TrueType font renumbers its glyphs, and Subset::renumbered says where each went:

use daegun::shape::ShapeOptions;
use daegun::Location;

let here = Location::default();
let run = font.shape("Wave", &here, &ShapeOptions::DEFAULT);
let subset = font.subset(&run.glyphs, &here)?;

// The W's glyph id in the new font, which differs from its id in the old one.
let w = subset.renumbered(run.glyphs[0]).expect("a glyph asked for is kept");

A CFF or CFF2 font subset by glyph id keeps its glyphs where they were: the ones dropped are emptied, and the ids and the glyph count stay. Font::glyph_closure answers the other question on its own: the glyphs a subset of these would hold, which is them and every glyph they reach.

When it fails

Subsetting returns an error where the subsetter, or for a variable font the instancer, can't write the font: ErrorKind::Malformed for a table that doesn't read, ErrorKind::Missing for one it needs, such as a font without a cmap given text, ErrorKind::Unsupported for one it can't write, and ErrorKind::LimitExceeded past its bounds.

The C API

C can do everything the Rust API does, bar a handful of helpers that would be pointless there. daegun.h is the contract. It includes a header for each area, as the Rust modules are, and five rules hold for every call in them.

The same loop as in Rust: open a font, shape a string, and draw each glyph.

#include "daegun.h"

daegun_font *font = NULL;
if (daegun_font_open(data, len, &font) != DAEGUN_OK) return 1;

daegun_shaped_run *run = NULL;
if (daegun_font_shape(font, "Wave", 4, NULL, NULL, &run) != DAEGUN_OK) return 1;

size_t n = 0;
const uint32_t *gids = daegun_shaped_run_glyphs(run, &n);
const double *advances = daegun_shaped_run_advances(run, &n); /* in font units */

/* your rasterizer's callbacks, and the state they draw into */
daegun_pen pen = { on_move, on_line, on_quad, on_cubic, on_close, &my_rasterizer };
daegun_prepared_glyph glyph;
if (daegun_font_prepared_outline(font, gids[0], NULL, 32.0f, NULL, &pen, &glyph) != DAEGUN_OK) return 1;
/* the callbacks got the outline in pixels, and glyph.advance_width is in pixels too */

daegun_shaped_run_free(run);
daegun_font_free(font);

A fallible call returns a daegun_status and answers through an out parameter. Text goes in as UTF-8 with its length in bytes. A NULL where a call takes a location means the default instance, and a NULL where it takes options means the defaults. To get pixels from daegun itself, hand the glyph to its rasterizer instead of a pen.

Locations

A variable font's axes are resolved once into a location handle, and every call that depends on one takes it:

const daegun_coord coords[] = {
    { DAEGUN_TAG('w', 'g', 'h', 't'), 700.0 },
    { DAEGUN_TAG('o', 'p', 's', 'z'), 28.0 },
};
daegun_location *bold = NULL;
if (daegun_font_location(font, coords, 2, &bold) != DAEGUN_OK) return 1;

daegun_shaped_run *run = NULL;
if (daegun_font_shape(font, "Wave", 4, bold, NULL, &run) != DAEGUN_OK) return 1;

/* No handle borrows another, so these go in any order. */
daegun_location_free(bold);
daegun_shaped_run_free(run);

Options

An options struct opens with its own size, which its _default fills in along with every default. Set what you want after that. Because the library reads no byte past that size, a program built against this header keeps working with a newer library whose struct has grown.

daegun_shape_options opts;
if (daegun_shape_options_default(&opts, sizeof opts) != DAEGUN_OK) return 1;
opts.language = "tr";

daegun_shaped_run *run = NULL;
if (daegun_font_shape(font, "fit", 3, NULL, &opts, &run) != DAEGUN_OK) return 1;
daegun_shaped_run_free(run);

Lists fill your buffer

A list of fixed-size items, such as tags, axes or glyph ids, goes into a buffer of yours, so one kept between calls means none allocates. The count is set whenever the call succeeds, and also when the buffer is too small. A NULL buffer with a length of 0 asks for the count alone, and a buffer too small answers DAEGUN_INVALID_ARGUMENT and writes nothing into it.

size_t count = 0;
if (daegun_font_table_tags(font, NULL, 0, &count) != DAEGUN_OK) return 1;

daegun_tag *tags = malloc(count * sizeof *tags);
if (!tags) return 1;
if (daegun_font_table_tags(font, tags, count, &count) != DAEGUN_OK) return 1;
/* tags[0] to tags[count - 1], in tag order */
free(tags);

Strings and whatever nests come back as handles instead, each with its own _free.

When a call fails

Every failure has a status of its kind and its name in daegun_status_name. All but DAEGUN_NULL, a pointer of your own, leave their reason in daegun_last_error, which is kept per thread like errno. A call that fails sets a handle out to NULL, and every _free takes NULL, so cleanup needs no checks.

daegun_font *broken = NULL;
daegun_status status = daegun_font_open((const uint8_t *)"not a font", 10, &broken);
if (status != DAEGUN_OK) {
    daegun_str name = daegun_status_name(status);
    daegun_str why = daegun_last_error();
    fprintf(stderr, "%s: %s\n", name.data, why.data); /* DAEGUN_MALFORMED: TTF/OTF: file too short */
}
daegun_font_free(broken); /* NULL after the failure, which is fine */

DAEGUN_ABSENT is not a failure. It is the answer that the font has no such glyph, table or value, separate from DAEGUN_OK because C has no Option and zero is a real glyph id.

Subsetting

Subsetting mirrors the Rust call, and the bytes are borrowed until the subset is freed:

const char *text = "Type is the voice of the page.";
daegun_subset *subset = NULL;
if (daegun_font_subset_text(font, text, strlen(text), NULL, &subset) != DAEGUN_OK) return 1;

size_t ttf_len = 0;
const uint8_t *ttf = daegun_subset_bytes(subset, &ttf_len);
fwrite(ttf, 1, ttf_len, out);
daegun_subset_free(subset);

Where to go next

  • The rules: the five every call keeps, and the conventions for text, buffers, options and callbacks.
  • Outlines in C: pens, options, curves, polygons and color scenes.
  • Rasterizing in C: glyphs to pixels with daegun's own rasterizer.

The reference has every function, type and constant, each with what it borrows, how long that stays valid and the statuses it answers, and an example for every function and type.

The rules

Every function in the headers obeys all five of these, so there is nothing to remember per call. They are stated in full at the top of daegun/base.h.

  1. A fallible call returns daegun_status, and its results come back through out parameters. A call that fails leaves a number or a struct out as it was, so you may preset a fallback, and sets a handle out to NULL, so freeing it on the way out is always safe.
  2. NULL where a pointer is required answers DAEGUN_NULL. It is never dereferenced. A pointer that may be NULL is marked DAEGUN_NULLABLE in the header, and every other is required. One that comes with a count may be NULL where the count is 0, unless its call says it may be NULL whatever the count. A location is never required: NULL is the default instance.
  3. daegun allocates and daegun frees. A handle comes back through a non-const T ** out, or as what a _new call returns, and has one _free, which takes NULL as free(NULL) does. Anything const is borrowed. Never call free() on a pointer daegun gave you: the library has its own allocator. No handle borrows another, so free them in any order: a run, a layout or a location may outlive its font.
  4. A borrowed view is a const pointer plus a count. It is valid until the handle it came from is freed, or changed by a call that takes it as non-const. Copy it if you need it longer.
  5. A handle a call takes as const may be used from several threads at once. Sharing a font scales, each thread keeping its own working state. A handle a call takes as non-const (a path being built, quads being rewound, a packer, a table map), or one a pen draws into, needs that handle to itself until it returns. Any handle may be freed on any thread, once no call is using it.

A crash from breaking these is a bug in the calling code. A crash from following them is a vulnerability, and worth reporting.

The rules make one cleanup path enough, whatever failed:

int result = 1;
daegun_font *font = NULL;
daegun_shaped_run *run = NULL;

if (daegun_font_open(data, len, &font) != DAEGUN_OK) goto done;
if (daegun_font_shape(font, "Wave", 4, NULL, NULL, &run) != DAEGUN_OK) goto done;
/* use the run */
result = 0;

done:
daegun_shaped_run_free(run); /* NULL if shaping never ran or failed, which is fine */
daegun_font_free(font);

Status codes

CodeValueMeaning
DAEGUN_OK0The call did what it says.
DAEGUN_NULL-1A required pointer was NULL. Always the caller's bug.
DAEGUN_MALFORMED-2Font data the call needs is malformed: truncated, out of range or inconsistent.
DAEGUN_INVALID_ARGUMENT-3An argument is out of range, not a number, or not UTF-8.
DAEGUN_ABSENT-4The font has no such glyph, table or value. An answer, not a failure.
DAEGUN_UNSUPPORTED-6A format, version or options struct daegun doesn't read.
DAEGUN_MISSING-7A table or record the call needs isn't in the font.
DAEGUN_LIMIT_EXCEEDED-8The font asks for more work or memory than daegun allows one font.
DAEGUN_NO_OUTLINE-9The glyph has no outline to draw.
DAEGUN_OVERFLOW-10A value outgrows what its type can hold once scaled.

The values are frozen: a compiled caller carries the numbers, not the names, so new codes append rather than renumber. Treat a code you don't know as a failure. -5 meant unsupported in 1.x and is never reused.

daegun_last_error gives the reason for the last failure on the calling thread, as UTF-8, valid until the next failure that gives one or until the thread ends. Every status gives a reason except DAEGUN_OK, DAEGUN_NULL, which is a pointer of your own, and DAEGUN_ABSENT, which is an answer. Those leave the last reason as it was, so read it right after the failure, on the same thread. daegun_status_name gives a status's name for a log.

Units

Every metric, advance, offset, bound and outline is in font units, a double, y up and unrounded, as the font's units per em measure them. Calls that hint or prepare a glyph take a pixel size and answer in pixels.

Text

Text comes as UTF-8 and a count of its bytes, so a slice of a larger buffer goes in without a copy, and U+0000 is a character like any other. A u8"" literal, whose characters are char8_t from C23 and C++20, goes in cast to const char *. A short identifier, such as a BCP 47 language tag, is NUL-terminated instead.

Text that isn't UTF-8 answers DAEGUN_INVALID_ARGUMENT, with the byte where it stops being UTF-8 in daegun_last_error. A position in text is a byte offset where a character starts, so text + start is where what it names begins.

Buffers

A list of fixed-size items, such as glyph ids, tags or axes, goes into your buffer rather than a handle, so a buffer kept between calls means none allocates. Handles hold strings and what nests.

  • The count a result needs is set whenever the call gets as far as working it out: on success, and when the buffer is too small. A call that fails for another reason, or answers DAEGUN_ABSENT, leaves the count as it was.
  • A NULL buffer and a length of 0 ask for the count alone and answer DAEGUN_OK.
  • A buffer too small answers DAEGUN_INVALID_ARGUMENT and writes nothing into it.
  • A result counted per byte or per character fits room for the text's byte count, as no character takes less than a byte. A call whose count has a bound you can know says so.
  • A buffer a call fills, and the count it sets, share no byte with the text or array the call reads or with each other, as with memcpy. Buffers that overlap answer DAEGUN_INVALID_ARGUMENT, and nothing is written.

Options

Each options struct opens with size_t size, the bytes your build of it holds. Fill one with its _default(&opts, sizeof opts), which zeroes it, sets its defaults and its size, then set the fields you want. A NULL options pointer is the defaults.

daegun reads no byte past size, so a struct from an older header works with a newer library. One from a newer header, larger than the library knows, answers DAEGUN_UNSUPPORTED. One below 2.0's size, as a zeroed struct's 0 is, answers DAEGUN_INVALID_ARGUMENT.

Yes, no and codes

A yes or no is a bool, given or answered, field or argument. A list of them comes as bytes, 1 for yes and 0 for no. A code that names one of several, such as a DAEGUN_ALIGN_ mode, is an int32_t, and one that names none of its constants answers DAEGUN_INVALID_ARGUMENT rather than a guess.

Callbacks

A function you hand daegun (a pen's, a paint visitor's, a word segmenter, a record search's key_at) runs on the thread that called daegun, before that call returns, and nothing of it is kept after. It must return normally. A C++ exception or a longjmp out of one is undefined behavior, as is ending the thread inside one.

Declare C++ callbacks noexcept, so a throw ends the process inside the callback in every build. Under MSVC each callback type uses C's calling convention, DAEGUN_CALLBACK: if you build with /Gv or /Gz, mark your callbacks DAEGUN_CALLBACK.

Threads and what they keep

A thread keeps what it last hinted with and the locations it last read at: up to 4 hinting contexts, 4 autohinters and 2 locations. So a freed font's bytes may stay until that thread hints or reads at locations of other fonts, ends, or calls daegun_thread_release. A pool's worker calls it as it goes idle.

A freed handle is kept for the thread's next one of its kind. A library built with --cfg daegun_no_spares frees each at once, so ASan or Valgrind sees a use after the free.

Panics and memory

The library calls neither unwrap nor expect outside its tests, which a lint in the release gate enforces. Were a panic to occur all the same, it would end the process rather than unwind into your stack frame. Running out of memory ends the process too, as Rust's allocations do. daegun_font_buffer_new alone answers NULL.

Signals, fork and unloading

No call is safe in a signal handler: calls allocate and take locks. The child of a fork from a process with other threads may call nothing here until it execs, as a lock one of those threads held stays held. Unloading the library while a thread that called it runs may leave it loaded, or leak what the thread kept, depending on the platform.

Outlines in C

There are two ways to get a glyph's shape. daegun_font_outline draws it as the font stores it, in font units. daegun_font_prepared_outline draws it ready for a rasterizer: scaled to a pixel size, and hinted, leaned, transformed, stroked or emboldened as you ask. Both draw onto a pen.

A pen

A daegun_pen is five callbacks and a pointer of yours that each one is handed back untouched. A callback left NULL skips its event.

typedef struct { size_t contours, curves; } counter;

static void on_move(void *user, float x, float y) { (void)x; (void)y; ((counter *)user)->contours++; }
static void on_line(void *user, float x, float y) { (void)user; (void)x; (void)y; }
static void on_quad(void *user, float cx, float cy, float x, float y)
{ (void)cx; (void)cy; (void)x; (void)y; ((counter *)user)->curves++; }
static void on_cubic(void *user, float c1x, float c1y, float c2x, float c2y, float x, float y)
{ (void)c1x; (void)c1y; (void)c2x; (void)c2y; (void)x; (void)y; ((counter *)user)->curves++; }
static void on_close(void *user) { (void)user; }

uint32_t w = 0;
if (daegun_font_glyph_id(font, 'W', &w) != DAEGUN_OK) return 1;

counter count = { 0, 0 };
daegun_pen pen = { on_move, on_line, on_quad, on_cubic, on_close, &count };
daegun_prepared_glyph glyph;
if (daegun_font_prepared_outline(font, w, NULL, 32.0f, NULL, &pen, &glyph) != DAEGUN_OK) return 1;
/* One contour with 16 curves, in pixels at 32 px to the em, y up from the glyph's origin. */

The callbacks run on your thread, before the call returns, and must return normally: no longjmp and no C++ exception out of one. TrueType outlines arrive as quadratic curves and CFF outlines as cubic ones, so a pen sees whichever the font has.

A path

A daegun_path is an outline held as a value. daegun_path_as_pen gives a pen that draws into it, so any call that draws can be recorded, read back, replayed or stroked later.

uint32_t w = 0;
if (daegun_font_glyph_id(font, 'W', &w) != DAEGUN_OK) return 1;

daegun_path *path = daegun_path_new();
daegun_pen pen;
if (daegun_path_as_pen(path, &pen) != DAEGUN_OK) return 1;
if (daegun_font_outline(font, w, NULL, &pen) != DAEGUN_OK) return 1;

size_t verbs_len = 0, points_len = 0;
const uint8_t *verbs = daegun_path_verbs(path, &verbs_len);
const daegun_point *points = daegun_path_points(path, &points_len);
/* verbs[i] is a DAEGUN_VERB_ code, and the points follow in the order the verbs take them. */

daegun_bounds box;
if (daegun_path_bounds(path, &box) != DAEGUN_OK) return 1; /* in font units here */
daegun_path_free(path);

Options

daegun_outline_options carries the rest. Passing NULL means the defaults, so you need not build the struct to get them. What it holds is applied in this order: hinting, then the oblique and the transform, then a stroke or an embolden.

uint32_t w = 0;
if (daegun_font_glyph_id(font, 'W', &w) != DAEGUN_OK) return 1;

daegun_outline_options opts;
if (daegun_outline_options_default(&opts, sizeof opts) != DAEGUN_OK) return 1;
opts.hinting = DAEGUN_HINT_AUTO;
opts.embolden = 40.0f; /* font units */
opts.has_embolden = true;

daegun_prepared_glyph glyph;
if (daegun_font_prepared_outline(font, w, NULL, 32.0f, &opts, &pen, &glyph) != DAEGUN_OK) return 1;
/* glyph.advance_width is in pixels and includes the embolden, and glyph.hinted says a hinter ran. */

A value that may be absent comes with a has_ flag beside it: has_transform, has_stroke, has_embolden, has_oblique. The call answers DAEGUN_INVALID_ARGUMENT unless the pixel size is finite and above zero and the options are finite, and DAEGUN_OVERFLOW for anything past FLT_MAX once scaled. Either way it draws nothing.

An embolden overlaps itself, and so does a stroke wherever a corner is too tight for its width or two parts lie closer than it is wide. A non-zero fill hides that, and a rasterizer that sums coverage needs the overlaps resolved first, as below. daegun's own rasterizer does that itself.

Quadratic curves

A GPU rasterizer that evaluates curves in a shader wants quadratics only. daegun_font_quads gives a glyph that way, in font units, wound clockwise:

uint32_t w = 0;
if (daegun_font_glyph_id(font, 'W', &w) != DAEGUN_OK) return 1;

daegun_quads *quads = NULL;
if (daegun_font_quads(font, w, NULL, &quads) != DAEGUN_OK) return 1;

size_t n = 0;
const daegun_quad *curves = daegun_quads_data(quads, &n);
/* n is 32: each curves[i] has a start, a control and an end. */
daegun_quads_free(quads);

A glyph that draws nothing, such as a space, answers DAEGUN_NO_OUTLINE.

Polygons and overlaps

A rasterizer that walks straight edges wants polygons. daegun_path_flatten makes them, and daegun_max_area_for gives the tolerance for a path in font units drawn at a pixel size. daegun_contours_resolve_overlaps then replaces contours that cross with boundaries that don't, each wound with the filled side on its left, for a rasterizer that sums coverage:

uint32_t w = 0;
uint16_t upem = 0;
if (daegun_font_glyph_id(font, 'W', &w) != DAEGUN_OK) return 1;
if (daegun_font_units_per_em(font, &upem) != DAEGUN_OK) return 1;

daegun_path *path = daegun_path_new();
daegun_pen pen;
if (daegun_path_as_pen(path, &pen) != DAEGUN_OK) return 1;
if (daegun_font_outline(font, w, NULL, &pen) != DAEGUN_OK) return 1;

daegun_contours *polygons = NULL;
if (daegun_path_flatten(path, daegun_max_area_for(32.0f, upem), &polygons) != DAEGUN_OK) return 1;

daegun_contours *merged = NULL;
daegun_status status = daegun_contours_resolve_overlaps(polygons, &merged);
if (status == DAEGUN_OK) {
    /* The W's strokes cross, so draw `merged`: one counterclockwise boundary. */
} else if (status == DAEGUN_ABSENT) {
    /* Nothing to merge: draw `polygons` as they are. */
}

daegun_contours_free(merged);
daegun_contours_free(polygons);
daegun_path_free(path);

Color glyphs

A color glyph comes back as a scene: ops to draw in order over the paths, clip shapes and gradients the scene holds. DAEGUN_ABSENT means the glyph has no color description, so draw its plain outline instead.

uint32_t a = 0;
if (daegun_font_glyph_id(font, 'A', &a) != DAEGUN_OK) return 1;

daegun_scene *scene = NULL;
daegun_status status = daegun_font_color_scene(font, a, NULL, NULL, &scene);
if (status == DAEGUN_ABSENT) return 0; /* not a color glyph */
if (status != DAEGUN_OK) return 1;

size_t n = 0;
const daegun_scene_op *ops = daegun_scene_ops(scene, &n);
for (size_t i = 0; i < n; i++) {
    if (ops[i].kind != DAEGUN_OP_FILL) continue; /* the rest push and pop clips and layers */
    daegun_path_view outline;
    if (daegun_scene_path_at(scene, ops[i].path, &outline) != DAEGUN_OK) return 1;
    /* Fill `outline`, placed by ops[i].transform, with ops[i].color,
       or with the scene's gradient ops[i].gradient where ops[i].has_gradient is set. */
}
daegun_scene_free(scene);

Everything in a scene is in font units, y up. The scene's views are borrowed until daegun_scene_free. To get pixels without drawing the scene yourself, see Rasterizing in C.

Rasterizing in C

A daegun_rasterizer turns a glyph into pixels. It lends an image placed by its left and top from the glyph's origin on the baseline, and it keeps its buffers between calls, so once warm it allocates nothing. Each call takes the rasterizer whole, so give each thread its own.

A run, set into a canvas of one byte a pixel:

daegun_shaped_run *run = NULL;
if (daegun_font_shape(font, "Wave", 4, NULL, NULL, &run) != DAEGUN_OK) return 1;
size_t n = 0;
const uint32_t *gids = daegun_shaped_run_glyphs(run, &n);
const double *advances = daegun_shaped_run_advances(run, &n);
const daegun_offset *offsets = daegun_shaped_run_offsets(run, &n);
uint16_t upem = 0;
if (daegun_font_units_per_em(font, &upem) != DAEGUN_OK) return 1;
const double scale = 32.0 / upem;
const int baseline = 30;
static uint8_t canvas[40][96];

daegun_rasterizer *rasterizer = daegun_rasterizer_new();
daegun_raster_options opts;
if (daegun_raster_options_default(&opts, sizeof opts) != DAEGUN_OK) return 1;
double pen = 2.0;
for (size_t i = 0; i < n; i++) {
    /* whole pixels place the image, and the fraction moves the glyph within it */
    double x = pen + offsets[i].x * scale, y = offsets[i].y * scale;
    opts.offset[0] = (float)(x - (int)x);
    opts.offset[1] = (float)(y - (int)y);
    daegun_image image;
    if (daegun_rasterizer_glyph(rasterizer, font, gids[i], NULL, 32.0f, &opts, &image) != DAEGUN_OK) return 1;
    int left = (int)x + image.left, top = baseline - (int)y - image.top;
    for (uint32_t row = 0; row < image.height; row++) {
        for (uint32_t col = 0; col < image.width; col++) {
            unsigned sum = canvas[top + (int)row][left + (int)col] + image.pixels[row * image.stride + col];
            canvas[top + (int)row][left + (int)col] = sum > 255 ? 255 : (uint8_t)sum;
        }
    }
    pen += advances[i] * scale;
}
daegun_rasterizer_free(rasterizer);
daegun_shaped_run_free(run);

The image

A daegun_image borrows the rasterizer's pixels, so it is valid until the next call on that rasterizer or its free. It has height rows, stride bytes apart, top first. left is how far its left edge sits right of the glyph's origin, and top how far its top sits above it. channels says what a pixel holds: 1 byte of coverage or of distance, 3 for a display's stripes or a multi-channel distance field, or 4 for a color glyph's premultiplied RGBA.

Options

daegun_raster_options starts from daegun_raster_options_default, and NULL means those defaults. It points at the outline options and at a subpixel layout, both of which may stay NULL:

daegun_outline_options outline;
if (daegun_outline_options_default(&outline, sizeof outline) != DAEGUN_OK) return 1;
outline.hinting = DAEGUN_HINT_AUTO;

daegun_subpixel_layout *stripes = NULL;
if (daegun_subpixel_layout_horizontal(DAEGUN_STRIPES_RGB, &stripes) != DAEGUN_OK) return 1;

daegun_raster_options opts;
if (daegun_raster_options_default(&opts, sizeof opts) != DAEGUN_OK) return 1;
opts.outline = &outline;
opts.layout = stripes;
opts.darken = true; /* widen thin stems, for small text */
opts.gamma = DAEGUN_GAMMA_SRGB; /* alpha for a compositor that blends sRGB values */
opts.text = (daegun_rgba){ 0, 0, 0, 255 };
opts.contrast = 0.5f;

uint32_t a = 0;
if (daegun_font_glyph_id(font, 'a', &a) != DAEGUN_OK) return 1;
daegun_rasterizer *rasterizer = daegun_rasterizer_new();
daegun_image image;
if (daegun_rasterizer_glyph(rasterizer, font, a, NULL, 14.0f, &opts, &image) != DAEGUN_OK) return 1;
/* image.channels is 3 now: a byte for each of the display's stripes. */

daegun_rasterizer_free(rasterizer);
daegun_subpixel_layout_free(stripes);

Color glyphs, distance fields and paths

uint32_t a = 0;
if (daegun_font_glyph_id(font, 'A', &a) != DAEGUN_OK) return 1;
daegun_rasterizer *rasterizer = daegun_rasterizer_new();
daegun_image image;

/* A COLR color glyph, as premultiplied RGBA. DAEGUN_ABSENT for a glyph with no color description. */
daegun_status status = daegun_rasterizer_color_glyph(rasterizer, font, a, NULL, 64.0f, NULL, NULL, &image);
if (status != DAEGUN_OK && status != DAEGUN_ABSENT) return 1;

/* A signed distance field, for text a shader scales. DAEGUN_FIELD_MSDF keeps corners sharp. */
if (daegun_rasterizer_distance_field(rasterizer, font, a, NULL, 32.0f, DAEGUN_FIELD_SDF, 4.0f, &image)
    != DAEGUN_OK) return 1;

daegun_rasterizer_free(rasterizer);

daegun_rasterizer_path fills any daegun_path of your own, taking its units as pixels, after an optional 2x3 transform.

Drawing into your own pixels

The calls above lend an image of at most DAEGUN_MAX_SIDE pixels a side and DAEGUN_MAX_DRAW_BYTES bytes of drawing. To draw straight into pixels of your own, at any size, fill in a daegun_target and use daegun_rasterizer_glyph_into, daegun_rasterizer_color_glyph_into or daegun_rasterizer_path_into:

static uint8_t pixels[64 * 64];
/* The target's top left corner sits 0 pixels right of the glyph's origin and 48 above it. */
daegun_target target = { 0, 48, 64, 64, 64, pixels, sizeof pixels };

uint32_t a = 0;
if (daegun_font_glyph_id(font, 'a', &a) != DAEGUN_OK) return 1;
daegun_rasterizer *rasterizer = daegun_rasterizer_new();
if (daegun_rasterizer_glyph_into(rasterizer, font, a, NULL, 48.0f, NULL, &target) != DAEGUN_OK) return 1;
daegun_rasterizer_free(rasterizer);

Keeping what was drawn

Give a font's raster cache a budget and the font keeps the images drawn of its glyphs, lent again in place of being drawn. It is off until you do:

if (daegun_font_set_cache_budget(font, DAEGUN_CACHE_RASTER, 1 << 20) != DAEGUN_OK) return 1;

For a GPU, a daegun_shelf_packer finds room for each image in an atlas texture: daegun_shelf_packer_insert takes a width and a height and answers the rectangle to copy it to, or DAEGUN_ABSENT where it has no room: a glyph empty or larger than the atlas, or an atlas that is full.

Reference

1383 names: everything daegun 2.0.0 makes public, in Rust and in C. Each entry says what the thing does, what comes back and what happens when it can't. Every function, method and type shows an example that was compiled and run against 2.0.0.

The lists themselves come from the engine's source, the Rust side as the compiler exports it and the C side as the headers declare it, so no name is transcribed by hand and none is left out. Both languages are filed under the same areas, in the order daegun.h includes its headers.

SectionNames
Rust methods and functions323
Rust types141
Rust constants225
C functions349
C types99
C constants and macros246

Press / or ⌘K to search all of them by name, fields and variants included. A name in an entry's text that is itself an entry links to it.

Loading Rust methods and functions…

Loading Rust types…

Loading Rust constants…

Loading C functions…

Loading C types…

Loading C constants…

Type to search.