zztaeha

C types

99 types in daegun 2.0.0, as its headers declare them, filed by header: structs with each of their fields, the opaque handles a call makes and a _free releases, and the scalar and callback types. Each has an example that was compiled and run against 2.0.0.

Every struct but an options struct is frozen for the life of an ABI major, so its size is safe to compile in. An options struct opens with its own size and may grow at its end.

Base

daegun/base.h: what every other header builds on. Statuses, the views and owned results calls hand back, the ABI version, the last error, tags, boxes, and the font and location handles.

daegun_status
typedef int32_t daegun_status;

What every fallible call returns: whether it worked, and if not, what kind of thing went wrong.

A call that can fail returns one of these and hands its results back through out parameters. Compare it with DAEGUN_OK, the only status after which the results are there to read. On any other status a number or struct out is left as it was, so you may preset a fallback, and a handle out is set to NULL, so freeing it on the way out is always safe. A buffer call is the one exception: it sets its count even when it answers DAEGUN_INVALID_ARGUMENT for a buffer too small.

Two statuses are not failures. DAEGUN_NULL means a pointer the call requires was NULL, which is a bug in the calling code, and DAEGUN_ABSENT is an answer: the font has no such glyph, table or value. The other seven are failures, one for each kind: DAEGUN_MALFORMED, DAEGUN_INVALID_ARGUMENT, DAEGUN_UNSUPPORTED, DAEGUN_MISSING, DAEGUN_LIMIT_EXCEEDED, DAEGUN_NO_OUTLINE and DAEGUN_OVERFLOW. Each of those leaves its reason in daegun_last_error, and daegun_status_name gives any status its name for a log.

It is an int32_t, and the values are frozen: a compiled program carries the numbers, not the names. A status added later comes after the last, so treat one you don't know as a failure. No status is -5. That value is retired and is never used.

daegun_shaped_run *run = NULL;
daegun_status status = daegun_font_shape(font, "Wave", 4, NULL, NULL, &run);
if (status != DAEGUN_OK) {
    fprintf(stderr, "%s: %s\n", daegun_status_name(status).data, daegun_last_error().data);
    return 1;
}
/* read the run */
daegun_shaped_run_free(run);
  • Size: 4 bytes.
daegun_bytes
typedef struct {
    const uint8_t *data;
    size_t len;
} daegun_bytes;

A run of bytes that daegun owns and lends you: a pointer and a length.

daegun_font_table fills one with a table of a font, and daegun_table_map_get and daegun_table_map_bytes_at with a table of a map. Read the bytes in place and never free them.

They stay valid until the handle they came from is freed or changed: a font's until daegun_font_free, and a map's until daegun_table_map_set, daegun_table_map_remove or daegun_table_map_free. Copy what you need for longer.

daegun_bytes head;
if (daegun_font_table(font, DAEGUN_TAG('h', 'e', 'a', 'd'), &head) != DAEGUN_OK) return 1;
/* head.len is 54, and bytes 12 to 15 hold the table's magic number, 0x5F0F3CF5. */
uint32_t magic = (uint32_t)head.data[12] << 24 | (uint32_t)head.data[13] << 16
    | (uint32_t)head.data[14] << 8 | (uint32_t)head.data[15];
const uint8_t *data
The first byte. There is no NUL after the last, so read exactly len of them.
size_t len
How many bytes data points at. An empty table has 0, which is not the same as the table being absent.
  • Size: 2 bytes * sizeof(size_t).
daegun_str
typedef struct {
    const char *data;
    size_t len;
} daegun_str;

A UTF-8 string that daegun owns and lends you: a pointer and a length in bytes.

It is NUL-terminated and counted both, so data goes straight to printf or strlen, and len saves you the scan. len does not count the NUL.

A string in a font may hold a NUL of its own, as a name in the name table may. daegun replaces each with U+FFFD, the replacement character, so the string never ends early and strlen(data) agrees with len. A glyph name is the one exception: one holding a NUL comes back empty, as a glyph with no name does.

How long it stays valid depends on where it came from. One that names something fixed, as daegun_version and daegun_status_name return, is static and valid for the life of the program. One read out of a handle, as daegun_text_str and daegun_str_list_at fill, is valid until that handle is freed. daegun_last_error has a rule of its own. Never free one.

daegun_str version = daegun_version();
printf("daegun %s\n", version.data);
/* Prints "daegun 2.0.0": version.len is 5, the same as strlen(version.data). */
const char *data
The string, with a NUL after its last byte. Once a call has filled the struct it is never NULL: an empty string points at a lone NUL.
size_t len
The length in bytes, the NUL not counted. Bytes, not characters: one character may take up to four.
  • Size: 2 bytes * sizeof(size_t).
daegun_tag
typedef uint32_t daegun_tag;

A four-byte OpenType tag, packed into a uint32_t with its first byte highest.

Fonts name their tables, scripts, languages, features, baselines and variation axes with four characters, and daegun passes every one of them as this number. The first character sits in the high byte, as the font stores it, so DAEGUN_TAG('w', 'g', 'h', 't') is 0x77676874.

Build one with DAEGUN_TAG, or from text with daegun_tag_from_string. DAEGUN_UNTAG gives the four characters back for printing. A tag shorter than four characters is padded with spaces, as fonts store lao and CFF .

Where a call or a field takes a tag it may go without, 0 means none: no font has a tag of four NULs.

daegun_tag weight = DAEGUN_TAG('w', 'g', 'h', 't');
/* 0x77676874: the four letters, from the high byte down. */

bool has = false;
if (daegun_font_has_table(font, DAEGUN_TAG('G', 'S', 'U', 'B'), &has) != DAEGUN_OK) return 1;
/* has is true: Inter has a GSUB table. */
  • Size: 4 bytes.
daegun_bounds
typedef struct {
    double x_min;
    double y_min;
    double x_max;
    double y_max;
} daegun_bounds;

A box: its left, bottom, right and top edges, y up.

daegun_font_glyph_bounds fills one with the tight box around a glyph's ink, daegun_font_bounds with the box the font states for all its glyphs, and daegun_font_colr_clip_box with a color glyph's clip box, each in font units. daegun_path_bounds fills one in the units its path was drawn in.

y points up, so y_min is the bottom edge and y_max the top. The width is x_max - x_min and the height is y_max - y_min.

There is no empty box. A glyph that draws nothing, such as a space, answers DAEGUN_ABSENT and leaves the struct as it was, which is not the same as a box of zero size.

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

daegun_bounds box;
if (daegun_font_glyph_bounds(font, gid, NULL, &box) != DAEGUN_OK) return 1;
double width = box.x_max - box.x_min, height = box.y_max - box.y_min;
/* Inter's A sits on the baseline, 1309 units wide and 1490 tall. */
double x_min
The left edge.
double y_min
The bottom edge.
double x_max
The right edge.
double y_max
The top edge.
  • Size: 32 bytes.
daegun_blob
typedef struct daegun_blob daegun_blob;

A run of bytes you own: a font file that daegun built.

An opaque handle. daegun_font_instance hands one back with a variable font pinned at a location, and daegun_table_map_build with a font file made from a map of tables. daegun_blob_data lends you the bytes, and daegun_blob_free frees them.

It is one of base.h's three owned results, the handles that bytes and strings come back in, beside daegun_text for one string and daegun_str_list for many. A list of fixed-size items, such as glyph ids or tags, fills a buffer of yours and needs no handle.

No call changes a blob once it is made, so threads may read one at the same time, and any thread may free it once no call is using it.

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

/* Inter pinned at weight 700, as a font file of its own that is no longer variable. */
daegun_blob *file = NULL;
if (daegun_font_instance(font, bold, &file) != DAEGUN_OK) return 1;
size_t size = 0;
const uint8_t *bytes = daegun_blob_data(file, &size);
/* Write the bytes to disk, or open them with daegun_font_open. */

daegun_blob_free(file);
daegun_location_free(bold);
daegun_str_list
typedef struct daegun_str_list daegun_str_list;

A list of strings you own.

An opaque handle. daegun_font_glyph_names hands one back with the name of every glyph. daegun_str_list_count says how many strings it holds, daegun_str_list_at lends one by index, and daegun_str_list_free frees the list and every string in it.

No call changes a list once it is made, so threads may read one at the same time.

daegun_str_list *names = NULL;
if (daegun_font_glyph_names(font, &names) != DAEGUN_OK) return 1;

size_t count = 0;
if (daegun_str_list_count(names, &count) != DAEGUN_OK) return 1;
for (size_t i = 0; i < count; i++) {
    daegun_str name;
    if (daegun_str_list_at(names, i, &name) != DAEGUN_OK) return 1;
    /* name.data is the name of glyph i, borrowed from the list. */
}
/* Inter has 2937 glyphs, so the list holds 2937 names. */

daegun_str_list_free(names);
daegun_text
typedef struct daegun_text daegun_text;

One string you own.

An opaque handle. daegun_font_family_name and daegun_font_name hand one back with a name read from the font. daegun_text_str lends you the string as a daegun_str, and daegun_text_free frees it.

No call changes the string once it is made, so threads may read one at the same time.

daegun_text *family = NULL;
if (daegun_font_family_name(font, NULL, &family) != DAEGUN_OK) return 1;

daegun_str name;
if (daegun_text_str(family, &name) != DAEGUN_OK) return 1;
/* name.data is "Inter Variable". */

daegun_text_free(family);
daegun_glyph_value
typedef struct {
    uint32_t glyph;
    uint16_t value;
} daegun_glyph_value;

A glyph paired with the value a table maps it to.

daegun_aat_lookup_entries fills an array of them, one for each glyph an AAT lookup table maps. What the value means depends on the table the lookup was read from.

The pairs come as one array of structs, not as two arrays side by side, because neither half means anything without the other.

/* An AAT lookup table in format 6 that maps glyph 3 to 30 and glyph 7 to 70. */
static const uint8_t table[20] = { 0, 6, 0, 4, 0, 2, 0, 8, 0, 1, 0, 0, 0, 3, 0, 30, 0, 7, 0, 70 };
daegun_aat_lookup *lookup = NULL;
if (daegun_aat_lookup_parse(table, sizeof table, 10, &lookup) != DAEGUN_OK) return 1;

daegun_glyph_value pairs[4];
size_t count = 0;
if (daegun_aat_lookup_entries(lookup, pairs, 4, &count) != DAEGUN_OK) return 1;
for (size_t i = 0; i < count; i++) {
    /* pairs[i].glyph maps to pairs[i].value. */
}

daegun_aat_lookup_free(lookup);
uint32_t glyph
The glyph id.
uint16_t value
The 16-bit value the table maps that glyph to.
  • Size: 8 bytes.
daegun_font
typedef struct daegun_font daegun_font;

An open font: the handle that nearly every call takes.

Opaque: you hold a pointer and never see inside. daegun_font_open makes one from the bytes of a font file and copies them, so the bytes are yours to free as soon as it returns. daegun_font_open_collection opens one face of a collection, daegun_font_open_static reads bytes that stay valid for the rest of the program without copying them, and daegun_font_open_owned takes over a buffer from daegun_font_buffer_new. daegun_font_free frees a font however it was opened.

No handle borrows the font. A shaped run, a layout or a daegun_location made from it may outlive it, so free them in any order.

Threads. Every call takes the font as const, so any number of threads may use one font at the same time, with no lock of your own. One font serves them all, each thread keeping its own working state. Any thread may free the font, once no call is using it.

That working state can hold on to a font's bytes: a thread keeps what it last hinted with and the locations it last read at. So after daegun_font_free the bytes may stay in memory until the thread hints or reads at locations of other fonts, ends, or calls daegun_thread_release.

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

uint32_t glyphs = 0;
if (daegun_font_glyph_count(mine, &glyphs) != DAEGUN_OK) return 1;
/* Inter Variable has 2937 glyphs. */

daegun_font_free(mine);
daegun_location
typedef struct daegun_location daegun_location;

A place in a variable font's design space, such as weight 700, resolved once and passed to every call that depends on one.

Opaque. daegun_font_location makes one from an array of daegun_coord, one for each axis you set, and daegun_location_free frees it. Metrics, advances, outlines, shaping, layout, color and instancing all take one.

A location is never required. Wherever a call takes one, NULL means the font's default instance, so a static font, or a variable font at its defaults, needs none.

It keeps the coordinates you gave, so it is not tied to the font that made it. It may outlive that font, and passed to another font it is resolved again from those coordinates. daegun_location_coords reads back what it resolved to.

Every call takes a location as const, so threads may share one. Any thread may free it, once no call is using it.

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

daegun_shaped_run *run = NULL;
if (daegun_font_shape(font, "Wave", 4, bold, NULL, &run) != DAEGUN_OK) return 1;
double width = 0.0;
if (daegun_shaped_run_width(run, &width) != DAEGUN_OK) return 1;
/* Inter sets "Wave" 5572 units wide at weight 700, and 5339 at its default weight. */

daegun_shaped_run_free(run);
daegun_location_free(bold);
daegun_coord
typedef struct {
    daegun_tag tag;
    double value;
} daegun_coord;

One axis value of a location: an axis tag and a value in that axis's own units.

Pass an array of them to daegun_font_location, one for each axis you want off its default. The value is in the units the axis declares, the ones daegun_font_axes reports its range in: 700 for a weight, 28 for an optical size.

A value past the axis's range is clamped to it, a tag the font has no axis for is ignored, and of a repeated tag the last one counts.

daegun_location_coords and daegun_named_instances_coords lend arrays of the same struct.

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;

size_t count = 0;
const daegun_coord *resolved = daegun_location_coords(bold, &count);
/* Both come back, in the order the font declares its axes: opsz 28, then wght 700. */

daegun_location_free(bold);
daegun_tag tag
The axis, such as DAEGUN_TAG('w', 'g', 'h', 't') for weight.
double value
The position on that axis, in the axis's own units.
  • Size: 16 bytes on a 64-bit target.

Fonts

daegun/font.h: opening a font and asking what it is. Its names, its tables, its variation axes and the locations they make, and the caches that keep its work.

daegun_axis
typedef struct {
    daegun_tag tag;
    uint16_t name_id;
    bool hidden;
    double min;
    double default_value;
    double max;
} daegun_axis;

One axis of a variable font, as its fvar table declares it: a tag, a range, a default and a name.

daegun_font_axes fills an array of these, in the font's own order. An axis is one way the design varies, such as weight or optical size. Its values are in the axis's own units, the same ones a daegun_coord takes: a weight of 700, an optical size of 14.

A slider for an axis runs from min to max and starts at default_value. daegun_font_location clamps a value outside that range to it.

daegun_axis axes[8];
size_t count = 0;
if (daegun_font_axes(font, axes, 8, &count) != DAEGUN_OK) return 1;

/* Inter has two. The second is weight, from 100 to 900 with a default of 400. */
const daegun_axis *weight = &axes[1];

daegun_text *label = NULL;
if (daegun_font_name(font, weight->name_id, NULL, &label) != DAEGUN_OK) return 1;
daegun_str text;
if (daegun_text_str(label, &text) != DAEGUN_OK) return 1;
/* text.data is "Weight", the name to show beside a slider. */
daegun_text_free(label);
daegun_tag tag
The axis's four-letter tag, such as DAEGUN_TAG('w', 'g', 'h', 't') for weight. DAEGUN_UNTAG splits it back into characters for printing.
uint16_t name_id
The ID of the axis's display name in the font's name table. daegun_font_name with this ID gives text such as Weight.
bool hidden
True where the font asks for the axis to be kept out of user interfaces.
double min
The lowest value the axis takes.
double default_value
The axis's value at the default instance, which is where the font sits when a call is given no location.
double max
The highest value the axis takes.
  • Size: 32 bytes.
daegun_named_instances
typedef struct daegun_named_instances daegun_named_instances;

The named instances of a variable font: the designs its fvar table lists by name, such as Light or Bold, each with its coordinates.

An opaque handle from daegun_font_named_instances. daegun_named_instances_count says how many it holds. daegun_named_instances_name, daegun_named_instances_postscript_name and daegun_named_instances_coords read one by its index, and daegun_named_instances_free frees it.

It holds copies of what it read, so it stays valid after the font is freed. The strings and coordinate arrays it lends are valid until it is freed itself.

daegun_named_instances *instances = NULL;
if (daegun_font_named_instances(font, &instances) != DAEGUN_OK) return 1;
size_t count = 0;
if (daegun_named_instances_count(instances, &count) != DAEGUN_OK) return 1;

/* Find the instance called "Bold" and make its location. */
daegun_location *bold = NULL;
for (size_t i = 0; i < count && !bold; i++) {
    daegun_str name;
    if (daegun_named_instances_name(instances, i, &name) != DAEGUN_OK) continue;
    if (strcmp(name.data, "Bold") != 0) continue;
    size_t n = 0;
    const daegun_coord *coords = daegun_named_instances_coords(instances, i, &n);
    if (daegun_font_location(font, coords, n, &bold) != DAEGUN_OK) return 1;
}
/* Inter has one, so `bold` is set: pass it to any call that takes a location. */

daegun_location_free(bold);
daegun_named_instances_free(instances);
daegun_names
typedef struct daegun_names daegun_names;

Every name of a font's name table at one location, each with its name ID.

An opaque handle from daegun_font_names. daegun_names_count says how many names it holds, daegun_names_at reads one by its index, and daegun_names_free frees it.

It holds copies of the names, so it stays valid after the font is freed. The strings it lends are valid until it is freed itself.

daegun_names *names = NULL;
if (daegun_font_names(font, NULL, &names) != DAEGUN_OK) return 1;
size_t count = 0;
if (daegun_names_count(names, &count) != DAEGUN_OK) return 1;

/* Find the version string, name ID 5. */
const char *version = NULL;
for (size_t i = 0; i < count && !version; i++) {
    uint16_t id = 0;
    daegun_str name;
    if (daegun_names_at(names, i, &id, &name) != DAEGUN_OK) return 1;
    if (id == 5) version = name.data;
}
/* For this Inter it is "Version 4.001;git-9221beed3", borrowed until `names` is freed. */

daegun_names_free(names);
daegun_localized_names
typedef struct daegun_localized_names daegun_localized_names;

One name of a font in each language its name table records it in.

An opaque handle from daegun_font_localized_names. daegun_localized_names_count says how many languages it holds, daegun_localized_names_at reads one entry, a language and the name in it, and daegun_localized_names_free frees it.

It holds copies, so it stays valid after the font is freed. The strings it lends are valid until it is freed itself.

/* The family name, ID 1, of Source Han Sans, in each language the font gives it in. */
daegun_localized_names *names = NULL;
if (daegun_font_localized_names(font, 1, NULL, &names) != DAEGUN_OK) return 1;
size_t count = 0;
if (daegun_localized_names_count(names, &count) != DAEGUN_OK) return 1;

/* Take the Japanese one where there is one. */
const char *japanese = NULL;
for (size_t i = 0; i < count && !japanese; i++) {
    daegun_str language, name;
    if (daegun_localized_names_at(names, i, &language, &name) != DAEGUN_OK) return 1;
    if (strcmp(language.data, "ja") == 0) japanese = name.data;
}
/* japanese is "源ノ角ゴシック JP VF", borrowed until `names` is freed. */

daegun_localized_names_free(names);
daegun_table_map
typedef struct daegun_table_map daegun_table_map;

A set of font tables, each a tag with its bytes, that daegun owns and you may change.

It is what instancing produces and what building a font file takes. daegun_font_instance_tables fills one with a font's tables at a location, daegun_table_map_new makes an empty one, and daegun_table_map_build writes one out as a font file. In between it is yours to edit, so you can take an instance, drop a table, patch another and build the result.

An opaque handle. The map keeps its tables sorted by tag, one per tag, and holds its own copy of every byte, so it borrows nothing from a font and may outlive the one it came from. daegun_table_map_count, daegun_table_map_tag_at and daegun_table_map_bytes_at walk it by index, daegun_table_map_get looks a tag up, and daegun_table_map_set and daegun_table_map_remove change it. Free it with daegun_table_map_free.

daegun_table_map_set and daegun_table_map_remove take the map as non-const: while one of them runs, no other thread may use that map. The calls that take it as const only read it, and any number of threads may make those at once. Bytes that a read lent you are valid until the map is next changed or freed.

/* The tables of the default instance: drop one, then build a font file from the rest. */
daegun_table_map *tables = NULL;
if (daegun_font_instance_tables(font, NULL, &tables) != DAEGUN_OK) return 1;
if (daegun_table_map_remove(tables, DAEGUN_TAG('G', 'P', 'O', 'S')) != DAEGUN_OK) return 1;

daegun_blob *file = NULL;
if (daegun_table_map_build(tables, &file) != DAEGUN_OK) return 1;
daegun_table_map_free(tables);

size_t size = 0;
const uint8_t *bytes = daegun_blob_data(file, &size);
/* `bytes` is a static Inter without its GPOS table, so without kerning: write it out, or
   open it as any other font. */
daegun_blob_free(file);
daegun_cache_stats
typedef struct {
    size_t entries;
    size_t bytes;
} daegun_cache_stats;

What a cache holds: how many entries, and how many bytes they count for.

daegun_font_cache_stats fills one for a single cache of a font, and daegun_cache_pool_stats for a whole pool. Both numbers are as of the call. It is a plain struct of two size_t that you declare yourself, so there is nothing to free.

/* What the font holds in memory, cache by cache. */
const int32_t caches[] = {
    DAEGUN_CACHE_SHAPE, DAEGUN_CACHE_INSTANCE, DAEGUN_CACHE_OUTLINE, DAEGUN_CACHE_RASTER,
};
size_t entries = 0, bytes = 0;
for (size_t i = 0; i < 4; i++) {
    daegun_cache_stats stats;
    if (daegun_font_cache_stats(font, caches[i], &stats) != DAEGUN_OK) return 1;
    entries += stats.entries;
    bytes += stats.bytes;
}
/* A font that has done nothing yet holds nothing: both sums are 0. */
size_t entries
How many entries are held: runs, locations, outlines or images, depending on the cache.
size_t bytes
What those entries cost in bytes, as the cache counts them: the number a budget is held against. For DAEGUN_CACHE_INSTANCE it also counts what dropped locations left for the next to reuse, which no budget holds.
  • Size: 2 bytes * sizeof(size_t).
daegun_cache_pool
typedef struct daegun_cache_pool daegun_cache_pool;

One budget in bytes that the caches of several fonts share.

Each font has budgets of its own, which add up as you open more fonts. A pool caps their total as well. Every cache that joins draws on the one budget, and when the pool is over it, the entry used longest ago across all of them goes first, whichever font it belongs to. So the fonts in use keep their entries, and the fonts lying idle give theirs up.

An opaque handle. daegun_cache_pool_new makes one, daegun_font_set_cache_pool puts a cache of a font into it or takes it out, daegun_cache_pool_set_budget and daegun_cache_pool_stats change and read it, and daegun_cache_pool_free frees it. Caches of different kinds may share a pool, shaped runs beside outlines. The budget is a ceiling the caches grow toward, never memory set aside.

Every call but daegun_cache_pool_free takes the pool as const, so threads may share one as they share a font.

Freeing the handle does not take the caches out. A cache that joined goes on drawing from the pool, and keeping to its budget, until it leaves through daegun_font_set_cache_pool with a NULL pool or its font is freed. With the handle gone you can no longer read the pool or change its budget, so take the caches out first unless you mean to leave them capped.

/* `inter` and `garamond` are two open fonts. One megabyte for the shaped runs of both. */
daegun_cache_pool *pool = daegun_cache_pool_new(1 << 20);
const daegun_font *fonts[] = { inter, garamond };
for (size_t i = 0; i < 2; i++) {
    if (daegun_font_set_cache_pool(fonts[i], DAEGUN_CACHE_SHAPE, pool) != DAEGUN_OK) return 1;
    daegun_shaped_run *run = NULL;
    if (daegun_font_shape(fonts[i], "Shared", 6, NULL, NULL, &run) != DAEGUN_OK) return 1;
    daegun_shaped_run_free(run);
}

daegun_cache_stats held;
if (daegun_cache_pool_stats(pool, &held) != DAEGUN_OK) return 1;
/* held.entries is 2: one run from each font, counted together under the one budget. */

/* Take each cache out before the pool is freed, or it stays capped by the pool's budget. */
for (size_t i = 0; i < 2; i++) {
    if (daegun_font_set_cache_pool(fonts[i], DAEGUN_CACHE_SHAPE, NULL) != DAEGUN_OK) return 1;
}
daegun_cache_pool_free(pool);

Metrics

daegun/metrics.h: a font's metrics in font units, y up. Line spacing, the OS/2 and post tables, STAT, tracking and the flags a PDF writer needs.

daegun_line_metrics
typedef struct {
    double ascent;
    double descent;
    double line_gap;
} daegun_line_metrics;

A line's measures in font units: how far it reaches above the baseline, how far below, and the gap the font asks for between lines.

daegun_font_line_metrics fills one. All three fields are in font units with y up, so descent lies below the baseline and is negative for an ordinary font. For pixels, multiply by the pixel size over the units per em, which daegun_font_units_per_em gives.

The distance from one baseline to the next is ascent - descent + line_gap, which daegun_line_metrics_line_height works out for you.

For DAEGUN_VERTICAL the fields describe a column of vertical text: ascent and descent reach to either side of the column's center line, and line_gap is the space between columns.

daegun_line_metrics line;
if (daegun_font_line_metrics(font, NULL, DAEGUN_HORIZONTAL, &line) != DAEGUN_OK) return 1;
uint16_t upem = 0;
if (daegun_font_units_per_em(font, &upem) != DAEGUN_OK) return 1;

/* In pixels at 16 px. The descent is negative: the bottom of the line is below the baseline. */
double top = line.ascent * 16.0 / upem, bottom = line.descent * 16.0 / upem;
/* Inter: ascent 1984, descent -494 and line_gap 0, so top is 15.5 px and bottom -3.859375 px. */
double ascent
From the baseline up to the top of the line.
double descent
From the baseline down to the bottom of the line. Negative when the bottom is below the baseline, as it nearly always is.
double line_gap
The extra space the font asks for between the bottom of one line and the top of the next. Many fonts state 0.
  • Size: 24 bytes.
daegun_os2
typedef struct {
    uint16_t version;
    uint16_t weight_class;
    uint16_t width_class;
    uint16_t fs_type;
    uint16_t family_class;
    uint16_t selection;
    bool has_weight_class;
    bool has_width_class;
    bool has_fs_type;
    bool has_family_class;
    bool has_selection;
    bool has_win_metrics;
    bool has_typo_metrics;
    double win_ascent;
    double win_descent;
    double typo_ascender;
    double typo_descender;
    double typo_line_gap;
} daegun_os2;

What a font's OS/2 table says of its weight, width, style, embedding license and line metrics.

daegun_font_os2 fills one. OS/2 is the table where a font states how it is to be classified and spaced: how bold and how wide it is, whether it is italic, whether its license lets it be embedded in a document, and two sets of line metrics. The metrics are in font units.

Each has_ flag says whether the table reached the field or fields it guards. A table cut short stops before its later fields, and such a field reads 0 with its flag false, so check the flag before you trust a 0. Some old fonts carry a shortened version 0 table that ends before the typographic and Windows metrics.

The five daegun_os2_ calls, such as daegun_os2_is_bold, read the style bits of selection for you.

daegun_os2 os2;
daegun_status status = daegun_font_os2(font, NULL, &os2);
if (status == DAEGUN_ABSENT) return 0; /* the font has no OS/2 table */
if (status != DAEGUN_OK) return 1;

unsigned weight = os2.has_weight_class ? os2.weight_class : 400;
bool may_embed = !os2.has_fs_type || (os2.fs_type & 0x2) == 0;
/* Inter: an OS/2 of version 4, weight 400, width 5, and free to embed. */
uint16_t version
The table's version number, as the font states it. Version 2 added the x-height and the cap height, and version 4 defined the typo metrics and oblique bits of selection.
uint16_t weight_class
How bold the font is, on the 1 to 1000 scale of CSS's font-weight: 400 is regular and 700 bold. At a location of a font with a wght axis, it is that axis's value there, rounded.
uint16_t width_class
How wide the font is, from 1 for ultra-condensed to 9 for ultra-expanded, with 5 for normal. At a location of a font with a wdth axis, it is the class nearest to the width there.
uint16_t fs_type
What the font's license allows when the font is embedded in a document. 0 lets it be embedded and installed freely. Otherwise it is a set of bits: 0x2 forbids embedding, 0x4 allows it for preview and print, 0x8 allows it in documents that are edited, 0x100 forbids subsetting, and 0x200 allows only the font's bitmaps to be embedded.
uint16_t family_class
The font's design class. The high byte is the class, such as 1 to 5 and 7 for the serif classes, 8 for sans serif and 10 for scripts, and the low byte is a subclass within it. 0 means the font states none.
uint16_t selection
The font's style bits. Read them with daegun_os2_is_italic, daegun_os2_is_bold, daegun_os2_is_regular, daegun_os2_is_oblique and daegun_os2_uses_typo_metrics. At a location the bold, italic, regular and oblique bits are those of the instance there.
bool has_weight_class
Whether weight_class was in the table. False only for a table that ends before the field.
bool has_width_class
Whether width_class was in the table.
bool has_fs_type
Whether fs_type was in the table.
bool has_family_class
Whether family_class was in the table.
bool has_selection
Whether selection was in the table. When it is false, the five style calls all answer false.
bool has_win_metrics
Whether win_ascent and win_descent were in the table.
bool has_typo_metrics
Whether typo_ascender, typo_descender and typo_line_gap were in the table.
double win_ascent
The Windows ascent: how far above the baseline the font may draw before Windows clips it.
double win_descent
The Windows descent: how far below the baseline the font may draw before Windows clips it. It is a distance, as OS/2 stores it, so it is positive below the baseline, unlike every other descent here.
double typo_ascender
The typographic ascender: the top of the line as the designer set it, above the baseline.
double typo_descender
The typographic descender: the bottom of the line as the designer set it. Negative below the baseline.
double typo_line_gap
The typographic line gap: the space the designer asks for between lines.
  • Size: 64 bytes on a 64-bit target.
daegun_typographic_metrics
typedef struct {
    bool has_x_height;
    bool has_underline;
    bool has_strikeout;
    bool has_subscript;
    bool has_superscript;
    double x_height;
    double underline_position;
    double underline_thickness;
    double strikeout_position;
    double strikeout_thickness;
    double subscript_x_size;
    double subscript_y_size;
    double subscript_x_offset;
    double subscript_y_offset;
    double superscript_x_size;
    double superscript_y_size;
    double superscript_x_offset;
    double superscript_y_offset;
} daegun_typographic_metrics;

The measures a font gives for setting text: its x-height, where to draw an underline and a strikeout, and how to size and place subscripts and superscripts.

daegun_font_typographic_metrics fills one. Every value is in font units. A position is measured from the baseline with y up, so one below the baseline is negative. The one exception is subscript_y_offset, which OS/2 stores as a distance downward.

Each group of fields has a has_ flag. Where it is false the font gave no such value and the group's fields are 0: fall back on measures of your own, and don't draw an underline at 0. The underline comes from the post table and the rest from OS/2.

daegun_typographic_metrics m;
if (daegun_font_typographic_metrics(font, NULL, &m) != DAEGUN_OK) return 1;
uint16_t upem = 0;
if (daegun_font_units_per_em(font, &upem) != DAEGUN_OK) return 1;

/* An underline for 32 px text, with a fallback for a font that states none. */
double scale = 32.0 / upem;
double y = m.has_underline ? m.underline_position * scale : -3.0;
double thickness = m.has_underline ? m.underline_thickness * scale : 2.0;
/* Inter puts it 348 units below the baseline and makes it 140 thick: y -5.4375 px, 2.1875 px thick. */
bool has_x_height
Whether x_height is set: the font has an OS/2 table of version 2 or later, long enough to hold the cap height that follows the field.
bool has_underline
Whether underline_position and underline_thickness are set: the font has a post table that reaches them.
bool has_strikeout
Whether strikeout_position and strikeout_thickness are set: the font has an OS/2 table that reaches them.
bool has_subscript
Whether the four subscript_ fields are set: the font has an OS/2 table that reaches them.
bool has_superscript
Whether the four superscript_ fields are set: the font has an OS/2 table that reaches them.
double x_height
The height of the lowercase letters that have no ascender, such as x, above the baseline. A font may state 0.
double underline_position
Where the underline goes, from the baseline: negative, below it, for most fonts. OpenType defines it as the line's top edge.
double underline_thickness
How thick to draw the underline.
double strikeout_position
Where the strikeout goes, from the baseline: positive, above it, for most fonts. OpenType defines it as the line's top edge.
double strikeout_thickness
How thick to draw the strikeout.
double subscript_x_size
The em to set a subscript at, across: scale its glyphs by this over the units per em.
double subscript_y_size
The em to set a subscript at, up and down.
double subscript_x_offset
How far to move a subscript across.
double subscript_y_offset
How far to lower a subscript. It is as OS/2 stores it, a distance below the baseline, so a positive value moves the subscript down.
double superscript_x_size
The em to set a superscript at, across: scale its glyphs by this over the units per em.
double superscript_y_size
The em to set a superscript at, up and down.
double superscript_x_offset
How far to move a superscript across.
double superscript_y_offset
How far to raise a superscript above the baseline.
  • Size: 112 bytes.
daegun_stat
typedef struct daegun_stat daegun_stat;

A font's STAT table read out: its design axes, the values it names on them, and their names.

STAT, the style attributes table, is how a font describes its styles: the axes they differ along, such as weight and optical size, and a name for particular values on each, such as Bold for weight 700. An application uses it to put a style name together from parts, to group a family in a font menu, or to label the stops of a slider.

An opaque handle. daegun_font_stat makes one and daegun_stat_free frees it. daegun_stat_axes lends the axes, daegun_stat_value_count and daegun_stat_value_at read the values, and daegun_stat_axis_name, daegun_stat_value_name and daegun_stat_elided_fallback_name lend the names.

Every array and string it lends belongs to the handle and stays valid until daegun_stat_free. The handle holds its own copy of all of it, so it may outlive the font. No call changes it, so threads may read one at the same time.

daegun_stat *stat = NULL;
if (daegun_font_stat(font, NULL, &stat) != DAEGUN_OK) return 1;

size_t axis_count = 0, value_count = 0;
const daegun_stat_axis *axes = daegun_stat_axes(stat, &axis_count);
if (daegun_stat_value_count(stat, &value_count) != DAEGUN_OK) return 1;
for (size_t i = 0; i < value_count; i++) {
    daegun_stat_value v;
    daegun_str name;
    if (daegun_stat_value_at(stat, i, &v) != DAEGUN_OK) break;
    if (daegun_stat_value_name(stat, i, &name) != DAEGUN_OK) continue;
    /* name.data names v, which for every kind but DAEGUN_STAT_COMBO lies on axes[v.axis_index]. */
}
/* Inter describes 3 axes and names 12 values on them. */

daegun_stat_free(stat);
daegun_stat_axis
typedef struct {
    daegun_tag tag;
    uint16_t ordering;
    bool has_name;
} daegun_stat_axis;

One design axis a font's STAT table describes.

daegun_stat_axes lends an array of them. STAT may list an axis the font does not vary along: an upright font lists ital to say where it stands in a family that also has an italic. So these are not the font's variation axes, which daegun_font_axes gives.

daegun_stat *stat = NULL;
if (daegun_font_stat(font, NULL, &stat) != DAEGUN_OK) return 1;

size_t count = 0;
const daegun_stat_axis *axes = daegun_stat_axes(stat, &count);
for (size_t i = 0; i < count; i++) {
    const daegun_stat_axis *axis = &axes[i];
    daegun_str name = { "", 0 };
    if (axis->has_name && daegun_stat_axis_name(stat, i, &name) != DAEGUN_OK) break;
    /* axis->tag is the axis, name.data what to call it, axis->ordering its place in a style name. */
}
/* Inter lists opsz, wght and ital, ordered 0, 1 and 2. Only the first two are axes it varies along. */

daegun_stat_free(stat);
daegun_tag tag
The axis's tag, such as wght for weight, the same tag a variation axis of that kind has. Compare it with DAEGUN_TAG('w', 'g', 'h', 't').
uint16_t ordering
Where the axis's part goes when a style name is put together from the names of values: the parts are sorted by this number, lowest first.
bool has_name
Whether daegun_stat_axis_name has a name to give for the axis.
  • Size: 8 bytes.
daegun_stat_value
typedef struct {
    int32_t kind;
    uint16_t axis_index;
    bool elidable;
    bool has_name;
    bool older_sibling;
    double value;
    double min;
    double max;
    double linked_value;
    uint32_t combo_start;
    uint32_t combo_count;
} daegun_stat_value;

One value a font's STAT table names on its axes, such as Bold at weight 700.

daegun_stat_value_at fills one. STAT has four kinds of value, and this one struct holds any of them: kind is a DAEGUN_STAT_ code that says which, and so which of the other fields mean anything. A field that doesn't apply to the kind is 0.

Values are in the axis's own units, the ones a daegun_coord uses, such as 700 for a weight.

The value's name comes from daegun_stat_value_name. To name the style at a location, take the value that holds there on each axis, leave out those marked elidable, and join the names that remain in the order of their axes' ordering. If none remains, use daegun_stat_elided_fallback_name.

daegun_stat *stat = NULL;
if (daegun_font_stat(font, NULL, &stat) != DAEGUN_OK) return 1;
size_t axis_count = 0, count = 0, weight = 0;
const daegun_stat_axis *axes = daegun_stat_axes(stat, &axis_count);
while (weight < axis_count && axes[weight].tag != DAEGUN_TAG('w', 'g', 'h', 't')) weight++;
if (daegun_stat_value_count(stat, &count) != DAEGUN_OK) return 1;

/* What does the font call weight 700? */
daegun_str name = { "", 0 };
for (size_t i = 0; i < count; i++) {
    daegun_stat_value v;
    if (daegun_stat_value_at(stat, i, &v) != DAEGUN_OK) break;
    if (v.kind == DAEGUN_STAT_COMBO || v.axis_index != weight) continue;
    bool holds = v.kind == DAEGUN_STAT_RANGE ? v.min <= 700.0 && 700.0 <= v.max : v.value == 700.0;
    if (holds && daegun_stat_value_name(stat, i, &name) == DAEGUN_OK) break;
}
/* Inter: name.data is "Bold". */

daegun_stat_free(stat);
int32_t kind
Which kind of value this is: DAEGUN_STAT_SINGLE, DAEGUN_STAT_RANGE, DAEGUN_STAT_LINKED or DAEGUN_STAT_COMBO.
uint16_t axis_index
The axis the value is on, as an index into the array daegun_stat_axes lends. 0 and without meaning for DAEGUN_STAT_COMBO, whose pairs each name an axis of their own.
bool elidable
True when the value's name is left out where a style name is put together, as the Regular of a weight axis is, so that a style reads Display and not Display Regular.
bool has_name
Whether daegun_stat_value_name has a name to give for the value.
bool older_sibling
True when the value describes other fonts of the family and not this one. A font carries such a value for siblings released before it that say nothing of the axis.
double value
The value on the axis that the name is for. For DAEGUN_STAT_RANGE it is the nominal value within the range. 0 for DAEGUN_STAT_COMBO.
double min
The low end of the range, for DAEGUN_STAT_RANGE. 0 for the other kinds.
double max
The high end of the range, for DAEGUN_STAT_RANGE. 0 for the other kinds.
double linked_value
For DAEGUN_STAT_LINKED, the value on the same axis that this one is paired with, as 700 is for a Regular at 400. 0 for the other kinds.
uint32_t combo_start
For DAEGUN_STAT_COMBO, the index of its first pair in the array daegun_stat_combo_values lends. 0 for the other kinds.
uint32_t combo_count
For DAEGUN_STAT_COMBO, how many pairs it has, counted from combo_start. 0 for the other kinds.
  • Size: 56 bytes on a 64-bit target.
daegun_axis_value
typedef struct {
    uint16_t axis_index;
    double value;
} daegun_axis_value;

One axis and a value on it: a part of a STAT value that spans several axes.

A DAEGUN_STAT_COMBO value names a point on several axes at once, as a list of these pairs. daegun_stat_combo_values lends the pairs of every such value in one array.

daegun_stat *stat = NULL;
if (daegun_font_stat(font, NULL, &stat) != DAEGUN_OK) return 1;

size_t pair_count = 0;
const daegun_axis_value *pairs = daegun_stat_combo_values(stat, &pair_count);
for (size_t i = 0; i < pair_count; i++) {
    /* pairs[i].value on the axis at index pairs[i].axis_index. */
}
/* Inter names no value across several axes, so pair_count is 0. */

daegun_stat_free(stat);
uint16_t axis_index
The axis, as an index into the array daegun_stat_axes lends.
double value
The value on that axis, in the axis's own units.
  • Size: 16 bytes on a 64-bit target.

Shaping

daegun/shape.h: text to glyphs placed in font units, one run or the runs of mixed-direction text, and the carets that hit testing reads off them.

daegun_shaped_run
typedef struct daegun_shaped_run daegun_shaped_run;

A shaped run: the glyphs of a piece of text in the order they are drawn, each with its advance, its offset and the cluster of text it came from.

An opaque handle. daegun_font_shape makes one, the daegun_shaped_run_ calls read it, and daegun_shaped_run_free frees it. daegun_font_shape_into, daegun_font_justify and daegun_font_shape_justified make one too. Its advances and offsets are in font units, and its clusters are byte offsets into the text.

A run that comes out of daegun_bidi_runs_at or out of a layout is borrowed, not yours: read it, and never free it. daegun_shaped_run_copy gives you a copy to keep.

A run is read-only once shaped, so any number of threads may read one at the same time. The exception is daegun_font_shape_into, which writes into a run and needs it to itself.

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 *glyphs = daegun_shaped_run_glyphs(run, &n);
/* n is 4: one glyph a letter here. */

daegun_shaped_run_free(run);
daegun_offset
typedef struct {
    double x;
    double y;
} daegun_offset;

How far one glyph sits from where its advance puts it, in font units, y up.

daegun_shaped_run_offsets lends an array of these, one per glyph. Most are zero. A mark's offset moves it onto its base, and in vertical text the offset puts each glyph under the pen. Draw glyph i at the pen plus its offset, then move the pen by its advance.

The same struct is the offset of a daegun_layout_run, where it says where the run starts from its line's origin: in x along a horizontal line, and in y down a vertical one. There, and only there, a larger y is lower.

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

size_t n = 0;
const daegun_offset *offsets = daegun_shaped_run_offsets(run, &n);
const double *advances = daegun_shaped_run_advances(run, &n);
double pen = 0.0;
for (size_t i = 0; i < n; i++) {
    double x = pen + offsets[i].x, y = offsets[i].y;
    /* Draw glyph i at (x, y). */
    pen += advances[i];
}

daegun_shaped_run_free(run);
double x
Across. A positive value moves right.
double y
Up. A positive value moves a glyph up.
  • Size: 16 bytes.
daegun_feature
typedef struct {
    daegun_tag tag;
    uint32_t value;
    uint32_t start;
    uint32_t end;
} daegun_feature;

One OpenType feature to turn on, turn off or set to a value, over a byte range of the text.

Point features of a daegun_shape_options at an array of them. Some common tags: kern for kerning, liga for standard ligatures, smcp for small caps, tnum for tabular figures.

A feature zeroed apart from its tag and value covers the whole text, since an end of 0 means the text's end. daegun_feature_from_string reads one from text such as -liga.

A feature that is on or off over the whole text costs nothing. One the font has, over a byte range or with a value above 1, takes bits from a budget of 27 that the shaping model's own features draw on too: 1 bit for on or off, and up to 8 for a higher value. Those that no longer fit, counted in tag order, are left out without an error, and wholly: a kern off over a few bytes that finds no room leaves the whole text unkerned. So keep ranged and valued features to a handful.

/* Kerning off, over the whole text. */
daegun_feature features[] = { { DAEGUN_TAG('k', 'e', 'r', 'n'), 0, 0, 0 } };

daegun_shape_options opts;
if (daegun_shape_options_default(&opts, sizeof opts) != DAEGUN_OK) return 1;
opts.features = features;
opts.features_len = 1;

daegun_shaped_run *run = NULL;
if (daegun_font_shape(font, "Wave", 4, NULL, &opts, &run) != DAEGUN_OK) return 1;
double width = 0.0;
if (daegun_shaped_run_width(run, &width) != DAEGUN_OK) return 1;
/* Inter sets "Wave" 5513 units wide without kerning, and 5339 with it. */

daegun_shaped_run_free(run);
daegun_tag tag
The feature's tag, as DAEGUN_TAG('k', 'e', 'r', 'n').
uint32_t value
0 turns the feature off and 1 turns it on. For a feature that picks among alternates, such as aalt, a higher value picks which one, up to 255: only the low 8 bits count, so 256 turns it off and 257 acts as 1.
uint32_t start
The byte offset in the text where the feature starts to apply.
uint32_t end
The byte offset where it stops, not included. 0 or UINT32_MAX runs to the text's end.
  • Size: 16 bytes.
daegun_shape_options
typedef struct {
    size_t size;
    int32_t direction;
    daegun_tag script;
    const char *language;
    const daegun_feature *features;
    size_t features_len;
    const char *before;
    size_t before_len;
    const char *after;
    size_t after_len;
    int32_t cluster_level;
    int32_t ignorables;
    uint32_t invisible_glyph;
    uint32_t not_found_glyph;
    uint32_t not_found_variation_selector_glyph;
    daegun_tag seed_script;
    bool beginning_of_text;
    bool has_point_size;
    bool report_unsafe_to_concat;
    bool report_tatweel_positions;
    bool suppress_dotted_circle;
    bool has_invisible_glyph;
    bool has_not_found_variation_selector_glyph;
    double point_size;
} daegun_shape_options;

Everything shaping can be told: direction, script, language, features, the text around the run and what to draw for characters the font can't.

Fill one with daegun_shape_options_default, then set the fields you want. Passing NULL where a call takes options means the defaults. They shape text the way it reads: direction and script taken from the text, the font's default features, no language.

The struct opens with its own size, so a program built against this header keeps working with a newer library that has added fields at the end. Apart from size every default is zero, yet zeroing the struct yourself is not enough: a size of 0 makes the call you pass it to answer DAEGUN_INVALID_ARGUMENT.

The shape cache. daegun_font_shape keeps runs and as a rule hands the same one out for the same request. It keeps a request that sets nothing beyond a direction other than DAEGUN_DIRECTION_BTT, the text around the run, a language and a seed script. Any other field means the run is shaped afresh on every call, as is a run too long for the cache to keep: daegun_font_shape says how long that is.

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, "fi", 2, NULL, &opts, &run) != DAEGUN_OK) return 1;
size_t n = 0;
daegun_shaped_run_glyphs(run, &n);
/* EB Garamond joins f and i into one ligature glyph, but not in Turkish: n is 2. */

daegun_shaped_run_free(run);
size_t size
The size of the struct in bytes as your header has it. daegun_shape_options_default sets it.
int32_t direction
A DAEGUN_DIRECTION_ code. DAEGUN_DIRECTION_DEFAULT takes left to right or right to left from the text.
daegun_tag script
An OpenType script tag, such as DAEGUN_TAG('l', 'a', 't', 'n'), whose lookups to use in place of those the text's own script selects. 0 goes by the text. A tag the font lacks falls back to the font's default script, DFLT, or to latn where it has none. The tag also takes part in picking the shaping model, as DAEGUN_SHAPER_DEFAULT explains: under DFLT or latn, text of an Indic script or Myanmar is shaped by the general model, and qaag asks for the Zawgyi one.
const char *language
The language of the text as a BCP 47 tag, such as tr or sr-Latn, NUL-terminated, so the font can apply the forms it keeps for that language. NULL for none.
const daegun_feature *features
An array of daegun_feature to turn on, off or set. NULL with a length of 0 leaves the font's defaults.
size_t features_len
How many features the array holds.
const char *before
The text just before the run, as UTF-8. Shaping reads the 5 characters nearest the run, and reads them for joining only: an Arabic letter at the edge takes the form its neighbor calls for. Kerning, ligatures and the font's other lookups do not reach across the edge.
size_t before_len
The length of before in bytes.
const char *after
The text just after the run, read the same way.
size_t after_len
The length of after in bytes.
int32_t cluster_level
A DAEGUN_CLUSTER_ code: how clusters are formed.
int32_t ignorables
A DAEGUN_IGNORABLES_ code: what becomes of default ignorables.
uint32_t invisible_glyph
The glyph a hidden ignorable is drawn with, read only when has_invisible_glyph is true. Otherwise it is the font's space, as it is for glyph 0. A font with no space then drops hidden ignorables from the run.
uint32_t not_found_glyph
The glyph that stands in for a character the font has no glyph for and no other way to draw, as daegun_font_shape explains. 0 is .notdef.
uint32_t not_found_variation_selector_glyph
The glyph for a variation selector the font can't apply, read only when has_not_found_variation_selector_glyph is true. Otherwise such a selector is treated as a default ignorable. The glyph takes no advance and no offset, so it draws on top of whatever comes next unless you make room. With the default cluster level it shares the cluster of the character before it, and it stays in the run under DAEGUN_IGNORABLES_REMOVE too.
daegun_tag seed_script
The script to shape the run as, an ISO 15924 code as a tag in any case, such as DAEGUN_TAG('A', 'r', 'a', 'b'). 0 scans the text for its script. The run takes the model daegun picks for that script in this font and, while direction is DAEGUN_DIRECTION_DEFAULT, that script's direction: digits seeded as Arabic come out right to left unless direction is DAEGUN_DIRECTION_LTR.
bool beginning_of_text
True when nothing comes before the run. A combining mark that opens the text then gets a dotted circle to sit on, if the font has one and before is empty.
bool has_point_size
Whether point_size is set.
bool report_unsafe_to_concat
Whether to fill what daegun_shaped_run_unsafe_to_concat lends.
bool report_tatweel_positions
Whether to fill what daegun_shaped_run_safe_to_insert_tatweel lends.
bool suppress_dotted_circle
True leaves out the dotted circle daegun would otherwise add. One goes in for a vowel sign or mark with no base under the models that shape by syllable, DAEGUN_SHAPER_INDIC, DAEGUN_SHAPER_KHMER, DAEGUN_SHAPER_MYANMAR and DAEGUN_SHAPER_UNIVERSAL. One goes in too for a Hangul tone mark with no syllable, and under beginning_of_text for a mark that opens the text. Each of those needs the font to have the dotted circle glyph. Under the Indic and Universal models one also goes in, glyph or not, before the last character of a vowel written as a sequence Unicode forbids, such as अ then ा for आ: a font without the glyph draws it as not_found_glyph. Devanagari left to the general model, as it is in a Latin font, gets no circle for a vowel sign with no base or for a forbidden sequence.
bool has_invisible_glyph
Whether invisible_glyph is set.
bool has_not_found_variation_selector_glyph
Whether not_found_variation_selector_glyph is set.
double point_size
The point size that tracking from the font's trak table is read at, when has_point_size is true. Otherwise, or for a size that isn't finite and above zero, it is DAEGUN_DEFAULT_POINT_SIZE. daegun tracks only a font that also has a STAT table, so any other font shapes the same at any size.
  • Size: 112 bytes on a 64-bit target.
daegun_bidi_runs
typedef struct daegun_bidi_runs daegun_bidi_runs;

The runs of a line of mixed-direction text, in the order they are drawn.

An opaque handle from daegun_font_shape_bidi. daegun_bidi_runs_count and daegun_bidi_runs_at read it, and daegun_bidi_runs_free frees it along with every run it lent.

const char *text = "Read مرحبا aloud";
daegun_bidi_runs *runs = NULL;
if (daegun_font_shape_bidi(font, text, strlen(text), NULL, DAEGUN_BASE_AUTO, NULL, &runs) != DAEGUN_OK)
    return 1;

size_t count = 0;
if (daegun_bidi_runs_count(runs, &count) != DAEGUN_OK) return 1;
/* count is 4: "Read ", the Arabic word, a space and "aloud". */

daegun_bidi_runs_free(runs);

Unicode

daegun/unicode.h: text analysis that needs no font. Bidi, grapheme and word boundaries, line breaking, scripts and character properties. Every position is a byte offset where a character starts.

daegun_word_segmenter
typedef size_t (*daegun_word_segmenter)(
    void *user,
    const char *text,
    size_t len,
    size_t *out,
    size_t cap
);

A function of yours that finds the word boundaries in text written without spaces between words, such as Thai, so that lines can break there.

The letters of Thai, Lao, Khmer, Myanmar and some other scripts have the line breaking class SA in UAX #14. Their words run together with no space between, so no rule can tell where a line may break, and something that knows the words has to. This is the type of the function that does. daegun_line_break_opportunities takes one, and so does the segmenter field of a daegun_layout_options.

daegun calls it once for each run of such text, a stretch of SA characters with nothing else between them. text is that run alone, len bytes of UTF-8. It is not NUL-terminated, so go by len. user is the pointer you handed over with the function, which daegun never reads through.

Write the boundaries you find to out, each as a byte offset from the start of the run, in ascending order, and return how many you wrote. cap is the room in out: one fewer than the characters of the run, which is every place a boundary could go. For a run of one character it is 0, and you write nothing.

A boundary counts only where a line could start. An offset of 0, one at or past the end of the run, one inside a character and one in front of a combining mark are ignored, and a return value above cap is read as cap. Each boundary kept becomes an allowed break, not a mandatory one.

The function runs on the thread that called daegun, before that call returns, and nothing of it is kept afterward. It must return normally: a longjmp or a C++ exception out of it is undefined behavior. No lock is held while it runs, so it may call daegun itself, on the font being laid out too. Under MSVC it has C's calling convention, which DAEGUN_CALLBACK names.

/* A segmenter that knows one word: it reports a boundary wherever that word begins inside the run. */
static size_t DAEGUN_CALLBACK before_word(void *user, const char *text, size_t len, size_t *out,
                                          size_t cap)
{
    const char *word = user;
    size_t word_len = strlen(word), found = 0;
    for (size_t at = 1; at + word_len <= len && found < cap; at++) {
        if (memcmp(text + at, word, word_len) == 0) out[found++] = at;
    }
    return found;
}

/* Two Thai words, with no space between them. The second starts at byte 18. */
const char *text = "สวัสดีครับ";
char word[] = "ครับ";
daegun_word_segmenter segmenter = before_word;

daegun_line_break breaks[31]; /* text_len + 1 always fits */
size_t count = 0;
if (daegun_line_break_opportunities(text, 30, segmenter, word, breaks, 31, &count) != DAEGUN_OK) return 1;
/* count is 2: a line may now break at byte 18, and the text ends at byte 30. */
daegun_line_break
typedef struct {
    size_t at;
    bool mandatory;
} daegun_line_break;

A place where a line may break: the byte offset the next line starts at, and whether the text demands the break.

daegun_line_break_opportunities fills an array of these, in text order.

A break is either allowed or mandatory. An allowed one is a place a line may end when it has run out of room, such as after a space or a hyphen. A mandatory one is a place the line must end however much room is left: after a newline, and at the end of the text.

const char *text = "one two\nthree";
daegun_line_break breaks[14]; /* text_len + 1 always fits */
size_t count = 0;
if (daegun_line_break_opportunities(text, 13, NULL, NULL, breaks, 14, &count) != DAEGUN_OK) return 1;

/* Cut the text at the breaks it demands. The allowed ones are for a line that runs out of room. */
size_t line_start = 0, lines = 0;
for (size_t i = 0; i < count; i++) {
    const daegun_line_break *b = &breaks[i];
    if (!b->mandatory) continue;
    /* A line: the bytes from text + line_start up to text + b->at. */
    line_start = b->at;
    lines++;
}
/* Two lines, cut at bytes 8 and 13. The break at byte 4, before "two", is only allowed. */
size_t at
The byte offset where the next line starts, so the line that ends here is the bytes before it. It is the start of a character, and it comes after any spaces: they stay at the end of the line they close.
bool mandatory
True where the text demands the break: after a line feed, a carriage return (CR LF counts once), a vertical tab, a form feed, U+0085, U+2028 or U+2029, and at the end of the text. False where the break is only allowed.
  • Size: 16 bytes on a 64-bit target.
daegun_script_run
typedef struct {
    size_t start;
    size_t end;
    daegun_tag script;
} daegun_script_run;

One stretch of text in a single script: its byte range and the script.

daegun_script_runs fills an array of these. The runs come in text order, each starting where the one before it ended, and together they cover the whole text.

const char *text = "Read مرحبا aloud";
daegun_script_run runs[21]; /* text_len always fits */
size_t count = 0;
if (daegun_script_runs(text, 21, runs, 21, &count) != DAEGUN_OK) return 1;
for (size_t i = 0; i < count; i++) {
    daegun_str name;
    if (daegun_script_name(runs[i].script, &name) != DAEGUN_OK) return 1;
    /* Run i is the bytes runs[i].start to runs[i].end of the text, in the script name.data. */
}
/* Three runs: Latin for bytes 0 to 5, Arabic for 5 to 16, the space after the word with it,
   and Latin for 16 to 21. */
size_t start
The byte offset where the run starts.
size_t end
The byte offset where it ends, not included. The run is the end - start bytes at text + start.
daegun_tag script
The run's script as its ISO 15924 code packed into a tag, such as DAEGUN_TAG('L', 'a', 't', 'n') for Latin. daegun_script_name turns it into a name.
  • Size: 24 bytes on a 64-bit target.
daegun_bidi_paragraph
typedef struct daegun_bidi_paragraph daegun_bidi_paragraph;

A text resolved by the Unicode bidirectional algorithm: the direction level of every byte, and the order its characters are drawn in.

Text that mixes directions, such as Arabic or Hebrew inside English, is stored in the order it is read and drawn in another. The bidirectional algorithm (UAX #9) works out the second from the first by giving every character a level. An even level reads left to right and an odd one right to left. Plain left-to-right text is at level 0 and right-to-left text at level 1. Levels nest, so a number or a Latin word inside right-to-left text is at level 2.

An opaque handle. daegun_bidi_paragraph_new makes one from a text and a base direction, and daegun_bidi_paragraph_free frees it. daegun_bidi_paragraph_levels, daegun_bidi_paragraph_visual_order and daegun_bidi_paragraph_paragraphs each lend an array out of it, valid until it is freed. daegun_bidi_paragraph_visual_runs cuts one line of the text into the runs to draw.

Despite the name it takes any text: one that holds several paragraphs is resolved a paragraph at a time. It needs no font, and it holds the levels but not the text. Nothing changes it once it is made, so any number of threads may read one at the same time.

To shape and draw mixed text with a font, daegun_font_shape_bidi does this work and the shaping in one call. This handle is for when you want the analysis by itself.

/* "abc", then a Hebrew word, which reads right to left. */
const char *text = "abc שלום";
daegun_bidi_paragraph *paragraph = NULL;
if (daegun_bidi_paragraph_new(text, strlen(text), DAEGUN_BASE_AUTO, &paragraph) != DAEGUN_OK) return 1;

size_t n = 0;
const uint8_t *levels = daegun_bidi_paragraph_levels(paragraph, &n);
/* n is 12, a level for each byte: 0 for the four bytes of "abc " and 1 for the eight of the Hebrew. */

daegun_bidi_paragraph_free(paragraph);
daegun_paragraph_run
typedef struct {
    size_t start;
    size_t end;
    uint8_t level;
} daegun_paragraph_run;

One paragraph of a resolved text: its byte range and its direction level.

daegun_bidi_paragraph_paragraphs lends an array of these, in text order. Each paragraph starts where the one before it ended, so together they cover the whole text.

A paragraph ends with the separator that closes it, which is counted as part of it. The separators are a line feed, a carriage return, a CR LF pair taken as one, U+0085, U+2029 and the three information separators U+001C to U+001E. The last paragraph ends with the text. The line separator U+2028, a vertical tab and a form feed end a line but not a paragraph.

/* A Hebrew word, a newline, then "abc". */
const char *text = "שלום\nabc";
daegun_bidi_paragraph *paragraph = NULL;
if (daegun_bidi_paragraph_new(text, strlen(text), DAEGUN_BASE_AUTO, &paragraph) != DAEGUN_OK) return 1;

size_t n = 0;
const daegun_paragraph_run *paragraphs = daegun_bidi_paragraph_paragraphs(paragraph, &n);
for (size_t i = 0; i < n; i++) {
    const daegun_paragraph_run *p = &paragraphs[i];
    /* Paragraph i is the bytes p->start to p->end, and reads right to left if p->level is 1. */
}
/* Two paragraphs: bytes 0 to 9 at level 1, the newline included, and bytes 9 to 12 at level 0. */

daegun_bidi_paragraph_free(paragraph);
size_t start
The byte offset where the paragraph starts.
size_t end
The byte offset just past the separator that ends it, or the length of the text for a last paragraph with no separator.
uint8_t level
Its base level: 0 where the paragraph reads left to right, 1 where it reads right to left.
  • Size: 24 bytes on a 64-bit target.
daegun_visual_run
typedef struct {
    size_t start;
    size_t end;
    uint8_t level;
} daegun_visual_run;

One stretch of a line that reads in a single direction, in the place it is drawn.

daegun_bidi_paragraph_visual_runs fills an array of these, ordered from the left end of the line to the right. Draw them in that order, each to the right of the one before it.

The bytes of a run are a single piece of the text, whichever way the run reads. Shape that piece in the direction its level gives: daegun_font_shape with DAEGUN_DIRECTION_RTL in its options returns the glyphs of a right-to-left run already in the order they are drawn.

/* English with an Arabic word in it. */
const char *text = "Read مرحبا aloud";
daegun_bidi_paragraph *paragraph = NULL;
if (daegun_bidi_paragraph_new(text, 21, DAEGUN_BASE_AUTO, &paragraph) != DAEGUN_OK) return 1;

daegun_visual_run runs[21]; /* end - start always fits */
size_t count = 0;
if (daegun_bidi_paragraph_visual_runs(paragraph, text, 21, 0, 21, runs, 21, &count) != DAEGUN_OK) return 1;
for (size_t i = 0; i < count; i++) {
    bool right_to_left = runs[i].level % 2 == 1;
    /* Draw the bytes runs[i].start to runs[i].end next, to the right of what is drawn so far. */
}
/* Three runs, from the left: bytes 0 to 5 at level 0, the Arabic word, bytes 5 to 15, at level 1,
   and bytes 15 to 21 at level 0. */

daegun_bidi_paragraph_free(paragraph);
size_t start
The byte offset in the text where the run starts.
size_t end
The byte offset where it ends, not included.
uint8_t level
Its level. Odd means the run reads right to left, so its last character is drawn leftmost. Even means left to right.
  • Size: 24 bytes on a 64-bit target.

Layout

daegun/layout.h: paragraphs laid out in lines, aligned, in either writing mode, and one line justified by a font's JSTF table. All in font units.

daegun_layout_options
typedef struct {
    size_t size;
    double max_inline_size;
    double line_height;
    double tab_size;
    const char *language;
    daegun_word_segmenter segmenter;
    void *segmenter_user;
    size_t max_lines;
    bool has_line_height;
    bool has_max_lines;
    int32_t align;
    int32_t writing_mode;
    int32_t text_orientation;
    int32_t base_direction;
    int32_t strategy;
    const daegun_feature *features;
    size_t features_len;
} daegun_layout_options;

Everything a layout can be told: the width to wrap at, the alignment, the writing mode, the line height, how lines are chosen and how many, the language and the features.

Fill one with daegun_layout_options_default, set the fields you want, and pass it to daegun_font_layout. NULL there means the same defaults: no wrapping, so lines end only at hard breaks such as a newline, set across from the start edge.

Don't zero one by hand. Three defaults are not zero: max_inline_size is infinity, tab_size is 8 and base_direction is DAEGUN_BASE_AUTO, which is -1. A zeroed struct is refused in any case, since its size of 0 answers DAEGUN_INVALID_ARGUMENT.

The sizes are in font units, like everything a layout answers. For a width in pixels, multiply the pixels by the units per em over the pixel size. daegun_font_units_per_em gives the units per em.

The struct opens with its own size, so a program built against this header keeps working with a newer library that has added fields at the end. The layout keeps nothing the options point at: language, features and the segmenter are read during the call only.

uint16_t upem = 0;
if (daegun_font_units_per_em(font, &upem) != DAEGUN_OK) return 1;
double units = upem / 16.0; /* font units to a pixel, at 16 px */

daegun_layout_options opts;
if (daegun_layout_options_default(&opts, sizeof opts) != DAEGUN_OK) return 1;
opts.max_inline_size = 200.0 * units; /* wrap at 200 px */
opts.align = DAEGUN_ALIGN_CENTER;
opts.has_line_height = true;
opts.line_height = 24.0 * units; /* baselines 24 px apart */

const char *text = "The quick brown fox jumps over the lazy dog.";
daegun_layout *layout = NULL;
if (daegun_font_layout(font, text, strlen(text), NULL, &opts, &layout) != DAEGUN_OK) return 1;

daegun_layout_line first, second;
if (daegun_layout_line_at(layout, 0, &first) != DAEGUN_OK) return 1;
if (daegun_layout_line_at(layout, 1, &second) != DAEGUN_OK) return 1;
/* Two lines, the second 24 px below the first. */
daegun_layout_free(layout);
size_t size
The size of the struct in bytes as your header has it. daegun_layout_options_default sets it.
double max_inline_size
The measure: the width lines wrap at, in font units, or the height of a column in vertical text. Infinity, the default, wraps only at hard breaks such as a newline, and the lines then align against the widest one. A word wider than the measure is cut between graphemes, the characters a reader sees, so a line is wider than the measure only where a single glyph cluster is. NaN reads as infinity and a value below 0 as 0, which puts every glyph cluster on a line of its own.
double line_height
The distance from one baseline to the next, in font units, read only when has_line_height is true. Otherwise it is the font's own: ascent less descent plus line gap, as daegun_font_line_metrics gives them for the orientation of the writing mode.
double tab_size
The distance between tab stops, counted in advances of the space, as the CSS tab-size property counts it. 8 by default. A tab is shaped as a space and given the advance that reaches the next stop, measured from the start edge of its line. A stop nearer than half the advance of the digit 0 is skipped for the one after it, with half an em standing in for that advance in a font with no 0. A tab_size that is 0, below 0, infinite or not a number gives a tab no width. Tabs that end a line hang past it, as spaces do.
const char *language
The language of the text as a BCP 47 tag, such as tr or ja, NUL-terminated, so the font can apply the forms it keeps for that language. NULL for none.
daegun_word_segmenter segmenter
A daegun_word_segmenter of yours that finds the word boundaries in text written without spaces between words, such as Thai, Lao, Khmer and Myanmar, so that lines can break between words. NULL uses the word lists of the dictionaries build feature if the library was built with it, which daegun_has_dictionaries reports. With neither, such text breaks only where other text would.
void *segmenter_user
A pointer of your own, handed to segmenter as its first argument each time it is called. daegun never reads through it.
size_t max_lines
The most lines to lay out, read only when has_max_lines is true. Text past the last line is left out, and truncated of daegun_layout_info says where it begins.
bool has_line_height
Whether line_height is set.
bool has_max_lines
Whether max_lines is set.
int32_t align
A DAEGUN_ALIGN_ code: where each line sits in the measure. DAEGUN_ALIGN_START by default.
int32_t writing_mode
A DAEGUN_WRITING_ code: whether lines run across or down. DAEGUN_WRITING_HORIZONTAL by default.
int32_t text_orientation
A DAEGUN_TEXT_ORIENTATION_ code: how characters stand in vertical lines. It changes nothing in horizontal text. DAEGUN_TEXT_ORIENTATION_MIXED by default.
int32_t base_direction
A DAEGUN_BASE_ code: the direction of the paragraphs, which decides the order of the runs on a line and which edge is the start. DAEGUN_BASE_AUTO, the default, lets the first strongly directional character of each paragraph decide for that paragraph. A newline, a carriage return, a next line (U+0085) or a paragraph separator (U+2029) starts a new paragraph. A line separator (U+2028), a vertical tab or a form feed ends the line, and the text after it keeps the paragraph's direction. The information separators U+001C to U+001E start a new paragraph too, without ending the line.
int32_t strategy
A DAEGUN_BREAK_ code: how lines are chosen. DAEGUN_BREAK_GREEDY by default.
const daegun_feature *features
An array of daegun_feature to turn on, off or set, such as small capitals or tabular figures. The start and end of each are byte offsets into the whole text. NULL with a length of 0 leaves the font's defaults.
size_t features_len
How many features the array holds.
  • Size: 104 bytes on a 64-bit target.
daegun_layout
typedef struct daegun_layout daegun_layout;

Text laid out in lines: every line with its place in the block, and every run of glyphs with its place on the line.

An opaque handle. daegun_font_layout makes one, daegun_layout_info_of, daegun_layout_line_at and daegun_layout_run_at read it, and daegun_layout_free frees it. Everything it answers is in font units.

It owns the shaped runs of its lines and only lends them. A run that daegun_layout_run_at hands out is valid until the layout is freed and must never go to daegun_shaped_run_free. daegun_shaped_run_copy makes one you can keep.

A layout borrows nothing from the font or the text, so it may outlive both. It is read-only once made, so any number of threads may read one at the same time.

const char *text = "First line\nSecond line";
daegun_layout *layout = NULL;
if (daegun_font_layout(font, text, strlen(text), NULL, NULL, &layout) != DAEGUN_OK) return 1;

daegun_layout_info info;
if (daegun_layout_info_of(layout, &info) != DAEGUN_OK) return 1;
/* The newline makes two lines. With no measure set, nothing else wraps. */

daegun_layout_free(layout);
daegun_layout_info
typedef struct {
    size_t line_count;
    double inline_size;
    double block_size;
    size_t truncated;
    bool has_truncated;
} daegun_layout_info;

A layout as a whole: how many lines it has, how much room they take together, and where the text was cut off if it was.

daegun_layout_info_of fills one. The sizes are in font units. Along the line means across in horizontal text and down in vertical text.

daegun_layout_options opts;
if (daegun_layout_options_default(&opts, sizeof opts) != DAEGUN_OK) return 1;
opts.max_inline_size = 25600.0; /* 200 px at 16 px in Inter, whose em is 2048 units */
opts.has_max_lines = true;
opts.max_lines = 1;

const char *text = "The quick brown fox jumps over the lazy dog.";
daegun_layout *layout = NULL;
if (daegun_font_layout(font, text, strlen(text), NULL, &opts, &layout) != DAEGUN_OK) return 1;

daegun_layout_info info;
if (daegun_layout_info_of(layout, &info) != DAEGUN_OK) return 1;
if (info.has_truncated) {
    /* text + info.truncated is what didn't fit: "jumps over the lazy dog." */
}
/* One line, 19776 units wide and 2478 tall, with the rest of the text starting at byte 20. */

daegun_layout_free(layout);
size_t line_count
How many lines the layout has, which is the bound for daegun_layout_line_at. 0 for empty text.
double inline_size
The widest line's extent along the line: a width in horizontal text, the height of the tallest column in vertical text. It measures the text, so it may be less than the measure the lines were wrapped at.
double block_size
The extent of the lines together, from the first line's ascent to the last line's descent: a height in horizontal text, a width in vertical text.
size_t truncated
The byte offset in the text where the part that was left out begins, read only when has_truncated is true. Otherwise 0.
bool has_truncated
True when max_lines of the options cut the layout short, so the end of the text is in no line.
  • Size: 40 bytes on a 64-bit target.
daegun_layout_line
typedef struct {
    size_t run_count;
    size_t start;
    size_t end;
    double baseline;
    double inline_size;
    double ascent;
    double descent;
    bool hard_break;
} daegun_layout_line;

One line of a layout: the text it covers, where its baseline lies, its size and how many runs it holds.

daegun_layout_line_at fills one. Everything is in font units, and the byte offsets count into the text the layout was made from. The ascent and descent come from the font's line metrics, so every line of a layout has the same.

/* A Japanese sentence set in columns 5000 units tall, the first column at the right. */
daegun_layout_options opts;
if (daegun_layout_options_default(&opts, sizeof opts) != DAEGUN_OK) return 1;
opts.writing_mode = DAEGUN_WRITING_VERTICAL_RL;
opts.max_inline_size = 5000.0;

const char *text = "日本語のテキストABC。";
daegun_layout *layout = NULL;
if (daegun_font_layout(font, text, strlen(text), NULL, &opts, &layout) != DAEGUN_OK) return 1;

daegun_layout_info info;
if (daegun_layout_info_of(layout, &info) != DAEGUN_OK) return 1;
for (size_t i = 0; i < info.line_count; i++) {
    daegun_layout_line line;
    if (daegun_layout_line_at(layout, i, &line) != DAEGUN_OK) return 1;
    /* line.baseline is how far this column's baseline is from the left edge of the block:
       2500, then 1500, then 500 units. The block is info.block_size wide, 3000 units. */
}

daegun_layout_free(layout);
size_t run_count
How many runs the line holds, which is the bound for daegun_layout_run_at. A line of nothing but a line break or spaces holds none.
size_t start
The byte offset in the text where the line's text starts.
size_t end
The byte offset where it ends, not included. The spaces and the line break that end a line are inside this range, though they are in no run.
double baseline
Where the baseline lies in the block. In horizontal text it is the distance down from the top edge of the block, so for the first line it equals the ascent. In vertical text it is the distance from the left edge of the block: lines advance rightward under DAEGUN_WRITING_VERTICAL_LR and leftward under DAEGUN_WRITING_VERTICAL_RL, where the first line is the rightmost.
double inline_size
The line's extent along the line, which is the sum of its runs' widths. Spaces that end the line hang past it and are not counted. On a justified line it counts its spaces as justification set them.
double ascent
How far the line reaches above its baseline. In a vertical line that is to the right of the baseline.
double descent
How far the line reaches below its baseline, as a negative number. In a vertical line that is to the left of the baseline.
bool hard_break
True when the text itself ends the line: at a newline or another mandatory break, and at the end of the text. False where the line was wrapped.
  • Size: 64 bytes on a 64-bit target.
daegun_layout_run
typedef struct {
    const daegun_shaped_run *run;
    daegun_offset offset;
    size_t start;
    size_t end;
    uint8_t level;
    bool upright;
} daegun_layout_run;

One run of a line: its shaped glyphs, where it starts on the line, the text it covers and its direction.

A line is cut into runs wherever the script, the bidi level or, in vertical text, the orientation changes. daegun_layout_run_at fills one. Runs are indexed in visual order: from the left in a horizontal line, from the top in a vertical one.

The run is borrowed from the layout. Read it with the daegun_shaped_run_ calls. It is valid until daegun_layout_free, and must never be passed to daegun_shaped_run_free. To keep it longer, take a copy with daegun_shaped_run_copy.

To draw a run, start a pen at its offset and move it by each glyph's advance: rightward along a horizontal line, downward along a vertical one. The layout measures its vertical positions down from the top, while a glyph's daegun_offset is y up, so add the glyph's x and subtract its y.

In a horizontal line a glyph's origin is the pen plus the glyph's x, from the left edge of the measure, and the line's baseline less the glyph's y, down from the top of the block. In a vertical line an upright glyph's origin is the line's baseline plus the glyph's x, from the left edge of the block, and the pen less the glyph's y, down from the top of the measure.

const char *text = "Read مرحبا aloud";
daegun_layout *layout = NULL;
if (daegun_font_layout(font, text, strlen(text), NULL, NULL, &layout) != DAEGUN_OK) return 1;

daegun_layout_line line;
if (daegun_layout_line_at(layout, 0, &line) != DAEGUN_OK) return 1;
for (size_t k = 0; k < line.run_count; k++) {
    daegun_layout_run run;
    if (daegun_layout_run_at(layout, 0, k, &run) != DAEGUN_OK) return 1;
    /* run.run is borrowed from the layout: never free it. It shows bytes run.start to run.end,
       run.offset.x units from the left of the line, right to left if run.level is odd. */
}
/* Four runs from the left. The second is the Arabic word: level 1, bytes 5 to 15, 4358 units in. */

daegun_layout_free(layout);
const daegun_shaped_run *run
The shaped glyphs, borrowed until the layout is freed. Its clusters count bytes from start, so add start to place one in the whole text. Where the line is justified, the advances of its spaces are already changed.
daegun_offset offset
Where the run starts, alignment included. In a horizontal line x is the distance from the left edge of the measure, the max_inline_size of the daegun_layout_options, and y is 0. In a vertical line x is 0 and y is the distance down from the top edge of the measure, so a larger y is lower. Where the measure is infinite, the widest line stands in for it.
size_t start
The byte offset in the text where the run's text starts.
size_t end
The byte offset where it ends, not included.
uint8_t level
The bidi embedding level: odd reads right to left, even left to right.
bool upright
True when the glyphs stand upright, as they always do in horizontal text. An upright run of a vertical line is shaped top to bottom. False for a run that lies on its side in a vertical line, as Latin letters do under DAEGUN_TEXT_ORIENTATION_MIXED. Such a run is shaped as horizontal text, for you to draw turned a quarter turn clockwise, so that what would run left to right runs top to bottom: its glyphs come in the order they go down the line, each advance moving the pen down, and a glyph's own x then counts down the line and its y to the right. The layout places such a run along the line only: its offset.x is 0, and where its alphabetic baseline sits across the column is left to you.
  • Size: 48 bytes on a 64-bit target.
daegun_justify_options
typedef struct {
    size_t size;
    daegun_tag script;
    daegun_tag language_system;
    double target_width;
    double tolerance;
} daegun_justify_options;

What to justify a line to: the width to reach, how close counts as reaching it, and which script's JSTF data to use.

Fill one with daegun_justify_options_default, set script and target_width, and pass it to daegun_font_justify. Every default is 0, and NULL there means the same. A script of 0 names no JSTF data, and a target of 0 is a width that any text with a width is past, so the natural run comes back with best_effort true. Set both.

JSTF is the OpenType justification table. For each script it lists priority levels, and each level names lookups of the font to turn on or off to make a line narrower or wider.

The struct opens with its own size, so a program built against this header keeps working with a newer library that has added fields at the end.

/* `font` is a test font with JSTF priority levels for the arab script. */
daegun_justify_options opts;
if (daegun_justify_options_default(&opts, sizeof opts) != DAEGUN_OK) return 1;
opts.script = DAEGUN_TAG('a', 'r', 'a', 'b');
opts.target_width = 8100.0;
opts.tolerance = 50.0; /* anything from 8050 to 8150 will do */

const char *text = "Aa الماس";
daegun_shaped_run *run = NULL;
daegun_justification info;
if (daegun_font_justify(font, text, strlen(text), NULL, DAEGUN_HORIZONTAL, &opts, &run, &info) != DAEGUN_OK)
    return 1;
/* The first level sets the line 8127 units wide, which is close enough. */

daegun_shaped_run_free(run);
size_t size
The size of the struct in bytes as your header has it. daegun_justify_options_default sets it.
daegun_tag script
The OpenType script tag whose JSTF priority levels apply, such as DAEGUN_TAG('a', 'r', 'a', 'b'). A script the font's JSTF table doesn't list gives no levels, and 0 names none, so the line keeps its natural shaping.
daegun_tag language_system
The OpenType language system tag whose levels apply. 0 takes the script's default, and so does a language system the script does not list.
double target_width
The width to reach, in font units.
double tolerance
How far from target_width a width may be and still count as reaching it, in font units. 0 asks for the exact width. Below 0, or NaN, it accepts nothing, so even a line at the exact width comes back with best_effort true.
  • Size: 32 bytes on a 64-bit target.
daegun_justification
typedef struct {
    double width;
    size_t level;
    int32_t adjustment;
    bool has_level;
    bool best_effort;
} daegun_justification;

How daegun_font_justify justified a line: the width it reached, the JSTF level it used and whether that was close enough.

The call fills one through out_info. Check best_effort first: when it is true the font could not bring the line to the width you asked for, and the rest of the gap is yours to close, for example by spacing the words.

daegun_justify_options opts;
if (daegun_justify_options_default(&opts, sizeof opts) != DAEGUN_OK) return 1;
opts.script = DAEGUN_TAG('l', 'a', 't', 'n');
opts.target_width = 6000.0;

daegun_shaped_run *run = NULL;
daegun_justification info;
if (daegun_font_justify(font, "Wave", 4, NULL, DAEGUN_HORIZONTAL, &opts, &run, &info) != DAEGUN_OK) return 1;
if (info.best_effort) {
    /* The font got the line to info.width. Spread the missing width over the line yourself. */
    double missing = opts.target_width - info.width;
}
/* Inter has no JSTF table, so the line keeps its natural width of 5339 units and no level is used. */

daegun_shaped_run_free(run);
double width
The width of the run that came back, in font units.
size_t level
The index of the JSTF priority level the line was shaped at, 0 being the highest priority, read only when has_level is true. Otherwise 0.
int32_t adjustment
Which way the line had to go: DAEGUN_ADJUST_SHRINK where its natural width is past the target by more than the tolerance, and DAEGUN_ADJUST_EXTEND otherwise, which includes a line that already fit.
bool has_level
True when the run was shaped at a JSTF level. False when the line kept its natural shaping.
bool best_effort
True when no shaping came within the tolerance of the target, so the run is only the nearest one. False when the target was reached.
  • Size: 24 bytes on a 64-bit target.
daegun_jstf_priorities
typedef struct daegun_jstf_priorities daegun_jstf_priorities;

A script's JSTF priority levels, highest priority first.

An opaque handle. daegun_font_justification_priorities makes one for a script and a language system, daegun_jstf_priorities_count and daegun_jstf_priorities_lookups read it, daegun_font_shape_justified shapes with one of its levels, and daegun_jstf_priorities_free frees it.

A level holds up to eight lists of lookup indices: GSUB and GPOS lookups to turn on and to turn off, once for shrinking a line and once for extending it. The DAEGUN_JSTF_ codes name the lists. The JstfMax data a level may also carry is not read.

It holds a copy of the levels and borrows nothing from the font, so it may outlive the font. It is read-only, so threads may share one.

daegun_jstf_priorities *levels = NULL;
daegun_status status =
    daegun_font_justification_priorities(font, DAEGUN_TAG('a', 'r', 'a', 'b'), 0, &levels);
if (status == DAEGUN_OK) {
    size_t count = 0;
    if (daegun_jstf_priorities_count(levels, &count) != DAEGUN_OK) return 1;
    /* Levels 0 to count - 1, to read or to shape with. This test font has two. */
}
daegun_jstf_priorities_free(levels);

Outlines

daegun/outline.h: a glyph's shape, as the font stores it in font units, hinted in pixels, or prepared for a rasterizer of your own, with the paths, pens, strokes, curves and polygons around it.

daegun_pen
typedef struct {
    void (*move_to)(void *user, float x, float y);
    void (*line_to)(void *user, float x, float y);
    void (*quad_to)(void *user, float cx, float cy, float x, float y);
    void (*curve_to)(void *user, float c1x, float c1y, float c2x, float c2y, float x, float y);
    void (*close)(void *user);
    void *user;
} daegun_pen;

What you hand daegun to receive an outline: five callbacks, and a pointer of yours that each one is passed.

The calls that draw an outline each take one: daegun_font_outline, daegun_font_prepared_outline, daegun_hinted_outline_draw, daegun_path_replay, daegun_path_stroke, daegun_path_stroke_simplified and daegun_outline_glyf_bytes. daegun walks the outline and calls move_to where a contour starts, line_to, quad_to or curve_to for each segment after that, each one starting where the last ended, and close where the contour ends. A contour is one closed loop of an outline: an "o" has two, its outside and its hole.

The coordinates are floats, y up, in the units of whatever is drawing: font units from daegun_font_outline, pixels from daegun_font_prepared_outline and daegun_hinted_outline_draw, and the path's own units from daegun_path_replay and the stroke calls. A font with TrueType outlines draws its curves as quadratics, through quad_to, and one with CFF or CFF2 outlines draws them as cubics, through curve_to, so a pen meant for any font sets both.

A callback left NULL skips its event. A pen that only counts contours sets move_to alone, and a pen of { 0 } is valid and draws nothing. user is yours: daegun never reads what it points at, and hands it back untouched as the first argument of every callback. It may be NULL.

A callback runs on the thread that called daegun, before that call returns, and daegun keeps nothing of the pen afterward, so the struct can live on the stack. A callback must return normally: leaving one with longjmp or a C++ exception is undefined behavior, and so is ending the thread inside one. Declare a C++ callback noexcept. If your build changes the default calling convention, as /Gv and /Gz do under MSVC, mark each callback DAEGUN_CALLBACK.

A callback may call back into daegun, on the same font too: daegun holds no lock while one runs.

To keep an outline you need no callbacks of your own. daegun_path_as_pen fills in a pen that draws into a daegun_path.

/* A pen that writes an outline as SVG path data to the file its `user` points at. */
static void on_move(void *user, float x, float y) { fprintf(user, "M%g %g ", x, y); }
static void on_line(void *user, float x, float y) { fprintf(user, "L%g %g ", x, y); }
static void on_quad(void *user, float cx, float cy, float x, float y)
{
    fprintf(user, "Q%g %g %g %g ", cx, cy, x, y);
}
static void on_cubic(void *user, float c1x, float c1y, float c2x, float c2y, float x, float y)
{
    fprintf(user, "C%g %g %g %g %g %g ", c1x, c1y, c2x, c2y, x, y);
}
static void on_close(void *user) { fprintf(user, "Z "); }

FILE *out = stdout;
daegun_pen pen = { on_move, on_line, on_quad, on_cubic, on_close, out };

uint32_t gid = 0;
if (daegun_font_glyph_id(font, 'I', &gid) != DAEGUN_OK) return 1;
if (daegun_font_outline(font, gid, NULL, &pen) != DAEGUN_OK) return 1;
/* Inter's "I" is one box, in font units: M370 1490 L370 0 L180 0 L180 1490 Z */
void (*move_to)(void *user, float x, float y)
Starts a new contour at the point (x, y).
void (*line_to)(void *user, float x, float y)
A straight line from where the last event ended to (x, y).
void (*quad_to)(void *user, float cx, float cy, float x, float y)
A quadratic curve from where the last event ended to (x, y), bent toward the control point (cx, cy). TrueType outlines are made of these.
void (*curve_to)(void *user, float c1x, float c1y, float c2x, float c2y, float x, float y)
A cubic curve from where the last event ended to (x, y), with the two control points (c1x, c1y) and (c2x, c2y). CFF and CFF2 outlines are made of these.
void (*close)(void *user)
Ends the contour. Where its last point is not the one it started at, a straight line back to the start closes it.
void *user
Your own pointer, passed as the first argument of every callback and otherwise left alone. Point it at whatever the callbacks draw into.
  • Size: 6 bytes * sizeof(void *).
daegun_point
typedef struct {
    float x;
    float y;
} daegun_point;

A point of an outline: an x and a y as floats, y up, in the units the outline was drawn in.

daegun_path_points lends an array of them, as do daegun_contours_points and daegun_hinted_outline_points, and a daegun_quad is three of them. The units are those of whatever drew the outline: font units for a glyph from daegun_font_outline, pixels for one from daegun_font_prepared_outline, and for a path you build yourself, whatever you put in.

daegun_path *path = daegun_path_new();
daegun_path_move_to(path, 0.0f, 0.0f);
daegun_path_line_to(path, 100.0f, 0.0f);
daegun_path_line_to(path, 50.0f, 80.0f);
daegun_path_close(path);

size_t count = 0;
const daegun_point *points = daegun_path_points(path, &count);
float top = 0.0f;
for (size_t i = 0; i < count; i++) {
    if (points[i].y > top) top = points[i].y;
}
/* Three points, the highest at y 80. */

daegun_path_free(path);
float x
Across. A larger x is further right.
float y
Up. A larger y is higher, which is the other way around from most pixel grids.
  • Size: 8 bytes.
daegun_path
typedef struct daegun_path daegun_path;

An outline held as a value: a list of verbs and the points they take, which you can build, read, replay and stroke.

An opaque handle. daegun_path_new makes an empty one and daegun_path_free frees it. You fill it with the five calls a pen receives (daegun_path_move_to, daegun_path_line_to, daegun_path_quad_to, daegun_path_curve_to and daegun_path_close), or you let daegun draw into it through the pen that daegun_path_as_pen gives. daegun_scene_path_copy hands you one as well.

Once it holds an outline you can read it (daegun_path_verbs, daegun_path_points, daegun_path_bounds), draw it again through a transform (daegun_path_replay), stroke it (daegun_path_stroke), flatten it into polygons (daegun_path_flatten), turn it into quadratic curves (daegun_path_quads) or fill it (daegun_rasterizer_path). Its points are floats, y up, in whatever units went in.

Threads. A call that takes the path as const daegun_path * only reads it, and any number of threads may make such calls on one path at the same time. The five building calls and daegun_path_clear change the path, which is why they take it as daegun_path *, and any call that draws into it through its pen changes it too. While one of those runs, no other thread may use the path. A path may be freed on any thread, once no call is using it.

What it lends. The arrays from daegun_path_verbs and daegun_path_points are valid until the path is drawn into, cleared or freed. The pen from daegun_path_as_pen points at the path and is valid until the path is freed.

/* A triangle, built by hand. */
daegun_path *path = daegun_path_new();
daegun_path_move_to(path, 0.0f, 0.0f);
daegun_path_line_to(path, 100.0f, 0.0f);
daegun_path_line_to(path, 50.0f, 80.0f);
daegun_path_close(path);

daegun_bounds box;
if (daegun_path_bounds(path, &box) != DAEGUN_OK) return 1;
/* It is 100 wide and 80 tall. */

daegun_path_free(path);
daegun_stroke_style
typedef struct {
    float width;
    int32_t cap;
    int32_t join;
    float miter_limit;
} daegun_stroke_style;

How a path is stroked: how wide the line is, how it ends and how it turns corners.

daegun_path_stroke and daegun_path_stroke_simplified take a pointer to one, and stroke of a daegun_outline_options holds one for daegun_font_prepared_outline.

It is a plain struct with no _default call, so set every field. A zeroed one is valid and draws nothing, its width being 0. The Rust API's default is a width of 1, DAEGUN_CAP_BUTT, DAEGUN_JOIN_MITER and a miter limit of 4.

A stroke call answers DAEGUN_INVALID_ARGUMENT for a cap or a join that is none of its constants, and for a width that is not finite.

/* A hairpin: out along the x axis to (100, 0), then back to (0, 20). */
daegun_path *path = daegun_path_new();
daegun_path_move_to(path, 0.0f, 0.0f);
daegun_path_line_to(path, 100.0f, 0.0f);
daegun_path_line_to(path, 0.0f, 20.0f);

daegun_path *stroked = daegun_path_new();
daegun_pen pen;
if (daegun_path_as_pen(stroked, &pen) != DAEGUN_OK) return 1;

daegun_stroke_style style = { 0 };
style.width = 10.0f;
style.cap = DAEGUN_CAP_BUTT;
style.join = DAEGUN_JOIN_MITER;
style.miter_limit = 4.0f;
if (daegun_path_stroke(path, &style, 0.1f, &pen) != DAEGUN_OK) return 1;
daegun_bounds box;
if (daegun_path_bounds(stroked, &box) != DAEGUN_OK) return 1;
/* The turn is too sharp for a limit of 4, so the corner is cut off just past x 100. */

style.miter_limit = 20.0f;
daegun_path_clear(stroked);
if (daegun_path_stroke(path, &style, 0.1f, &pen) != DAEGUN_OK) return 1;
if (daegun_path_bounds(stroked, &box) != DAEGUN_OK) return 1;
/* Given the room, the miter runs out to a point at about x 150. */

daegun_path_free(stroked);
daegun_path_free(path);
float width
The full width of the stroke, half of it to each side of the path, in the path's units. In a daegun_outline_options that is font units. Its sign is ignored, 0 draws nothing, and it must be finite.
int32_t cap
A DAEGUN_CAP_ code: how the stroke ends an open contour.
int32_t join
A DAEGUN_JOIN_ code: how the stroke turns a corner.
float miter_limit
How far the point of a miter may reach from its corner, in half widths, before the corner is beveled instead. Read with DAEGUN_JOIN_MITER only. A right angle reaches 1.414, so it stays sharp from 1.42 up. A limit that is not above 0, or NaN, means 4, and one below 1 acts as 1, which bevels every corner.
  • Size: 16 bytes.
daegun_contours
typedef struct daegun_contours daegun_contours;

A list of closed polygons: what a path is once its curves are cut into straight lines.

An opaque handle. daegun_path_flatten makes one from a path, daegun_contours_new from points of your own, and daegun_contours_resolve_overlaps from other contours. daegun_contours_count and daegun_contours_points read it, and daegun_contours_free frees it.

Each contour is one closed polygon: a run of daegun_points whose last point joins its first, in the units of the path it came from, y up.

No call changes contours once they are made, so any number of threads may read them at the same time.

/* A shape with two straight sides and one curved side. */
daegun_path *path = daegun_path_new();
daegun_path_move_to(path, 0.0f, 0.0f);
daegun_path_line_to(path, 100.0f, 0.0f);
daegun_path_quad_to(path, 100.0f, 100.0f, 0.0f, 100.0f);
daegun_path_close(path);

daegun_contours *contours = NULL;
if (daegun_path_flatten(path, 100.0f, &contours) != DAEGUN_OK) return 1;

size_t n = 0;
const daegun_point *points = daegun_contours_points(contours, 0, &n);
/* One polygon of 6 points: the straight sides as they were, and the curve as four lines. */

daegun_contours_free(contours);
daegun_path_free(path);
daegun_quad
typedef struct {
    daegun_point start;
    daegun_point control;
    daegun_point end;
} daegun_quad;

A quadratic curve: where it starts, the control point it bends toward and where it ends.

daegun_quads_data lends an array of them. The curve leaves start heading for control and arrives at end coming from it, without touching the control: its point at t, from 0 to 1, is (1-t)*(1-t)*start + 2*(1-t)*t*control + t*t*end. A straight line is a curve whose control is the midpoint of its ends.

It is three daegun_points, six floats in a row, in the units the curves were made in, y up.

uint32_t gid = 0;
if (daegun_font_glyph_id(font, 'W', &gid) != DAEGUN_OK) return 1;
daegun_quads *quads = NULL;
if (daegun_font_quads(font, gid, NULL, &quads) != DAEGUN_OK) return 1;

size_t n = 0;
const daegun_quad *curves = daegun_quads_data(quads, &n);
/* The point halfway along the first curve, at t = 0.5. */
daegun_quad q = curves[0];
float x = 0.25f * q.start.x + 0.5f * q.control.x + 0.25f * q.end.x;
float y = 0.25f * q.start.y + 0.5f * q.control.y + 0.25f * q.end.y;
/* This curve is a straight side of the W, so its control is its midpoint, and so is (x, y):
   (255, 745) in font units. */

daegun_quads_free(quads);
daegun_point start
Where the curve starts.
daegun_point control
The control point the curve bends toward. For a straight line it is the midpoint of start and end.
daegun_point end
Where the curve ends.
  • Size: 24 bytes.
daegun_quads
typedef struct daegun_quads daegun_quads;

A list of quadratic curves: an outline with every line and every cubic turned into quadratics.

An opaque handle. daegun_font_quads makes one from a glyph and daegun_path_quads from a path. daegun_quads_data lends the curves, daegun_quads_normalize_winding rewinds them in place, and daegun_quads_free frees the handle.

The list is flat. Nothing marks where one contour stops and the next starts, and every contour in it is closed.

Threads may read one at the same time. daegun_quads_normalize_winding changes it, so that call needs the handle to itself.

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

daegun_quads *quads = NULL;
if (daegun_font_quads(font, gid, NULL, &quads) != DAEGUN_OK) return 1;
size_t n = 0;
const daegun_quad *curves = daegun_quads_data(quads, &n);
/* Inter's W is 32 curves. */

daegun_quads_free(quads);
daegun_hinted_outline
typedef struct daegun_hinted_outline daegun_hinted_outline;

A glyph's outline as a hinter left it at one pixel size: its points in pixels, what each point is and where each contour ends.

An opaque handle from daegun_font_hinted_outline. daegun_hinted_outline_points, daegun_hinted_outline_kinds and daegun_hinted_outline_contours lend its three arrays, daegun_hinted_outline_draw draws it onto a pen, and daegun_hinted_outline_free frees it.

It holds points the way a font stores an outline, on the curve and off it, and not drawing calls. Read the arrays if your rasterizer walks points, and use the draw call if it takes moves, lines and curves.

No call changes one once it is made, so threads may read it at the same time.

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

daegun_hinted_outline *hinted = NULL;
if (daegun_font_hinted_outline(font, gid, NULL, 16.0f, DAEGUN_HINT_AUTO, &hinted) != DAEGUN_OK) return 1;

size_t n = 0, contours = 0;
const daegun_point *points = daegun_hinted_outline_points(hinted, &n);
const size_t *ends = daegun_hinted_outline_contours(hinted, &contours);
/* Inter's H at 16 px: 12 points in one contour, which ends at point 11. */

daegun_hinted_outline_free(hinted);
daegun_cff_stem
typedef struct {
    float min;
    float max;
    bool vertical;
} daegun_cff_stem;

One stem hint of a CFF glyph: the two edges of a stem, in font units.

A stem hint tells a CFF hinter where a stroke of the letter lies, so that it can fit both of its edges to the pixel grid together. daegun_cff_hints_stems lends an array of them. The edges are as the glyph's charstring states them: not scaled, and not fitted to anything.

A charstring may also hint a single edge. It writes that as a stem with a width of -20 or -21, and the stem is passed on as written, so its max is below its min.

uint32_t gid = 0;
if (daegun_font_glyph_id(font, 'H', &gid) != DAEGUN_OK) return 1;
daegun_cff_hints *hints = NULL;
if (daegun_font_cff_hints(font, gid, NULL, &hints) != DAEGUN_OK) return 1;

size_t n = 0;
const daegun_cff_stem *stems = daegun_cff_hints_stems(hints, &n);
daegun_cff_stem upright = stems[3];
/* STIX Two Math's H has 5 stems. The fourth is its left upright: vertical, from x 133 to 225. */

daegun_cff_hints_free(hints);
float min
The edge the charstring states first: the lower edge of a horizontal stem as a y position, or the left edge of a vertical stem as an x position.
float max
min plus the width the charstring gives: the upper edge, or the right one. It is below min for an edge hint.
bool vertical
True for a vertical stem, whose edges are x positions. False for a horizontal stem, whose edges are y positions.
  • Size: 12 bytes.
daegun_cff_mask
typedef struct {
    size_t point;
    const uint8_t *bits;
    size_t bits_len;
} daegun_cff_mask;

One hint mask of a CFF glyph: which of its stems are in force from a given point on.

Two stems that overlap cannot both be fitted at once. A charstring deals with that by setting a mask as it draws: from there on, the stems whose bit is set are the ones in force, until the next mask. daegun_cff_hints_mask_at fills one of these.

Stem i of daegun_cff_hints_stems is bit 0x80 >> (i % 8) of bits[i / 8].

uint32_t gid = 0;
if (daegun_font_glyph_id(font, 'E', &gid) != DAEGUN_OK) return 1;
daegun_cff_hints *hints = NULL;
if (daegun_font_cff_hints(font, gid, NULL, &hints) != DAEGUN_OK) return 1;

daegun_cff_mask mask;
if (daegun_cff_hints_mask_at(hints, 0, &mask) != DAEGUN_OK) return 1;
/* Whether stem i is in force under this mask. */
size_t i = 1;
bool in_force = (mask.bits[i / 8] & (0x80 >> (i % 8))) != 0;
/* STIX Two Math's E has 9 stems, so 2 bytes a mask. Its first mask applies from point 0 and
   turns on stem 1 but not stem 0: the two overlap. */

daegun_cff_hints_free(hints);
size_t point
The index of the first point the mask applies to, counting the glyph's points from 0, on-curve points and controls alike, as daegun_hinted_outline_points lists them. A contour's closing line back to its start adds no point here, though a pen drawing the glyph is handed one. A glyph's masks come in order, so this never falls from one mask to the next.
const uint8_t *bits
The mask: one bit per stem in the order daegun_cff_hints_stems gives them, the high bit of the first byte first, a set bit meaning the stem is in force. Borrowed from the hints and valid until daegun_cff_hints_free.
size_t bits_len
How many bytes bits holds: a bit for every stem, rounded up to whole bytes, so 2 for a glyph of 9 stems.
  • Size: 24 bytes on a 64-bit target.
daegun_cff_hints
typedef struct daegun_cff_hints daegun_cff_hints;

The stem hints and hint masks of one CFF or CFF2 glyph.

An opaque handle from daegun_font_cff_hints. daegun_cff_hints_stems lends the stems, daegun_cff_hints_mask_count and daegun_cff_hints_mask_at read the masks, and daegun_cff_hints_free frees it.

These are the hints as the font states them, in font units, for a caller that hints CFF outlines itself or wants to look at them. For a glyph already hinted, call daegun_font_hinted_outline with DAEGUN_HINT_FONT. The masks are the hint masks alone: a charstring's counter masks are not kept.

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

daegun_cff_hints *hints = NULL;
if (daegun_font_cff_hints(font, gid, NULL, &hints) != DAEGUN_OK) return 1;
size_t stems = 0, masks = 0;
daegun_cff_hints_stems(hints, &stems);
if (daegun_cff_hints_mask_count(hints, &masks) != DAEGUN_OK) return 1;
/* STIX Two Math's E: 9 stems and 5 masks. */

daegun_cff_hints_free(hints);
daegun_outline_options
typedef struct {
    size_t size;
    int32_t hinting;
    float transform[6];
    daegun_stroke_style stroke;
    float embolden;
    float oblique;
    bool has_transform;
    bool has_stroke;
    bool has_embolden;
    bool has_oblique;
} daegun_outline_options;

What daegun_font_prepared_outline does to a glyph's outline on its way to your pen: hinting, a lean, a transform, and a stroke or extra weight.

Fill one with daegun_outline_options_default, then set the fields you want. Every default is zero, which draws the outline as the font has it, and passing NULL where the call takes options means the same. The struct opens with its own size, so a program built against this header keeps working with a newer library that has added fields at the end.

The steps apply in a fixed order: hinting, then the oblique, then the transform, then a stroke or an embolden. Each of the last four is a value and a has_ flag, and the value is read only while its flag is true.

Every length is in font units, whatever the pixel size: the offsets of the transform, the width of a stroke and the embolden. The call scales them to pixels along with the outline.

An embolden overlaps itself: it draws the outline, and over its edge a stroke as wide as the embolden. A stroke overlaps itself where it is wide enough to run into itself, or where the outline crosses itself. A nonzero fill paints both right. For a rasterizer that sums coverage, flatten what was drawn and pass it through daegun_contours_resolve_overlaps, which answers DAEGUN_ABSENT where there was nothing to merge.

uint32_t gid = 0;
if (daegun_font_glyph_id(font, 'H', &gid) != 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.has_embolden = true;
opts.embolden = 64.0f; /* font units: half a pixel at 16 px, as Inter has 2048 units to the em */

daegun_path *path = daegun_path_new();
daegun_pen pen;
if (daegun_path_as_pen(path, &pen) != DAEGUN_OK) return 1;
daegun_prepared_glyph glyph;
if (daegun_font_prepared_outline(font, gid, NULL, 16.0f, &opts, &pen, &glyph) != DAEGUN_OK) return 1;
/* The path holds a bolder H, hinted for 16 px. Its advance is 12.390625 px, half a pixel more
   than the plain H's 11.890625. */

daegun_path_free(path);
size_t size
The size of the struct in bytes as your header has it. daegun_outline_options_default sets it. A struct that was only zeroed has a size of 0, which daegun_font_prepared_outline refuses with DAEGUN_INVALID_ARGUMENT.
int32_t hinting
A DAEGUN_HINT_ code: which hinter fits the glyph to the pixel grid at the size asked for. It has no flag: DAEGUN_HINT_NONE, which is 0, means none. A glyph the hinter does not take is drawn unhinted.
float transform[6]
A 2x3 transform [a, b, c, d, dx, dy], read while has_transform is true. It moves a point (x, y) to (a*x + c*y + dx, b*x + d*y + dy), with dx and dy in font units. It applies after hinting and after the oblique, and it scales neither a stroke, an embolden nor the advances.
daegun_stroke_style stroke
A daegun_stroke_style, read while has_stroke is true: the outline is stroked, and the stroke is drawn in place of the fill. Its width is in font units, and a width of 0 draws nothing. A style left zeroed has butt caps and miter joins.
float embolden
Extra stem width in font units, read while has_embolden is true. Every edge moves out by half of it, so a stem grows by all of it. The advance across grows by it too, and so does the advance down in a font with vertical metrics. It is ignored while a stroke is set, which takes its place, and at zero or below.
float oblique
The tangent of the angle to lean the glyph from upright, read while has_oblique is true. Positive leans to the right: a point moves right by oblique times its height above the baseline. It applies before the transform, so the glyph leans in its own frame.
bool has_transform
Whether transform is read.
bool has_stroke
Whether stroke is read. While true, the glyph is stroked and not filled.
bool has_embolden
Whether embolden is read.
bool has_oblique
Whether oblique is read.
  • Size: 64 bytes on a 64-bit target.
daegun_prepared_glyph
typedef struct {
    float advance_width;
    float advance_height;
    bool hinted;
} daegun_prepared_glyph;

What daegun_font_prepared_outline reports about the glyph it drew: its advances in pixels, and whether it was hinted.

It is filled through the out parameter of daegun_font_prepared_outline, at the pixel size of that call. The advances are the font's own at the location, scaled to the size. They are not rounded to whole pixels, with a hinter or without. An embolden adds to the advance across, and to the advance down where the font has vertical metrics. A transform leaves both as they are.

uint32_t gid = 0;
if (daegun_font_glyph_id(font, 0x65E5, &gid) != DAEGUN_OK) return 1; /* 日 */

/* A pen with no callbacks draws nothing: this asks for the advances alone. */
daegun_pen pen = { NULL, NULL, NULL, NULL, NULL, NULL };
daegun_prepared_glyph glyph;
if (daegun_font_prepared_outline(font, gid, NULL, 32.0f, NULL, &pen, &glyph) != DAEGUN_OK) return 1;
/* Source Han Sans has vertical metrics, and sets this glyph on a full em both ways: at 32 px
   it advances 32 px across, or 32 px down. No hinting was asked for, so glyph.hinted is false. */
float advance_width
How far the pen moves across after the glyph, in pixels: the glyph's advance, plus any embolden, scaled to the size.
float advance_height
How far the pen moves down after the glyph in vertical text, in pixels. It is 0 for a font without vertical metrics, embolden or no embolden.
bool hinted
True if a hinter fitted the outline to the pixel grid. False if the options asked for none, or if no hinter took the glyph and it was drawn unhinted.
  • Size: 12 bytes.

Color

daegun/color.h: color glyphs. Bitmap strikes, COLR layers and palettes, paint graphs and the scenes made from them, and the color math to sample a gradient and composite a layer.

daegun_rgba
typedef struct {
    uint8_t r;
    uint8_t g;
    uint8_t b;
    uint8_t a;
} daegun_rgba;

A color as four bytes: red, green, blue and alpha, in sRGB with straight alpha.

Straight means the red, green and blue are not multiplied by the alpha. An alpha of 0 is fully transparent and 255 fully opaque. Palette colors, layer colors, gradient stops and what daegun_ramp_at samples all come as this struct, and the text color of a daegun_scene_options goes in as one.

C has no calls for a color's arithmetic, so scaling an alpha or turning the bytes into floats is yours to write. daegun_blend and daegun_composite take a color as three floats from 0 to 1 with the alpha apart. Neither converts a color space: divided by 255 the bytes composite as sRGB values, and to match daegun's own renderer, which composites in linear light, decode them to linear light first.

daegun_rgba colors[2];
size_t count = 0;
if (daegun_font_palette_colors(font, 0, colors, 2, &count) != DAEGUN_OK) return 1;

/* The first color of Bungee Tint's default palette is an opaque red: 201, 9, 0, 255. */
daegun_rgba red = colors[0];

/* The color as daegun_composite takes one, in sRGB values: three floats from 0 to 1, the alpha apart. */
float rgb[3] = { red.r / 255.0f, red.g / 255.0f, red.b / 255.0f };
float alpha = red.a / 255.0f;
uint8_t r
Red, 0 to 255.
uint8_t g
Green, 0 to 255.
uint8_t b
Blue, 0 to 255.
uint8_t a
Alpha: 0 is transparent and 255 is opaque.
  • Size: 4 bytes.
daegun_bitmap
typedef struct daegun_bitmap daegun_bitmap;

A glyph's picture from one of the font's bitmap strikes.

An opaque handle. daegun_font_bitmap makes one, daegun_bitmap_info_of reads it, and daegun_bitmap_free frees it. A strike is a set of glyph pictures drawn for one size, counted in pixels per em. Noto Color Emoji stores its glyphs this way.

The handle holds its own copy of the picture, so it stays good after the font is freed. Nothing changes it once made, so several threads may read one at the same time.

uint32_t gid = 0;
if (daegun_font_glyph_id(font, 0x1F600, &gid) != DAEGUN_OK) return 1;

daegun_bitmap *bitmap = NULL;
if (daegun_font_bitmap(font, gid, 64, &bitmap) != DAEGUN_OK) return 1;
daegun_bitmap_info info;
if (daegun_bitmap_info_of(bitmap, &info) != DAEGUN_OK) return 1;
/* Noto Color Emoji stores this glyph as a PNG file: info.data points at its info.data_len bytes. */

daegun_bitmap_free(bitmap);
daegun_bitmap_info
typedef struct {
    int32_t format;
    uint16_t ppem;
    int16_t left;
    int16_t top;
    uint16_t width;
    uint16_t height;
    bool mirrored;
    const uint8_t *data;
    size_t data_len;
} daegun_bitmap_info;

What a bitmap holds: its format, the size of the strike it came from, where the picture sits and its bytes.

daegun_bitmap_info_of fills one. The picture is drawn for ppem pixels per em, the size of the strike daegun picked, which may not be the size you asked for. To draw at another size, scale it by your size over ppem.

left and top place the picture against the glyph's origin, the point on the baseline the pen stands at. Its top left corner is left pixels to the right of the origin and top pixels above it, counted at the strike's size, and the picture runs right and down from there.

format says what data holds. A color glyph is the PNG file the font stores, DAEGUN_BITMAP_PNG, for a PNG decoder of yours. A monochrome or grayscale glyph is decoded to one byte of coverage a pixel, DAEGUN_BITMAP_COVERAGE.

data is borrowed from the bitmap and valid until daegun_bitmap_free. Copy it to keep it longer.

uint32_t gid = 0;
if (daegun_font_glyph_id(font, 0x1F600, &gid) != DAEGUN_OK) return 1;
daegun_bitmap *bitmap = NULL;
if (daegun_font_bitmap(font, gid, 64, &bitmap) != DAEGUN_OK) return 1;

daegun_bitmap_info info;
if (daegun_bitmap_info_of(bitmap, &info) != DAEGUN_OK) return 1;
if (info.format == DAEGUN_BITMAP_PNG) {
    /* info.data is a PNG file of info.data_len bytes: decode it with a PNG library. */
} else if (info.format == DAEGUN_BITMAP_COVERAGE) {
    size_t width = info.width, height = info.height;
    for (size_t y = 0; y < height; y++) {
        const uint8_t *row = info.data + y * width;
        /* row[x] is how much of pixel x the glyph covers, 0 to 255. */
    }
}
/* This glyph is a PNG file, so the first branch runs. */

daegun_bitmap_free(bitmap);
int32_t format
DAEGUN_BITMAP_PNG or DAEGUN_BITMAP_COVERAGE: what data holds.
uint16_t ppem
The strike's size in pixels per em. It may not be the size asked for.
int16_t left
The picture's left edge, in pixels at ppem, counted to the right of the glyph's origin.
int16_t top
The picture's top edge, in pixels at ppem, counted up from the glyph's origin.
uint16_t width
With DAEGUN_BITMAP_COVERAGE, the width of the picture in pixels. 0 for a PNG, whose own header holds its size.
uint16_t height
With DAEGUN_BITMAP_COVERAGE, the height of the picture in pixels, which is its number of rows. 0 for a PNG.
bool mirrored
True where the picture is to be drawn mirrored left to right, as a flip record of Apple's sbix asks. Only a picture from sbix sets it.
const uint8_t *data
The bytes: a whole PNG file, or width times height bytes of coverage, rows from the top. Borrowed until the bitmap is freed.
size_t data_len
How many bytes data points at.
  • Size: 32 bytes on a 64-bit target.
daegun_colr_layer
typedef struct {
    uint32_t glyph;
    daegun_rgba color;
    bool foreground;
} daegun_colr_layer;

One layer of a COLR version 0 color glyph: a glyph whose outline is filled with one color.

COLR version 0 is the plain kind of color glyph: a stack of ordinary outlines, each filled with one flat color from a palette. daegun_font_colr_layers fills an array of these in drawing order, the first at the back. Draw each by filling the outline of its glyph, which daegun_font_outline gives, over the layers before it. Every layer is placed at the origin of the color glyph itself.

daegun_font_color_scene does that work for you and hands the same layers back as fills ready to draw.

uint32_t gid = 0;
if (daegun_font_glyph_id(font, 'A', &gid) != DAEGUN_OK) return 1;
daegun_colr_layer layers[8];
size_t count = 0;
if (daegun_font_colr_layers(font, gid, 0, layers, 8, &count) != DAEGUN_OK) return 1;

daegun_rgba text = { 0, 0, 0, 255 }; /* the color the text around it is drawn in */
for (size_t i = 0; i < count; i++) {
    daegun_rgba color = layers[i].foreground ? text : layers[i].color;
    /* Fill the outline of layers[i].glyph with `color`, over what the layers before it drew. */
}
/* Bungee Tint's A is 2 layers, and neither asks for the text's color. */
uint32_t glyph
The glyph whose outline this layer fills.
daegun_rgba color
The layer's color in the palette asked for. Where foreground is true it is opaque black, 0, 0, 0, 255: draw the layer in the text's color as it is.
bool foreground
True where the layer takes the text's color in place of color.
  • Size: 12 bytes.
daegun_palette
typedef struct {
    uint16_t index;
    uint16_t name_id;
    bool light_safe;
    bool dark_safe;
    bool has_name_id;
} daegun_palette;

One of the font's color palettes, as a color picker lists it.

A font with a CPAL table holds one or more palettes. Each is a list of colors, the same number in every palette, and a color glyph names its colors by their place in that list. Choosing another palette recolors every color glyph of the font at once.

daegun_font_palettes fills an array of these. index is what you pass as the palette of daegun_font_colr_layers, daegun_font_paint_graph and daegun_scene_options, and palette 0 is the default. A font may mark a palette as made for a light or for a dark background, and may give it a name.

daegun_palette palettes[8];
size_t count = 0;
if (daegun_font_palettes(font, palettes, 8, &count) != DAEGUN_OK) return 1;

/* Take the first palette the font marks for a dark background, or else the default. */
uint16_t chosen = 0;
for (size_t i = 0; i < count; i++) {
    if (palettes[i].dark_safe) {
        chosen = palettes[i].index;
        break;
    }
}
/* This font has 3 palettes and marks palette 1 for dark backgrounds. It names none of them. */
uint16_t index
Its index, the palette argument that selects it.
uint16_t name_id
The ID of the palette's name in the font's name table, for daegun_font_name. Read it only where has_name_id is true. Otherwise it is 0.
bool light_safe
Whether the font marks the palette as readable on a light background.
bool dark_safe
Whether the font marks the palette as readable on a dark background.
bool has_name_id
Whether the font names this palette, which is when name_id means something.
  • Size: 8 bytes.
daegun_scene_options
typedef struct {
    size_t size;
    daegun_rgba foreground;
    uint16_t palette;
} daegun_scene_options;

What a color glyph is drawn with: the palette its colors come from and the text's color.

daegun_font_color_scene, daegun_rasterizer_color_glyph and daegun_rasterizer_color_glyph_into take one. Passing NULL there means the defaults: palette 0 and opaque black text.

Fill it with daegun_scene_options_default, then set the fields you want. Zeroing the struct is not the default. A zeroed struct has a size of 0, which the call you pass it to answers with DAEGUN_INVALID_ARGUMENT. And if you set size yourself and leave the rest zeroed, the text color is transparent black, so every paint that takes the text color draws nothing you can see.

The struct opens with its own size, so a program built against this header keeps working with a newer library that has added fields at the end.

daegun_scene_options opts;
if (daegun_scene_options_default(&opts, sizeof opts) != DAEGUN_OK) return 1;
opts.palette = 1; /* the font's second palette */

uint32_t gid = 0;
if (daegun_font_glyph_id(font, 'A', &gid) != DAEGUN_OK) return 1;
daegun_scene *scene = NULL;
if (daegun_font_color_scene(font, gid, NULL, &opts, &scene) != DAEGUN_OK) return 1;

size_t n = 0;
const daegun_scene_op *ops = daegun_scene_ops(scene, &n);
/* Bungee Tint's A is red in palette 0. In palette 1 its first layer is white. */

daegun_scene_free(scene);
size_t size
The size of the struct in bytes as your header has it. daegun_scene_options_default sets it.
daegun_rgba foreground
The text's color, a daegun_rgba: sRGB with straight alpha. A layer or a paint that asks for the text color in place of a palette entry takes this one, with its alpha scaled by the paint's own. Opaque black by default.
uint16_t palette
Which of the font's CPAL palettes to read colors from, by index. An index past the font's last palette reads palette 0, the default one. daegun_font_palettes lists them.
  • Size: 16 bytes on a 64-bit target.
daegun_scene
typedef struct daegun_scene daegun_scene;

A color glyph as a scene: ops to draw in order, over the paths, clip shapes and gradients the scene holds.

An opaque handle from daegun_font_color_scene. daegun_scene_ops lends the ops, each a daegun_scene_op. An op names what it draws by index: a path, read with daegun_scene_path_at, a gradient in what daegun_scene_gradients lends, whose stops are in what daegun_scene_stops lends, or a run of the clip shapes that daegun_scene_shapes lends. daegun_scene_ramp makes one of its gradients ready to sample. Everything is in font units, y up.

A scene holds copies of all it needs and borrows nothing from the font, so it may outlive the font. It is read-only once made, so any number of threads may read one at the same time. Free it with daegun_scene_free.

uint32_t gid = 0;
if (daegun_font_glyph_id(font, 'A', &gid) != DAEGUN_OK) return 1;
daegun_scene *scene = NULL;
if (daegun_font_color_scene(font, gid, NULL, NULL, &scene) != DAEGUN_OK) return 1;

size_t ops = 0, shapes = 0, gradients = 0, stops = 0, paths = 0;
daegun_scene_ops(scene, &ops);
daegun_scene_shapes(scene, &shapes);
daegun_scene_gradients(scene, &gradients);
daegun_scene_stops(scene, &stops);
if (daegun_scene_path_count(scene, &paths) != DAEGUN_OK) return 1;
/* Bungee Tint's A: 2 ops over 2 paths, and no clip shapes, gradients or stops. */

daegun_scene_free(scene);
daegun_scene_op
typedef struct {
    double transform[6];
    int32_t kind;
    int32_t rule;
    int32_t blend;
    float opacity;
    size_t path;
    size_t gradient;
    size_t shapes_start;
    size_t shapes_end;
    daegun_rgba color;
    bool has_gradient;
} daegun_scene_op;

One step of a scene: a path filled, a clip pushed or popped, or a layer pushed or popped.

daegun_scene_ops lends them in drawing order. One struct serves all five kinds: kind says which the op is, and each other field is read by the kinds its entry names. A field the kind does not read is zero, so the transform of a clip or a layer is six zeros, not the identity.

A fill (DAEGUN_OP_FILL) draws. Take path path with daegun_scene_path_at, place it by transform, and paint the points its rule covers: with color, or where has_gradient is set, with entry gradient of what daegun_scene_gradients lends. A fill goes over what its layer already holds, as DAEGUN_COMPOSITE_SRC_OVER does, and only inside the clips now open.

A transform is [a, b, c, d, e, f]: a point (x, y) lands at x' = a*x + c*y + e and y' = b*x + d*y + f. It places the path only. A gradient has a transform of its own, which already leads to the scene's space, so do not apply the fill's to it as well.

A clip limits drawing to a region. DAEGUN_OP_PUSH_CLIP names a run of the scene's clip shapes, and from there to the DAEGUN_OP_POP_CLIP that pairs with it, what is drawn shows only inside those shapes. A renderer builds a mask from the shapes at the push, keeping only what lies inside the clip already open, and goes back to the earlier clip at the pop.

A layer is a group drawn on its own and then laid on as one. At DAEGUN_OP_PUSH_LAYER a renderer starts a new transparent surface and draws the ops that follow into it. At the DAEGUN_OP_POP_LAYER that pairs with it, it multiplies that surface by the push's opacity and composites it onto the surface below by the push's blend, inside the clip that was open at the push. daegun_composite does that arithmetic for a pixel. daegun's own renderer does all of this in linear light, premultiplied: it decodes each sRGB color first, and encodes the result back once the scene is drawn.

Pushes and pops pair like brackets: a pop closes the last push still open, a clip's pop for a clip and a layer's for a layer. In a scene from daegun_font_color_scene they always balance, and never nest more than 128 deep. A COLR composite whose two paints both draw comes as two layers. The outer one is pushed with DAEGUN_COMPOSITE_SRC_OVER and takes the backdrop paint first. The inner one is pushed with the composite's own mode and takes the source paint. Its pop composites the source onto the backdrop, and the outer pop lays the result over what the glyph has drawn so far.

daegun_scene *scene = NULL;
if (daegun_font_color_scene(font, 156, NULL, NULL, &scene) != DAEGUN_OK) return 1;

size_t n = 0;
const daegun_scene_op *ops = daegun_scene_ops(scene, &n);
int fills = 0, depth = 0, deepest = 0;
for (size_t i = 0; i < n; i++) {
    const daegun_scene_op *op = &ops[i];
    switch (op->kind) {
    case DAEGUN_OP_FILL:
        /* Fill path op->path, placed by op->transform, by op->rule: with gradient op->gradient
           if op->has_gradient, and with op->color if not. */
        fills++;
        break;
    case DAEGUN_OP_PUSH_CLIP:
        /* Clip to shapes op->shapes_start up to op->shapes_end, inside the clip already open. */
        depth++;
        break;
    case DAEGUN_OP_PUSH_LAYER:
        /* Start a transparent layer, and keep op->blend and op->opacity for its pop. */
        depth++;
        break;
    case DAEGUN_OP_POP_CLIP:
        /* Go back to the clip that was open before. */
        depth--;
        break;
    case DAEGUN_OP_POP_LAYER:
        /* Composite the top layer onto the one below, by the blend and opacity of its push. */
        depth--;
        break;
    }
    if (depth > deepest) deepest = depth;
}
/* Glyph 156 of the COLR test font: 12 ops, of which 2 fill, with clips and layers up to 4 deep.
   Every push has had its pop by the end. */

daegun_scene_free(scene);
double transform[6]
DAEGUN_OP_FILL: where the path is placed, as [a, b, c, d, e, f] with x' = a*x + c*y + e and y' = b*x + d*y + f. Six zeros for the other kinds.
int32_t kind
Which op this is, a DAEGUN_OP_ code. It decides which of the other fields are read.
int32_t rule
DAEGUN_OP_FILL: which points the path covers, DAEGUN_FILL_NONZERO or DAEGUN_FILL_EVENODD.
int32_t blend
DAEGUN_OP_PUSH_LAYER: how the layer combines with what lies under it when it is popped, a DAEGUN_COMPOSITE_ code.
float opacity
DAEGUN_OP_PUSH_LAYER: what the layer is multiplied by as it composites, 0 for nothing to 1 for all of it. Every layer of a scene from daegun_font_color_scene has 1, as COLR keeps its alpha in its colors.
size_t path
DAEGUN_OP_FILL: the index of the path to fill, for daegun_scene_path_at.
size_t gradient
DAEGUN_OP_FILL with has_gradient: the index of its gradient in what daegun_scene_gradients lends. Otherwise 0, and the fill is color.
size_t shapes_start
DAEGUN_OP_PUSH_CLIP: the index of its first clip shape in what daegun_scene_shapes lends.
size_t shapes_end
DAEGUN_OP_PUSH_CLIP: one past the index of its last clip shape, so its shapes number shapes_end - shapes_start.
daegun_rgba color
DAEGUN_OP_FILL without has_gradient: the color to fill with, sRGB with straight alpha. The palette and the text color of the scene's options are already worked into it. All zeros where the fill has a gradient.
bool has_gradient
DAEGUN_OP_FILL: true where the fill is painted with a gradient, false where it is one color.
  • Size: 104 bytes on a 64-bit target.
daegun_clip_shape
typedef struct {
    double transform[6];
    size_t path;
    int32_t rule;
} daegun_clip_shape;

One shape of a clip: one of the scene's paths, placed by a transform and filled by a rule.

daegun_scene_shapes lends every clip shape of a scene in one array, and a daegun_scene_op whose kind is DAEGUN_OP_PUSH_CLIP names its own by shapes_start and shapes_end. The region a shape allows is what its path covers under rule, once transform has placed it.

In a scene from daegun_font_color_scene every clip has exactly one shape. It is the outline of a glyph that other paints are drawn through, or a rectangle: the clip box of the glyph itself or of a color glyph it draws.

daegun_scene *scene = NULL;
if (daegun_font_color_scene(font, 180, NULL, NULL, &scene) != DAEGUN_OK) return 1;

size_t count = 0;
const daegun_clip_shape *shapes = daegun_scene_shapes(scene, &count);
const daegun_clip_shape *shape = &shapes[1];
daegun_path_view path;
if (daegun_scene_path_at(scene, shape->path, &path) != DAEGUN_OK) return 1;

const double *m = shape->transform;
for (size_t i = 0; i < path.points_len; i++) {
    double x = path.points[i].x, y = path.points[i].y;
    double sx = m[0] * x + m[2] * y + m[4], sy = m[1] * x + m[3] * y + m[5];
    /* (sx, sy) is the point where the clip has it, in the scene's space. */
}
/* This shape is a square turned half a turn: its transform is [-1, 0, 0, -1, 1000, 1200]. */

daegun_scene_free(scene);
double transform[6]
Where the path is placed, as [a, b, c, d, e, f]: a point (x, y) of the path lands at x' = a*x + c*y + e and y' = b*x + d*y + f.
size_t path
The index of the path, for daegun_scene_path_at.
int32_t rule
Which points the path covers, DAEGUN_FILL_NONZERO or DAEGUN_FILL_EVENODD.
  • Size: 64 bytes on a 64-bit target.
daegun_stop
typedef struct {
    float offset;
    daegun_rgba color;
} daegun_stop;

One stop of a gradient: a place along it and the color there.

daegun_scene_stops lends every stop of a scene in one array, and each daegun_gradient names its own by stops_start and stops_count. A gradient's stops come sorted by offset, all within 0 to 1.

Between two stops the color runs from one to the other, and how it is mixed is the renderer's choice: daegun_scene_ramp takes DAEGUN_INTERPOLATE_LINEAR_LIGHT or DAEGUN_INTERPOLATE_SRGB. Two stops at one offset make a hard edge: the first colors what lies before it, the last what lies at and after it.

daegun_scene *scene = NULL;
if (daegun_font_color_scene(font, 8, NULL, NULL, &scene) != DAEGUN_OK) return 1;

size_t count = 0;
const daegun_stop *stops = daegun_scene_stops(scene, &count);
for (size_t i = 0; i < count; i++) {
    /* stops[i].color lies at stops[i].offset along its gradient. */
}
/* Two stops: red at offset 0 and blue at offset 1. */

daegun_scene_free(scene);
float offset
Where along the gradient the stop lies: 0 at its start and 1 at its end.
daegun_rgba color
The color there, sRGB with straight alpha. A stop that takes the text color already holds the scene options' foreground, its alpha scaled by the stop's own.
  • Size: 8 bytes.
daegun_gradient
typedef struct {
    double transform[6];
    float values[6];
    int32_t kind;
    int32_t extend;
    size_t stops_start;
    size_t stops_count;
} daegun_gradient;

A gradient of a scene: its shape, the transform that places it, how it goes on past its ends, and its stops.

daegun_scene_gradients lends them, and a daegun_scene_op that fills with one names it by index. kind is the shape, and values hold its numbers: for DAEGUN_GRADIENT_LINEAR the line from (x0, y0) to (x1, y1), for DAEGUN_GRADIENT_RADIAL the circles x0, y0, r0 and x1, y1, r1, and for DAEGUN_GRADIENT_SWEEP the center cx, cy and the angles start_angle and end_angle, in degrees counterclockwise.

The shape is in the gradient's own space. transform takes that space to the scene's, in font units, and it is complete: the transform of the op that fills with the gradient places that op's path, and is not applied to the gradient too.

Its stops are stops_count entries of what daegun_scene_stops lends, from index stops_start. There are always two or more, sorted by offset within 0 to 1. A gradient with a single stop reaches you as a fill of one color, and one with none as no fill at all, as does one whose stops all lie at one offset under DAEGUN_EXTEND_REPEAT or DAEGUN_EXTEND_REFLECT, which COLR calls ill-formed.

COLR lets a gradient's first and last stops lie anywhere, inside 0 to 1 or past it. daegun moves the geometry to them instead, so that the first stop is at offset 0 and the last at 1, unless every stop lies at one offset. That is why a radial gradient's r0 or r1 can come out below 0: the gradient paints nothing where its radius would be negative.

To paint with one, daegun_scene_ramp makes it ready to sample at your pixels and daegun_ramp_at reads a color.

daegun_scene *scene = NULL;
if (daegun_font_color_scene(font, 8, NULL, NULL, &scene) != DAEGUN_OK) return 1;

size_t count = 0, stop_count = 0;
const daegun_gradient *gradients = daegun_scene_gradients(scene, &count);
const daegun_stop *stops = daegun_scene_stops(scene, &stop_count);

const daegun_gradient *g = &gradients[0];
if (g->kind == DAEGUN_GRADIENT_LINEAR) {
    float x0 = g->values[0], y0 = g->values[1], x1 = g->values[2], y1 = g->values[3];
    const daegun_stop *first = &stops[g->stops_start];
    const daegun_stop *last = &stops[g->stops_start + g->stops_count - 1];
    /* first->color at (x0, y0), last->color at (x1, y1), both moved by g->transform. */
}
/* Glyph 8 of the COLR test font: a line from (100, 250) to (900, 250), red to blue, that repeats
   past its ends. Its transform is the identity. */

daegun_scene_free(scene);
double transform[6]
Takes the gradient's own space, the one values are in, to the scene's: [a, b, c, d, e, f] with x' = a*x + c*y + e and y' = b*x + d*y + f.
float values[6]
The numbers of the shape, as kind says. Linear: x0, y0, x1, y1. Radial: x0, y0, r0, x1, y1, r1. Sweep: cx, cy, start_angle, end_angle. Those a kind does not use are 0.
int32_t extend
What it paints before offset 0 and after offset 1: DAEGUN_EXTEND_PAD, DAEGUN_EXTEND_REPEAT or DAEGUN_EXTEND_REFLECT.
size_t stops_start
The index of its first stop in what daegun_scene_stops lends.
size_t stops_count
How many stops it has, from stops_start on. Always 2 or more.
  • Size: 96 bytes on a 64-bit target.
daegun_path_view
typedef struct {
    const uint8_t *verbs;
    size_t verbs_len;
    const daegun_point *points;
    size_t points_len;
} daegun_path_view;

One path of a scene, lent as its verbs and the points they take.

daegun_scene_path_at fills one. A verb is one drawing step, a DAEGUN_VERB_ byte, and takes its points from the front of what is left of points: DAEGUN_VERB_MOVE and DAEGUN_VERB_LINE take one, DAEGUN_VERB_QUAD two, a control point then the end, DAEGUN_VERB_CUBIC three, two control points then the end, and DAEGUN_VERB_CLOSE none. The points are in font units, y up.

Both arrays are borrowed from the scene and valid until daegun_scene_free. For a path to keep, or to pass to a call that takes a daegun_path, use daegun_scene_path_copy.

daegun_scene *scene = NULL;
if (daegun_font_color_scene(font, 2, NULL, NULL, &scene) != DAEGUN_OK) return 1;

daegun_path_view path;
if (daegun_scene_path_at(scene, 0, &path) != DAEGUN_OK) return 1;
size_t p = 0, curves = 0;
for (size_t v = 0; v < path.verbs_len; v++) {
    const daegun_point *pt = &path.points[p];
    switch (path.verbs[v]) {
    case DAEGUN_VERB_MOVE:  /* start a contour at pt[0] */                   p += 1; break;
    case DAEGUN_VERB_LINE:  /* a line to pt[0] */                            p += 1; break;
    case DAEGUN_VERB_QUAD:  /* a curve to pt[1], bent by pt[0] */  curves++; p += 2; break;
    case DAEGUN_VERB_CUBIC: /* a curve to pt[2], bent by pt[0] and pt[1] */  p += 3; break;
    case DAEGUN_VERB_CLOSE: /* close the contour */                          break;
    }
}
/* The first layer of Bungee Tint's A: 29 verbs, 12 of them quadratic curves, over 39 points. */

daegun_scene_free(scene);
const uint8_t *verbs
The drawing steps, one DAEGUN_VERB_ byte each, in order.
size_t verbs_len
How many verbs there are.
const daegun_point *points
The points the verbs take, in order, as daegun_point.
size_t points_len
How many points there are.
  • Size: 32 bytes on a 64-bit target.
daegun_ramp
typedef struct daegun_ramp daegun_ramp;

A gradient of a scene made ready to sample: what it paints at each pixel, worked out once for where it is placed.

An opaque handle. daegun_scene_ramp makes one from a gradient of a daegun_scene and a transform to your pixels, daegun_ramp_at asks it for the color of a pixel, and daegun_ramp_free frees it. Making one does the work that is the same for every pixel, so make one for each gradient and transform and keep it while you fill, not one for each pixel.

It samples the gradient as COLR defines it: along a line, between two circles or around a point, and past its first and last stops by padding, repeating or reflecting. The ramp keeps its own copy of what it needs, so it may outlive the scene. Sampling only reads it, so several threads may sample one ramp at the same time.

A ramp comes only from a gradient that a scene holds. C has no call that takes a gradient you describe yourself, so the gradients of a paint graph you walk by hand are yours to sample. To have daegun sample them, take the glyph as a scene with daegun_font_color_scene.

daegun_scene *scene = NULL;
if (daegun_font_color_scene(font, 8, NULL, NULL, &scene) != DAEGUN_OK) return 1;
/* The glyph at 100 px per em in a font of 1000 units, y flipped, its origin at pixel (0, 100). */
const double to_device[6] = { 0.1, 0.0, 0.0, -0.1, 0.0, 100.0 };

daegun_ramp *ramp = NULL;
if (daegun_scene_ramp(scene, 0, to_device, DAEGUN_INTERPOLATE_LINEAR_LIGHT, &ramp) != DAEGUN_OK) return 1;
daegun_scene_free(scene); /* the ramp no longer needs it */

/* One ramp serves every pixel of the fill. */
daegun_rgba row[100];
for (int x = 0; x < 100; x++) {
    if (daegun_ramp_at(ramp, x, 74, &row[x]) != DAEGUN_OK) return 1;
}
/* The gradient runs from red on the left to blue on the right: row[10] is 254, 0, 18 and row[89]
   is 18, 0, 254. */

daegun_ramp_free(ramp);
daegun_color_stop
typedef struct {
    double offset;
    daegun_rgba color;
    bool foreground;
} daegun_color_stop;

One stop of a gradient in a paint graph: where it lies along the gradient's color line, and its color.

A color line is the run of colors a gradient paints along. daegun_paint_graph_stops lends every stop of a graph, and each gradient paint names its own with stops_start and stops_count. A visitor is handed them with the gradient.

The stops are the font's own, in the order it stores them, which need not be sorted. An offset may lie below 0 or above 1: the color line then starts or ends past the points the gradient names. A daegun_stop of a scene is the same stop made ready to draw: sorted, moved within 0 to 1, and with the text's color filled in.

daegun_paint_graph *graph = NULL;
if (daegun_font_paint_graph(font, 148, NULL, 0, &graph) != DAEGUN_OK) return 1;
size_t count = 0;
const daegun_color_stop *stops = daegun_paint_graph_stops(graph, &count);

daegun_rgba text = { 0, 0, 0, 255 }; /* the color the text is drawn in */
for (size_t i = 0; i < count; i++) {
    daegun_rgba color = stops[i].color;
    if (stops[i].foreground) {
        /* The text's color, its alpha scaled by the stop's. */
        color = text;
        color.a = (uint8_t)((text.a * stops[i].color.a + 127) / 255);
    }
    /* `color` lies at stops[i].offset along the gradient. */
}
/* Glyph 148's gradient has 3 stops, at 0, 0.5 and 1. The middle one takes the text's color. */

daegun_paint_graph_free(graph);
double offset
Where the stop lies along the color line: 0 at the line's start and 1 at its end. It may be below 0 or above 1.
daegun_rgba color
The palette's color, with its alpha scaled by the stop's own alpha. Where foreground is true it is black at that alpha.
bool foreground
True where the stop takes the text's color in place of color, with the text color's alpha scaled by the alpha in color.
  • Size: 16 bytes.
daegun_paint_node
typedef struct {
    double values[6];
    double center[2];
    size_t end;
    size_t stops_start;
    size_t stops_count;
    uint32_t glyph;
    int32_t kind;
    int32_t extend;
    int32_t mode;
    daegun_rgba color;
    bool foreground;
    bool has_center;
} daegun_paint_node;

One paint of a COLR version 1 paint graph: its kind, and the values that kind reads.

One struct serves every kind of paint, so most of its fields are 0 for any one paint. Read kind first. It is a DAEGUN_PAINT_ code, and it says which of the other fields mean something. DAEGUN_PAINT_LAYERS explains how the paints fit together.

Positions and distances are in font units, with y up. Angles are in degrees and run counterclockwise. Scales and the first four terms of a matrix are plain factors.

daegun_paint_graph_nodes lends a graph's paints in the order a visitor meets them, the root first, so each paint is followed by everything below it. The first child of paint i is paint i + 1, where that index is below nodes[i].end. Each next child starts at the end of the child before it, and the children stop at the paint's own end.

What values holds, by kind. DAEGUN_PAINT_LINEAR_GRADIENT: x0, y0, x1, y1, x2, y2. DAEGUN_PAINT_RADIAL_GRADIENT: x0, y0, r0, x1, y1, r1. DAEGUN_PAINT_SWEEP_GRADIENT: cx, cy, start_angle, end_angle. DAEGUN_PAINT_TRANSFORM: xx, yx, xy, yy, dx, dy. DAEGUN_PAINT_TRANSLATE: dx, dy. DAEGUN_PAINT_SCALE: sx, sy. DAEGUN_PAINT_SCALE_UNIFORM: s. DAEGUN_PAINT_ROTATE: angle. DAEGUN_PAINT_SKEW: x_angle, y_angle. The other kinds leave all six at 0.

daegun_paint_graph *graph = NULL;
if (daegun_font_paint_graph(font, 84, NULL, 0, &graph) != DAEGUN_OK) return 1;
size_t count = 0;
const daegun_paint_node *nodes = daegun_paint_graph_nodes(graph, &count);

/* The root is nodes[0]. Its first child is the next paint, and each next child starts where the
   one before it ends. */
const daegun_paint_node *root = &nodes[0];
size_t children = 0;
for (size_t child = 1; child < root->end; child = nodes[child].end) {
    /* nodes[child] is a child of the root. */
    children++;
}
/* Glyph 84's root is a composite, so it has 2: its source, then its backdrop. */

/* The source scales what is below it by 0.5 across and 1.5 up, about the point (500, 500). */
const daegun_paint_node *source = &nodes[1];
if (source->kind == DAEGUN_PAINT_SCALE) {
    double sx = source->values[0], sy = source->values[1];
    double cx = source->has_center ? source->center[0] : 0.0;
    double cy = source->has_center ? source->center[1] : 0.0;
}

daegun_paint_graph_free(graph);
double values[6]
Up to six numbers whose meaning goes by kind: a gradient's points, radii and angles, or a transform's terms. Positions are in font units with y up, and angles in degrees counterclockwise. The ones a kind does not use are 0.
double center[2]
For DAEGUN_PAINT_SCALE, DAEGUN_PAINT_SCALE_UNIFORM, DAEGUN_PAINT_ROTATE and DAEGUN_PAINT_SKEW with has_center true: the point the transform keeps fixed, x then y, in font units with y up. Otherwise both are 0.
size_t end
The index one past the last paint below this one, which is where its children stop. In a visitor it is 0, as the calls to enter and leave carry the nesting.
size_t stops_start
For the three gradient kinds: the index of the gradient's first stop among those daegun_paint_graph_stops lends. For any other kind it is where the graph's stops stood when the paint came, which means nothing, as its stops_count is 0. In a visitor it is 0, and the stops are handed to enter.
size_t stops_count
For the three gradient kinds: how many stops the gradient has. 0 for every other kind.
uint32_t glyph
For DAEGUN_PAINT_GLYPH: the glyph whose outline clips the child. For DAEGUN_PAINT_COLR_GLYPH: the color glyph whose paint graph is the child. 0 for every other kind.
int32_t kind
A DAEGUN_PAINT_ code: which paint this is, and so which of the other fields to read.
int32_t extend
For the three gradient kinds: a DAEGUN_EXTEND_ code, how the colors go on past the first and last stop.
int32_t mode
For DAEGUN_PAINT_COMPOSITE: a DAEGUN_COMPOSITE_ code, how the source combines with the backdrop. A mode the font numbers past the last of them reads as DAEGUN_COMPOSITE_CLEAR.
daegun_rgba color
For DAEGUN_PAINT_SOLID: the palette's color, with its alpha scaled by the paint's own alpha. Where foreground is true it is black at that alpha.
bool foreground
For DAEGUN_PAINT_SOLID: true where the paint takes the text's color in place of color, with the text color's alpha scaled by the alpha in color.
bool has_center
For DAEGUN_PAINT_SCALE, DAEGUN_PAINT_SCALE_UNIFORM, DAEGUN_PAINT_ROTATE and DAEGUN_PAINT_SKEW: whether center is set. Where it is false the transform is about the origin.
  • Size: 112 bytes on a 64-bit target.
daegun_paint_graph
typedef struct daegun_paint_graph daegun_paint_graph;

A COLR version 1 glyph's paint graph: every paint the glyph is drawn with, and the stops of its gradients.

An opaque handle. daegun_font_paint_graph makes one, daegun_paint_graph_nodes and daegun_paint_graph_stops read it, and daegun_paint_graph_free frees it.

COLR version 1 describes a color glyph as a tree of paints: fills, gradients, clips to an outline, transforms and composites. The graph is that tree as the font states it, laid out in one array, for a renderer that wants to work the paints itself. For the same glyph as fills ready to draw, use daegun_font_color_scene.

A graph comes only from a font: C has no call to build one by hand. It holds its own copy of what it read, so it may outlive the font, and nothing changes it once made, so several threads may read one at the same time.

daegun_paint_graph *graph = NULL;
if (daegun_font_paint_graph(font, 8, NULL, 0, &graph) != DAEGUN_OK) return 1;

size_t count = 0;
const daegun_paint_node *nodes = daegun_paint_graph_nodes(graph, &count);
for (size_t i = 0; i < count; i++) {
    switch (nodes[i].kind) {
    case DAEGUN_PAINT_GLYPH:
        /* Clip to the outline of nodes[i].glyph, then paint the child. */
        break;
    case DAEGUN_PAINT_LINEAR_GRADIENT:
        /* Fill the clip with the gradient that nodes[i].values lays out. */
        break;
    default:
        break;
    }
}
/* Glyph 8 is 2 paints: its own outline as the clip, and a linear gradient inside it. */

daegun_paint_graph_free(graph);
daegun_paint_visitor
typedef struct {
    void (*enter)(void *user, const daegun_paint_node *node, const daegun_color_stop *stops, size_t stops_count);
    void (*leave)(void *user);
    void *user;
} daegun_paint_visitor;

The callbacks daegun_font_visit_paint_graph runs as it walks a glyph's paints: one on entering a paint and one on leaving it.

Set the functions you want and pass the struct to daegun_font_visit_paint_graph. The walk enters a paint, goes through its children, then leaves it, so the calls nest like brackets and every enter is matched by a leave. Children come in the order of daegun_paint_graph_nodes: layers from the bottom up, and a composite's source before its backdrop. Either callback may be NULL, and a NULL one is skipped.

enter is handed your user pointer, the paint, and for a gradient its stops with their count. For any other paint, and for a gradient with no stops, stops is NULL and the count 0. The paint and the stops are lent for that one call, so copy what you need before you return. No graph is built, so the paint's end and stops_start are 0, and its stops_count is the count handed in. leave is handed user alone.

Both run on the thread that called daegun_font_visit_paint_graph, before that call returns, and daegun keeps nothing of the struct afterward. A callback must return normally: a longjmp or a C++ exception out of one is undefined behavior, as is ending the thread inside one. A callback may call back into daegun, on the same font too, as no lock is held while it runs.

Under MSVC each callback has C's calling convention, which DAEGUN_CALLBACK names.

struct nesting {
    size_t now, deepest;
};

static void DAEGUN_CALLBACK on_enter(void *user, const daegun_paint_node *node,
                                     const daegun_color_stop *stops, size_t stops_count)
{
    struct nesting *nest = user;
    if (++nest->now > nest->deepest) nest->deepest = nest->now;
    /* node->kind says which paint this is. For a gradient, `stops` holds `stops_count` stops. */
    (void)node;
    (void)stops;
    (void)stops_count;
}

static void DAEGUN_CALLBACK on_leave(void *user)
{
    struct nesting *nest = user;
    nest->now--;
}

struct nesting nest = { 0, 0 };
daegun_paint_visitor visitor = { on_enter, on_leave, &nest };
if (daegun_font_visit_paint_graph(font, 84, NULL, 0, &visitor) != DAEGUN_OK) return 1;
/* Glyph 84's paints nest 4 deep, and every enter was matched by a leave. */
void (*enter)(void *user, const daegun_paint_node *node, const daegun_color_stop *stops, size_t stops_count)
Called as the walk reaches a paint, before its children. It is handed user, the paint, and the stops of a gradient with their count, or NULL and 0 for any other paint and for a gradient with no stops. NULL to skip it.
void (*leave)(void *user)
Called once a paint's children have all been walked. It is handed user alone, and closes the last paint entered and not yet left. NULL to skip it.
void *user
Passed to both callbacks as their first argument. daegun never reads it, so it may be NULL.

Math

daegun/mathtable.h: the MATH table, for setting formulas. Its constants, each glyph's italic correction and kerning, and the larger variants and assemblies a stretched glyph is built from, in font units at a location.

daegun_math_constants
typedef struct {
    double script_percent_scale_down;
    double script_script_percent_scale_down;
    double delimited_sub_formula_min_height;
    double display_operator_min_height;
    double math_leading;
    double axis_height;
    double accent_base_height;
    double flattened_accent_base_height;
    double subscript_shift_down;
    double subscript_top_max;
    double subscript_baseline_drop_min;
    double superscript_shift_up;
    double superscript_shift_up_cramped;
    double superscript_bottom_min;
    double superscript_baseline_drop_max;
    double sub_superscript_gap_min;
    double superscript_bottom_max_with_subscript;
    double space_after_script;
    double upper_limit_gap_min;
    double upper_limit_baseline_rise_min;
    double lower_limit_gap_min;
    double lower_limit_baseline_drop_min;
    double stack_top_shift_up;
    double stack_top_display_style_shift_up;
    double stack_bottom_shift_down;
    double stack_bottom_display_style_shift_down;
    double stack_gap_min;
    double stack_display_style_gap_min;
    double stretch_stack_top_shift_up;
    double stretch_stack_bottom_shift_down;
    double stretch_stack_gap_above_min;
    double stretch_stack_gap_below_min;
    double fraction_numerator_shift_up;
    double fraction_numerator_display_style_shift_up;
    double fraction_denominator_shift_down;
    double fraction_denominator_display_style_shift_down;
    double fraction_numerator_gap_min;
    double fraction_num_display_style_gap_min;
    double fraction_rule_thickness;
    double fraction_denominator_gap_min;
    double fraction_denom_display_style_gap_min;
    double skewed_fraction_horizontal_gap;
    double skewed_fraction_vertical_gap;
    double overbar_vertical_gap;
    double overbar_rule_thickness;
    double overbar_extra_ascender;
    double underbar_vertical_gap;
    double underbar_rule_thickness;
    double underbar_extra_descender;
    double radical_vertical_gap;
    double radical_display_style_vertical_gap;
    double radical_rule_thickness;
    double radical_extra_ascender;
    double radical_kern_before_degree;
    double radical_kern_after_degree;
    double radical_degree_bottom_raise_percent;
} daegun_math_constants;

A math font's constants: the distances and percentages that say where each piece of a formula goes.

These are the numbers a font designer sets for formulas in their font: how far to raise a superscript, how thick to draw a fraction bar, how much room to leave over a root. A math layout reads them rather than guessing, so that a formula suits the font it is set in. daegun_font_math_constants fills one, every field of it.

All but three fields are distances in font units, so a distance in pixels is the value times the pixel size over the font's units per em, which daegun_font_units_per_em gives. The three are percentages: script_percent_scale_down, script_script_percent_scale_down and radical_degree_bottom_raise_percent. A height is measured up from the baseline, and a shift or a drop downward is a positive number. A value that places one element against a base, such as the shift of a superscript, is taken from the font of the base and scaled by the size of the base.

At a location of a variable font, each distance has its variation delta added and is not rounded, so it may carry a fraction. Five fields are plain numbers in the table and are the same at every location: the three percentages, delimited_sub_formula_min_height and display_operator_min_height.

Two terms come up in the fields. Display style is how a formula is set on a line of its own, with more room than one inside a paragraph. Cramped style is the tighter setting used where something lies overhead, as under a root sign or in a denominator.

The fields are named as the OpenType MATH table names its constants, and come in its order: 56 doubles and nothing else. It is a result, not an options struct, so it has no size field and no _default call.

daegun_math_constants constants;
if (daegun_font_math_constants(font, NULL, &constants) != DAEGUN_OK) return 1;
uint16_t upem = 0;
if (daegun_font_units_per_em(font, &upem) != DAEGUN_OK) return 1;

/* A superscript on text of 20 px: the size to set it at, and how far to raise its baseline. */
double px = 20.0;
double script_px = px * constants.script_percent_scale_down / 100.0;
double raise_px = constants.superscript_shift_up * px / upem;
/* STIX Two Math sets scripts at 70 percent and raises them 360 units: 14 px text, 7.2 px up. */
double script_percent_scale_down
The size to set a first-level script at, as a percentage of the size of the text it is attached to. A superscript or subscript on ordinary formula text is first level, and 70 means 70 percent. A percentage, not font units.
double script_script_percent_scale_down
The size to set a second-level script at, a script on a script, as a percentage. A percentage, not font units.
double delimited_sub_formula_min_height
The least height, in font units, of an expression inside delimiters such as parentheses for it to be treated as a sub-formula that the delimiters grow around.
double display_operator_min_height
The least height, in font units, of a big operator such as a sum or an integral in display style.
double math_leading
The white space, in font units, to leave between the bottom of one line of math and the top of the next, so that formulas set one under another keep their spacing.
double axis_height
How far the math axis lies above the baseline, in font units. The axis is the horizontal line that a minus sign, a fraction bar and a big operator are centered on.
double accent_base_height
The tallest a base may be, in font units, for an accent to sit over it at the height the font drew the accent. Over a taller base the accent has to be raised.
double flattened_accent_base_height
The tallest a base may be, in font units, and still take the ordinary form of an accent. A taller base takes the flattened form, a shallower drawing that some fonts keep for accents over capitals.
double subscript_shift_down
How far a subscript's baseline is set below the baseline of its base, in font units. Positive is down.
double subscript_top_max
The highest the top of a subscript may reach above the baseline, in font units. A subscript that would reach higher is moved further down.
double subscript_baseline_drop_min
The least distance, in font units, that a subscript's baseline is dropped below the bottom of its base. It is checked for a base that is a box or an extended shape, such as a tall delimiter.
double superscript_shift_up
How far a superscript's baseline is set above the baseline of its base, in font units.
double superscript_shift_up_cramped
How far a superscript's baseline is set above the baseline of its base in cramped style, in font units. It takes the place of superscript_shift_up there.
double superscript_bottom_min
The lowest the bottom of a superscript may sit above the baseline, in font units. A superscript that would sit lower is moved further up.
double superscript_baseline_drop_max
The most, in font units, that a superscript's baseline may lie below the top of its base. It is checked for a base that is a box or an extended shape, so that a superscript on a tall delimiter stays near its top.
double sub_superscript_gap_min
The least gap, in font units, between the bottom of a superscript and the top of a subscript on the same base.
double superscript_bottom_max_with_subscript
How high above the baseline, in font units, the bottom of a superscript may be pushed to open the gap to a subscript below it. Past that, the subscript is moved down instead.
double space_after_script
Extra white space, in font units, added after every superscript and subscript that follows its base, and before every one that is set before its base.
double upper_limit_gap_min
The least gap, in font units, between the bottom of an upper limit and the top of its operator. A limit is an expression set over or under a big operator, as the bounds of a sum are.
double upper_limit_baseline_rise_min
The least distance, in font units, from the top of an operator up to the baseline of its upper limit.
double lower_limit_gap_min
The least gap, in font units, between the top of a lower limit and the bottom of its operator.
double lower_limit_baseline_drop_min
The least distance, in font units, from the bottom of an operator down to the baseline of its lower limit.
double stack_top_shift_up
How far the baseline of a stack's top element is set above the baseline, in font units. A stack is one expression over another with no bar between, as in a binomial coefficient.
double stack_top_display_style_shift_up
How far the baseline of a stack's top element is set above the baseline in display style, in font units.
double stack_bottom_shift_down
How far the baseline of a stack's bottom element is set below the baseline, in font units. Positive is down.
double stack_bottom_display_style_shift_down
How far the baseline of a stack's bottom element is set below the baseline in display style, in font units. Positive is down.
double stack_gap_min
The least gap, in font units, between the bottom of a stack's top element and the top of its bottom element.
double stack_display_style_gap_min
The least gap between the two elements of a stack in display style, in font units.
double stretch_stack_top_shift_up
How far the element set over a stretched glyph is shifted up from the baseline, in font units. A stretch stack is a stretched glyph, such as a long arrow or a brace, with an expression over or under it.
double stretch_stack_bottom_shift_down
How far the element set under a stretched glyph is shifted down from the baseline, in font units. Positive is down.
double stretch_stack_gap_above_min
The least gap, in font units, between a stretched glyph and the bottom of the element set over it.
double stretch_stack_gap_below_min
The least gap, in font units, between a stretched glyph and the top of the element set under it.
double fraction_numerator_shift_up
How far a numerator's baseline is set above the baseline of its fraction, in font units.
double fraction_numerator_display_style_shift_up
How far a numerator's baseline is set above the baseline of its fraction in display style, in font units.
double fraction_denominator_shift_down
How far a denominator's baseline is set below the baseline of its fraction, in font units. Positive is down.
double fraction_denominator_display_style_shift_down
How far a denominator's baseline is set below the baseline of its fraction in display style, in font units. Positive is down.
double fraction_numerator_gap_min
The least gap, in font units, between the bottom of a numerator and the fraction bar.
double fraction_num_display_style_gap_min
The least gap between the bottom of a numerator and the fraction bar in display style, in font units.
double fraction_rule_thickness
How thick the fraction bar is, in font units.
double fraction_denominator_gap_min
The least gap, in font units, between the fraction bar and the top of a denominator.
double fraction_denom_display_style_gap_min
The least gap between the fraction bar and the top of a denominator in display style, in font units.
double skewed_fraction_horizontal_gap
The horizontal distance, in font units, between the numerator and the denominator of a skewed fraction: one set on a slant, the numerator raised before a slash and the denominator lowered after it.
double skewed_fraction_vertical_gap
The vertical distance, in font units, between the numerator and the denominator of a skewed fraction.
double overbar_vertical_gap
The gap, in font units, between an overbar and the top of the expression it is drawn over.
double overbar_rule_thickness
How thick an overbar is, in font units.
double overbar_extra_ascender
White space, in font units, kept clear above an overbar.
double underbar_vertical_gap
The gap, in font units, between an underbar and the bottom of the expression it is drawn under.
double underbar_rule_thickness
How thick an underbar is, in font units.
double underbar_extra_descender
White space, in font units, kept clear below an underbar.
double radical_vertical_gap
The gap, in font units, between the top of the expression under a root sign and the bar over it.
double radical_display_style_vertical_gap
The gap between the top of the expression under a root sign and the bar over it in display style, in font units.
double radical_rule_thickness
How thick the bar over a root is, in font units, which is the thickness of the bar drawn into the root sign glyphs.
double radical_extra_ascender
White space, in font units, kept clear above the bar of a root.
double radical_kern_before_degree
Horizontal space, in font units, added before the degree of a root. The degree is the small index, as the 3 of a cube root.
double radical_kern_after_degree
Horizontal space, in font units, added after the degree of a root. It is normally negative, which draws the root sign back under the degree.
double radical_degree_bottom_raise_percent
How high the bottom of a root's degree is raised, as a percentage of the height of the root sign. A percentage, not font units.
  • Size: 56 bytes * sizeof(double).
daegun_math_variant
typedef struct {
    uint32_t glyph;
    double advance;
} daegun_math_variant;

One ready-made size of a glyph that stretches: the glyph to draw, and how much it covers along the stretch.

A variant is a glyph in its own right, with its own outline and metrics, so you draw it as you would any glyph. advance is what you compare with the size you need. daegun_math_construction_variants lends an array of them, in the order the font lists them.

uint32_t paren = 0;
if (daegun_font_glyph_id(font, '(', &paren) != DAEGUN_OK) return 1;
daegun_math_construction *stretch = NULL;
if (daegun_font_math_glyph_variants(font, paren, NULL, DAEGUN_VERTICAL, &stretch) != DAEGUN_OK) return 1;

size_t count = 0;
const daegun_math_variant *variants = daegun_math_construction_variants(stretch, &count);
for (size_t i = 0; i < count; i++) {
    daegun_math_variant size = variants[i];
    /* size.glyph draws the parenthesis size.advance units tall. */
}
/* STIX Two Math draws 13 sizes: the parenthesis itself, 933 units tall, up to one of 3821. */

daegun_math_construction_free(stretch);
uint32_t glyph
The id of the glyph that draws this size.
double advance
How much the glyph covers along the direction of the stretch, in font units: its height for a vertical stretch, its width for a horizontal one. It is the same at every location.
  • Size: 16 bytes on a 64-bit target.
daegun_glyph_part
typedef struct {
    uint32_t glyph;
    double start_connector_length;
    double end_connector_length;
    double full_advance;
    bool extender;
} daegun_glyph_part;

One part of a glyph assembly: the glyph to draw, how long it is along the stretch, and how much of each end may overlap its neighbor.

A part is an ordinary glyph of the font, drawn like any other. What this adds is how parts join. Each end of a part has a connector, a length of plain straight stroke that can lie over the connector of the neighboring part without changing the shape.

The three lengths are in font units, measured along the direction of the stretch: heights in a vertical assembly, widths in a horizontal one. They are the same at every location. The parts come as the parts array of a daegun_glyph_assembly, which says how to lay them.

uint32_t paren = 0;
if (daegun_font_glyph_id(font, '(', &paren) != DAEGUN_OK) return 1;
daegun_math_construction *stretch = NULL;
if (daegun_font_math_glyph_variants(font, paren, NULL, DAEGUN_VERTICAL, &stretch) != DAEGUN_OK) return 1;
/* Preset empty: where the font gives no parts the call leaves it so, and the loop does nothing. */
daegun_glyph_assembly assembly = { 0.0, NULL, 0 };
bool has_parts = daegun_math_construction_assembly(stretch, &assembly) == DAEGUN_OK;

for (size_t i = 0; i + 1 < assembly.parts_len; i++) {
    const daegun_glyph_part *below = &assembly.parts[i], *above = &assembly.parts[i + 1];
    /* The overlap where these two join can be no more than the shorter of the connectors
       that meet there. */
    double most = fmin(below->end_connector_length, above->start_connector_length);
}
/* STIX Two Math builds a parenthesis from three parts, bottom to top: the lower hook, a
   straight piece that may repeat, and the upper hook. Each join allows up to 250 units. */

daegun_math_construction_free(stretch);
uint32_t glyph
The id of the glyph to draw for this part.
double start_connector_length
The length of connector at the start of the part, its bottom or left end. The part before may overlap this one by up to that much.
double end_connector_length
The length of connector at the end of the part, its top or right end. The part after may overlap this one by up to that much.
double full_advance
The whole length of the part along the stretch. Laid with no overlap, the part would take this much.
bool extender
True for a part that may be left out, or repeated any number of times, to reach the size. False for a part that is used exactly once.
  • Size: 40 bytes on a 64-bit target.
daegun_glyph_assembly
typedef struct {
    double italics_correction;
    const daegun_glyph_part *parts;
    size_t parts_len;
} daegun_glyph_assembly;

How to build a stretched glyph of any size from parts.

Where a glyph has to be larger than any ready-made variant, a math font gives parts to join: for a parenthesis, a bottom hook, a top hook and a straight piece to go between them. daegun_math_construction_assembly fills one of these from a construction, or answers DAEGUN_ABSENT where the font gives the glyph ready-made sizes only.

Lay the parts one after another along the direction of the stretch, in the order given: from the bottom up for a vertical glyph, from the left for a horizontal one. A part marked extender may be left out or repeated as often as needed, and every other part is used exactly once. Where there are several extenders, as in a brace, repeat each the same number of times. Each part starts where the one before it ends, less the overlap between the two.

The overlap at a join is yours to choose, within limits. It is at least what daegun_font_math_min_connector_overlap gives, and at most the shorter of the two connectors that meet there: the end_connector_length of the first part and the start_connector_length of the next. So, for a size you need, take the fewest extenders whose longest build reaches it, then widen the overlaps evenly until the build comes down to that size.

parts is borrowed. It points into the daegun_math_construction the assembly was read from and is valid until that handle goes to daegun_math_construction_free. Don't free it, and copy the parts if you need them longer.

uint32_t paren = 0;
if (daegun_font_glyph_id(font, '(', &paren) != DAEGUN_OK) return 1;
double overlap = 0.0;
if (daegun_font_math_min_connector_overlap(font, &overlap) != DAEGUN_OK) return 1;

daegun_math_construction *stretch = NULL;
if (daegun_font_math_glyph_variants(font, paren, NULL, DAEGUN_VERTICAL, &stretch) != DAEGUN_OK) return 1;
/* Preset empty: where the font gives no parts the call leaves it so, and the loop does nothing. */
daegun_glyph_assembly assembly = { 0.0, NULL, 0 };
bool has_parts = daegun_math_construction_assembly(stretch, &assembly) == DAEGUN_OK;

/* Lay each part once, bottom to top, each over the one before by the least overlap. */
double y = 0.0;
for (size_t i = 0; i < assembly.parts_len; i++) {
    if (i > 0) y -= overlap;
    /* assembly.parts[i].glyph goes at y along the stretch. */
    y += assembly.parts[i].full_advance;
}
/* The three parts of the STIX Two Math parenthesis, laid this way, come to 3598 units. */

daegun_math_construction_free(stretch);
double italics_correction
The italic correction of the built glyph, in font units, whatever size it is built to. Use it as you would the answer of daegun_font_math_italics_correction for a single glyph. It is the one value here that follows the location.
const daegun_glyph_part *parts
The parts in the order they are laid: from the bottom for a vertical stretch, from the left for a horizontal one. An array of parts_len entries, borrowed from the construction.
size_t parts_len
How many parts the array holds.
  • Size: 24 bytes on a 64-bit target.
daegun_math_construction
typedef struct daegun_math_construction daegun_math_construction;

How one glyph stretches in one direction: its ready-made sizes, and the parts to build it larger.

An opaque handle that daegun_font_math_glyph_variants makes. daegun_math_construction_variants lends its ready-made sizes and daegun_math_construction_assembly its parts. Try the sizes first: each is a whole glyph the designer drew at that size, so it looks best. Go to the parts for a size past the largest. A font may give a glyph sizes alone, parts alone or both.

The handle is yours: free it with daegun_math_construction_free. The array of sizes and the parts of an assembly are borrowed from it and stay valid until then. It holds its own copy of what it read, so it does not depend on the font and may be freed before or after it.

Nothing writes to a construction once it is made, so several threads may read one at the same time.

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

daegun_math_construction *stretch = NULL;
if (daegun_font_math_glyph_variants(font, brace, NULL, DAEGUN_VERTICAL, &stretch) != DAEGUN_OK) return 1;

size_t count = 0;
const daegun_math_variant *variants = daegun_math_construction_variants(stretch, &count);
daegun_glyph_assembly assembly = { 0.0, NULL, 0 };
bool has_parts = daegun_math_construction_assembly(stretch, &assembly) == DAEGUN_OK;
/* STIX Two Math draws 13 sizes of the brace, the first of them the brace itself, and gives
   five parts to go past the largest. */

/* `variants` and `assembly.parts` point into the handle, so this ends them too. */
daegun_math_construction_free(stretch);

Tables

daegun/tables.h: subsetting with its glyph closure, BASE baselines and extents, and the scripts, language systems and features a font's GSUB and GPOS tables offer.

daegun_subset
typedef struct daegun_subset daegun_subset;

A subset font: the bytes of a smaller font file, and where each glyph of the source font went in it.

An opaque handle. daegun_font_subset and daegun_font_subset_text make one, daegun_subset_bytes lends its font file, daegun_subset_renumbered maps a glyph id of the source font to its id in the subset, and daegun_subset_free frees it.

The file is a complete font in the flavor of its source: TrueType outlines stay TrueType, and CFF or CFF2 outlines stay what they were. It is static. It holds one location of a variable font, the one the call was given, and no variation tables.

A subset borrows nothing from the font it was cut from, so either may be freed first. It is read-only once made, so any number of threads may read one at the same time.

/* Inter at weight 700. */
daegun_coord coords[] = { { DAEGUN_TAG('w', 'g', 'h', 't'), 700.0 } };
daegun_location *bold = NULL;
if (daegun_font_location(font, coords, 1, &bold) != DAEGUN_OK) return 1;

daegun_subset *subset = NULL;
if (daegun_font_subset_text(font, "Wave", 4, bold, &subset) != DAEGUN_OK) return 1;
daegun_location_free(bold);

size_t size = 0;
const uint8_t *file = daegun_subset_bytes(subset, &size);
/* `file` is a font file of `size` bytes, borrowed from the subset. Opening it copies it,
   so the subset can go once the font is open. */
daegun_font *small = NULL;
if (daegun_font_open(file, size, &small) != DAEGUN_OK) return 1;
daegun_subset_free(subset);

/* It is a static font: Inter at weight 700 and nowhere else. */
bool variable = true;
if (daegun_font_is_variable(small, &variable) != DAEGUN_OK) return 1;
daegun_font_free(small);
daegun_baseline
typedef struct {
    daegun_tag tag;
    double position;
} daegun_baseline;

One baseline of a script: its tag, and where it lies.

daegun_base_script_baselines lends an array of these. A baseline is named by a four-letter tag: romn for the roman baseline Latin letters stand on, ideo and idtp for the bottom and top of the ideographic em box, icfb and icft for the bottom and top of the ideographic character face, hang for the hanging baseline and math for the line math is centered on.

The position is in font units: a y value where the baselines were asked for with DAEGUN_HORIZONTAL, and an x value with DAEGUN_VERTICAL.

daegun_tag kana = DAEGUN_TAG('k', 'a', 'n', 'a');
daegun_base_script *script = NULL;
if (daegun_font_base_script(font, kana, NULL, DAEGUN_VERTICAL, &script) != DAEGUN_OK) return 1;

size_t count = 0;
const daegun_baseline *baselines = daegun_base_script_baselines(script, &count);
double roman_x = 0.0;
for (size_t i = 0; i < count; i++) {
    /* Each position is an x value, as the line is vertical. */
    if (baselines[i].tag == DAEGUN_TAG('r', 'o', 'm', 'n')) roman_x = baselines[i].position;
}
/* Source Han Sans gives kana four, in tag order: icfb 53, icft 947, ideo 0 and romn 120. */
if (roman_x != 120.0) return 1;

daegun_base_script_free(script);
daegun_tag tag
The baseline's tag, as DAEGUN_TAG('r', 'o', 'm', 'n').
double position
Where the baseline lies, in font units: y for horizontal text, x for vertical text.
  • Size: 16 bytes on a 64-bit target.
daegun_base_script
typedef struct daegun_base_script daegun_base_script;

A script's baselines along one orientation, as the font's BASE table gives them.

An opaque handle. daegun_font_base_script makes one, daegun_base_script_baselines lends its baselines, daegun_base_script_default_baseline names the one the script's glyphs sit on, and daegun_base_script_free frees it.

To line up text of two scripts, or of one script at two sizes, pick a baseline tag, most often the default baseline of the line's main script, and shift each run so that its position for that tag lands on the same line. Positions are in font units, so scale each by the size its run is set at.

It holds its own copy of what the font gave, so it may outlive the font.

daegun_base_script *han = NULL;
daegun_tag hani = DAEGUN_TAG('h', 'a', 'n', 'i');
if (daegun_font_base_script(font, hani, NULL, DAEGUN_HORIZONTAL, &han) != DAEGUN_OK) return 1;

daegun_tag sits_on = 0;
if (daegun_base_script_default_baseline(han, &sits_on) != DAEGUN_OK) return 1;
size_t count = 0;
const daegun_baseline *baselines = daegun_base_script_baselines(han, &count);
double position = 0.0;
for (size_t i = 0; i < count; i++) {
    if (baselines[i].tag == sits_on) position = baselines[i].position;
}
/* Han characters sit on the ideographic baseline, which Source Han Sans puts at -120. */
if (position != -120.0) return 1;

daegun_base_script_free(han);
daegun_extents
typedef struct {
    double min;
    double max;
    bool has_min;
    bool has_max;
} daegun_extents;

How far a script's glyphs reach to either side of the line, as the font's BASE table states it.

What daegun_font_base_extents fills. For horizontal text min is the lowest y the glyphs reach and max the highest. For vertical text they are the leftmost and the rightmost x. Both are in font units, in the glyphs' own coordinates, so a min below the baseline is negative.

A font may state one side and not the other, so each has a flag. Read min only where has_min is true, and max only where has_max is. A side the font leaves out is written as 0.

daegun_tag hani = DAEGUN_TAG('h', 'a', 'n', 'i');
daegun_extents extents = { 0.0, 0.0, false, false };
daegun_status status = daegun_font_base_extents(font, hani, NULL, DAEGUN_HORIZONTAL, 0, 0, &extents);
if (status != DAEGUN_OK && status != DAEGUN_ABSENT) return 1;

/* Take each side from BASE where it states one, and from the font's line metrics where not.
   DAEGUN_ABSENT leaves the struct as it was, with both flags false. */
double bottom = 0.0, top = 0.0;
if (daegun_font_descender(font, NULL, &bottom) != DAEGUN_OK) return 1;
if (daegun_font_ascender(font, NULL, &top) != DAEGUN_OK) return 1;
if (extents.has_min) bottom = extents.min;
if (extents.has_max) top = extents.max;
/* Source Han Sans states no extents for Han, so these are its descender and ascender:
   -288 and 1160. */
double min
The lowest point the glyphs reach: a y value in horizontal text, the leftmost x in vertical text. 0 where has_min is false.
double max
The highest point the glyphs reach: a y value in horizontal text, the rightmost x in vertical text. 0 where has_max is false.
bool has_min
Whether the font states a minimum, so that min holds one.
bool has_max
Whether the font states a maximum, so that max holds one.
  • Size: 24 bytes on a 64-bit target.

Raw tables

daegun/raw.h: font data at the byte level, for tools that read or write a table daegun has no call for. Bounds-checked reads and writes, the structures several tables share, loca and glyf, and building a font file from its tables.

daegun_aat_lookup
typedef struct daegun_aat_lookup daegun_aat_lookup;

An AAT lookup table read from bytes you hold: the map from glyph to 16-bit value that Apple's tables are built on.

Apple's tables, morx, kerx, ankr and the rest, keep their maps from glyph to value as lookup tables, in one of six formats: 0, a value for every glyph; 2, ranges of glyphs that share a value; 4, ranges with an array of values each; 6, single glyphs with a value each; 8, a value for each glyph of a run from a first glyph on; and 10, the same with values of 1, 2, 4 or 8 bytes. What a value means is the table's business: a class, a glyph to put in another's place, an offset.

An opaque handle. daegun_aat_lookup_parse makes one, daegun_aat_lookup_value asks for one glyph's value, daegun_aat_lookup_entries lists them all, and daegun_aat_lookup_free frees it.

The handle keeps a copy of the bytes it was made from, so they may go as soon as the parse returns, and reads its copy again on each call. Every call takes it as const, so threads may share one.

/* TestMORXOne's morx holds one chain of one subtable, of type 4: a lookup from glyph to glyph. Its body
   follows the table's 8-byte header, the chain's 16, 12 for each of the chain's features and the
   subtable's own 12. */
daegun_bytes morx;
if (daegun_font_table(font, DAEGUN_TAG('m', 'o', 'r', 'x'), &morx) != DAEGUN_OK) return 1;
uint32_t features = 0, glyphs = 0;
if (daegun_read_u32_be(morx.data, morx.len, 16, &features) != DAEGUN_OK) return 1;
if (daegun_font_glyph_count(font, &glyphs) != DAEGUN_OK) return 1;
size_t body = 8 + 16 + 12 * (size_t)features + 12;

daegun_aat_lookup *lookup = NULL;
if (daegun_aat_lookup_parse(morx.data + body, morx.len - body, glyphs, &lookup) != DAEGUN_OK) return 1;
uint16_t value = 0;
if (daegun_aat_lookup_value(lookup, 2, &value) != DAEGUN_OK) return 1;
/* The font puts glyph 5 in place of glyph 2. */
daegun_aat_lookup_free(lookup);
daegun_aat_entry
typedef struct {
    uint16_t new_state;
    uint16_t flags;
    uint16_t word1;
    uint16_t word2;
} daegun_aat_entry;

One entry of an AAT state table: the state to go to next, the entry's flags and up to two extra words.

daegun_aat_state_table_entry fills one. Each cell of a state table, a state and a class, names an entry, and many cells share one. The struct is four 16-bit words, 8 bytes.

The flags and the extra words mean what the subtable's type says they mean. In every type of morx subtable, flag 0x4000 tells the machine not to advance, so it handles the same glyph again in the new state. In contextual and insertion subtables an extra word of 0xFFFF means no action.

/* The ligature subtable of this test font, found as daegun_aat_state_table shows. */
daegun_bytes morx;
if (daegun_font_table(font, DAEGUN_TAG('m', 'o', 'r', 'x'), &morx) != DAEGUN_OK) return 1;
uint32_t features = 0, glyphs = 0;
if (daegun_read_u32_be(morx.data, morx.len, 16, &features) != DAEGUN_OK) return 1;
if (daegun_font_glyph_count(font, &glyphs) != DAEGUN_OK) return 1;
size_t body = 8 + 16 + 12 * (size_t)features + 12;
daegun_aat_state_table *table = NULL;
if (daegun_aat_state_table_parse(morx.data + body, morx.len - body, 1, glyphs, &table) != DAEGUN_OK) return 1;

daegun_aat_entry entry;
if (daegun_aat_state_table_entry(table, DAEGUN_AAT_STATE_START_OF_TEXT, 6, &entry) != DAEGUN_OK) return 1;
/* new_state 0, flags 0xA000: add the glyph to the components and perform the action, whose index,
   word1, is 0. word2 is 0, as ligature entries carry one word. */
daegun_aat_state_table_free(table);
uint16_t new_state
The state the machine is in for the next glyph. DAEGUN_AAT_STATE_START_OF_TEXT, 0, is the one it started in.
uint16_t flags
The flags, whose bits each subtable type defines. In a ligature subtable, 0x8000 adds the glyph to the components and 0x2000 performs the ligature action.
uint16_t word1
The first extra word, 0 for a table parsed with extra_words of 0. In a ligature subtable it is the index of the first ligature action, in a contextual one the index of the substitution table for the marked glyph, and in an insertion one the index of the glyphs to insert at the current glyph.
uint16_t word2
The second extra word, 0 for a table parsed with fewer than 2. In a contextual subtable it is the index of the substitution table for the current glyph, and in an insertion one the index of the glyphs to insert at the marked glyph.
  • Size: 8 bytes.
daegun_aat_state_table
typedef struct daegun_aat_state_table daegun_aat_state_table;

An extended AAT state table: the small machine a morx subtable runs over the glyphs of a line.

Four of morx's subtable types, rearrangement, contextual, ligature and insertion, are state machines, and so are some kerx subtables. A machine walks the glyphs in order. A class table sorts each glyph into a class, and the machine is always in a state. For each glyph it takes the cell for its state and the glyph's class, which names an entry: the state to go to, flags saying what to do, and for most types one or two extra words that point into the subtable's own tables of actions.

Run one by hand as a loop. Start in DAEGUN_AAT_STATE_START_OF_TEXT. For each glyph, take its class with daegun_aat_state_table_class and the entry with daegun_aat_state_table_entry, act on the entry and go to its new_state. After the last glyph, take the entry for DAEGUN_AAT_CLASS_END_OF_TEXT.

An opaque handle. daegun_aat_state_table_parse makes one and daegun_aat_state_table_free frees it. It keeps a copy of the bytes it was made from and reads its copy again on each call. Every call takes it as const, so threads may share one.

/* The test font's one subtable is a ligature machine. Its state table follows the 8-byte morx header,
   the chain's 16, 12 for each feature and the subtable's own 12. Ligature entries carry 1 extra word. */
daegun_bytes morx;
if (daegun_font_table(font, DAEGUN_TAG('m', 'o', 'r', 'x'), &morx) != DAEGUN_OK) return 1;
uint32_t features = 0, glyphs = 0;
if (daegun_read_u32_be(morx.data, morx.len, 16, &features) != DAEGUN_OK) return 1;
if (daegun_font_glyph_count(font, &glyphs) != DAEGUN_OK) return 1;
size_t body = 8 + 16 + 12 * (size_t)features + 12;
daegun_aat_state_table *table = NULL;
if (daegun_aat_state_table_parse(morx.data + body, morx.len - body, 1, glyphs, &table) != DAEGUN_OK) return 1;

/* Run it over glyphs 2, 3 and 4, then the end of text, counting the entries that perform an action. */
const uint32_t run[3] = { 2, 3, 4 };
uint16_t state = DAEGUN_AAT_STATE_START_OF_TEXT;
size_t acted_at = 9;
for (size_t i = 0; i <= 3; i++) {
    uint16_t class_id = DAEGUN_AAT_CLASS_END_OF_TEXT;
    if (i < 3 && daegun_aat_state_table_class(table, run[i], &class_id) != DAEGUN_OK) return 1;
    daegun_aat_entry entry;
    if (daegun_aat_state_table_entry(table, state, class_id, &entry) != DAEGUN_OK) return 1;
    if (entry.flags & 0x2000) acted_at = i;
    state = entry.new_state;
}
/* The entry for glyph 4, the third, performs the ligature action. */
daegun_aat_state_table_free(table);
daegun_ankr
typedef struct daegun_ankr daegun_ankr;

Apple's anchor point table, ankr: for each glyph, a list of points that marks attach by.

A kerx subtable of format 4 may attach a mark to a base by naming a point on each, by its index in the glyph's list here, and moves the mark so the two meet. Each point is an x and a y in font units, y up.

The table opens with a 16-bit version and flags, then two 32-bit offsets: of an AAT lookup table, like daegun_aat_lookup, that maps each glyph to where its points start in the glyph data, and of that glyph data. A glyph's points are a 32-bit count, then 4 bytes for each point.

An opaque handle. daegun_ankr_parse makes one, daegun_ankr_point_count and daegun_ankr_anchor_point read it, and daegun_ankr_free frees it. daegun_ankr_version and daegun_ankr_control_point read bytes with no handle. The handle keeps a copy of the bytes it was made from and reads it again on each call. Every call takes it as const, so threads may share one.

/* No bundled font has ankr, so this one is built by hand, for three glyphs. Its header: version and
   flags, then the lookup at 12 and the glyph data at 20. The lookup, format 0, puts glyph 1's points at 0
   in the glyph data and the others' at 12. Glyph 1 has two points, the others none. */
static const uint8_t bytes[36] = {
    0, 0, 0, 0, 0, 0, 0, 12, 0, 0, 0, 20,
    0, 0, 0, 12, 0, 0, 0, 12,
    0, 0, 0, 2, 0, 10, 0, 20, 0xFF, 0xE2, 0, 40,
    0, 0, 0, 0,
};
daegun_ankr *ankr = NULL;
if (daegun_ankr_parse(bytes, sizeof bytes, 3, &ankr) != DAEGUN_OK) return 1;
uint32_t count = 0;
if (daegun_ankr_point_count(ankr, 1, &count) != DAEGUN_OK) return 1;
for (uint16_t i = 0; i < count; i++) {
    int16_t x = 0, y = 0;
    if (daegun_ankr_anchor_point(ankr, 1, i, &x, &y) != DAEGUN_OK) return 1;
    /* (10, 20), then (-30, 40). */
}
daegun_ankr_free(ankr);
daegun_ivs
typedef struct daegun_ivs daegun_ivs;

An item variation store: regions of a variable font's design space, and the deltas that values such as advances, metrics and positions take in them.

A variable font stores a value such as a glyph's advance once, for its default design, and stores beside it how the value changes across the design space. An item variation store is where those changes live. It holds a list of regions, each a part of the design space with a peak where it counts in full, and one or more item variation data subtables. A subtable lists the regions it has deltas for and holds rows of deltas: one row for an item, and in the row one delta for each of those regions. Two numbers pick an item's row: the outer index, which subtable, and the inner index, which row in it.

Reading a value at a location takes two steps. daegun_ivs_region_scalars works out how much each region counts at the location, a scalar from 0 to 1. daegun_ivs_delta then multiplies an item's row by those scalars and sums it, and that sum is what the location adds to the default value.

The store does not know what its items are. The table that holds it does. HVAR and VVAR keep the deltas of each glyph's advance, reached through a daegun_delta_set_index_map. MVAR keeps those of font-wide metrics such as the underline, and each of its value records names an outer and an inner index. GDEF keeps the ones that positioning values in GPOS point at.

daegun_ivs_parse makes a store from a table's bytes, the daegun_ivs_ calls read it, and daegun_ivs_free frees it. The handle holds the store decoded in full and keeps no pointer into the bytes it was parsed from, so they may go as soon as the parse returns. Nothing changes a store once it is parsed, so any number of threads may read one at the same time.

/* MVAR varies font-wide metrics. It keeps the offset of its store as a uint16 at byte 10. */
daegun_bytes mvar = { NULL, 0 };
if (daegun_font_table(font, DAEGUN_TAG('M', 'V', 'A', 'R'), &mvar) != DAEGUN_OK) return 1;
uint16_t store_at = 0;
if (daegun_read_u16_be(mvar.data, mvar.len, 10, &store_at) != DAEGUN_OK) return 1;

daegun_ivs *ivs = NULL;
if (daegun_ivs_parse(mvar.data, mvar.len, store_at, &ivs) != DAEGUN_OK) return 1;
size_t regions = 0, subtables = 0, rows = 0;
if (daegun_ivs_region_count(ivs, &regions) != DAEGUN_OK) return 1;
if (daegun_ivs_ivd_count(ivs, &subtables) != DAEGUN_OK) return 1;
if (daegun_ivs_ivd_rows(ivs, 0, &rows) != DAEGUN_OK) return 1;
/* Inter's MVAR store: 5 regions, and 1 subtable of 4 rows of deltas. */

daegun_ivs_free(ivs);
daegun_region_axis
typedef struct {
    double start;
    double peak;
    double end;
} daegun_region_axis;

One axis of a region: where along that axis the region starts to count, where it counts in full and where it stops.

daegun_ivs_region lends an array of these, one for each axis of the store, in the order of the font's axes. The three values are normalized coordinates, the scale daegun_location_normalized answers in: 0 is the axis's default, -1 its minimum and 1 its maximum.

Along the axis, the region's weight rises from 0 at start to 1 at peak and falls back to 0 at end. A location exactly at peak gets the full weight, also where peak equals start or end, as it does for a region that peaks at the edge of an axis. A region's scalar at a location is the product of its weights on every axis, which is what daegun_ivs_region_scalars works out.

An axis whose peak is 0 takes no part in the region: the region counts the same wherever the location sits on it. daegun also leaves out an axis whose three values are out of order, or whose start is below 0 while its end is above 0.

daegun_bytes hvar = { NULL, 0 };
if (daegun_font_table(font, DAEGUN_TAG('H', 'V', 'A', 'R'), &hvar) != DAEGUN_OK) return 1;
uint32_t store_at = 0;
if (daegun_read_u32_be(hvar.data, hvar.len, 4, &store_at) != DAEGUN_OK) return 1;
daegun_ivs *ivs = NULL;
if (daegun_ivs_parse(hvar.data, hvar.len, store_at, &ivs) != DAEGUN_OK) return 1;

size_t regions = 0;
if (daegun_ivs_region_count(ivs, &regions) != DAEGUN_OK) return 1;
for (size_t r = 0; r < regions; r++) {
    size_t axes = 0;
    const daegun_region_axis *axis = daegun_ivs_region(ivs, r, &axes);
    for (size_t j = 0; axis && j < axes; j++) {
        /* On axis j, region r starts at axis[j].start, peaks at axis[j].peak, ends at axis[j].end. */
    }
}
/* Region 1 of Inter's HVAR store is the light side of the weight axis, which is axis 1: -1, -1, 0.
   It counts in full at the lightest weight and fades out by the default. */

daegun_ivs_free(ivs);
double start
The normalized coordinate where the region begins. Its weight rises from 0 here.
double peak
The normalized coordinate where the region counts in full, a weight of 1. A peak of 0 means the axis takes no part in the region.
double end
The normalized coordinate where the region ends, its weight back at 0.
  • Size: 24 bytes.
daegun_delta_set_index_map
typedef struct daegun_delta_set_index_map daegun_delta_set_index_map;

A delta-set index map: the list that says which row of an item variation store belongs to each item.

A table that keeps a delta for each item, as HVAR does for each glyph's advance, may number the rows of its store as it likes and let many items share a row. The map makes the link: entry i is the outer and the inner index of item i, the two numbers daegun_ivs_delta takes. In HVAR and VVAR the item is a glyph id.

daegun_delta_set_index_map_parse makes one, daegun_delta_set_index_map_lookup reads it, and daegun_delta_set_index_map_free frees it. The handle holds its entries decoded and keeps no pointer into the bytes it was parsed from, so they may go as soon as the parse returns. Threads may share one.

A table may have no map, which it says with an offset of 0 where the offset of the map would be. A glyph's advance deltas in HVAR and VVAR are then read from subtable 0 of the store, at the row of its glyph id: the outer index is 0 and the inner index is the glyph id. Check for the 0 before you parse, since byte 0 is the start of the table, not a map.

daegun_bytes hvar = { NULL, 0 };
if (daegun_font_table(font, DAEGUN_TAG('H', 'V', 'A', 'R'), &hvar) != DAEGUN_OK) return 1;
/* HVAR keeps the offset of its advance map as a uint32 at byte 8. A 0 there means no map. */
uint32_t map_at = 0;
if (daegun_read_u32_be(hvar.data, hvar.len, 8, &map_at) != DAEGUN_OK) return 1;
daegun_delta_set_index_map *map = NULL;
if (map_at != 0 && daegun_delta_set_index_map_parse(hvar.data, hvar.len, map_at, &map) != DAEGUN_OK)
    return 1;

uint32_t glyph = 0;
if (daegun_font_glyph_id(font, 'A', &glyph) != DAEGUN_OK) return 1;
/* With no map, a glyph's deltas are in subtable 0, in the row of its glyph id. */
size_t outer = 0, inner = glyph;
if (map && daegun_delta_set_index_map_lookup(map, glyph, &outer, &inner) != DAEGUN_OK) return 1;
/* EB Garamond's HVAR has no map, so its A, glyph 1, reads row 1 of subtable 0. */

daegun_delta_set_index_map_free(map);
daegun_feature_variations
typedef struct daegun_feature_variations daegun_feature_variations;

A layout table's FeatureVariations: the records that swap one feature for another in a part of a variable font's design space.

GSUB and GPOS, the tables that hold a font's substitution and positioning features, may carry a FeatureVariations table. Each of its records has a set of conditions, such as a range on one axis, and a list of substitutions: where the conditions hold, use this other feature table in place of the feature with that index. It is how a font changes which lookups a feature applies as the design changes.

daegun_feature_variations_parse finds the table through the header of a GSUB or GPOS table, and daegun_feature_variations_at takes an offset you already know. daegun_feature_variations_find answers which record applies at a location, and daegun_feature_variations_substitute what that record puts in place of a feature. daegun_feature_variations_free frees the handle.

The handle keeps a copy of the whole layout table it was given, so those bytes may go as soon as the call that made it returns. Nothing is decoded ahead of time. Each call reads the copy with every read checked against its length: what lies past the end reads as nothing, so a record cut off doesn't hold, and nothing is read out of bounds. Threads may share a handle.

/* A GSUB table of version 1.1, written out by hand. Its one record swaps feature 3 where axis 1 is
   from 0.5 to 1.0. */
static const uint8_t gsub[] = {
    0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 14,         /* header: FeatureVariations at byte 14 */
    0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 16, 0, 0, 0, 30,  /* 1 record */
    0, 1, 0, 0, 0, 6, 0, 1, 0, 1, 0x20, 0, 0x40, 0,    /* its condition: axis 1, 0.5 to 1.0 */
    0, 1, 0, 0, 0, 1, 0, 3, 0, 0, 0, 12,               /* its substitution: feature 3 */
    0, 0, 0, 1, 0, 5,                                  /* the feature table that takes its place */
};
daegun_feature_variations *variations = NULL;
if (daegun_feature_variations_parse(gsub, sizeof gsub, &variations) != DAEGUN_OK) return 1;

/* Normalized coordinates as F2DOT14 integers, 16384 being 1.0: axis 0 at its default, axis 1 at 0.75. */
const int32_t coords[] = { 0, 12288 };
uint32_t record = 0;
size_t alternate = 0;
if (daegun_feature_variations_find(variations, coords, 2, NULL, &record) == DAEGUN_OK
    && daegun_feature_variations_substitute(variations, record, 3, &alternate) == DAEGUN_OK) {
    /* Record 0 applies there, and feature 3 uses the feature table at byte 56 of the GSUB. */
}

daegun_feature_variations_free(variations);

Rasterizing

daegun/raster.h: daegun's own rasterizer, which turns glyphs and paths into pixels, and what any rasterizer needs beyond outlines. Subpixel layouts with their filters, and an atlas packer.

daegun_subpixel_layout
typedef struct daegun_subpixel_layout daegun_subpixel_layout;

How a glyph drawn at several samples per pixel becomes one value per channel: plain coverage, the stripes of a display, or a filter of your own.

Plain text rendering gives each pixel one number, its coverage: the share of the pixel the glyph covers, from 0 to 255. That is the grayscale layout, one byte a pixel, and what NULL in the layout of a daegun_raster_options means.

A pixel of an LCD is three stripes, one red, one green and one blue, most often side by side. Each is lit on its own, so across the stripes a display shows three times the detail it does in whole pixels. Subpixel text uses that: the glyph is drawn three times as fine, and each stripe gets the coverage of its own third of the pixel. Small text comes out sharper, at the price of an image of three bytes a pixel that is right for one arrangement of stripes only.

Giving each stripe its own sample and nothing else colors the edges of stems, as an edge that covers the red stripe of a pixel and not the blue lights them unequally. So the stripe layouts pass the samples through a filter: each channel is a weighted sum of the samples in a small window around its stripe, which spreads each sample onto its neighbors and evens out the color.

A layout holds what that takes, and the daegun_subpixel_layout_ readers give it back: how many samples a pixel (daegun_subpixel_layout_oversample), the size of the window (daegun_subpixel_layout_taps), where it starts (daegun_subpixel_layout_origin) and its weights (daegun_subpixel_layout_weights). Make one with daegun_subpixel_layout_grayscale, daegun_subpixel_layout_horizontal or daegun_subpixel_layout_vertical for stripes, daegun_subpixel_layout_unfiltered for stripes with no filter, or daegun_subpixel_layout_from_weights for a filter you state yourself. Free it with daegun_subpixel_layout_free.

Point the layout of a daegun_raster_options at it, and daegun_rasterizer_glyph lends an image of daegun_subpixel_layout_channels bytes a pixel, red, green, blue for the stripe layouts, already grown by daegun_subpixel_layout_pad. The options only point at it, so it must stay alive through every call they go to. daegun_rasterizer_glyph_into and the color calls take the grayscale layout only.

The readers and the drawing calls take it as const, so any number of threads may read one layout and draw through it at the same time.

uint32_t gid = 0;
if (daegun_font_glyph_id(font, 'g', &gid) != DAEGUN_OK) return 1;
daegun_subpixel_layout *lcd = NULL;
if (daegun_subpixel_layout_horizontal(DAEGUN_STRIPES_RGB, &lcd) != DAEGUN_OK) return 1;

daegun_raster_options opts;
if (daegun_raster_options_default(&opts, sizeof opts) != DAEGUN_OK) return 1;
opts.layout = lcd;
daegun_rasterizer *rasterizer = daegun_rasterizer_new();
daegun_image image;
if (daegun_rasterizer_glyph(rasterizer, font, gid, NULL, 20.0f, &opts, &image) != DAEGUN_OK) return 1;
/* Three bytes a pixel, and a pixel more on the left and the right than the gray image's 10 by 17. */
for (uint32_t y = 0; y < image.height; y++) {
    for (uint32_t x = 0; x < image.width; x++) {
        const uint8_t *pixel = image.pixels + y * image.stride + 3 * x;
        /* Blend each channel of the text color over the background by its own byte. */
        uint8_t red = pixel[0], green = pixel[1], blue = pixel[2];
    }
}
daegun_rasterizer_free(rasterizer);
daegun_subpixel_layout_free(lcd);
daegun_rect
typedef struct {
    size_t x;
    size_t y;
    size_t w;
    size_t h;
} daegun_rect;

Where a rectangle landed in an atlas, in pixels: its left and top edges, its width and its height.

daegun_shelf_packer_insert fills one for each glyph it places. x and y count from the top left corner of the atlas, with y running down, the way rows of pixels are stored, so the glyph's row r goes at byte (y + r) * atlas_width + x of an atlas of one byte a pixel. w and h are the size you asked for, unchanged.

enum { SIDE = 256 };
static uint8_t atlas[SIDE * SIDE];
daegun_shelf_packer *packer = daegun_shelf_packer_new(SIDE, SIDE);
daegun_rect rect;
if (daegun_shelf_packer_insert(packer, 12, 17, &rect) != DAEGUN_OK) return 1;
/* An empty atlas puts it at the top left corner: x 0, y 0, w 12, h 17. */

/* Copy a glyph's rows into the atlas at the rect, one byte a pixel here. */
uint8_t glyph[17][12];
memset(glyph, 255, sizeof glyph);
for (size_t row = 0; row < rect.h; row++) memcpy(&atlas[(rect.y + row) * SIDE + rect.x], glyph[row], rect.w);
daegun_shelf_packer_free(packer);
size_t x
The left edge: pixels from the left side of the atlas.
size_t y
The top edge: pixels down from the top of the atlas.
size_t w
The width, in pixels.
size_t h
The height, in pixels.
  • Size: 4 bytes * sizeof(size_t).
daegun_shelf_packer
typedef struct daegun_shelf_packer daegun_shelf_packer;

Packs rectangles into an atlas of a fixed size, in rows called shelves.

An atlas is one large image that holds many glyphs, so a renderer can draw text from a single texture. The packer decides where each glyph goes. It holds no pixels: you give it sizes, it answers with places, and you copy the pixels there yourself.

A shelf is a band across the atlas, as tall as the rectangle that opened it and filled from the left. The first shelf is at the top, and each new one opens right below the last. daegun_shelf_packer_insert puts a rectangle on the shortest shelf that can take it, and opens a new shelf where none can. Rectangles sit edge to edge with no gap, so if your renderer samples the atlas with filtering, add the gutter you need to the size you ask for.

A placed rectangle never moves, and no call frees one. When the packer answers DAEGUN_ABSENT for a glyph, start another atlas, or call daegun_shelf_packer_reset and draw the glyphs of this one again. Skip a glyph with an empty image, such as a space, before you insert: its DAEGUN_ABSENT doesn't mean the atlas is full.

Make one with daegun_shelf_packer_new and free it with daegun_shelf_packer_free. Inserting and resetting change it, so one thread at a time may use a packer.

enum { SIDE = 40 };
static uint8_t atlas[SIDE * SIDE];
daegun_shelf_packer *packer = daegun_shelf_packer_new(SIDE, SIDE);
daegun_rasterizer *rasterizer = daegun_rasterizer_new();

const char *letters = "glyph";
daegun_rect placed[5];
for (size_t i = 0; i < 5; i++) {
    uint32_t gid = 0;
    daegun_image image;
    if (daegun_font_glyph_id(font, (uint32_t)letters[i], &gid) != DAEGUN_OK) return 1;
    if (daegun_rasterizer_glyph(rasterizer, font, gid, NULL, 20.0f, NULL, &image) != DAEGUN_OK) return 1;
    if (image.width == 0 || image.height == 0) continue; /* nothing to draw, as for a space */
    daegun_rect rect;
    daegun_status status = daegun_shelf_packer_insert(packer, image.width, image.height, &rect);
    if (status == DAEGUN_ABSENT) break; /* full: start another atlas, or reset this one */
    if (status != DAEGUN_OK) return 1;
    for (size_t row = 0; row < rect.h; row++)
        memcpy(&atlas[(rect.y + row) * SIDE + rect.x], image.pixels + row * image.stride, rect.w);
    placed[i] = rect;
}
/* The g opened a shelf 17 pixels tall at the top left, and l, y and p went on it to its right.
   The h found no room left across, so it opened a second shelf below, at y 17. */
daegun_rasterizer_free(rasterizer);
daegun_shelf_packer_free(packer);
daegun_rasterizer
typedef struct daegun_rasterizer daegun_rasterizer;

Draws glyphs, color glyphs, distance fields and paths into images of pixels, keeping its buffers from one draw to the next.

Make one with daegun_rasterizer_new and keep it for as long as you draw. daegun_rasterizer_glyph gives a glyph as coverage, a byte for each pixel that says how much of the pixel the glyph covers. daegun_rasterizer_color_glyph gives a color glyph as RGBA, daegun_rasterizer_distance_field a distance field for a GPU, and daegun_rasterizer_path fills a daegun_path of your own.

Those calls lend a daegun_image that points into the rasterizer and is valid until its next call or its free: copy the pixels you keep. The calls that end in _into draw into a daegun_target instead, pixels you own, and take any size, where a lent image stops at DAEGUN_MAX_SIDE and DAEGUN_MAX_DRAW_BYTES.

Coverage is an area, not a count of sample points: each byte is the share of its pixel that the outline covers, exact too where contours overlap, so a pixel that two contours each half cover in the same place reads 128, not 255.

It keeps its buffers between calls, so they grow only to fit the largest image it has drawn. It also keeps what it learns of each glyph at its first draw, its outline and where its contours overlap, under the budget of daegun_rasterizer_set_cache_budget. The images themselves are kept only when the font's DAEGUN_CACHE_RASTER has a budget.

A rasterizer holds no font: you pass one to each call, and one rasterizer draws from any number of fonts. Every drawing call takes it as non-const, so it is for one thread at a time: give each thread its own. It may be freed on any thread once no call is using it.

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 *glyphs = 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;

/* Set "Wave" at 32 px into a canvas of one byte a pixel, with the baseline on row 30. */
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 its pixel. */
    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;
    daegun_status st = daegun_rasterizer_glyph(rasterizer, font, glyphs[i], NULL, 32.0f, &opts, &image);
    if (st != 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++) {
            uint8_t *dst = &canvas[top + (int)row][left + (int)col];
            unsigned sum = *dst + image.pixels[row * image.stride + col];
            *dst = sum > 255 ? 255 : (uint8_t)sum;
        }
    }
    pen += advances[i] * scale;
}
/* The word is inked across columns 2 to 83 and rows 6 to 30 of the canvas. */
daegun_rasterizer_free(rasterizer);
daegun_shaped_run_free(run);
daegun_image
typedef struct {
    int32_t left;
    int32_t top;
    uint32_t width;
    uint32_t height;
    size_t stride;
    const uint8_t *pixels;
    size_t pixels_len;
    uint8_t channels;
} daegun_image;

Pixels a rasterizer lends: a rectangle of rows, and where it sits from the origin of what was drawn.

Every drawing call that does not take a daegun_target fills one. It is BORROWED from the rasterizer: its pixels are valid until the rasterizer's next call, one that fails included, or until daegun_rasterizer_free. To keep an image longer, or to draw another glyph before you are done with this one, copy its pixels out.

left and top place it. They are measured from the origin, which for a glyph is the point on the baseline where the pen stands: the image starts left pixels to the right of it and top pixels above it, and its rows run down from there. With the pen at column pen_x of the baseline on row baseline_y of a canvas whose rows run down, pixel (x, y) of the image goes at (pen_x + left + x, baseline_y - top + y).

Byte c of pixel (x, y) is pixels[y * stride + x * channels + c]. An image is as large as what was drawn and no larger, and it is 0 by 0 when nothing was, as for a space.

uint32_t gid = 0;
if (daegun_font_glyph_id(font, 'L', &gid) != DAEGUN_OK) return 1;
daegun_rasterizer *rasterizer = daegun_rasterizer_new();
daegun_image image;
if (daegun_rasterizer_glyph(rasterizer, font, gid, NULL, 12.0f, NULL, &image) != DAEGUN_OK) return 1;
/* Inter's L at 12 px: 6 by 9 pixels, from 1 pixel right of the origin and 9 above the baseline,
   so it stands on the line. */
for (uint32_t y = 0; y < image.height; y++) {
    const uint8_t *row = image.pixels + y * image.stride;
    /* Row 0 is the top one, the tip of the stem: 176, 31, 0, 0, 0, 0. */
}

/* The pixels are the rasterizer's until its next call: copy them to keep them. */
uint8_t *kept = malloc(image.pixels_len);
if (!kept) return 1;
memcpy(kept, image.pixels, image.pixels_len);
daegun_rasterizer_free(rasterizer);
free(kept);
int32_t left
How many pixels the left edge lies to the right of the origin. Negative where the image starts left of it.
int32_t top
How many pixels the top edge lies above the origin, counting up, which for a glyph is the baseline. A letter whose lowest point is on the baseline, as an L's is, has a top equal to its height, one that reaches below the line, as a g or an o does, a smaller one, and an image wholly below the baseline a top of 0 or less.
uint32_t width
Pixels across.
uint32_t height
Pixels down, which is the number of rows.
size_t stride
Bytes from the start of one row to the start of the next. In every image a rasterizer lends it is width * channels, with no padding between rows.
const uint8_t *pixels
The bytes of the rows, the top row first. BORROWED until the next call on the rasterizer or its free. When nothing was drawn pixels_len is 0, and there is nothing to read here.
size_t pixels_len
How many bytes pixels holds: stride * height.
uint8_t channels
Bytes a pixel. 1 for coverage and for a DAEGUN_FIELD_SDF field. 3 for a subpixel layout, red, green, blue, and for a DAEGUN_FIELD_MSDF field. 4 for a color glyph: red, green, blue and alpha, sRGB and premultiplied.
  • Size: 48 bytes on a 64-bit target.
daegun_target
typedef struct {
    int32_t left;
    int32_t top;
    uint32_t width;
    uint32_t height;
    size_t stride;
    uint8_t *pixels;
    size_t pixels_len;
} daegun_target;

Pixels you own, described for a rasterizer to draw into: a rectangle of rows and where it lies from the origin of what is drawn.

The _into calls take one: daegun_rasterizer_glyph_into, daegun_rasterizer_path_into and daegun_rasterizer_color_glyph_into. Where a lent daegun_image tells you which rectangle a glyph fell in, a target tells the rasterizer which rectangle you want. You fill in every field.

left and top are read as those of an image are: the left edge of the rectangle is left pixels to the right of the origin, and its top edge top pixels above it. So to put the origin at column ox and row oy of your pixels, counting rows down from the top, pass a left of -ox and a top of oy.

A call that draws writes every pixel of the rectangle: the drawing where it falls inside, and zeros elsewhere. What the pixels held is replaced, not added to or blended with. Whatever lies outside the rectangle is cut off. The bytes of a row past its width pixels, where the stride is longer, are left alone, so a target can be a cell inside a larger canvas.

A pixel is one byte of coverage, or four of RGBA for daegun_rasterizer_color_glyph_into. The pixels hold the rows when stride is at least width times the bytes a pixel and pixels_len is at least (height - 1) * stride plus that, and otherwise the call answers DAEGUN_INVALID_ARGUMENT before it writes a byte. NULL pixels with a pixels_len above 0 answers DAEGUN_NULL. A width or height of 0 is fine, and nothing is written.

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

/* 16 by 24 pixels of your own, with the glyph's origin at column 2 of row 16. */
static uint8_t pixels[24][16];
daegun_target target = {
    .left = -2, .top = 16, .width = 16, .height = 24,
    .stride = sizeof pixels[0], .pixels = &pixels[0][0], .pixels_len = sizeof pixels,
};
daegun_rasterizer *rasterizer = daegun_rasterizer_new();
if (daegun_rasterizer_glyph_into(rasterizer, font, gid, NULL, 20.0f, NULL, &target) != DAEGUN_OK) return 1;
/* Inter's g now fills columns 3 to 12 of rows 4 to 20, and every other pixel is 0. */
daegun_rasterizer_free(rasterizer);
int32_t left
How many pixels the left edge of the rectangle lies to the right of the origin: -ox for the origin at column ox.
int32_t top
How many pixels the top edge lies above the origin, counting up: oy for the origin at row oy, rows counted down from the top.
uint32_t width
Pixels across.
uint32_t height
Pixels down, which is the number of rows.
size_t stride
Bytes from the start of one row to the start of the next. At least width times the bytes a pixel, and more where the rectangle is a cell of a wider canvas.
uint8_t *pixels
Your pixels, the top row first. The call writes into them and keeps no pointer after it returns.
size_t pixels_len
How many bytes pixels holds, at least (height - 1) * stride plus a row.
  • Size: 40 bytes on a 64-bit target.
daegun_raster_options
typedef struct {
    size_t size;
    const daegun_outline_options *outline;
    const daegun_subpixel_layout *layout;
    float offset[2];
    int32_t gamma;
    daegun_rgba text;
    float contrast;
    bool darken;
} daegun_raster_options;

How daegun_rasterizer_glyph draws: the outline options, the subpixel offset, the layout of the pixels, stem darkening and gamma.

Fill it with daegun_raster_options_default, then set the fields you want. Passing NULL where a call takes options means the defaults: the glyph as the font holds it, its origin on a pixel corner, as plain coverage, one byte a pixel.

Every default is zero, so a struct you zero yourself and then give its size is the same as what daegun_raster_options_default fills. Zeroing alone is not enough: a size of 0 makes the call you pass it to answer DAEGUN_INVALID_ARGUMENT. The struct opens with its own size, so a program built against this header keeps working with a newer library that has added fields at the end.

The two pointers are read during each call that takes the options, not copied when you set them, so what they point at must live through those calls.

daegun_rasterizer_glyph reads every field. daegun_rasterizer_glyph_into reads them too but refuses a layout other than grayscale. daegun_rasterizer_color_glyph and daegun_rasterizer_color_glyph_into read the offset and the outline's transform and oblique, refuse a layout other than grayscale, hinting, a stroke and an embolden above 0, and pass over the rest. daegun_rasterizer_distance_field and daegun_rasterizer_path take no options.

/* Small text for an LCD: hinted, its thin stems darkened, filtered for stripes in the order RGB. */
daegun_outline_options outline;
if (daegun_outline_options_default(&outline, sizeof outline) != DAEGUN_OK) return 1;
outline.hinting = DAEGUN_HINT_AUTO;
daegun_subpixel_layout *lcd = NULL;
if (daegun_subpixel_layout_horizontal(DAEGUN_STRIPES_RGB, &lcd) != 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 = lcd;
opts.darken = true;

uint32_t gid = 0;
if (daegun_font_glyph_id(font, 'g', &gid) != DAEGUN_OK) return 1;
daegun_rasterizer *rasterizer = daegun_rasterizer_new();
daegun_image image;
if (daegun_rasterizer_glyph(rasterizer, font, gid, NULL, 12.0f, &opts, &image) != DAEGUN_OK) return 1;
/* Three bytes a pixel: red, green and blue. */
daegun_rasterizer_free(rasterizer);
daegun_subpixel_layout_free(lcd);
size_t size
The size of the struct in bytes as your header has it. daegun_raster_options_default sets it.
const daegun_outline_options *outline
A daegun_outline_options for what happens to the outline before it is filled: hinting, a transform, a stroke, an embolden or an oblique lean, each with the meaning it has in daegun_font_prepared_outline. NULL means its defaults, the outline as the font holds it. Its own size is checked as this struct's is.
const daegun_subpixel_layout *layout
A daegun_subpixel_layout for how samples become the bytes of a pixel. NULL is grayscale, one byte of coverage a pixel, the same as a layout from daegun_subpixel_layout_grayscale. A layout for the stripes of a display gives three bytes a pixel, red, green, blue, and an image grown by daegun_subpixel_layout_pad.
float offset[2]
How far the glyph moves right (offset[0]) and up (offset[1]) before it is drawn, in pixels. It is for the fraction of a pen position, so text set between whole pixels keeps the spacing shaping gave it: place the image by the whole part and pass the fraction here. Any finite value is taken. A whole number of pixels moves left or top by that much, and the bytes come out the same or a level apart, as the outline is placed in single precision, and further apart as the offset grows, as much as 3 levels at 12,345 pixels: pass the fraction alone. A value that is not finite answers DAEGUN_INVALID_ARGUMENT. 0 and 0 put the origin on a pixel corner.
int32_t gamma
A DAEGUN_GAMMA_ code for how coverage becomes the alpha you blend with: DAEGUN_GAMMA_LINEAR, the default, leaves coverage as it is, and DAEGUN_GAMMA_SRGB corrects it for a compositor that blends sRGB bytes. A code that is neither answers DAEGUN_INVALID_ARGUMENT.
daegun_rgba text
With DAEGUN_GAMMA_SRGB, the color of the text, as a daegun_rgba. Its alpha is not read. A one-byte image is corrected for the text's luminance, as a gray, and each byte of a three-byte image for the text's own red, green or blue. Not read under DAEGUN_GAMMA_LINEAR.
float contrast
With DAEGUN_GAMMA_SRGB, how much to thicken the coverage before it is corrected, from 0 for none to 1. A coverage a becomes a + k * a * (1 - a), where k is the contrast times the linear light of the ground, the text color inverted: it weighs fully on black text and not at all on white. Above 1 counts as 1, and 0, below 0 or NaN as none.
bool darken
Whether thin stems are widened at small sizes, where text otherwise reads too light. The glyph is emboldened by 0.4 pixels for a stem half a pixel wide or less, falling to 0.275 pixels for a stem of 1 pixel, 0.275 up to 1 2/3 pixels, then falling to nothing at 2 1/3 pixels. The stem is measured once per font and location across the middle of its l, else its I, else taken as 0.075 em: Inter measures 180 units of its 2048, so its text is darkened below 26.55 px. A stroked glyph is not darkened. False by default, and any byte but 0 is true.
  • Size: 48 bytes on a 64-bit target.

Type to search.